Debian Codegraph @

spec/keyword.spec.ts

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