Debian Codegraph @

spec/async_validate.spec.ts

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 import getAjvAsyncInstances from "./ajv_async_instances"
2 import _Ajv from "./ajv"
3 import chai from "./chai"
4 const should = chai.should()
5
6 describe("async schemas, formats and keywords", function () {
7 let ajv, instances
8
9 beforeEach(() => {
10 instances = getAjvAsyncInstances()
11 ajv = instances[0]
12 })
13
14 describe("async schemas without async elements", () => {
15 it("should return result as promise", () => {
16 const schema = {
17 $async: true,
18 type: "string",
19 maxLength: 3,
20 }
21
22 return repeat(() => {
23 return Promise.all(instances.map(test))
24 })
25
26 function test(_ajv) {
27 const validate = _ajv.compile(schema)
28
29 return Promise.all([
30 shouldBeValid(validate("abc"), "abc"),
31 shouldBeInvalid(validate("abcd")),
32 shouldBeInvalid(validate(1)),
33 ])
34 }
35 })
36
37 it("should fail compilation if async schema is inside sync schema", () => {
38 const schema: any = {
39 type: "object",
40 properties: {
41 foo: {
42 $async: true,
43 type: "string",
44 maxLength: 3,
45 },
46 },
47 }
48
49 should.throw(() => {
50 ajv.compile(schema)
51 }, "async schema in sync schema")
52
53 ajv.compile({...schema, $async: true})
54 })
55 })
56
57 describe("async formats", () => {
58 beforeEach(addFormatEnglishWord)
59
60 it("should fail compilation if async format is inside sync schema", () => {
61 instances.forEach((_ajv) => {
62 let schema: any = {
63 type: "string",
64 format: "english_word",
65 }
66
67 should.throw(() => {
68 _ajv.compile(schema)
69 }, "async format in sync schema")
70 schema = {...schema, $async: true}
71 _ajv.compile(schema)
72 })
73 })
74 })
75
76 describe("async user-defined keywords", () => {
77 beforeEach(() => {
78 instances.forEach((_ajv) => {
79 _ajv.addKeyword({
80 keyword: "idExists",
81 async: true,
82 type: "number",
83 validate: checkIdExists,
84 errors: false,
85 })
86
87 _ajv.addKeyword({
88 keyword: "idExistsWithError",
89 async: true,
90 type: "number",
91 validate: checkIdExistsWithError,
92 errors: true,
93 })
94 })
95 })
96
97 it("should fail compilation if async keyword is inside sync schema", () => {
98 instances.forEach((_ajv) => {
99 let schema: any = {
100 type: "object",
101 properties: {
102 userId: {
103 type: "integer",
104 idExists: {table: "users"},
105 },
106 },
107 }
108
109 should.throw(() => {
110 _ajv.compile(schema)
111 }, "async keyword in sync schema")
112
113 schema = {...schema, $async: true}
114 _ajv.compile(schema)
115 })
116 })
117
118 it("should return user-defined error", () => {
119 return Promise.all(
120 instances.map((_ajv) => {
121 const schema = {
122 $async: true,
123 type: "object",
124 properties: {
125 userId: {
126 type: "integer",
127 idExistsWithError: {table: "users"},
128 },
129 postId: {
130 type: "integer",
131 idExistsWithError: {table: "posts"},
132 },
133 },
134 }
135
136 const validate = _ajv.compile(schema)
137
138 return Promise.all([
139 shouldBeInvalid(validate({userId: 5, postId: 10}), ["id not found in table posts"]),
140 shouldBeInvalid(validate({userId: 9, postId: 25}), ["id not found in table users"]),
141 ])
142 })
143 )
144 })
145
146 function checkIdExists(schema, data) {
147 switch (schema.table) {
148 case "users":
149 return check([1, 5, 8])
150 case "posts":
151 return check([21, 25, 28])
152 default:
153 throw new Error("no such table")
154 }
155
156 function check(IDs) {
157 return Promise.resolve(IDs.indexOf(data) >= 0)
158 }
159 }
160
161 function checkIdExistsWithError(schema, data) {
162 const {table} = schema
163 switch (table) {
164 case "users":
165 return check(table, [1, 5, 8])
166 case "posts":
167 return check(table, [21, 25, 28])
168 default:
169 throw new Error("no such table")
170 }
171
172 function check(_table, IDs) {
173 if (IDs.indexOf(data) >= 0) return Promise.resolve(true)
174 const error = {
175 keyword: "idExistsWithError",
176 message: "id not found in table " + _table,
177 }
178 return Promise.reject(new _Ajv.ValidationError([error]))
179 }
180 }
181 })
182
183 describe("async referenced schemas", () => {
184 beforeEach(() => {
185 instances = getAjvAsyncInstances({inlineRefs: false, ignoreKeywordsWithRef: true})
186 addFormatEnglishWord()
187 })
188
189 it("should validate referenced async schema", () => {
190 const schema = {
191 $async: true,
192 definitions: {
193 english_word: {
194 $async: true,
195 type: "string",
196 format: "english_word",
197 },
198 },
199 type: "object",
200 properties: {
201 word: {$ref: "#/definitions/english_word"},
202 },
203 }
204
205 return repeat(() => {
206 return Promise.all(
207 instances.map((_ajv) => {
208 const validate = _ajv.compile(schema)
209 const validData = {word: "tomorrow"}
210
211 return Promise.all([
212 shouldBeValid(validate(validData), validData),
213 shouldBeInvalid(validate({word: "manana"})),
214 shouldBeInvalid(validate({word: 1})),
215 shouldThrow(validate({word: "today"}), "unknown word"),
216 ])
217 })
218 )
219 })
220 })
221
222 it("should validate recursive async schema", () => {
223 const schema = {
224 $async: true,
225 definitions: {
226 english_word: {
227 $async: true,
228 type: "string",
229 format: "english_word",
230 },
231 },
232 type: "object",
233 properties: {
234 foo: {
235 anyOf: [{$ref: "#/definitions/english_word"}, {$ref: "#"}],
236 },
237 },
238 }
239
240 return recursiveTest(schema)
241 })
242
243 it("should validate recursive ref to async sub-schema, issue #612", () => {
244 const schema = {
245 $async: true,
246 type: "object",
247 properties: {
248 foo: {
249 $async: true,
250 anyOf: [
251 {
252 type: "string",
253 format: "english_word",
254 },
255 {
256 type: "object",
257 properties: {
258 foo: {$ref: "#/properties/foo"},
259 },
260 },
261 ],
262 },
263 },
264 }
265
266 return recursiveTest(schema)
267 })
268
269 it("should validate ref from referenced async schema to root schema", () => {
270 const schema = {
271 $async: true,
272 definitions: {
273 wordOrRoot: {
274 $async: true,
275 anyOf: [
276 {
277 type: "string",
278 format: "english_word",
279 },
280 {$ref: "#"},
281 ],
282 },
283 },
284 type: "object",
285 properties: {
286 foo: {$ref: "#/definitions/wordOrRoot"},
287 },
288 }
289
290 return recursiveTest(schema)
291 })
292
293 it("should validate refs between two async schemas", () => {
294 const schemaObj = {
295 $id: "http://e.com/obj.json#",
296 $async: true,
297 type: "object",
298 properties: {
299 foo: {$ref: "http://e.com/word.json#"},
300 },
301 }
302
303 const schemaWord = {
304 $id: "http://e.com/word.json#",
305 $async: true,
306 anyOf: [
307 {
308 type: "string",
309 format: "english_word",
310 },
311 {$ref: "http://e.com/obj.json#"},
312 ],
313 }
314
315 return recursiveTest(schemaObj, schemaWord)
316 })
317
318 it("should fail compilation if sync schema references async schema", () => {
319 let schema: any = {
320 $id: "http://e.com/obj.json#",
321 type: "object",
322 properties: {
323 foo: {$ref: "http://e.com/word.json#"},
324 },
325 }
326
327 const schemaWord = {
328 $id: "http://e.com/word.json#",
329 $async: true,
330 anyOf: [
331 {
332 type: "string",
333 format: "english_word",
334 },
335 {$ref: "http://e.com/obj.json#"},
336 ],
337 }
338
339 ajv.addSchema(schemaWord)
340 ajv.addFormat("english_word", {
341 async: true,
342 validate: checkWordOnServer,
343 })
344
345 should.throw(() => {
346 ajv.compile(schema)
347 }, "async schema referenced by sync schema")
348
349 schema = {...schema, $id: "http://e.com/obj2.json#", $async: true}
350
351 ajv.compile(schema)
352 })
353
354 function recursiveTest(schema, refSchema?) {
355 return repeat(() => {
356 return Promise.all(
357 instances.map((_ajv) => {
358 if (refSchema) _ajv.addSchema(refSchema)
359 const validate = _ajv.compile(schema)
360 let data
361
362 return Promise.all([
363 shouldBeValid(validate((data = {foo: "tomorrow"})), data),
364 shouldBeInvalid(validate({foo: "manana"})),
365 shouldBeInvalid(validate({foo: 1})),
366 shouldThrow(validate({foo: "today"}), "unknown word"),
367 shouldBeValid(validate((data = {foo: {foo: "tomorrow"}})), data),
368 shouldBeInvalid(validate({foo: {foo: "manana"}})),
369 shouldBeInvalid(validate({foo: {foo: 1}})),
370 shouldThrow(validate({foo: {foo: "today"}}), "unknown word"),
371 shouldBeValid(validate((data = {foo: {foo: {foo: "tomorrow"}}})), data),
372 shouldBeInvalid(validate({foo: {foo: {foo: "manana"}}})),
373 shouldBeInvalid(validate({foo: {foo: {foo: 1}}})),
374 shouldThrow(validate({foo: {foo: {foo: "today"}}}), "unknown word"),
375 ])
376 })
377 )
378 })
379 }
380 })
381
382 function addFormatEnglishWord() {
383 instances.forEach((_ajv) => {
384 _ajv.addFormat("english_word", {
385 async: true,
386 validate: checkWordOnServer,
387 })
388 })
389 }
390 })
391
392 function checkWordOnServer(str) {
393 return str === "tomorrow"
394 ? Promise.resolve(true)
395 : str === "manana"
396 ? Promise.resolve(false)
397 : Promise.reject(new Error("unknown word"))
398 }
399
400 function shouldBeValid(p, data) {
401 return p.then((valid) => valid.should.equal(data))
402 }
403
404 const SHOULD_BE_INVALID = "test: should be invalid"
405 function shouldBeInvalid(p, expectedMessages?: string[]) {
406 return checkNotValid(p).then((err) => {
407 err.should.be.instanceof(_Ajv.ValidationError)
408 err.errors.should.be.an("array")
409 err.validation.should.equal(true)
410 if (expectedMessages) {
411 const messages = err.errors.map((e) => e.message)
412 messages.should.eql(expectedMessages)
413 }
414 })
415 }
416
417 function shouldThrow(p, exception) {
418 return checkNotValid(p).then((err) => err.message.should.equal(exception))
419 }
420
421 function checkNotValid(p) {
422 return p
423 .then((/* valid */) => {
424 throw new Error(SHOULD_BE_INVALID)
425 })
426 .catch((err) => {
427 err.should.be.instanceof(Error)
428 if (err.message === SHOULD_BE_INVALID) throw err
429 return err
430 })
431 }
432
433 function repeat(func) {
434 return func()
435 // var promises = [];
436 // for (var i=0; i<1000; i++) promises.push(func());
437 // return Promise.all(promises);
438 }