forked from typescript-eslint/typescript-eslint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
schemas.test.ts
187 lines (172 loc) · 5.52 KB
/
schemas.test.ts
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import 'jest-specific-snapshot';
import { compile } from '@typescript-eslint/rule-schema-to-typescript-types';
import type { JSONSchema4 } from '@typescript-eslint/utils/json-schema';
import fs, { mkdirSync } from 'fs';
import path from 'path';
import { format, resolveConfig } from 'prettier';
import rules from '../src/rules/index';
import { areOptionsValid } from './areOptionsValid';
const snapshotFolder = path.resolve(__dirname, 'schema-snapshots');
try {
mkdirSync(snapshotFolder);
} catch {
// ignore failure as it means it already exists probably
}
const prettierConfigJson = {
...(resolveConfig.sync(__filename) ?? {}),
filepath: path.join(__dirname, 'schema.json'),
};
const SKIPPED_RULES_FOR_TYPE_GENERATION = new Set(['indent']);
// Set this to a rule name to only run that rule
const ONLY = '';
describe('Rule schemas should be convertible to TS types for documentation purposes', () => {
for (const [ruleName, ruleDef] of Object.entries(rules)) {
if (SKIPPED_RULES_FOR_TYPE_GENERATION.has(ruleName)) {
// eslint-disable-next-line jest/no-disabled-tests -- intentional skip for documentation purposes
it.skip(ruleName, () => {});
continue;
}
(ruleName === ONLY ? it.only : it)(ruleName, () => {
const schemaString = format(
JSON.stringify(
ruleDef.meta.schema,
(k, v: unknown) => {
if (k === 'enum' && Array.isArray(v)) {
// sort enum arrays for consistency regardless of source order
v.sort();
} else if (
typeof v === 'object' &&
v != null &&
!Array.isArray(v)
) {
// sort properties for consistency regardless of source order
return Object.fromEntries(
Object.entries(v).sort(([a], [b]) => a.localeCompare(b)),
);
}
return v;
},
// use the indent feature as it forces all objects to be multiline
// if we don't do this then prettier decides what objects are multiline
// based on what fits on a line - which looks less consistent
// and makes changes harder to understand as you can have multiple
// changes per line, or adding a prop can restructure an object
2,
),
prettierConfigJson,
);
const compilationResult = compile(ruleDef.meta.schema);
expect(
[
'',
'# SCHEMA:',
'',
schemaString,
'',
'# TYPES:',
'',
compilationResult,
].join('\n'),
).toMatchSpecificSnapshot(path.join(snapshotFolder, `${ruleName}.shot`));
});
}
});
test('There should be no old snapshots for rules that have been deleted', () => {
const files = fs.readdirSync(snapshotFolder);
const names = new Set(
Object.keys(rules)
.filter(k => !SKIPPED_RULES_FOR_TYPE_GENERATION.has(k))
.map(k => `${k}.shot`),
);
for (const file of files) {
expect(names).toContain(file);
}
});
const VALID_SCHEMA_PROPS = new Set([
'$defs',
'$ref',
'$schema',
'additionalItems',
'additionalProperties',
'allOf',
'anyOf',
'default',
'definitions',
'dependencies',
'description',
'enum',
'exclusiveMaximum',
'exclusiveMinimum',
'extends',
'format',
'id',
'items',
'maximum',
'maxItems',
'maxLength',
'maxProperties',
'minimum',
'minItems',
'minLength',
'minProperties',
'multipleOf',
'not',
'oneOf',
'pattern',
'patternProperties',
'properties',
'required',
'title',
'type',
'uniqueItems',
] satisfies (keyof JSONSchema4)[]);
describe('Rules should only define valid keys on schemas', () => {
for (const [ruleName, ruleDef] of Object.entries(rules)) {
(ruleName === ONLY ? it.only : it)(ruleName, () => {
JSON.stringify(ruleDef.meta.schema, (key, value: unknown) => {
if (key === '') {
// the root object will have key ""
return value;
}
if (key === '$defs' || key === 'definitions' || key === 'properties') {
// definition keys and property keys should not be validated, only the values
return Object.values(value as object);
}
if (parseInt(key).toString() === key) {
// hack to detect arrays as JSON.stringify will traverse them and stringify the number
return value;
}
expect(VALID_SCHEMA_PROPS).toContain(key);
return value;
});
});
}
});
describe('Rule schemas should validate options correctly', () => {
// Normally, we use the rule's default options as an example of valid options.
// However, the defaults might not actually be valid (especially in the case
// where the defaults have to cover multiple incompatible options).
// This override allows providing example valid options for rules which don't
// accept their defaults.
const overrideValidOptions: Record<string, unknown> = {
semi: ['never'],
'func-call-spacing': ['never'],
};
for (const [ruleName, rule] of Object.entries(rules)) {
test(`${ruleName} must accept valid options`, () => {
if (
!areOptionsValid(
rule,
overrideValidOptions[ruleName] ?? rule.defaultOptions,
)
) {
throw new Error(`Options failed validation against rule's schema`);
}
});
test(`${ruleName} rejects arbitrary options`, () => {
if (areOptionsValid(rule, [{ 'arbitrary-schemas.test.ts': true }])) {
throw new Error(`Options succeeded validation for arbitrary options`);
}
});
}
});