Debian Codegraph @

spec/keyword.spec.ts

raw symbols ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 import type {ErrorObject, SchemaObject, SchemaValidateFunction} from "../lib/types"
2 import type AjvCore from "../dist/core"
3 // currently most tests include compiled code, if any code re-compiled locally, instanceof would fail
4 import {_, nil} from "../dist/compile/codegen/code"
5 import getAjvAllInstances from "./ajv_all_instances"
6 import _Ajv from "./ajv"
7 import equal from "../dist/runtime/equal"
8 import * as assert from "assert"
9 import chai from "./chai"
10 const should = chai.should()
11
12 describe("User-defined keywords", () => {
13 let ajv: AjvCore, instances: AjvCore[]
14
15 beforeEach(() => {
16 instances = getAjvAllInstances(
17 {
18 allErrors: true,
19 verbose: true,
20 inlineRefs: false,
21 },
22 {allowUnionTypes: true}
23 )
24 ajv = instances[0]
25 })
26
27 describe("user-defined keyword", () => {
28 describe('keyword with "validate" function', () => {
29 it("should add and validate keyword", () => {
30 testEvenKeyword({keyword: "x-even", type: "number", validate: validateEven})
31
32 function validateEven(schema, data) {
33 if (typeof schema != "boolean") {
34 throw new Error('The value of "even" keyword must be boolean')
35 }
36 return data % 2 ? !schema : schema
37 }
38 })
39
40 it("should add, validate keyword schema and validate rule", () => {
41 testEvenKeyword({
42 keyword: "x-even",
43 type: "number",
44 validate: validateEven,
45 metaSchema: {type: "boolean"},
46 })
47
48 shouldBeInvalidSchema({type: "number", "x-even": "not_boolean"})
49
50 function validateEven(schema, data) {
51 return data % 2 ? !schema : schema
52 }
53 })
54
55 it('should pass parent schema to "interpreted" keyword validation', () => {
56 testRangeKeyword({
57 keyword: "x-range",
58 type: "number",
59 validate: validateRange,
60 })
61
62 function validateRange(schema, data, parentSchema) {
63 validateRangeSchema(schema, parentSchema)
64
65 return parentSchema.exclusiveRange === true
66 ? data > schema[0] && data < schema[1]
67 : data >= schema[0] && data <= schema[1]
68 }
69 })
70
71 it('should validate meta schema and pass parent schema to "interpreted" keyword validation', () => {
72 testRangeKeyword({
73 keyword: "x-range",
74 type: "number",
75 validate: validateRange,
76 metaSchema: {
77 type: "array",
78 items: [{type: "number"}, {type: "number"}],
79 minItems: 2,
80 additionalItems: false,
81 },
82 })
83 shouldBeInvalidSchema({type: "number", "x-range": ["1", 2]})
84 shouldBeInvalidSchema({type: "number", "x-range": {}})
85 shouldBeInvalidSchema({type: "number", "x-range": [1, 2, 3]})
86
87 function validateRange(schema, data, parentSchema) {
88 return parentSchema.exclusiveRange === true
89 ? data > schema[0] && data < schema[1]
90 : data >= schema[0] && data <= schema[1]
91 }
92 })
93
94 it('should allow defining errors for "validate" keyword', () => {
95 const validateRange: SchemaValidateFunction = _validateRange
96 testRangeKeyword({keyword: "x-range", type: "number", validate: validateRange}, true)
97
98 function _validateRange(schema, data, parentSchema) {
99 validateRangeSchema(schema, parentSchema)
100 const min = schema[0],
101 max = schema[1],
102 exclusive = parentSchema.exclusiveRange === true
103
104 const minOk = exclusive ? data > min : data >= min
105 const maxOk = exclusive ? data < max : data <= max
106 const valid = minOk && maxOk
107
108 if (!valid) {
109 const err: Partial<ErrorObject> = {keyword: "x-range"}
110 validateRange.errors = [err]
111 let comparison, limit
112 if (minOk) {
113 comparison = exclusive ? "<" : "<="
114 limit = max
115 } else {
116 comparison = exclusive ? ">" : ">="
117 limit = min
118 }
119 err.message = "should be " + comparison + " " + limit
120 err.params = {
121 comparison: comparison,
122 limit: limit,
123 exclusive: exclusive,
124 }
125 }
126
127 return valid
128 }
129 })
130
131 it("should support schemaType", () => {
132 testEvenKeyword({
133 keyword: "x-even",
134 type: "number",
135 schemaType: "boolean",
136 validate: (schema, data) => (data % 2 ? !schema : schema),
137 })
138 })
139 })
140
141 describe('keyword with "compile" function', () => {
142 it("should add and validate keyword", () => {
143 testEvenKeyword({
144 keyword: "x-even",
145 type: "number",
146 compile: compileEven,
147 })
148 shouldBeInvalidSchema(
149 {
150 type: "number",
151 "x-even": "not_boolean",
152 },
153 'The value of "x-even" keyword must be boolean'
154 )
155
156 function compileEven(schema) {
157 if (typeof schema != "boolean") {
158 throw new Error('The value of "x-even" keyword must be boolean')
159 }
160 return schema ? isEven : isOdd
161 }
162
163 function isEven(data) {
164 return data % 2 === 0
165 }
166 function isOdd(data) {
167 return data % 2 !== 0
168 }
169 })
170
171 it("should add, validate keyword schema and validate rule", () => {
172 testEvenKeyword({
173 keyword: "x-even",
174 type: "number",
175 compile: compileEven,
176 metaSchema: {type: "boolean"},
177 })
178 shouldBeInvalidSchema({
179 type: "number",
180 "x-even": "not_boolean",
181 })
182
183 function compileEven(schema) {
184 return schema ? isEven : isOdd
185 }
186
187 function isEven(data) {
188 return data % 2 === 0
189 }
190 function isOdd(data) {
191 return data % 2 !== 0
192 }
193 })
194
195 it("should compile keyword validating function only once per schema", () => {
196 testConstantKeyword({keyword: "myConstant", compile: compileConstant})
197 })
198
199 it("should allow multiple schemas for the same keyword", () => {
200 testMultipleConstantKeyword({keyword: "x-constant", compile: compileConstant})
201 })
202
203 it('should pass parent schema to "compiled" keyword validation', () => {
204 testRangeKeyword({keyword: "x-range", type: "number", compile: compileRange})
205 })
206
207 it("should allow multiple parent schemas for the same keyword", () => {
208 testMultipleRangeKeyword({keyword: "x-range", type: "number", compile: compileRange})
209 })
210
211 it("should support schemaType", () => {
212 testEvenKeyword({
213 keyword: "x-even",
214 type: "number",
215 schemaType: "boolean",
216 compile: compileEven,
217 })
218 shouldBeInvalidSchema(
219 {
220 type: "number",
221 "x-even": "not_boolean",
222 },
223 'x-even value must be ["boolean"]'
224 )
225
226 function compileEven(schema) {
227 if (schema) return (data) => data % 2 === 0
228 return (data) => data % 2 !== 0
229 }
230 })
231 })
232
233 function compileConstant(schema) {
234 return typeof schema == "object" && schema !== null ? isDeepEqual : isStrictEqual
235
236 function isDeepEqual(data) {
237 return equal(data, schema)
238 }
239 function isStrictEqual(data) {
240 return data === schema
241 }
242 }
243
244 function compileRange(schema, parentSchema) {
245 validateRangeSchema(schema, parentSchema)
246
247 const min = schema[0]
248 const max = schema[1]
249
250 return parentSchema.exclusiveRange === true
251 ? (data) => data > min && data < max
252 : (data) => data >= min && data <= max
253 }
254 })
255
256 describe("macro keywords", () => {
257 it('should add and validate keywords with "macro" function', () => {
258 testEvenKeyword({keyword: "x-even", type: "number", macro: macroEven}, 2)
259 })
260
261 it("should add and expand macro rule", () => {
262 testConstantKeyword({keyword: "myConstant", macro: macroConstant}, 2)
263 })
264
265 it("should allow multiple schemas for the same macro keyword", () => {
266 testMultipleConstantKeyword({keyword: "x-constant", macro: macroConstant}, 2)
267 })
268
269 it('should pass parent schema to "macro" keyword', () => {
270 testRangeKeyword({keyword: "x-range", type: "number", macro: macroRange}, undefined, 2)
271 })
272
273 it("should allow multiple parent schemas for the same macro keyword", () => {
274 testMultipleRangeKeyword({keyword: "x-range", type: "number", macro: macroRange}, 2)
275 })
276
277 it("should support resolving $ref without id or $id", () => {
278 instances.forEach((_ajv) => {
279 _ajv.addKeyword({
280 keyword: "macroRef",
281 macro(schema, _parentSchema, it) {
282 // @ts-ignore
283 it.baseId.should.equal("#")
284 const ref = schema.$ref
285 const validate = _ajv.getSchema(ref)
286 if (!validate) throw new _Ajv.MissingRefError(_ajv.opts.uriResolver, it.baseId, ref)
287 return validate.schema
288 },
289 metaSchema: {
290 type: "object",
291 required: ["$ref"],
292 additionalProperties: false,
293 properties: {
294 $ref: {
295 type: "string",
296 },
297 },
298 },
299 })
300 const schema = {
301 macroRef: {
302 $ref: "#/definitions/schema",
303 },
304 definitions: {
305 schema: {
306 type: "string",
307 },
308 },
309 }
310 const validate = _ajv.compile(schema)
311 shouldBeValid(validate, "foo")
312 shouldBeInvalid(validate, 1, 2)
313 })
314 })
315
316 it("should recursively expand macro keywords", () => {
317 instances.forEach((_ajv) => {
318 _ajv.addKeyword({
319 keyword: "deepProperties",
320 type: "object",
321 macro: macroDeepProperties,
322 })
323 _ajv.addKeyword({keyword: "range", type: "number", macro: macroRange})
324
325 const schema = {
326 type: "object",
327 deepProperties: {
328 "a.b.c": {type: "number", range: [2, 4]},
329 "d.e.f.g": {type: "string"},
330 },
331 }
332
333 /* This schema recursively expands to:
334 {
335 "allOf": [
336 {
337 "properties": {
338 "a": {
339 "properties": {
340 "b": {
341 "properties": {
342 "c": {
343 "type": "number",
344 "minimum": 2,
345 "exclusiveMinimum": false,
346 "maximum": 4,
347 "exclusiveMaximum": false
348 }
349 }
350 }
351 }
352 }
353 }
354 },
355 {
356 "properties": {
357 "d": {
358 "properties": {
359 "e": {
360 "properties": {
361 "f": {
362 "properties": {
363 "g": {
364 "type": "string"
365 }
366 }
367 }
368 }
369 }
370 }
371 }
372 }
373 }
374 ]
375 }
376 */
377
378 const validate = _ajv.compile(schema)
379
380 shouldBeValid(validate, {
381 a: {b: {c: 3}},
382 d: {e: {f: {g: "foo"}}},
383 })
384
385 shouldBeInvalid(
386 validate,
387 {
388 a: {b: {c: 5}}, // out of range
389 d: {e: {f: {g: "foo"}}},
390 },
391 5
392 )
393
394 shouldBeInvalid(
395 validate,
396 {
397 a: {b: {c: "bar"}}, // not number
398 d: {e: {f: {g: "foo"}}},
399 },
400 4
401 )
402
403 shouldBeInvalid(
404 validate,
405 {
406 a: {b: {c: 3}},
407 d: {e: {f: {g: 2}}}, // not string
408 },
409 5
410 )
411
412 function macroDeepProperties(_schema) {
413 if (typeof _schema != "object") {
414 throw new Error("schema of deepProperty should be an object")
415 }
416
417 const expanded: any[] = []
418
419 for (const prop in _schema) {
420 const path = prop.split(".")
421 const properties = {}
422 if (path.length === 1) {
423 properties[prop] = _schema[prop]
424 } else {
425 const deepProperties = {}
426 deepProperties[path.slice(1).join(".")] = _schema[prop]
427 properties[path[0]] = {type: "object", deepProperties}
428 }
429 expanded.push({type: "object", properties})
430 }
431
432 return expanded.length === 1 ? expanded[0] : {allOf: expanded}
433 }
434 })
435 })
436
437 it("should correctly expand multiple macros on the same level", () => {
438 instances.forEach((_ajv) => {
439 _ajv.addKeyword({keyword: "range", type: "number", macro: macroRange})
440 _ajv.addKeyword({keyword: "even", type: "number", macro: macroEven})
441
442 const schema = {
443 type: "number",
444 range: [4, 6],
445 even: true,
446 }
447
448 const validate = _ajv.compile(schema)
449 const numErrors = _ajv.opts.allErrors ? 4 : 2
450
451 shouldBeInvalid(validate, 2, 2)
452 shouldBeInvalid(validate, 3, numErrors)
453 shouldBeValid(validate, 4)
454 shouldBeInvalid(validate, 5, 2)
455 shouldBeValid(validate, 6)
456 shouldBeInvalid(validate, 7, numErrors)
457 shouldBeInvalid(validate, 8, 2)
458 })
459 })
460
461 it("should validate macro keyword when it resolves to the same keyword as exists", () => {
462 instances.forEach((_ajv) => {
463 _ajv.addKeyword({keyword: "range", type: "number", macro: macroRange})
464
465 const schema = {
466 type: "number",
467 range: [1, 4],
468 minimum: 2.5,
469 }
470
471 const validate = _ajv.compile(schema)
472
473 shouldBeValid(validate, 3)
474 shouldBeInvalid(validate, 2)
475 })
476 })
477
478 it("should correctly expand macros in subschemas", () => {
479 instances.forEach((_ajv) => {
480 _ajv.addKeyword({keyword: "range", type: "number", macro: macroRange})
481
482 const schema = {
483 type: "number",
484 allOf: [{range: [4, 8]}, {range: [2, 6]}],
485 }
486
487 const validate = _ajv.compile(schema)
488
489 shouldBeInvalid(validate, 2, 2)
490 shouldBeInvalid(validate, 3, 2)
491 shouldBeValid(validate, 4)
492 shouldBeValid(validate, 5)
493 shouldBeValid(validate, 6)
494 shouldBeInvalid(validate, 7, 2)
495 shouldBeInvalid(validate, 8, 2)
496 })
497 })
498
499 it("should correctly expand macros in macro expansions", () => {
500 instances.forEach((_ajv) => {
501 _ajv.addKeyword({keyword: "range", type: "number", macro: macroRange})
502 _ajv.addKeyword({keyword: "exclusiveRange", metaSchema: {type: "boolean"}})
503 _ajv.addKeyword({keyword: "myContains", type: "array", macro: macroContains})
504
505 const schema = {
506 type: "array",
507 myContains: {
508 type: "number",
509 range: [4, 7],
510 exclusiveRange: true,
511 },
512 }
513
514 const validate = _ajv.compile(schema)
515
516 shouldBeInvalid(validate, [1, 2, 3], 2)
517 shouldBeInvalid(validate, [2, 3, 4], 2)
518 shouldBeValid(validate, [3, 4, 5]) // only 5 is in range
519 shouldBeValid(validate, [6, 7, 8]) // only 6 is in range
520 shouldBeInvalid(validate, [7, 8, 9], 2)
521 shouldBeInvalid(validate, [8, 9, 10], 2)
522
523 function macroContains(_schema) {
524 return {not: {items: {not: _schema}}}
525 }
526 })
527 })
528
529 it("should throw exception if macro expansion is an invalid schema", () => {
530 ajv.addKeyword({keyword: "invalid", macro: macroInvalid})
531 const schema = {invalid: true}
532
533 // @ts-ignore
534 should.throw(() => {
535 ajv.compile(schema)
536 }, /type must be equal to one of the allowed values/)
537
538 function macroInvalid(/* schema */) {
539 return {type: "invalid"}
540 }
541 })
542
543 function macroEven(schema) {
544 if (schema === true) return {multipleOf: 2}
545 if (schema === false) return {not: {multipleOf: 2}}
546 throw new Error('Schema for "even" keyword should be boolean')
547 }
548
549 function macroConstant(schema /*, parentSchema */) {
550 return {enum: [schema]}
551 }
552
553 function macroRange(schema, parentSchema) {
554 validateRangeSchema(schema, parentSchema)
555 const exclusive = !!parentSchema.exclusiveRange
556
557 return exclusive
558 ? {exclusiveMinimum: schema[0], exclusiveMaximum: schema[1]}
559 : {minimum: schema[0], maximum: schema[1]}
560 }
561 })
562
563 describe('"code" keywords', () => {
564 it('should add and validate keyword with "code" function', () => {
565 testEvenKeyword({
566 keyword: "x-even",
567 type: "number",
568 code(cxt) {
569 const {schema, data} = cxt
570 const op = schema ? _`===` : _`!==`
571 cxt.pass(_`${data} % 2 ${op} 0`)
572 },
573 })
574 })
575
576 it('should pass parent schema to "inline" keyword', () => {
577 testRangeKeyword({
578 keyword: "x-range",
579 type: "number",
580 code(cxt) {
581 const {
582 schema: [min, max],
583 parentSchema,
584 data,
585 } = cxt
586 const eq = parentSchema.exclusiveRange ? nil : _`=`
587 cxt.pass(_`${data} >${eq} ${min} && ${data} <${eq} ${max}`)
588 },
589 })
590 })
591
592 it("should allow defining keyword error", () => {
593 testRangeKeyword({
594 keyword: "x-range",
595 type: "number",
596 code(cxt) {
597 const {
598 gen,
599 schema: [min, max],
600 parentSchema,
601 data,
602 } = cxt
603 const eq = parentSchema.exclusiveRange ? nil : _`=`
604 const minOk = gen.const("minOk", _`${data} >${eq} ${min}`)
605 const maxOk = gen.const("maxOk", _`${data} <${eq} ${max}`)
606 cxt.setParams({minOk, maxOk, eq})
607 cxt.pass(_`${minOk} && ${maxOk}`)
608 },
609 error: {
610 message: ({params: {minOk, eq}, schema: [min, max]}) =>
611 _`${minOk} ? "should be <${eq} ${max}" : "should be >${eq} ${min}"`,
612 params: ({params: {minOk, eq}, schema: [min, max], parentSchema}) => _`{
613 comparison: ${minOk} ? "<${eq}" : ">${eq}",
614 limit: ${minOk} ? ${max} : ${min},
615 exclusive: ${!!parentSchema.exclusiveRange}
616 }`,
617 },
618 })
619 })
620 })
621
622 describe('$data reference support with "validate" keywords (with $data option)', () => {
623 beforeEach(() => {
624 instances = getAjvAllInstances(
625 {
626 allErrors: true,
627 verbose: true,
628 inlineRefs: false,
629 },
630 {$data: true, allowUnionTypes: true}
631 )
632 ajv = instances[0]
633 })
634
635 it('should validate "interpreted" rule', () => {
636 testEvenKeyword$data({
637 keyword: "x-even-$data",
638 type: "number",
639 $data: true,
640 validate: validateEven,
641 })
642
643 function validateEven(schema, data) {
644 if (typeof schema != "boolean") return false
645 return data % 2 ? !schema : schema
646 }
647 })
648
649 it('should validate rule with "compile" and "validate" funcs', () => {
650 let compileCalled
651 testEvenKeyword$data({
652 keyword: "x-even-$data",
653 type: "number",
654 $data: true,
655 compile: compileEven,
656 validate: validateEven,
657 })
658 compileCalled.should.equal(true)
659
660 function validateEven(schema, data) {
661 if (typeof schema != "boolean") return false
662 return data % 2 ? !schema : schema
663 }
664
665 function compileEven(schema) {
666 compileCalled = true
667 if (typeof schema != "boolean") {
668 throw new Error('The value of "even" keyword must be boolean')
669 }
670 return schema ? isEven : isOdd
671 }
672
673 function isEven(data) {
674 return data % 2 === 0
675 }
676 function isOdd(data) {
677 return data % 2 !== 0
678 }
679 })
680
681 it('should validate with "compile" and "validate" funcs with meta-schema', () => {
682 let compileCalled
683 testEvenKeyword$data({
684 keyword: "x-even-$data",
685 type: "number",
686 $data: true,
687 compile: compileEven,
688 validate: validateEven,
689 metaSchema: {type: "boolean"},
690 })
691 compileCalled.should.equal(true)
692 shouldBeInvalidSchema({
693 type: "number",
694 "x-even-$data": "false",
695 })
696
697 function validateEven(schema, data) {
698 return data % 2 ? !schema : schema
699 }
700
701 function compileEven(schema) {
702 compileCalled = true
703 return schema ? isEven : isOdd
704 }
705
706 function isEven(data) {
707 return data % 2 === 0
708 }
709 function isOdd(data) {
710 return data % 2 !== 0
711 }
712 })
713
714 it('should validate rule with "macro" and "validate" funcs', () => {
715 let macroCalled
716 testEvenKeyword$data(
717 {
718 keyword: "x-even-$data",
719 type: "number",
720 $data: true,
721 macro: macroEven,
722 validate: validateEven,
723 },
724 2
725 )
726 // @ts-ignore
727 macroCalled.should.equal(true)
728
729 function validateEven(schema, data) {
730 if (typeof schema != "boolean") return false
731 return data % 2 ? !schema : schema
732 }
733
734 function macroEven(schema) {
735 macroCalled = true
736 if (schema === true) return {multipleOf: 2}
737 if (schema === false) return {not: {multipleOf: 2}}
738 throw new Error('Schema for "even" keyword should be boolean')
739 }
740 })
741
742 it('should validate with "macro" and "validate" funcs with meta-schema', () => {
743 let macroCalled
744 testEvenKeyword$data(
745 {
746 keyword: "x-even-$data",
747 type: "number",
748 $data: true,
749 macro: macroEven,
750 validate: validateEven,
751 metaSchema: {type: "boolean"},
752 },
753 2
754 )
755 // @ts-ignore
756 macroCalled.should.equal(true)
757 shouldBeInvalidSchema({
758 type: "number",
759 "x-even-$data": "false",
760 })
761
762 function validateEven(schema, data) {
763 return data % 2 ? !schema : schema
764 }
765
766 function macroEven(schema): SchemaObject | void {
767 macroCalled = true
768 if (schema === true) return {multipleOf: 2}
769 if (schema === false) return {not: {multipleOf: 2}}
770 }
771 })
772
773 it('should validate rule with "code" keyword', () => {
774 testEvenKeyword$data({
775 keyword: "x-even-$data",
776 type: "number",
777 $data: true,
778 code(cxt) {
779 const {gen, schemaCode: s, data} = cxt
780 gen.if(_`${s} !== undefined`)
781 cxt.pass(_`typeof ${s} == "boolean" && (${data} % 2 ? !${s} : ${s})`)
782 },
783 })
784 })
785
786 it('should validate with "code" and meta-schema', () => {
787 testEvenKeyword$data({
788 keyword: "x-even-$data",
789 type: "number",
790 $data: true,
791 code(cxt) {
792 const {gen, schemaCode: s, data} = cxt
793 gen.if(_`${s} !== undefined`)
794 cxt.pass(_`typeof ${s} == "boolean" && (${data} % 2 ? !${s} : ${s})`)
795 },
796 metaSchema: {type: "boolean"},
797 })
798 shouldBeInvalidSchema({
799 type: "number",
800 "x-even-$data": "false",
801 })
802 })
803
804 it('should fail if "macro" keyword definition has "$data" but no "code" or "validate"', () => {
805 // @ts-ignore
806 should.throw(() => {
807 ajv.addKeyword({
808 keyword: "even",
809 type: "number",
810 $data: true,
811 macro: () => {
812 return {}
813 },
814 })
815 }, /\$data keyword must have "code" or "validate" function/)
816 })
817
818 it("should support schemaType with $data", () => {
819 testEvenKeyword$data({
820 keyword: "x-even-$data",
821 type: "number",
822 schemaType: "boolean",
823 $data: true,
824 validate: validateEven,
825 })
826
827 function validateEven(schema, data) {
828 return data % 2 ? !schema : schema
829 }
830 })
831 })
832
833 function testEvenKeyword(evenDefinition, numErrors = 1) {
834 instances.forEach((_ajv) => {
835 _ajv.addKeyword(evenDefinition)
836 const schema = {
837 type: ["number", "string"],
838 "x-even": true,
839 }
840 const validate = _ajv.compile(schema)
841
842 shouldBeValid(validate, 2)
843 shouldBeValid(validate, "abc")
844 shouldBeInvalid(validate, 2.5, numErrors)
845 shouldBeInvalid(validate, 3, numErrors)
846 })
847 }
848
849 function testEvenKeyword$data(definition, numErrors = 1) {
850 instances.forEach((_ajv) => {
851 _ajv.addKeyword(definition)
852
853 let schema: any = {
854 type: ["number", "string"],
855 "x-even-$data": true,
856 }
857 let validate = _ajv.compile(schema)
858
859 shouldBeValid(validate, 2)
860 shouldBeValid(validate, "abc")
861 shouldBeInvalid(validate, 2.5, numErrors)
862 shouldBeInvalid(validate, 3, numErrors)
863
864 schema = {
865 type: "object",
866 properties: {
867 data: {
868 type: ["number", "string"],
869 "x-even-$data": {$data: "1/evenValue"},
870 },
871 evenValue: {},
872 },
873 }
874 validate = _ajv.compile(schema)
875
876 shouldBeValid(validate, {data: 2, evenValue: true})
877 shouldBeInvalid(validate, {data: 2, evenValue: false})
878 shouldBeValid(validate, {data: "abc", evenValue: true})
879 shouldBeValid(validate, {data: "abc", evenValue: false})
880 shouldBeInvalid(validate, {data: 2.5, evenValue: true})
881 shouldBeValid(validate, {data: 2.5, evenValue: false})
882 shouldBeInvalid(validate, {data: 3, evenValue: true})
883 shouldBeValid(validate, {data: 3, evenValue: false})
884
885 shouldBeInvalid(validate, {data: 2, evenValue: "true"})
886
887 // valid if the value of x-even-$data keyword is undefined
888 shouldBeValid(validate, {data: 2})
889 shouldBeValid(validate, {data: 3})
890 })
891 }
892
893 function testConstantKeyword(definition, numErrors?: number) {
894 instances.forEach((_ajv) => {
895 _ajv.addKeyword(definition)
896
897 const schema = {myConstant: "abc"}
898 const validate = _ajv.compile(schema)
899
900 shouldBeValid(validate, "abc")
901 shouldBeInvalid(validate, 2, numErrors)
902 shouldBeInvalid(validate, {}, numErrors)
903 })
904 }
905
906 function testMultipleConstantKeyword(definition, numErrors?: number) {
907 instances.forEach((_ajv) => {
908 _ajv.addKeyword(definition)
909
910 const schema = {
911 type: ["object", "array"],
912 properties: {
913 a: {"x-constant": 1},
914 b: {"x-constant": 1},
915 },
916 additionalProperties: {"x-constant": {foo: "bar"}},
917 items: {"x-constant": {foo: "bar"}},
918 }
919 const validate = _ajv.compile(schema)
920
921 shouldBeValid(validate, {a: 1, b: 1})
922 shouldBeInvalid(validate, {a: 2, b: 1}, numErrors)
923
924 shouldBeValid(validate, {a: 1, c: {foo: "bar"}})
925 shouldBeInvalid(validate, {a: 1, c: {foo: "baz"}}, numErrors)
926
927 shouldBeValid(validate, [{foo: "bar"}])
928 shouldBeValid(validate, [{foo: "bar"}, {foo: "bar"}])
929
930 shouldBeInvalid(validate, [1], numErrors)
931 })
932 }
933
934 function testRangeKeyword(definition, createsErrors?: boolean, numErrors?: number) {
935 instances.forEach((_ajv) => {
936 _ajv.addKeyword(definition)
937 _ajv.addKeyword({keyword: "exclusiveRange", schemaType: "boolean"})
938
939 let schema: SchemaObject = {
940 type: ["number", "string"],
941 "x-range": [2, 4],
942 }
943 let validate = _ajv.compile(schema)
944
945 shouldBeValid(validate, 2)
946 shouldBeValid(validate, 3)
947 shouldBeValid(validate, 4)
948 shouldBeValid(validate, "abc")
949
950 shouldBeInvalid(validate, 1.99, numErrors)
951 if (createsErrors) {
952 shouldBeRangeError(validate.errors?.[0], "", "#/x-range", ">=", 2)
953 }
954 shouldBeInvalid(validate, 4.01, numErrors)
955 if (createsErrors) {
956 shouldBeRangeError(validate.errors?.[0], "", "#/x-range", "<=", 4)
957 }
958
959 schema = {
960 type: "object",
961 properties: {
962 foo: {
963 type: ["number"],
964 "x-range": [2, 4],
965 exclusiveRange: true,
966 },
967 },
968 }
969 validate = _ajv.compile(schema)
970
971 shouldBeValid(validate, {foo: 2.01})
972 shouldBeValid(validate, {foo: 3})
973 shouldBeValid(validate, {foo: 3.99})
974
975 shouldBeInvalid(validate, {foo: 2}, numErrors)
976 if (createsErrors) {
977 shouldBeRangeError(validate.errors?.[0], "/foo", "#/properties/foo/x-range", ">", 2, true)
978 }
979 shouldBeInvalid(validate, {foo: 4}, numErrors)
980 if (createsErrors) {
981 shouldBeRangeError(validate.errors?.[0], "/foo", "#/properties/foo/x-range", "<", 4, true)
982 }
983 })
984 }
985
986 function testMultipleRangeKeyword(definition, numErrors?: number) {
987 instances.forEach((_ajv) => {
988 _ajv.opts.strictTypes = false
989 _ajv.addKeyword(definition)
990 _ajv.addKeyword({keyword: "exclusiveRange", schemaType: "boolean"})
991
992 const schema = {
993 properties: {
994 a: {type: "number", "x-range": [2, 4], exclusiveRange: true},
995 b: {type: "number", "x-range": [2, 4], exclusiveRange: false},
996 },
997 additionalProperties: {type: "number", "x-range": [5, 7]},
998 items: {type: "number", "x-range": [5, 7]},
999 }
1000 const validate = _ajv.compile(schema)
1001
1002 shouldBeValid(validate, {a: 3.99, b: 4})
1003 shouldBeInvalid(validate, {a: 4, b: 4}, numErrors)
1004
1005 shouldBeValid(validate, {a: 2.01, c: 7})
1006 shouldBeInvalid(validate, {a: 2.01, c: 7.01}, numErrors)
1007
1008 shouldBeValid(validate, [5, 6, 7])
1009 shouldBeInvalid(validate, [7.01], numErrors)
1010 })
1011 }
1012
1013 function shouldBeRangeError(
1014 error,
1015 instancePath,
1016 schemaPath,
1017 comparison,
1018 limit,
1019 exclusive?: boolean
1020 ) {
1021 delete error.schema
1022 delete error.data
1023 // @ts-ignore
1024 error.should.eql({
1025 keyword: "x-range",
1026 instancePath,
1027 schemaPath,
1028 message: "should be " + comparison + " " + limit,
1029 params: {
1030 comparison: comparison,
1031 limit: limit,
1032 exclusive: !!exclusive,
1033 },
1034 })
1035 }
1036
1037 function validateRangeSchema(schema, parentSchema) {
1038 const schemaValid =
1039 Array.isArray(schema) &&
1040 schema.length === 2 &&
1041 typeof schema[0] == "number" &&
1042 typeof schema[1] == "number"
1043 if (!schemaValid) {
1044 throw new Error("Invalid schema for range keyword, should be array of 2 numbers")
1045 }
1046
1047 const exclusiveRangeSchemaValid =
1048 parentSchema.exclusiveRange === undefined || typeof parentSchema.exclusiveRange == "boolean"
1049 if (!exclusiveRangeSchemaValid) {
1050 throw new Error("Invalid schema for exclusiveRange keyword, should be boolean")
1051 }
1052 }
1053
1054 function shouldBeValid(validate, data) {
1055 // @ts-ignore
1056 validate(data).should.equal(true)
1057 should.not.exist(validate.errors)
1058 }
1059
1060 function shouldBeInvalid(validate, data, numErrors = 1) {
1061 // @ts-ignore
1062 validate(data).should.equal(false)
1063 // @ts-ignore
1064 validate.errors.should.have.length(numErrors)
1065 }
1066
1067 function shouldBeInvalidSchema(
1068 schema,
1069 msg: string | RegExp = /keyword .+ value is invalid at path/
1070 ) {
1071 instances.forEach((_ajv) => {
1072 should.throw(() => {
1073 _ajv.compile(schema)
1074 }, msg)
1075 })
1076 }
1077
1078 describe("addKeyword method", () => {
1079 const TEST_TYPES = [undefined, "number", "string", "boolean", ["number", "string"]]
1080
1081 it("should throw if defined keyword is passed", () => {
1082 testThrow(["minimum", "maximum", "multipleOf", "minLength", "maxLength"])
1083 testThrowDuplicate("user-defined")
1084
1085 function testThrow(keywords) {
1086 TEST_TYPES.forEach((dataType, index) => {
1087 should.throw(() => {
1088 _addKeyword(keywords[index], dataType)
1089 }, /already defined/)
1090 })
1091 }
1092
1093 function testThrowDuplicate(keywordPrefix) {
1094 let index = 0
1095 TEST_TYPES.forEach((dataType1) => {
1096 TEST_TYPES.forEach((dataType2) => {
1097 const keyword = keywordPrefix + index++
1098 _addKeyword(keyword, dataType1)
1099 should.throw(() => {
1100 _addKeyword(keyword, dataType2)
1101 }, /already defined/)
1102 })
1103 })
1104 }
1105 })
1106
1107 it("should throw if keyword is not a valid name", () => {
1108 should.not.throw(() => {
1109 ajv.addKeyword("mykeyword")
1110 })
1111
1112 should.not.throw(() => {
1113 ajv.addKeyword("hyphens-are-valid")
1114 })
1115
1116 should.not.throw(() => {
1117 ajv.addKeyword("colons:are-valid")
1118 })
1119
1120 should.throw(() => {
1121 ajv.addKeyword("single-'quote-not-valid")
1122 }, /invalid name/)
1123
1124 should.throw(() => {
1125 ajv.addKeyword("3-start-with-number-not-valid")
1126 }, /invalid name/)
1127
1128 should.throw(() => {
1129 ajv.addKeyword("-start-with-hyphen-not-valid")
1130 }, /invalid name/)
1131
1132 should.throw(() => {
1133 ajv.addKeyword("spaces not valid")
1134 }, /invalid name/)
1135 })
1136
1137 it("should return instance of itself", () => {
1138 const res = ajv.addKeyword("any")
1139 // @ts-ignore
1140 res.should.equal(ajv)
1141 })
1142
1143 it("should throw if unknown type is passed", () => {
1144 should.throw(() => {
1145 _addKeyword("user-defined1", "wrongtype")
1146 }, /type must be JSONType/)
1147
1148 should.throw(() => {
1149 _addKeyword("user-defined2", ["number", "wrongtype"])
1150 }, /type must be JSONType/)
1151
1152 should.throw(() => {
1153 _addKeyword("user-defined3", ["number", undefined])
1154 }, /type must be JSONType/)
1155 })
1156
1157 it("should support old API addKeyword", () => {
1158 ajv = new _Ajv({logger: false})
1159 //@ts-expect-error
1160 ajv.addKeyword("min", {
1161 type: "number",
1162 schemaType: "number",
1163 validate: (schema, data) => data >= schema,
1164 })
1165 const validate = ajv.compile({
1166 type: "number",
1167 min: 0,
1168 })
1169 // @ts-ignore
1170 validate(1).should.equal(true)
1171 // @ts-ignore
1172 validate(-1).should.equal(false)
1173 })
1174
1175 function _addKeyword(keyword, dataType) {
1176 ajv.addKeyword({
1177 keyword,
1178 type: dataType,
1179 validate: () => true,
1180 })
1181 }
1182 })
1183
1184 describe("getKeyword", () => {
1185 // TODO update this test
1186 it("should return false for unknown keywords", () => {
1187 // @ts-ignore
1188 ajv.getKeyword("unknown").should.equal(false)
1189 })
1190
1191 // TODO change to account for pre-defined keywords with definitions
1192 it("should return keyword definition", () => {
1193 const definition = {
1194 keyword: "mykeyword",
1195 validate: () => true,
1196 }
1197
1198 ajv.addKeyword(definition)
1199 const def = ajv.getKeyword("mykeyword")
1200 assert(typeof def == "object")
1201 // @ts-ignore
1202 def.keyword.should.equal("mykeyword")
1203 })
1204 })
1205
1206 describe("removeKeyword", () => {
1207 it("should remove and allow redefining keyword", () => {
1208 ajv = new _Ajv({strict: false})
1209
1210 ajv.addKeyword({
1211 keyword: "positive",
1212 type: "number",
1213 validate: (_schema, data) => data > 0,
1214 })
1215
1216 const schema = {type: "number", positive: true}
1217
1218 let validate = ajv.compile(schema)
1219 // @ts-ignore
1220 validate(0).should.equal(false)
1221 // @ts-ignore
1222 validate(1).should.equal(true)
1223
1224 should.throw(() => {
1225 ajv.addKeyword({
1226 keyword: "positive",
1227 type: "number",
1228 validate: function (_sch, data) {
1229 return data >= 0
1230 },
1231 })
1232 }, /already defined/)
1233
1234 ajv.removeKeyword("positive")
1235 ajv.removeSchema(schema)
1236 validate = ajv.compile(schema)
1237 // @ts-ignore
1238 validate(-1).should.equal(true)
1239 ajv.removeSchema(schema)
1240
1241 ajv.addKeyword({
1242 keyword: "positive",
1243 type: "number",
1244 validate: function (_sch, data) {
1245 return data >= 0
1246 },
1247 })
1248
1249 validate = ajv.compile(schema)
1250 // @ts-ignore
1251 validate(-1).should.equal(false)
1252 // @ts-ignore
1253 validate(0).should.equal(true)
1254 // @ts-ignore
1255 validate(1).should.equal(true)
1256 })
1257
1258 it("should remove and allow redefining standard keyword", () => {
1259 ajv = new _Ajv({strict: false})
1260
1261 const schema = {minimum: 1}
1262 let validate = ajv.compile(schema)
1263 // @ts-ignore
1264 validate(0).should.equal(false)
1265 // @ts-ignore
1266 validate(1).should.equal(true)
1267 // @ts-ignore
1268 validate(2).should.equal(true)
1269
1270 ajv.removeKeyword("minimum")
1271 ajv.removeSchema(schema)
1272
1273 validate = ajv.compile(schema)
1274 // @ts-ignore
1275 validate(0).should.equal(true)
1276 // @ts-ignore
1277 validate(1).should.equal(true)
1278 // @ts-ignore
1279 validate(2).should.equal(true)
1280
1281 ajv.addKeyword({
1282 keyword: "minimum",
1283 type: "number",
1284 // make minimum exclusive
1285 validate: (sch, data) => data > sch,
1286 })
1287 ajv.removeSchema(schema)
1288
1289 validate = ajv.compile(schema)
1290 // @ts-ignore
1291 validate(0).should.equal(false)
1292 // @ts-ignore
1293 validate(1).should.equal(false)
1294 // @ts-ignore
1295 validate(2).should.equal(true)
1296 })
1297
1298 it("should return instance of itself", () => {
1299 const res = ajv.addKeyword("any").removeKeyword("any")
1300 // @ts-ignore
1301 res.should.equal(ajv)
1302 })
1303 })
1304
1305 describe("user-defined keywords mutating data", () => {
1306 it("should NOT update data without option modifying", () => {
1307 should.throw(() => {
1308 testModifying(false)
1309 }, /expected false to equal true/)
1310 })
1311
1312 it("should update data with option modifying", () => {
1313 testModifying(true)
1314 })
1315
1316 function testModifying(withOption) {
1317 const collectionFormat = {
1318 csv: function (data, {parentData, parentDataProperty}) {
1319 parentData[parentDataProperty] = data.split(",")
1320 return true
1321 },
1322 }
1323
1324 ajv.addKeyword({
1325 keyword: "collectionFormat",
1326 type: "string",
1327 modifying: withOption,
1328 compile: function (schema) {
1329 return collectionFormat[schema]
1330 },
1331 metaSchema: {
1332 enum: ["csv"],
1333 },
1334 })
1335
1336 const validate = ajv.compile({
1337 type: "object",
1338 properties: {
1339 foo: {
1340 allOf: [
1341 {
1342 type: "string",
1343 collectionFormat: "csv",
1344 },
1345 {
1346 type: "array",
1347 items: {type: "string"},
1348 },
1349 ],
1350 },
1351 },
1352 additionalProperties: false,
1353 })
1354
1355 const obj: any = {foo: "bar,baz,quux"}
1356
1357 // @ts-ignore
1358 validate(obj).should.equal(true)
1359 // @ts-ignore
1360 obj.should.eql({foo: ["bar", "baz", "quux"]})
1361 }
1362 })
1363
1364 describe('"validate" keywords with predefined validation result', () => {
1365 it("should ignore result from validation function", () => {
1366 ajv.addKeyword({
1367 keyword: "pass",
1368 validate: () => false,
1369 valid: true,
1370 })
1371
1372 ajv.addKeyword({
1373 keyword: "fail",
1374 validate: () => true,
1375 valid: false,
1376 })
1377
1378 // @ts-ignore
1379 ajv.validate({pass: ""}, 1).should.equal(true)
1380 // @ts-ignore
1381 ajv.validate({fail: ""}, 1).should.equal(false)
1382 })
1383 })
1384
1385 describe('"dependencies" in keyword definition', () => {
1386 it("should require properties in the parent schema", () => {
1387 ajv.addKeyword({
1388 keyword: "allRequired",
1389 type: "object",
1390 macro: (schema, parentSchema) =>
1391 schema ? {required: Object.keys(parentSchema.properties)} : true,
1392 schemaType: "boolean",
1393 dependencies: ["properties"],
1394 })
1395
1396 const invalidSchema = {
1397 type: "object",
1398 allRequired: true,
1399 }
1400
1401 should.throw(() => {
1402 ajv.compile(invalidSchema)
1403 }, /parent schema must have dependencies of allRequired: properties/)
1404
1405 const schema = {
1406 type: "object",
1407 properties: {
1408 foo: true,
1409 },
1410 allRequired: true,
1411 }
1412
1413 const v = ajv.compile(schema)
1414 // @ts-ignore
1415 v({foo: 1}).should.equal(true)
1416 // @ts-ignore
1417 v({}).should.equal(false)
1418 })
1419 })
1420 })