Debian Codegraph @

spec/jtd-schema.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 AjvJTD from "../dist/jtd"
2 import type {SchemaObject, JTDParser} from "../dist/jtd"
3 import _AjvJTD from "./ajv_jtd"
4 import getAjvInstances from "./ajv_instances"
5 import {withStandalone} from "./ajv_standalone"
6 import * as jtdValidationTests from "./json-typedef-spec/tests/validation.json"
7 import * as jtdInvalidSchemasTests from "./json-typedef-spec/tests/invalid_schemas.json"
8 // tests from https://github.com/nst/JSONTestSuite
9 import * as jsonParseTests from "./json_parse_tests.json"
10 import * as assert from "assert"
11 import AjvPack from "../dist/standalone/instance"
12
13 interface TestCase {
14 schema: SchemaObject
15 instance: unknown
16 errors: TestCaseError[]
17 }
18
19 interface TestCaseError {
20 instancePath: string[]
21 schemaPath: string[]
22 }
23
24 interface JSONParseTest {
25 name: string
26 valid: boolean | null
27 json: string
28 data?: unknown
29 only?: boolean
30 skip?: boolean
31 }
32
33 interface JSONParseTestSuite {
34 suite: string
35 tests: JSONParseTest[]
36 }
37
38 interface JTDError {
39 instancePath: string
40 schemaPath: string
41 }
42
43 // const ONLY: RegExp[] = [
44 // "empty",
45 // "ref",
46 // "type",
47 // "enum",
48 // "elements",
49 // "properties",
50 // "optionalProperties",
51 // "discriminator",
52 // "values",
53 // ].map((s) => new RegExp(`(^|.*\\s)${s}\\s.*-`))
54
55 const ONLY: RegExp[] = []
56
57 describe("JSON Type Definition", () => {
58 describe("validation", function () {
59 this.timeout(10000)
60 let ajvs: AjvJTD[]
61
62 before(() => {
63 ajvs = getAjvInstances(_AjvJTD, {
64 allErrors: true,
65 inlineRefs: false,
66 code: {es5: true, lines: true, optimize: false},
67 }) as AjvJTD[]
68 ajvs.forEach((ajv) => (ajv.opts.code.source = true))
69 })
70
71 for (const testName in jtdValidationTests) {
72 const {schema, instance, errors} = jtdValidationTests[testName] as TestCase
73 const valid = errors.length === 0
74 describeOnly(testName, () =>
75 it(`should be ${valid ? "valid" : "invalid"}`, () =>
76 withStandalone(ajvs).forEach((ajv) => {
77 // console.log(ajv.compile(schema).toString())
78 // console.log(ajv.validate(schema, instance), ajv.errors)
79 assert.strictEqual(ajv.validate(schema, instance), valid)
80 const opts = ajv instanceof AjvPack ? ajv.ajv.opts : ajv.opts
81 if (opts.allErrors) {
82 assert.deepStrictEqual(cleanErrors(ajv.errors), valid ? null : convertErrors(errors))
83 }
84 }))
85 )
86 }
87
88 function cleanErrors(errors?: JTDError[] | null): JTDError[] | null | undefined {
89 if (errors) {
90 return sortErrors(errors.map(({instancePath, schemaPath}) => ({instancePath, schemaPath})))
91 }
92 return errors
93 }
94
95 function convertErrors(errors: TestCaseError[]): JTDError[] | null | undefined {
96 return sortErrors(
97 errors.map((e) => ({
98 instancePath: jsonPointer(e.instancePath),
99 schemaPath: jsonPointer(e.schemaPath),
100 }))
101 )
102 }
103
104 function sortErrors(errors?: JTDError[] | null): JTDError[] | null | undefined {
105 if (errors) {
106 errors.sort(
107 (e1: JTDError, e2: JTDError) =>
108 e1.schemaPath.localeCompare(e2.schemaPath) ||
109 e1.instancePath.localeCompare(e2.instancePath)
110 )
111 }
112 return errors
113 }
114
115 function jsonPointer(error: string[]): string {
116 return error.map((s) => `/${s}`).join("")
117 }
118 })
119
120 describe("invalid schemas", () => {
121 let ajv: AjvJTD
122 before(() => (ajv = new _AjvJTD()))
123
124 for (const testName in jtdInvalidSchemasTests) {
125 const schema = jtdInvalidSchemasTests[testName]
126 describe(testName, () =>
127 it("should be invalid schema", () => assert.throws(() => ajv.compile(schema)))
128 )
129 }
130 })
131
132 describe("serialize", () => {
133 const ajv = new _AjvJTD()
134
135 for (const testName in jtdValidationTests) {
136 const {schema, instance, errors} = jtdValidationTests[testName] as TestCase
137 const valid = errors.length === 0
138 if (!valid) continue
139 describe(testName, () =>
140 it(`should serialize data`, () => {
141 const serialize = ajv.compileSerializer(schema)
142 // console.log(serialize.toString())
143 assert.deepStrictEqual(JSON.parse(serialize(instance)), instance)
144 })
145 )
146 }
147 })
148
149 describe("serialize special numeric values", () => {
150 describe("fast", () => {
151 const ajv = new _AjvJTD({specialNumbers: "fast"})
152
153 it(`should serialize Infinity to literal`, () => {
154 const serialize = ajv.compileSerializer({type: "float64"})
155 const res = serialize(Infinity)
156 assert.equal(res, "Infinity")
157 assert.throws(() => JSON.parse(res))
158 })
159 it(`should serialize -Infinity to literal`, () => {
160 const serialize = ajv.compileSerializer({type: "float64"})
161 const res = serialize(-Infinity)
162 assert.equal(res, "-Infinity")
163 assert.throws(() => JSON.parse(res))
164 })
165 it(`should serialize NaN to literal`, () => {
166 const serialize = ajv.compileSerializer({type: "float64"})
167 const res = serialize(NaN)
168 assert.equal(res, "NaN")
169 assert.throws(() => JSON.parse(res))
170 })
171 })
172 describe("to null", () => {
173 const ajv = new _AjvJTD({specialNumbers: "null"})
174
175 it(`should serialize Infinity to null`, () => {
176 const serialize = ajv.compileSerializer({type: "float64"})
177 const res = serialize(Infinity)
178 assert.equal(res, "null")
179 assert.equal(JSON.parse(res), null)
180 })
181 it(`should serialize -Infinity to null`, () => {
182 const serialize = ajv.compileSerializer({type: "float64"})
183 const res = serialize(-Infinity)
184 assert.equal(res, "null")
185 assert.equal(JSON.parse(res), null)
186 })
187 it(`should serialize NaN to null`, () => {
188 const serialize = ajv.compileSerializer({type: "float64"})
189 const res = serialize(NaN)
190 assert.equal(res, "null")
191 assert.equal(JSON.parse(res), null)
192 })
193 })
194 })
195
196 describe("parse", () => {
197 let ajv: AjvJTD
198 before(() => (ajv = new _AjvJTD()))
199
200 for (const testName in jtdValidationTests) {
201 const {schema, instance, errors} = jtdValidationTests[testName] as TestCase
202 const valid = errors.length === 0
203 describeOnly(testName, () => {
204 if (valid) {
205 it(`should parse valid JSON string`, () => {
206 const parse = ajv.compileParser(schema)
207 // console.log(schema, instance, `"${JSON.stringify(instance)}"`, parse.toString())
208 shouldParse(parse, JSON.stringify(instance), instance)
209 shouldParse(parse, ` ${JSON.stringify(instance, null, 2)} `, instance)
210 })
211 } else {
212 it(`should return undefined on invalid JSON string`, () => {
213 const parse = ajv.compileParser(schema)
214 // console.log(parse.toString())
215 shouldFail(parse, JSON.stringify(instance))
216 shouldFail(parse, ` ${JSON.stringify(instance, null, 2)} `)
217 })
218 }
219 })
220 }
221 })
222
223 describe("parse tests nst/JSONTestSuite", () => {
224 const ajv = new _AjvJTD()
225 const parseJson: JTDParser = ajv.compileParser({})
226 const parse: {[K in "string" | "number" | "array" | "object"]: JTDParser} = {
227 string: ajv.compileParser({elements: {type: "string"}}),
228 number: ajv.compileParser({elements: {type: "float64"}}),
229 array: ajv.compileParser({elements: {}}),
230 object: ajv.compileParser({values: {}}),
231 }
232
233 for (const {suite, tests} of jsonParseTests as JSONParseTestSuite[]) {
234 describe(suite, () => {
235 for (const test of tests) {
236 const {valid, name, json, data} = test
237 if (valid) {
238 it(`should parse ${name}`, () => shouldParse(parseJson, json, data))
239 if (suite in parse) {
240 _it(test)(`should parse as ${suite}: ${name}`, () =>
241 shouldParse(parse[suite], json, data)
242 )
243 }
244 } else if (valid === false) {
245 it(`should fail parsing ${name}`, () => shouldFail(parseJson, json))
246 if (suite in parse) {
247 _it(test)(`should fail parsing as ${suite}: ${name}`, () =>
248 shouldFail(parse[suite], json)
249 )
250 }
251 }
252 }
253 })
254 }
255 })
256 })
257
258 type TestFunc = typeof it | typeof it.only | typeof it.skip
259
260 function _it({only, skip}: JSONParseTest): TestFunc {
261 return skip ? it.skip : only ? it.only : it
262 }
263
264 function shouldParse(parse: JTDParser, str: string, res: unknown): void {
265 assert.deepStrictEqual(parse(str), res)
266 assert.strictEqual(parse.message, undefined)
267 assert.strictEqual(parse.position, undefined)
268 }
269
270 function shouldFail(parse: JTDParser, str: string): void {
271 assert.strictEqual(parse(str), undefined)
272 assert.strictEqual(typeof parse.message, "string")
273 assert.strictEqual(typeof parse.position, "number")
274 }
275
276 function describeOnly(name: string, func: () => void) {
277 if (ONLY.length === 0 || ONLY.some((p) => p.test(name))) {
278 describe(name, func)
279 } else {
280 describe.skip(name, func)
281 }
282 }