aboutsummaryrefslogtreecommitdiff
path: root/test/ajv-schemas.test.js
blob: 102868dcebb68ee67f87519d71dc293ecc3ec2ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
 * Copyright (C) 2024  Yomitan Authors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

import Ajv from 'ajv';
import standaloneCode from 'ajv/dist/standalone/index.js';
import {readFileSync, readdirSync} from 'fs';
import {dirname, join} from 'path';
import {fileURLToPath} from 'url';
import {describe, test} from 'vitest';
import {parseJson} from '../dev/json.js';

/**
 * @param {string} path
 * @returns {import('ajv').AnySchema}
 */
function loadSchema(path) {
    return parseJson(readFileSync(path, {encoding: 'utf8'}));
}

const extDir = join(dirname(fileURLToPath(import.meta.url)), '..', 'ext');

describe('Ajv schema compilation', () => {
    const schemaDir = join(extDir, 'data/schemas/');
    const schemaFileNames = readdirSync(schemaDir);
    /** @type {{name: string, schema: import('ajv').AnySchema}[]} */
    const schemaTestCases = [];
    for (const schemaFileName of schemaFileNames) {
        schemaTestCases.push({name: schemaFileName, schema: loadSchema(join(schemaDir, schemaFileName))});
    }

    describe.each(schemaTestCases)('Validating $name', ({schema}) => {
        test('Compiles without warnings', ({expect}) => {
            /** @type {string[]} */
            const messages = [];
            /**
             * @param {...unknown} args
             */
            const log = (...args) => {
                messages.push(args.join(' '));
            };
            const ajv = new Ajv({
                schemas: [schema],
                code: {source: true, esm: true},
                allowUnionTypes: true,
                logger: {
                    log,
                    warn: log,
                    error: log,
                },
            });
            standaloneCode(ajv);
            if (messages.length > 0) {
                expect.fail(messages.join('\n'));
            }
        });
    });
});