Repository navigation
Expand file tree
/
Copy pathtest-compiler.js
More file actions
313 lines (283 loc) · 11.1 KB
/
Copy pathtest-compiler.js
File metadata and controls
313 lines (283 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
'use strict'
// Tests the @fastify/ajv-compiler-compatible factory so ata can serve as
// Fastify's GLOBAL default validator (not just a per-route compiler).
const Fastify = require('fastify')
const AtaCompiler = require('./compiler')
const { expandMergePatch } = require('./merge-patch')
let pass = 0
let fail = 0
function assert(cond, msg) {
if (cond) { pass++; console.log(` PASS ${msg}`) }
else { fail++; console.log(` FAIL ${msg}`) }
}
async function run() {
console.log('\nfastify-ata compiler (global default) Tests\n')
// Factory shape mirrors @fastify/ajv-compiler: factory() -> build(ext, opts) -> compile({schema}) -> validate
const factory = AtaCompiler()
const build = factory({}, { customOptions: {} })
const validate = build({ schema: { type: 'object', properties: { n: { type: 'integer' } }, required: ['n'] } })
assert(validate({ n: 1 }) === true || (validate({ n: 1 }) && validate({ n: 1 }).value), 'compiler: valid input accepted')
const bad = validate({})
assert(bad === false, 'compiler: invalid input rejected')
// The compiler path is Fastify's default-validator route: errors must be
// the exact ajv shape (no rich fields) and mutable, because ecosystem
// plugins like ajv-i18n assign to error.message. Rich errors belong to the
// plugin path.
const err0 = validate.errors && validate.errors[0]
assert(err0 && err0.keyword && err0.message && err0.code === undefined && err0.docUrl === undefined,
`compiler: ajv-shaped errors (got ${JSON.stringify(err0)})`)
err0.message = 'mutated'
assert(err0.message === 'mutated', 'compiler: error objects are mutable')
// As Fastify's GLOBAL default via schemaController, with cross-schema $ref
const app = Fastify({
schemaController: { compilersFactory: { buildValidator: AtaCompiler() } },
})
app.addSchema({ $id: 'addr', type: 'object', properties: { city: { type: 'string' } }, required: ['city'] })
app.post('/u', {
schema: {
body: {
type: 'object',
properties: { name: { type: 'string' }, address: { $ref: 'addr#' } },
required: ['name', 'address'],
},
},
}, (req, reply) => reply.send({ ok: true }))
await app.ready()
const okRes = await app.inject({ method: 'POST', url: '/u', payload: { name: 'M', address: { city: 'IST' } } })
assert(okRes.statusCode === 200, `compiler: cross-schema $ref valid -> 200 (got ${okRes.statusCode})`)
const badRes = await app.inject({ method: 'POST', url: '/u', payload: { name: 'M', address: {} } })
assert(badRes.statusCode === 400, `compiler: cross-schema $ref invalid -> 400 (got ${badRes.statusCode})`)
await app.close()
// coerceTypes default on (matches Fastify default): querystring "5" -> 5
const app2 = Fastify({
schemaController: { compilersFactory: { buildValidator: AtaCompiler() } },
})
app2.get('/q', {
schema: { querystring: { type: 'object', properties: { limit: { type: 'integer' } }, required: ['limit'] } },
}, (req, reply) => reply.send({ limit: req.query.limit, typ: typeof req.query.limit }))
await app2.ready()
const qRes = await app2.inject({ method: 'GET', url: '/q?limit=5' })
assert(qRes.statusCode === 200, `compiler: coerced querystring -> 200 (got ${qRes.statusCode})`)
assert(JSON.parse(qRes.payload).typ === 'number', `compiler: querystring coerced to number (got ${qRes.payload})`)
await app2.close()
// --- $merge / $patch expansion tests ---
// root $merge: required added via with
const mergeResult = expandMergePatch({
$merge: {
source: { type: 'object', properties: { q: { type: 'string' } } },
with: { required: ['q'] }
}
})
assert(
mergeResult.type === 'object' &&
Array.isArray(mergeResult.required) &&
mergeResult.required[0] === 'q',
'$merge: required added via with'
)
// root $patch: add op changes a property type
const patchResult = expandMergePatch({
$patch: {
source: { type: 'object', properties: { q: { type: 'string' } } },
with: [{ op: 'add', path: '/properties/q', value: { type: 'number' } }]
}
})
assert(
patchResult.properties && patchResult.properties.q && patchResult.properties.q.type === 'number',
'$patch: add op changes property type'
)
// nested $merge inside a larger schema
const nestedSchema = {
type: 'object',
properties: {
inner: {
$merge: {
source: { type: 'object', properties: { n: { type: 'integer' } } },
with: { required: ['n'] }
}
}
}
}
const nestedResult = expandMergePatch(nestedSchema)
assert(
nestedResult.properties.inner.required &&
nestedResult.properties.inner.required[0] === 'n' &&
nestedResult.properties.inner.type === 'object',
'$merge nested: expansion works inside properties'
)
// null deletes key in $merge
const nullDeleteResult = expandMergePatch({
$merge: {
source: { type: 'object', required: ['x'], properties: { x: { type: 'string' } } },
with: { required: null }
}
})
assert(
!('required' in nullDeleteResult),
'$merge null: null in with deletes the key'
)
// unsupported op throws
let threw = false
try {
expandMergePatch({
$patch: {
source: { type: 'object' },
with: [{ op: 'move', from: '/a', path: '/b' }]
}
})
} catch (e) {
threw = e.message.includes('unsupported op')
}
assert(threw, '$patch: unsupported op throws with clear message')
// remove on non-existent path throws
let removeMissingThrew = false
try {
expandMergePatch({
$patch: {
source: { type: 'object', properties: { x: { type: 'string' } } },
with: [{ op: 'remove', path: '/properties/y' }]
}
})
} catch (e) {
removeMissingThrew = e.message.includes('cannot remove non-existent path')
}
assert(removeMissingThrew, '$patch: remove on non-existent path throws')
// replace on non-existent path throws
let replaceMissingThrew = false
try {
expandMergePatch({
$patch: {
source: { type: 'object', properties: { x: { type: 'string' } } },
with: [{ op: 'replace', path: '/properties/z', value: { type: 'number' } }]
}
})
} catch (e) {
replaceMissingThrew = e.message.includes('cannot replace non-existent path')
}
assert(replaceMissingThrew, '$patch: replace on non-existent path throws')
// expansion depth limit: construct deeply nested $merge chain that exceeds limit
let depthThrew = false
const buildDeepMerge = (depth) => {
if (depth === 0) return { type: 'object' }
return { $merge: { source: buildDeepMerge(depth - 1), with: { properties: { x: { type: 'string' } } } } }
}
try {
expandMergePatch(buildDeepMerge(105))
} catch (e) {
depthThrew = e.message.includes('expansion exceeded depth limit')
}
assert(depthThrew, '$merge/$patch: expansion depth limit enforced')
// schema without $merge/$patch passes through unchanged (no copy)
const plain = { type: 'object', properties: { x: { type: 'string' } } }
assert(expandMergePatch(plain) === plain, '$merge/$patch: plain schema passes through without copy')
// $merge integration: compiler accepts expanded schema
const factory2 = AtaCompiler()
const build2 = factory2({}, { customOptions: {} })
const mergeSchema = {
$merge: {
source: { type: 'object', properties: { n: { type: 'integer' } } },
with: { required: ['n'] }
}
}
const validateMerge = build2({ schema: mergeSchema })
assert(validateMerge({ n: 1 }) !== false, '$merge compiler integration: valid input accepted')
assert(validateMerge({}) === false, '$merge compiler integration: missing required rejected')
// --- $ref resolvability checks ---
// (a) anchor-style local ref that does not exist -> must throw
{
const factory3 = AtaCompiler()
const build3 = factory3({}, { customOptions: {} })
let threw = false
let thrownMsg = ''
try {
build3({ schema: { type: 'object', properties: { name: { $ref: '#notExist' } } } })
} catch (e) {
threw = true
thrownMsg = e.message
}
assert(threw, 'ref-check: #notExist with no externals throws')
assert(thrownMsg === "can't resolve reference #notExist from id #",
`ref-check: #notExist message exact (got: ${thrownMsg})`)
}
// (b) external ref with no matching external schema -> must throw
{
const factory4 = AtaCompiler()
const build4 = factory4({}, { customOptions: {} })
let threw = false
let thrownMsg = ''
try {
build4({ schema: { type: 'object', properties: { id: { $ref: 'encapsulation#/properties/id' } } } })
} catch (e) {
threw = true
thrownMsg = e.message
}
assert(threw, 'ref-check: encapsulation#/properties/id with no externals throws')
assert(thrownMsg === "can't resolve reference encapsulation#/properties/id from id #",
`ref-check: encapsulation message exact (got: ${thrownMsg})`)
}
// (c) external ref WITH matching external schema -> must NOT throw
{
const factory5 = AtaCompiler()
const build5 = factory5(
{ encapsulation: { $id: 'encapsulation', type: 'object', properties: { id: { type: 'number' } } } },
{ customOptions: {} }
)
let threw = false
try {
build5({ schema: { type: 'object', properties: { id: { $ref: 'encapsulation#/properties/id' } } } })
} catch (e) {
threw = true
}
assert(!threw, 'ref-check: encapsulation#/properties/id with external schema does NOT throw')
}
// (d) local JSON-pointer ref -> always accepted even when definitions absent
{
const factory6 = AtaCompiler()
const build6 = factory6({}, { customOptions: {} })
let threw = false
try {
build6({ schema: { type: 'object', properties: { x: { $ref: '#/definitions/x' } } } })
} catch (e) {
threw = true
}
assert(!threw, 'ref-check: local JSON-pointer #/definitions/x does NOT throw (conservative)')
}
// (e) anchor that EXISTS as $id in a local definition -> must NOT throw
{
const factory7 = AtaCompiler()
const build7 = factory7({}, { customOptions: {} })
let threw = false
try {
build7({
schema: {
type: 'object',
definitions: { addr: { $id: '#addr', type: 'string' } },
properties: { city: { $ref: '#addr' } }
}
})
} catch (e) {
threw = true
}
assert(!threw, 'ref-check: anchor #addr existing as $id in local definitions does NOT throw')
}
// (f) trailing-slash URI variant: external key 'http://fastify.test/' must
// satisfy ref base 'http://fastify.test' (RFC 3986 normalization, ajv resolves it)
{
const factory8 = AtaCompiler()
const build8 = factory8(
{ 'http://fastify.test/': { $id: 'http://fastify.test/', type: 'object', properties: { hello: { type: 'string' } } } },
{ customOptions: {} }
)
let threw = false
let thrownMsg = ''
try {
build8({ schema: { type: 'array', items: { $ref: 'http://fastify.test#/properties/hello' } } })
} catch (e) {
threw = true
thrownMsg = e.message
}
assert(!threw, `ref-check: trailing-slash URI id variant does NOT throw (got: ${thrownMsg})`)
}
console.log(`\n${pass}/${pass + fail} tests passed\n`)
process.exit(fail > 0 ? 1 : 0)
}
run().catch((err) => { console.error(err); process.exit(1) })