Debian Codegraph @

spec/jtd-schema.spec.ts

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