@typescript-eslint/rule-tester 8.0.0-alpha.8 → 8.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/RuleTester.d.ts +4 -4
- package/dist/RuleTester.d.ts.map +1 -1
- package/dist/RuleTester.js +521 -360
- package/dist/RuleTester.js.map +1 -1
- package/dist/noFormat.js +1 -2
- package/dist/noFormat.js.map +1 -1
- package/dist/types/InvalidTestCase.d.ts +2 -2
- package/dist/types/InvalidTestCase.d.ts.map +1 -1
- package/dist/types/RuleTesterConfig.d.ts +9 -15
- package/dist/types/RuleTesterConfig.d.ts.map +1 -1
- package/dist/types/ValidTestCase.d.ts +22 -16
- package/dist/types/ValidTestCase.d.ts.map +1 -1
- package/dist/types/index.d.ts +3 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils/SourceCodeFixer.d.ts +6 -5
- package/dist/utils/SourceCodeFixer.d.ts.map +1 -1
- package/dist/utils/SourceCodeFixer.js +1 -2
- package/dist/utils/SourceCodeFixer.js.map +1 -1
- package/dist/utils/ajv.js +1 -2
- package/dist/utils/ajv.js.map +1 -1
- package/dist/utils/cloneDeeplyExcludesParent.js +2 -3
- package/dist/utils/cloneDeeplyExcludesParent.js.map +1 -1
- package/dist/utils/config-validator.d.ts.map +1 -1
- package/dist/utils/config-validator.js +3 -49
- package/dist/utils/config-validator.js.map +1 -1
- package/dist/utils/dependencyConstraints.d.ts.map +1 -1
- package/dist/utils/dependencyConstraints.js +4 -3
- package/dist/utils/dependencyConstraints.js.map +1 -1
- package/dist/utils/deprecation-warnings.js +1 -2
- package/dist/utils/deprecation-warnings.js.map +1 -1
- package/dist/utils/flat-config-schema.d.ts +66 -0
- package/dist/utils/flat-config-schema.d.ts.map +1 -0
- package/dist/utils/flat-config-schema.js +455 -0
- package/dist/utils/flat-config-schema.js.map +1 -0
- package/dist/utils/freezeDeeply.js +2 -3
- package/dist/utils/freezeDeeply.js.map +1 -1
- package/dist/utils/getRuleOptionsSchema.js +1 -2
- package/dist/utils/getRuleOptionsSchema.js.map +1 -1
- package/dist/utils/hasOwnProperty.d.ts.map +1 -1
- package/dist/utils/hasOwnProperty.js +1 -1
- package/dist/utils/hasOwnProperty.js.map +1 -1
- package/dist/utils/interpolate.d.ts +4 -0
- package/dist/utils/interpolate.d.ts.map +1 -1
- package/dist/utils/interpolate.js +10 -3
- package/dist/utils/interpolate.js.map +1 -1
- package/dist/utils/isReadonlyArray.js +1 -2
- package/dist/utils/isReadonlyArray.js.map +1 -1
- package/dist/utils/omitCustomConfigProperties.d.ts +3 -0
- package/dist/utils/omitCustomConfigProperties.d.ts.map +1 -0
- package/dist/utils/omitCustomConfigProperties.js +10 -0
- package/dist/utils/omitCustomConfigProperties.js.map +1 -0
- package/dist/utils/serialization.d.ts +7 -0
- package/dist/utils/serialization.d.ts.map +1 -0
- package/dist/utils/serialization.js +43 -0
- package/dist/utils/serialization.js.map +1 -0
- package/dist/utils/severity.d.ts +14 -0
- package/dist/utils/severity.d.ts.map +1 -0
- package/dist/utils/severity.js +40 -0
- package/dist/utils/severity.js.map +1 -0
- package/dist/utils/validationHelpers.d.ts +1 -13
- package/dist/utils/validationHelpers.d.ts.map +1 -1
- package/dist/utils/validationHelpers.js +6 -35
- package/dist/utils/validationHelpers.js.map +1 -1
- package/package.json +12 -6
- package/dist/utils/config-schema.d.ts +0 -3
- package/dist/utils/config-schema.d.ts.map +0 -1
- package/dist/utils/config-schema.js +0 -87
- package/dist/utils/config-schema.js.map +0 -1
package/dist/RuleTester.js
CHANGED
|
@@ -24,31 +24,21 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
24
24
|
__setModuleDefault(result, mod);
|
|
25
25
|
return result;
|
|
26
26
|
};
|
|
27
|
-
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
|
|
28
|
-
if (kind === "m") throw new TypeError("Private method is not writable");
|
|
29
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
|
|
30
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
|
|
31
|
-
return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
|
|
32
|
-
};
|
|
33
|
-
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
|
|
34
|
-
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
|
|
35
|
-
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
36
|
-
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
37
|
-
};
|
|
38
27
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
39
28
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
40
29
|
};
|
|
41
|
-
var _RuleTester_instances, _RuleTester_testerConfig, _RuleTester_rules, _RuleTester_linter, _RuleTester_normalizeTests, _RuleTester_testValidTemplate, _RuleTester_testInvalidTemplate;
|
|
42
30
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
43
31
|
exports.RuleTester = void 0;
|
|
44
32
|
const node_assert_1 = __importDefault(require("node:assert"));
|
|
45
33
|
const node_path_1 = __importDefault(require("node:path"));
|
|
46
34
|
const node_util_1 = __importDefault(require("node:util"));
|
|
35
|
+
const parser = __importStar(require("@typescript-eslint/parser"));
|
|
47
36
|
const eslint_utils_1 = require("@typescript-eslint/utils/eslint-utils");
|
|
48
37
|
const ts_eslint_1 = require("@typescript-eslint/utils/ts-eslint");
|
|
49
38
|
// we intentionally import from eslint here because we need to use the same class
|
|
50
39
|
// that ESLint uses, not our custom override typed version
|
|
51
40
|
const eslint_1 = require("eslint");
|
|
41
|
+
const json_stable_stringify_without_jsonify_1 = __importDefault(require("json-stable-stringify-without-jsonify"));
|
|
52
42
|
const lodash_merge_1 = __importDefault(require("lodash.merge"));
|
|
53
43
|
const TestFramework_1 = require("./TestFramework");
|
|
54
44
|
const ajv_1 = require("./utils/ajv");
|
|
@@ -59,52 +49,108 @@ const freezeDeeply_1 = require("./utils/freezeDeeply");
|
|
|
59
49
|
const getRuleOptionsSchema_1 = require("./utils/getRuleOptionsSchema");
|
|
60
50
|
const hasOwnProperty_1 = require("./utils/hasOwnProperty");
|
|
61
51
|
const interpolate_1 = require("./utils/interpolate");
|
|
62
|
-
const
|
|
52
|
+
const omitCustomConfigProperties_1 = require("./utils/omitCustomConfigProperties");
|
|
53
|
+
const serialization_1 = require("./utils/serialization");
|
|
63
54
|
const SourceCodeFixer = __importStar(require("./utils/SourceCodeFixer"));
|
|
64
55
|
const validationHelpers_1 = require("./utils/validationHelpers");
|
|
65
56
|
const ajv = (0, ajv_1.ajvBuilder)({ strictDefaults: true });
|
|
57
|
+
const RULE_TESTER_PLUGIN = '@rule-tester';
|
|
58
|
+
const RULE_TESTER_PLUGIN_PREFIX = `${RULE_TESTER_PLUGIN}/`;
|
|
66
59
|
const TYPESCRIPT_ESLINT_PARSER = '@typescript-eslint/parser';
|
|
67
60
|
const DUPLICATE_PARSER_ERROR_MESSAGE = `Do not set the parser at the test level unless you want to use a parser other than "${TYPESCRIPT_ESLINT_PARSER}"`;
|
|
61
|
+
// instead of creating a hard dependency, just use a soft require
|
|
62
|
+
// a bit weird, but if they're using this tooling, it'll be installed
|
|
63
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
64
|
+
const defaultParser = require(TYPESCRIPT_ESLINT_PARSER);
|
|
68
65
|
/*
|
|
69
66
|
* testerDefaultConfig must not be modified as it allows to reset the tester to
|
|
70
67
|
* the initial default configuration
|
|
71
68
|
*/
|
|
72
69
|
const testerDefaultConfig = {
|
|
73
|
-
parser: TYPESCRIPT_ESLINT_PARSER,
|
|
74
|
-
rules: {},
|
|
75
70
|
defaultFilenames: { ts: 'file.ts', tsx: 'react.tsx' },
|
|
71
|
+
languageOptions: {
|
|
72
|
+
parser: defaultParser,
|
|
73
|
+
},
|
|
74
|
+
rules: {},
|
|
76
75
|
};
|
|
77
76
|
let defaultConfig = (0, eslint_utils_1.deepMerge)({}, testerDefaultConfig);
|
|
77
|
+
const forbiddenMethods = [
|
|
78
|
+
'applyInlineConfig',
|
|
79
|
+
'applyLanguageOptions',
|
|
80
|
+
'finalize',
|
|
81
|
+
];
|
|
82
|
+
const forbiddenMethodCalls = new Map(forbiddenMethods.map(methodName => [methodName, new WeakSet()]));
|
|
83
|
+
/**
|
|
84
|
+
* Function to replace forbidden `SourceCode` methods. Allows just one call per method.
|
|
85
|
+
* @param methodName The name of the method to forbid.
|
|
86
|
+
* @param prototype The prototype with the original method to call.
|
|
87
|
+
* @returns The function that throws the error.
|
|
88
|
+
*/
|
|
89
|
+
function throwForbiddenMethodError(methodName, prototype) {
|
|
90
|
+
const original = prototype[methodName];
|
|
91
|
+
return function (...args) {
|
|
92
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
93
|
+
const called = forbiddenMethodCalls.get(methodName);
|
|
94
|
+
if (!called.has(this)) {
|
|
95
|
+
called.add(this);
|
|
96
|
+
return original.apply(this, args);
|
|
97
|
+
}
|
|
98
|
+
throw new Error(`\`SourceCode#${methodName}()\` cannot be called inside a rule.`);
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Extracts names of {{ placeholders }} from the reported message.
|
|
103
|
+
* @param message Reported message
|
|
104
|
+
* @returns Array of placeholder names
|
|
105
|
+
*/
|
|
106
|
+
function getMessagePlaceholders(message) {
|
|
107
|
+
const matcher = (0, interpolate_1.getPlaceholderMatcher)();
|
|
108
|
+
return Array.from(message.matchAll(matcher), ([, name]) => name.trim());
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Returns the placeholders in the reported messages but
|
|
112
|
+
* only includes the placeholders available in the raw message and not in the provided data.
|
|
113
|
+
* @param message The reported message
|
|
114
|
+
* @param raw The raw message specified in the rule meta.messages
|
|
115
|
+
* @param data The passed
|
|
116
|
+
* @returns Missing placeholder names
|
|
117
|
+
*/
|
|
118
|
+
function getUnsubstitutedMessagePlaceholders(message, raw, data = {}) {
|
|
119
|
+
const unsubstituted = getMessagePlaceholders(message);
|
|
120
|
+
if (unsubstituted.length === 0) {
|
|
121
|
+
return [];
|
|
122
|
+
}
|
|
123
|
+
// Remove false positives by only counting placeholders in the raw message, which were not provided in the data matcher or added with a data property
|
|
124
|
+
const known = getMessagePlaceholders(raw);
|
|
125
|
+
const provided = Object.keys(data);
|
|
126
|
+
return unsubstituted.filter(name => known.includes(name) && !provided.includes(name));
|
|
127
|
+
}
|
|
78
128
|
class RuleTester extends TestFramework_1.TestFramework {
|
|
129
|
+
#testerConfig;
|
|
130
|
+
#rules = {};
|
|
131
|
+
#linter;
|
|
79
132
|
/**
|
|
80
133
|
* Creates a new instance of RuleTester.
|
|
81
134
|
*/
|
|
82
135
|
constructor(testerConfig) {
|
|
83
136
|
super();
|
|
84
|
-
_RuleTester_instances.add(this);
|
|
85
|
-
_RuleTester_testerConfig.set(this, void 0);
|
|
86
|
-
_RuleTester_rules.set(this, {});
|
|
87
|
-
_RuleTester_linter.set(this, new ts_eslint_1.Linter());
|
|
88
137
|
/**
|
|
89
138
|
* The configuration to use for this tester. Combination of the tester
|
|
90
139
|
* configuration and the default configuration.
|
|
91
140
|
*/
|
|
92
|
-
|
|
93
|
-
rules: {
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
})
|
|
141
|
+
this.#testerConfig = (0, lodash_merge_1.default)({}, defaultConfig, testerConfig, {
|
|
142
|
+
rules: { [`${RULE_TESTER_PLUGIN_PREFIX}validate-ast`]: 'error' },
|
|
143
|
+
});
|
|
144
|
+
this.#linter = new ts_eslint_1.Linter({
|
|
145
|
+
configType: 'flat',
|
|
146
|
+
cwd: this.#testerConfig.languageOptions.parserOptions?.tsconfigRootDir,
|
|
147
|
+
});
|
|
99
148
|
// make sure that the parser doesn't hold onto file handles between tests
|
|
100
149
|
// on linux (i.e. our CI env), there can be very a limited number of watch handles available
|
|
101
150
|
const constructor = this.constructor;
|
|
102
151
|
constructor.afterAll(() => {
|
|
103
152
|
try {
|
|
104
|
-
|
|
105
|
-
// a bit weird, but if they're using this tooling, it'll be installed
|
|
106
|
-
const parser = require(TYPESCRIPT_ESLINT_PARSER);
|
|
107
|
-
parser.clearCaches();
|
|
153
|
+
defaultParser.clearCaches();
|
|
108
154
|
}
|
|
109
155
|
catch {
|
|
110
156
|
// ignored on purpose
|
|
@@ -146,15 +192,125 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
146
192
|
* Define a rule for one particular run of tests.
|
|
147
193
|
*/
|
|
148
194
|
defineRule(name, rule) {
|
|
149
|
-
|
|
195
|
+
this.#rules[name] = {
|
|
196
|
+
...rule,
|
|
197
|
+
// Create a wrapper rule that freezes the `context` properties.
|
|
198
|
+
create(context) {
|
|
199
|
+
(0, freezeDeeply_1.freezeDeeply)(context.options);
|
|
200
|
+
(0, freezeDeeply_1.freezeDeeply)(context.settings);
|
|
201
|
+
(0, freezeDeeply_1.freezeDeeply)(context.parserOptions);
|
|
202
|
+
return (typeof rule === 'function' ? rule : rule.create)(context);
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
#normalizeTests(rawTests) {
|
|
207
|
+
/*
|
|
208
|
+
Automatically add a filename to the tests to enable type-aware tests to "just work".
|
|
209
|
+
This saves users having to verbosely and manually add the filename to every
|
|
210
|
+
single test case.
|
|
211
|
+
Hugely helps with the string-based valid test cases as it means they don't
|
|
212
|
+
need to be made objects!
|
|
213
|
+
*/
|
|
214
|
+
const getFilename = (originalFilename, testOptions) => {
|
|
215
|
+
const resolvedOptions = (0, eslint_utils_1.deepMerge)(this.#testerConfig.languageOptions.parserOptions, testOptions);
|
|
216
|
+
const filename = originalFilename ??
|
|
217
|
+
(resolvedOptions.ecmaFeatures?.jsx
|
|
218
|
+
? this.#testerConfig.defaultFilenames.tsx
|
|
219
|
+
: this.#testerConfig.defaultFilenames.ts);
|
|
220
|
+
if (resolvedOptions.project) {
|
|
221
|
+
return node_path_1.default.join(resolvedOptions.tsconfigRootDir ?? process.cwd(), filename);
|
|
222
|
+
}
|
|
223
|
+
return filename;
|
|
224
|
+
};
|
|
225
|
+
const normalizeTest = (test) => {
|
|
226
|
+
const { languageOptions = {} } = test;
|
|
227
|
+
if (languageOptions.parser === parser) {
|
|
228
|
+
throw new Error(DUPLICATE_PARSER_ERROR_MESSAGE);
|
|
229
|
+
}
|
|
230
|
+
return {
|
|
231
|
+
...test,
|
|
232
|
+
filename: getFilename(test.filename, languageOptions.parserOptions),
|
|
233
|
+
languageOptions: {
|
|
234
|
+
...languageOptions,
|
|
235
|
+
parserOptions: {
|
|
236
|
+
// Re-running simulates --fix mode, which implies an isolated program
|
|
237
|
+
// (i.e. parseAndGenerateServicesCalls[test.filename] > 1).
|
|
238
|
+
disallowAutomaticSingleRunInference: true,
|
|
239
|
+
...languageOptions.parserOptions,
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
};
|
|
243
|
+
};
|
|
244
|
+
const normalizedTests = {
|
|
245
|
+
valid: rawTests.valid
|
|
246
|
+
.map(test => {
|
|
247
|
+
if (typeof test === 'string') {
|
|
248
|
+
return { code: test };
|
|
249
|
+
}
|
|
250
|
+
return test;
|
|
251
|
+
})
|
|
252
|
+
.map(normalizeTest),
|
|
253
|
+
invalid: rawTests.invalid.map(normalizeTest),
|
|
254
|
+
};
|
|
255
|
+
// convenience iterator to make it easy to loop all tests without a concat
|
|
256
|
+
const allTestsIterator = {
|
|
257
|
+
*[Symbol.iterator]() {
|
|
258
|
+
for (const testCase of normalizedTests.valid) {
|
|
259
|
+
yield testCase;
|
|
260
|
+
}
|
|
261
|
+
for (const testCase of normalizedTests.invalid) {
|
|
262
|
+
yield testCase;
|
|
263
|
+
}
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
const hasOnly = (() => {
|
|
267
|
+
for (const test of allTestsIterator) {
|
|
268
|
+
if (test.only) {
|
|
269
|
+
return true;
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return false;
|
|
273
|
+
})();
|
|
274
|
+
if (hasOnly) {
|
|
275
|
+
// if there is an `only: true` - don't try apply constraints - assume that
|
|
276
|
+
// we are in "local development" mode rather than "CI validation" mode
|
|
277
|
+
return normalizedTests;
|
|
278
|
+
}
|
|
279
|
+
const hasConstraints = (() => {
|
|
280
|
+
for (const test of allTestsIterator) {
|
|
281
|
+
if (test.dependencyConstraints &&
|
|
282
|
+
Object.keys(test.dependencyConstraints).length > 0) {
|
|
283
|
+
return true;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return false;
|
|
287
|
+
})();
|
|
288
|
+
if (!hasConstraints) {
|
|
289
|
+
return normalizedTests;
|
|
290
|
+
}
|
|
291
|
+
/*
|
|
292
|
+
Mark all unsatisfactory tests as `skip: true`.
|
|
293
|
+
We do this instead of just omitting the tests entirely because it gives the
|
|
294
|
+
test framework the opportunity to log the test as skipped rather than the test
|
|
295
|
+
just disappearing without a trace.
|
|
296
|
+
*/
|
|
297
|
+
const maybeMarkAsOnly = (test) => {
|
|
298
|
+
return {
|
|
299
|
+
...test,
|
|
300
|
+
skip: !(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(test.dependencyConstraints),
|
|
301
|
+
};
|
|
302
|
+
};
|
|
303
|
+
normalizedTests.valid = normalizedTests.valid.map(maybeMarkAsOnly);
|
|
304
|
+
normalizedTests.invalid = normalizedTests.invalid.map(maybeMarkAsOnly);
|
|
305
|
+
return normalizedTests;
|
|
150
306
|
}
|
|
151
307
|
/**
|
|
152
308
|
* Adds a new rule test to execute.
|
|
153
309
|
*/
|
|
154
310
|
run(ruleName, rule, test) {
|
|
155
311
|
const constructor = this.constructor;
|
|
156
|
-
if (
|
|
157
|
-
!(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(
|
|
312
|
+
if (this.#testerConfig.dependencyConstraints &&
|
|
313
|
+
!(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(this.#testerConfig.dependencyConstraints)) {
|
|
158
314
|
// for frameworks like mocha or jest that have a "skip" version of their function
|
|
159
315
|
// we can provide a nice skipped test!
|
|
160
316
|
constructor.describeSkip(ruleName, () => {
|
|
@@ -181,20 +337,9 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
181
337
|
...scenarioErrors,
|
|
182
338
|
].join('\n'));
|
|
183
339
|
}
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
__classPrivateFieldGet(this, _RuleTester_linter, "f").defineRule(ruleName, Object.assign({}, rule, {
|
|
188
|
-
// Create a wrapper rule that freezes the `context` properties.
|
|
189
|
-
create(context) {
|
|
190
|
-
(0, freezeDeeply_1.freezeDeeply)(context.options);
|
|
191
|
-
(0, freezeDeeply_1.freezeDeeply)(context.settings);
|
|
192
|
-
(0, freezeDeeply_1.freezeDeeply)(context.parserOptions);
|
|
193
|
-
return (typeof rule === 'function' ? rule : rule.create)(context);
|
|
194
|
-
},
|
|
195
|
-
}));
|
|
196
|
-
__classPrivateFieldGet(this, _RuleTester_linter, "f").defineRules(__classPrivateFieldGet(this, _RuleTester_rules, "f"));
|
|
197
|
-
const normalizedTests = __classPrivateFieldGet(this, _RuleTester_instances, "m", _RuleTester_normalizeTests).call(this, test);
|
|
340
|
+
const seenValidTestCases = new Set();
|
|
341
|
+
const seenInvalidTestCases = new Set();
|
|
342
|
+
const normalizedTests = this.#normalizeTests(test);
|
|
198
343
|
function getTestMethod(test) {
|
|
199
344
|
if (test.skip) {
|
|
200
345
|
return 'itSkip';
|
|
@@ -219,7 +364,7 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
219
364
|
return valid.name;
|
|
220
365
|
})();
|
|
221
366
|
constructor[getTestMethod(valid)]((0, validationHelpers_1.sanitize)(testName), () => {
|
|
222
|
-
|
|
367
|
+
this.#testValidTemplate(ruleName, rule, valid, seenValidTestCases);
|
|
223
368
|
});
|
|
224
369
|
});
|
|
225
370
|
});
|
|
@@ -234,7 +379,7 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
234
379
|
return invalid.name;
|
|
235
380
|
})();
|
|
236
381
|
constructor[getTestMethod(invalid)]((0, validationHelpers_1.sanitize)(name), () => {
|
|
237
|
-
|
|
382
|
+
this.#testInvalidTemplate(ruleName, rule, invalid, seenInvalidTestCases);
|
|
238
383
|
});
|
|
239
384
|
});
|
|
240
385
|
});
|
|
@@ -247,10 +392,39 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
247
392
|
* Use @private instead of #private to expose it for testing purposes
|
|
248
393
|
*/
|
|
249
394
|
runRuleForItem(ruleName, rule, item) {
|
|
250
|
-
|
|
395
|
+
this.defineRule(ruleName, rule);
|
|
396
|
+
let config = (0, lodash_merge_1.default)({}, this.#testerConfig, {
|
|
397
|
+
files: ['**'],
|
|
398
|
+
plugins: {
|
|
399
|
+
[RULE_TESTER_PLUGIN]: {
|
|
400
|
+
rules: {
|
|
401
|
+
/**
|
|
402
|
+
* Setup AST getters.
|
|
403
|
+
* The goal is to check whether or not AST was modified when
|
|
404
|
+
* running the rule under test.
|
|
405
|
+
*/
|
|
406
|
+
'validate-ast': {
|
|
407
|
+
create() {
|
|
408
|
+
return {
|
|
409
|
+
Program(node) {
|
|
410
|
+
beforeAST = (0, cloneDeeplyExcludesParent_1.cloneDeeplyExcludesParent)(node);
|
|
411
|
+
},
|
|
412
|
+
'Program:exit'(node) {
|
|
413
|
+
afterAST = node;
|
|
414
|
+
},
|
|
415
|
+
};
|
|
416
|
+
},
|
|
417
|
+
},
|
|
418
|
+
...this.#rules,
|
|
419
|
+
},
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
});
|
|
423
|
+
// Unlike other properties, we don't want to spread props between different parsers.
|
|
424
|
+
config.languageOptions.parser =
|
|
425
|
+
item.languageOptions?.parser ?? this.#testerConfig.languageOptions.parser;
|
|
251
426
|
let code;
|
|
252
427
|
let filename;
|
|
253
|
-
let output;
|
|
254
428
|
let beforeAST;
|
|
255
429
|
let afterAST;
|
|
256
430
|
if (typeof item === 'string') {
|
|
@@ -273,46 +447,25 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
273
447
|
*/
|
|
274
448
|
config = (0, lodash_merge_1.default)(config, itemConfig);
|
|
275
449
|
}
|
|
276
|
-
if (
|
|
450
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'only')) {
|
|
451
|
+
node_assert_1.default.ok(typeof item.only === 'boolean', "Optional test case property 'only' must be a boolean");
|
|
452
|
+
}
|
|
453
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'filename')) {
|
|
454
|
+
node_assert_1.default.ok(typeof item.filename === 'string', "Optional test case property 'filename' must be a string");
|
|
277
455
|
filename = item.filename;
|
|
278
456
|
}
|
|
457
|
+
const prefixedRuleName = `${RULE_TESTER_PLUGIN_PREFIX}${ruleName}`;
|
|
279
458
|
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'options')) {
|
|
280
459
|
(0, node_assert_1.default)(Array.isArray(item.options), 'options must be an array');
|
|
281
|
-
|
|
282
|
-
typeof rule === 'object' &&
|
|
283
|
-
(!rule.meta || (rule.meta && rule.meta.schema == null))) {
|
|
284
|
-
(0, validationHelpers_1.emitMissingSchemaWarning)(ruleName);
|
|
285
|
-
}
|
|
286
|
-
config.rules[ruleName] = ['error', ...item.options];
|
|
460
|
+
config.rules[prefixedRuleName] = ['error', ...item.options];
|
|
287
461
|
}
|
|
288
462
|
else {
|
|
289
|
-
config.rules[
|
|
463
|
+
config.rules[prefixedRuleName] = 'error';
|
|
290
464
|
}
|
|
465
|
+
config.languageOptions ??= {};
|
|
466
|
+
config.languageOptions.parser ??= defaultParser;
|
|
467
|
+
config.languageOptions.parser = (0, validationHelpers_1.wrapParser)(config.languageOptions.parser);
|
|
291
468
|
const schema = (0, getRuleOptionsSchema_1.getRuleOptionsSchema)(rule);
|
|
292
|
-
/*
|
|
293
|
-
* Setup AST getters.
|
|
294
|
-
* The goal is to check whether or not AST was modified when
|
|
295
|
-
* running the rule under test.
|
|
296
|
-
*/
|
|
297
|
-
__classPrivateFieldGet(this, _RuleTester_linter, "f").defineRule('rule-tester/validate-ast', {
|
|
298
|
-
create() {
|
|
299
|
-
return {
|
|
300
|
-
Program(node) {
|
|
301
|
-
beforeAST = (0, cloneDeeplyExcludesParent_1.cloneDeeplyExcludesParent)(node);
|
|
302
|
-
},
|
|
303
|
-
'Program:exit'(node) {
|
|
304
|
-
afterAST = node;
|
|
305
|
-
},
|
|
306
|
-
};
|
|
307
|
-
},
|
|
308
|
-
});
|
|
309
|
-
if (typeof config.parser === 'string') {
|
|
310
|
-
(0, node_assert_1.default)(node_path_1.default.isAbsolute(config.parser), 'Parsers provided as strings to RuleTester must be absolute paths');
|
|
311
|
-
}
|
|
312
|
-
else {
|
|
313
|
-
config.parser = require.resolve(TYPESCRIPT_ESLINT_PARSER);
|
|
314
|
-
}
|
|
315
|
-
__classPrivateFieldGet(this, _RuleTester_linter, "f").defineParser(config.parser, (0, validationHelpers_1.wrapParser)(require(config.parser)));
|
|
316
469
|
if (schema) {
|
|
317
470
|
ajv.validateSchema(schema);
|
|
318
471
|
if (ajv.errors) {
|
|
@@ -341,328 +494,336 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
341
494
|
throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
|
|
342
495
|
}
|
|
343
496
|
}
|
|
344
|
-
(0, config_validator_1.validate)(config,
|
|
497
|
+
(0, config_validator_1.validate)(config, RULE_TESTER_PLUGIN, id => (id === ruleName ? rule : null));
|
|
345
498
|
// Verify the code.
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
let
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
499
|
+
let initialMessages = null;
|
|
500
|
+
let messages = null;
|
|
501
|
+
let fixedResult = null;
|
|
502
|
+
let passNumber = 0;
|
|
503
|
+
const outputs = [];
|
|
504
|
+
const configWithoutCustomKeys = (0, omitCustomConfigProperties_1.omitCustomConfigProperties)(config);
|
|
505
|
+
do {
|
|
506
|
+
passNumber++;
|
|
507
|
+
const { applyLanguageOptions, applyInlineConfig, finalize } = eslint_1.SourceCode.prototype;
|
|
508
|
+
try {
|
|
509
|
+
forbiddenMethods.forEach(methodName => {
|
|
510
|
+
eslint_1.SourceCode.prototype[methodName] = throwForbiddenMethodError(methodName, eslint_1.SourceCode.prototype);
|
|
511
|
+
});
|
|
512
|
+
const actualConfig = (0, lodash_merge_1.default)(configWithoutCustomKeys, {
|
|
513
|
+
linterOptions: { reportUnusedDisableDirectives: 1 },
|
|
514
|
+
languageOptions: {
|
|
515
|
+
...configWithoutCustomKeys.languageOptions,
|
|
516
|
+
parserOptions: {
|
|
517
|
+
ecmaVersion: 'latest',
|
|
518
|
+
sourceType: 'module',
|
|
519
|
+
...configWithoutCustomKeys.languageOptions?.parserOptions,
|
|
520
|
+
},
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
messages = this.#linter.verify(code, actualConfig, filename);
|
|
524
|
+
}
|
|
525
|
+
finally {
|
|
526
|
+
eslint_1.SourceCode.prototype.applyInlineConfig = applyInlineConfig;
|
|
527
|
+
eslint_1.SourceCode.prototype.applyLanguageOptions = applyLanguageOptions;
|
|
528
|
+
eslint_1.SourceCode.prototype.finalize = finalize;
|
|
529
|
+
}
|
|
530
|
+
initialMessages ??= messages;
|
|
531
|
+
if (messages.length === 0) {
|
|
532
|
+
break;
|
|
533
|
+
}
|
|
534
|
+
const fatalErrorMessage = messages.find(m => m.fatal);
|
|
535
|
+
(0, node_assert_1.default)(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage?.message}`);
|
|
536
|
+
fixedResult = SourceCodeFixer.applyFixes(code, messages);
|
|
537
|
+
if (fixedResult.output === code) {
|
|
538
|
+
break;
|
|
539
|
+
}
|
|
540
|
+
code = fixedResult.output;
|
|
541
|
+
outputs.push(code);
|
|
542
|
+
// Verify if autofix makes a syntax error or not.
|
|
543
|
+
const errorMessageInFix = this.#linter
|
|
544
|
+
.verify(fixedResult.output, configWithoutCustomKeys, filename)
|
|
365
545
|
.find(m => m.fatal);
|
|
366
546
|
(0, node_assert_1.default)(!errorMessageInFix, [
|
|
367
547
|
'A fatal parsing error occurred in autofix.',
|
|
368
548
|
`Error: ${errorMessageInFix?.message}`,
|
|
369
549
|
'Autofix output:',
|
|
370
|
-
output,
|
|
550
|
+
fixedResult.output,
|
|
371
551
|
].join('\n'));
|
|
372
|
-
}
|
|
373
|
-
else {
|
|
374
|
-
output = code;
|
|
375
|
-
}
|
|
552
|
+
} while (fixedResult.fixed && passNumber < 10);
|
|
376
553
|
return {
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
554
|
+
config,
|
|
555
|
+
filename,
|
|
556
|
+
messages: initialMessages,
|
|
557
|
+
outputs,
|
|
558
|
+
// is definitely assigned within the `@rule-tester/validate-ast` rule
|
|
380
559
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
381
560
|
beforeAST: beforeAST,
|
|
382
|
-
// is definitely assigned within the
|
|
561
|
+
// is definitely assigned within the `@rule-tester/validate-ast` rule
|
|
383
562
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
384
563
|
afterAST: (0, cloneDeeplyExcludesParent_1.cloneDeeplyExcludesParent)(afterAST),
|
|
385
564
|
};
|
|
386
565
|
}
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
*/
|
|
397
|
-
const getFilename = (testOptions) => {
|
|
398
|
-
const resolvedOptions = (0, eslint_utils_1.deepMerge)(__classPrivateFieldGet(this, _RuleTester_testerConfig, "f").parserOptions, testOptions);
|
|
399
|
-
const filename = resolvedOptions.ecmaFeatures?.jsx
|
|
400
|
-
? __classPrivateFieldGet(this, _RuleTester_testerConfig, "f").defaultFilenames.tsx
|
|
401
|
-
: __classPrivateFieldGet(this, _RuleTester_testerConfig, "f").defaultFilenames.ts;
|
|
402
|
-
if (resolvedOptions.project) {
|
|
403
|
-
return node_path_1.default.join(resolvedOptions.tsconfigRootDir ?? process.cwd(), filename);
|
|
566
|
+
/**
|
|
567
|
+
* Check if the template is valid or not
|
|
568
|
+
* all valid cases go through this
|
|
569
|
+
*/
|
|
570
|
+
#testValidTemplate(ruleName, rule, itemIn, seenValidTestCases) {
|
|
571
|
+
const item = typeof itemIn === 'object' ? itemIn : { code: itemIn };
|
|
572
|
+
node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
|
|
573
|
+
if (item.name) {
|
|
574
|
+
node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
|
|
404
575
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
576
|
+
checkDuplicateTestCase(item, seenValidTestCases);
|
|
577
|
+
const result = this.runRuleForItem(ruleName, rule, item);
|
|
578
|
+
const messages = result.messages;
|
|
579
|
+
node_assert_1.default.strictEqual(messages.length, 0, node_util_1.default.format('Should have no errors but had %d: %s', messages.length, node_util_1.default.inspect(messages)));
|
|
580
|
+
assertASTDidntChange(result.beforeAST, result.afterAST);
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Check if the template is invalid or not
|
|
584
|
+
* all invalid cases go through this.
|
|
585
|
+
*/
|
|
586
|
+
#testInvalidTemplate(ruleName, rule, item, seenInvalidTestCases) {
|
|
587
|
+
node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
|
|
588
|
+
if (item.name) {
|
|
589
|
+
node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
|
|
410
590
|
}
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
parserOptions: {
|
|
415
|
-
// Re-running simulates --fix mode, which implies an isolated program
|
|
416
|
-
// (i.e. parseAndGenerateServicesCalls[test.filename] > 1).
|
|
417
|
-
disallowAutomaticSingleRunInference: true,
|
|
418
|
-
...test.parserOptions,
|
|
419
|
-
},
|
|
420
|
-
};
|
|
421
|
-
};
|
|
422
|
-
const normalizedTests = {
|
|
423
|
-
valid: rawTests.valid
|
|
424
|
-
.map(test => {
|
|
425
|
-
if (typeof test === 'string') {
|
|
426
|
-
return { code: test };
|
|
427
|
-
}
|
|
428
|
-
return test;
|
|
429
|
-
})
|
|
430
|
-
.map(normalizeTest),
|
|
431
|
-
invalid: rawTests.invalid.map(normalizeTest),
|
|
432
|
-
};
|
|
433
|
-
// convenience iterator to make it easy to loop all tests without a concat
|
|
434
|
-
const allTestsIterator = {
|
|
435
|
-
*[Symbol.iterator]() {
|
|
436
|
-
for (const testCase of normalizedTests.valid) {
|
|
437
|
-
yield testCase;
|
|
438
|
-
}
|
|
439
|
-
for (const testCase of normalizedTests.invalid) {
|
|
440
|
-
yield testCase;
|
|
441
|
-
}
|
|
442
|
-
},
|
|
443
|
-
};
|
|
444
|
-
const hasOnly = (() => {
|
|
445
|
-
for (const test of allTestsIterator) {
|
|
446
|
-
if (test.only) {
|
|
447
|
-
return true;
|
|
448
|
-
}
|
|
591
|
+
node_assert_1.default.ok(item.errors || item.errors === 0, `Did not specify errors for an invalid test of ${ruleName}`);
|
|
592
|
+
if (Array.isArray(item.errors) && item.errors.length === 0) {
|
|
593
|
+
node_assert_1.default.fail('Invalid cases must have at least one error');
|
|
449
594
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
595
|
+
checkDuplicateTestCase(item, seenInvalidTestCases);
|
|
596
|
+
const ruleHasMetaMessages = (0, hasOwnProperty_1.hasOwnProperty)(rule, 'meta') && (0, hasOwnProperty_1.hasOwnProperty)(rule.meta, 'messages');
|
|
597
|
+
const friendlyIDList = ruleHasMetaMessages
|
|
598
|
+
? `[${Object.keys(rule.meta.messages)
|
|
599
|
+
.map(key => `'${key}'`)
|
|
600
|
+
.join(', ')}]`
|
|
601
|
+
: null;
|
|
602
|
+
const result = this.runRuleForItem(ruleName, rule, item);
|
|
603
|
+
const messages = result.messages.map(message => ({
|
|
604
|
+
...message,
|
|
605
|
+
...(message.ruleId && {
|
|
606
|
+
ruleId: message.ruleId.startsWith(RULE_TESTER_PLUGIN_PREFIX)
|
|
607
|
+
? message.ruleId.slice(RULE_TESTER_PLUGIN_PREFIX.length)
|
|
608
|
+
: message.ruleId,
|
|
609
|
+
}),
|
|
610
|
+
}));
|
|
611
|
+
for (const message of messages) {
|
|
612
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(message, 'suggestions')) {
|
|
613
|
+
const seenMessageIndices = new Map();
|
|
614
|
+
for (let i = 0; i < message.suggestions.length; i += 1) {
|
|
615
|
+
const suggestionMessage = message.suggestions[i].desc;
|
|
616
|
+
const previous = seenMessageIndices.get(suggestionMessage);
|
|
617
|
+
node_assert_1.default.ok(!seenMessageIndices.has(suggestionMessage), `Suggestion message '${suggestionMessage}' reported from suggestion ${i} was previously reported by suggestion ${previous}. Suggestion messages should be unique within an error.`);
|
|
618
|
+
seenMessageIndices.set(suggestionMessage, i);
|
|
619
|
+
}
|
|
462
620
|
}
|
|
463
621
|
}
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
return normalizedTests;
|
|
468
|
-
}
|
|
469
|
-
/*
|
|
470
|
-
Mark all unsatisfactory tests as `skip: true`.
|
|
471
|
-
We do this instead of just omitting the tests entirely because it gives the
|
|
472
|
-
test framework the opportunity to log the test as skipped rather than the test
|
|
473
|
-
just disappearing without a trace.
|
|
474
|
-
*/
|
|
475
|
-
const maybeMarkAsOnly = (test) => {
|
|
476
|
-
return {
|
|
477
|
-
...test,
|
|
478
|
-
skip: !(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(test.dependencyConstraints),
|
|
479
|
-
};
|
|
480
|
-
};
|
|
481
|
-
normalizedTests.valid = normalizedTests.valid.map(maybeMarkAsOnly);
|
|
482
|
-
normalizedTests.invalid = normalizedTests.invalid.map(maybeMarkAsOnly);
|
|
483
|
-
return normalizedTests;
|
|
484
|
-
}, _RuleTester_testValidTemplate = function _RuleTester_testValidTemplate(ruleName, rule, itemIn) {
|
|
485
|
-
const item = typeof itemIn === 'object' ? itemIn : { code: itemIn };
|
|
486
|
-
node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
|
|
487
|
-
if (item.name) {
|
|
488
|
-
node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
|
|
489
|
-
}
|
|
490
|
-
const result = this.runRuleForItem(ruleName, rule, item);
|
|
491
|
-
const messages = result.messages;
|
|
492
|
-
node_assert_1.default.strictEqual(messages.length, 0, node_util_1.default.format('Should have no errors but had %d: %s', messages.length, node_util_1.default.inspect(messages)));
|
|
493
|
-
assertASTDidntChange(result.beforeAST, result.afterAST);
|
|
494
|
-
}, _RuleTester_testInvalidTemplate = function _RuleTester_testInvalidTemplate(ruleName, rule, item) {
|
|
495
|
-
node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
|
|
496
|
-
if (item.name) {
|
|
497
|
-
node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
|
|
498
|
-
}
|
|
499
|
-
node_assert_1.default.ok(item.errors || item.errors === 0, `Did not specify errors for an invalid test of ${ruleName}`);
|
|
500
|
-
if (Array.isArray(item.errors) && item.errors.length === 0) {
|
|
501
|
-
node_assert_1.default.fail('Invalid cases must have at least one error');
|
|
502
|
-
}
|
|
503
|
-
const ruleHasMetaMessages = (0, hasOwnProperty_1.hasOwnProperty)(rule, 'meta') && (0, hasOwnProperty_1.hasOwnProperty)(rule.meta, 'messages');
|
|
504
|
-
const friendlyIDList = ruleHasMetaMessages
|
|
505
|
-
? `[${Object.keys(rule.meta.messages)
|
|
506
|
-
.map(key => `'${key}'`)
|
|
507
|
-
.join(', ')}]`
|
|
508
|
-
: null;
|
|
509
|
-
const result = this.runRuleForItem(ruleName, rule, item);
|
|
510
|
-
const messages = result.messages;
|
|
511
|
-
for (const message of messages) {
|
|
512
|
-
if ((0, hasOwnProperty_1.hasOwnProperty)(message, 'suggestions')) {
|
|
513
|
-
const seenMessageIndices = new Map();
|
|
514
|
-
for (let i = 0; i < message.suggestions.length; i += 1) {
|
|
515
|
-
const suggestionMessage = message.suggestions[i].desc;
|
|
516
|
-
const previous = seenMessageIndices.get(suggestionMessage);
|
|
517
|
-
node_assert_1.default.ok(!seenMessageIndices.has(suggestionMessage), `Suggestion message '${suggestionMessage}' reported from suggestion ${i} was previously reported by suggestion ${previous}. Suggestion messages should be unique within an error.`);
|
|
518
|
-
seenMessageIndices.set(suggestionMessage, i);
|
|
622
|
+
if (typeof item.errors === 'number') {
|
|
623
|
+
if (item.errors === 0) {
|
|
624
|
+
node_assert_1.default.fail("Invalid cases must have 'error' value greater than 0");
|
|
519
625
|
}
|
|
626
|
+
node_assert_1.default.strictEqual(messages.length, item.errors, node_util_1.default.format('Should have %d error%s but had %d: %s', item.errors, item.errors === 1 ? '' : 's', messages.length, node_util_1.default.inspect(messages)));
|
|
520
627
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
const message = messages[i];
|
|
534
|
-
(0, node_assert_1.default)(hasMessageOfThisRule, 'Error rule name should be the same as the name of the rule being tested');
|
|
535
|
-
if (typeof error === 'string' || error instanceof RegExp) {
|
|
536
|
-
// Just an error message.
|
|
537
|
-
assertMessageMatches(message.message, error);
|
|
538
|
-
}
|
|
539
|
-
else if (typeof error === 'object' && error != null) {
|
|
540
|
-
/*
|
|
541
|
-
* Error object.
|
|
542
|
-
* This may have a message, messageId, data, node type, line, and/or
|
|
543
|
-
* column.
|
|
544
|
-
*/
|
|
545
|
-
Object.keys(error).forEach(propertyName => {
|
|
546
|
-
node_assert_1.default.ok(validationHelpers_1.ERROR_OBJECT_PARAMETERS.has(propertyName), `Invalid error property name '${propertyName}'. Expected one of ${validationHelpers_1.FRIENDLY_ERROR_OBJECT_PARAMETER_LIST}.`);
|
|
547
|
-
});
|
|
548
|
-
// @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
|
|
549
|
-
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'message')) {
|
|
550
|
-
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId'), "Error should not specify both 'message' and a 'messageId'.");
|
|
551
|
-
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'data'), "Error should not specify both 'data' and 'message'.");
|
|
552
|
-
assertMessageMatches(message.message,
|
|
553
|
-
// @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
|
|
554
|
-
error.message);
|
|
628
|
+
else {
|
|
629
|
+
node_assert_1.default.strictEqual(messages.length, item.errors.length, node_util_1.default.format('Should have %d error%s but had %d: %s', item.errors.length, item.errors.length === 1 ? '' : 's', messages.length, node_util_1.default.inspect(messages)));
|
|
630
|
+
const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
|
|
631
|
+
// console.log({ messages });
|
|
632
|
+
for (let i = 0, l = item.errors.length; i < l; i++) {
|
|
633
|
+
const error = item.errors[i];
|
|
634
|
+
const message = messages[i];
|
|
635
|
+
(0, node_assert_1.default)(hasMessageOfThisRule, 'Error rule name should be the same as the name of the rule being tested');
|
|
636
|
+
if (typeof error === 'string' || error instanceof RegExp) {
|
|
637
|
+
// Just an error message.
|
|
638
|
+
assertMessageMatches(message.message, error);
|
|
639
|
+
node_assert_1.default.ok(message.suggestions === undefined, `Error at index ${i} has suggestions. Please convert the test error into an object and specify 'suggestions' property on it to test suggestions.`);
|
|
555
640
|
}
|
|
556
|
-
else if (
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
641
|
+
else if (typeof error === 'object' && error != null) {
|
|
642
|
+
/*
|
|
643
|
+
* Error object.
|
|
644
|
+
* This may have a message, messageId, data, node type, line, and/or
|
|
645
|
+
* column.
|
|
646
|
+
*/
|
|
647
|
+
Object.keys(error).forEach(propertyName => {
|
|
648
|
+
node_assert_1.default.ok(validationHelpers_1.ERROR_OBJECT_PARAMETERS.has(propertyName), `Invalid error property name '${propertyName}'. Expected one of ${validationHelpers_1.FRIENDLY_ERROR_OBJECT_PARAMETER_LIST}.`);
|
|
649
|
+
});
|
|
650
|
+
// @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
|
|
651
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'message')) {
|
|
652
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId'), "Error should not specify both 'message' and a 'messageId'.");
|
|
653
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'data'), "Error should not specify both 'data' and 'message'.");
|
|
654
|
+
assertMessageMatches(message.message,
|
|
655
|
+
// @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
|
|
656
|
+
error.message);
|
|
571
657
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
node_assert_1.default.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
|
|
590
|
-
}
|
|
591
|
-
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'suggestions')) {
|
|
592
|
-
// Support asserting there are no suggestions
|
|
593
|
-
if (!error.suggestions ||
|
|
594
|
-
((0, isReadonlyArray_1.isReadonlyArray)(error.suggestions) &&
|
|
595
|
-
error.suggestions.length === 0)) {
|
|
596
|
-
if (Array.isArray(message.suggestions) &&
|
|
597
|
-
message.suggestions.length > 0) {
|
|
598
|
-
node_assert_1.default.fail(`Error should have no suggestions on error with message: "${message.message}"`);
|
|
658
|
+
else if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId')) {
|
|
659
|
+
node_assert_1.default.ok(ruleHasMetaMessages, "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'.");
|
|
660
|
+
if (!(0, hasOwnProperty_1.hasOwnProperty)(rule.meta.messages, error.messageId)) {
|
|
661
|
+
(0, node_assert_1.default)(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
|
|
662
|
+
}
|
|
663
|
+
node_assert_1.default.strictEqual(message.messageId, error.messageId, `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`);
|
|
664
|
+
const unsubstitutedPlaceholders = getUnsubstitutedMessagePlaceholders(message.message, rule.meta.messages[message.messageId], error.data);
|
|
665
|
+
node_assert_1.default.ok(unsubstitutedPlaceholders.length === 0, `The reported message has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(', ')}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? 'values' : 'value'} via the 'data' property in the context.report() call.`);
|
|
666
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'data')) {
|
|
667
|
+
/*
|
|
668
|
+
* if data was provided, then directly compare the returned message to a synthetic
|
|
669
|
+
* interpolated message using the same message ID and data provided in the test.
|
|
670
|
+
* See https://github.com/eslint/eslint/issues/9890 for context.
|
|
671
|
+
*/
|
|
672
|
+
const unformattedOriginalMessage = rule.meta.messages[error.messageId];
|
|
673
|
+
const rehydratedMessage = (0, interpolate_1.interpolate)(unformattedOriginalMessage, error.data);
|
|
674
|
+
node_assert_1.default.strictEqual(message.message, rehydratedMessage, `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`);
|
|
599
675
|
}
|
|
600
676
|
}
|
|
601
677
|
else {
|
|
602
|
-
|
|
678
|
+
node_assert_1.default.fail("Test error must specify either a 'messageId' or 'message'.");
|
|
679
|
+
}
|
|
680
|
+
if (error.type) {
|
|
681
|
+
node_assert_1.default.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
|
|
682
|
+
}
|
|
683
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'line')) {
|
|
684
|
+
node_assert_1.default.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
|
|
685
|
+
}
|
|
686
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'column')) {
|
|
687
|
+
node_assert_1.default.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
|
|
688
|
+
}
|
|
689
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'endLine')) {
|
|
690
|
+
node_assert_1.default.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
|
|
691
|
+
}
|
|
692
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'endColumn')) {
|
|
693
|
+
node_assert_1.default.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
|
|
694
|
+
}
|
|
695
|
+
node_assert_1.default.ok(!message.suggestions || (0, hasOwnProperty_1.hasOwnProperty)(error, 'suggestions'), `Error at index ${i} has suggestions. Please specify 'suggestions' property on the test error object.`);
|
|
696
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'suggestions')) {
|
|
697
|
+
// Support asserting there are no suggestions
|
|
698
|
+
const expectsSuggestions = Array.isArray(error.suggestions)
|
|
699
|
+
? error.suggestions.length > 0
|
|
700
|
+
: Boolean(error.suggestions);
|
|
701
|
+
const hasSuggestions = message.suggestions !== undefined;
|
|
702
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
603
703
|
const messageSuggestions = message.suggestions;
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'desc')) {
|
|
615
|
-
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data'), `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`);
|
|
616
|
-
// @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
|
|
617
|
-
const expectedDesc = expectedSuggestion.desc;
|
|
618
|
-
node_assert_1.default.strictEqual(actualSuggestion.desc, expectedDesc, `${suggestionPrefix} desc should be "${expectedDesc}" but got "${actualSuggestion.desc}" instead.`);
|
|
704
|
+
if (!hasSuggestions && expectsSuggestions) {
|
|
705
|
+
node_assert_1.default.ok(!error.suggestions, `Error should have suggestions on error with message: "${message.message}"`);
|
|
706
|
+
}
|
|
707
|
+
else if (hasSuggestions) {
|
|
708
|
+
node_assert_1.default.ok(expectsSuggestions, `Error should have no suggestions on error with message: "${message.message}"`);
|
|
709
|
+
if (typeof error.suggestions === 'number') {
|
|
710
|
+
node_assert_1.default.strictEqual(messageSuggestions.length, error.suggestions,
|
|
711
|
+
// It is possible that error.suggestions is a number
|
|
712
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
713
|
+
`Error should have ${error.suggestions} suggestions. Instead found ${messageSuggestions.length} suggestions`);
|
|
619
714
|
}
|
|
620
|
-
if ((
|
|
621
|
-
node_assert_1.default.
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
715
|
+
else if (Array.isArray(error.suggestions)) {
|
|
716
|
+
node_assert_1.default.strictEqual(messageSuggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${messageSuggestions.length} suggestions`);
|
|
717
|
+
error.suggestions.forEach((expectedSuggestion, index) => {
|
|
718
|
+
node_assert_1.default.ok(typeof expectedSuggestion === 'object' &&
|
|
719
|
+
expectedSuggestion != null, "Test suggestion in 'suggestions' array must be an object.");
|
|
720
|
+
Object.keys(expectedSuggestion).forEach(propertyName => {
|
|
721
|
+
node_assert_1.default.ok(validationHelpers_1.SUGGESTION_OBJECT_PARAMETERS.has(propertyName), `Invalid suggestion property name '${propertyName}'. Expected one of ${validationHelpers_1.FRIENDLY_SUGGESTION_OBJECT_PARAMETER_LIST}.`);
|
|
722
|
+
});
|
|
723
|
+
const actualSuggestion = messageSuggestions[index];
|
|
724
|
+
const suggestionPrefix = `Error Suggestion at index ${index}:`;
|
|
725
|
+
// @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
|
|
726
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'desc')) {
|
|
727
|
+
// @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
|
|
728
|
+
const expectedDesc = expectedSuggestion.desc;
|
|
729
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data'), `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`);
|
|
730
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'messageId'), `${suggestionPrefix} Test should not specify both 'desc' and 'messageId'.`);
|
|
731
|
+
node_assert_1.default.strictEqual(actualSuggestion.desc, expectedDesc, `${suggestionPrefix} desc should be "${expectedDesc}" but got "${actualSuggestion.desc}" instead.`);
|
|
732
|
+
}
|
|
733
|
+
else if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'messageId')) {
|
|
734
|
+
node_assert_1.default.ok(ruleHasMetaMessages, `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`);
|
|
735
|
+
node_assert_1.default.ok((0, hasOwnProperty_1.hasOwnProperty)(rule.meta.messages, expectedSuggestion.messageId), `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`);
|
|
736
|
+
node_assert_1.default.strictEqual(actualSuggestion.messageId, expectedSuggestion.messageId, `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`);
|
|
737
|
+
const unsubstitutedPlaceholders = getUnsubstitutedMessagePlaceholders(actualSuggestion.desc, rule.meta.messages[expectedSuggestion.messageId], expectedSuggestion.data);
|
|
738
|
+
node_assert_1.default.ok(unsubstitutedPlaceholders.length === 0, `The message of the suggestion has ${unsubstitutedPlaceholders.length > 1 ? `unsubstituted placeholders: ${unsubstitutedPlaceholders.map(name => `'${name}'`).join(', ')}` : `an unsubstituted placeholder '${unsubstitutedPlaceholders[0]}'`}. Please provide the missing ${unsubstitutedPlaceholders.length > 1 ? 'values' : 'value'} via the 'data' property for the suggestion in the context.report() call.`);
|
|
739
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data')) {
|
|
740
|
+
const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
|
|
741
|
+
const rehydratedDesc = (0, interpolate_1.interpolate)(unformattedMetaMessage, expectedSuggestion.data);
|
|
742
|
+
node_assert_1.default.strictEqual(actualSuggestion.desc, rehydratedDesc, `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
else if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data')) {
|
|
746
|
+
node_assert_1.default.fail(`${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`);
|
|
747
|
+
}
|
|
748
|
+
else {
|
|
749
|
+
node_assert_1.default.fail(`${suggestionPrefix} Test must specify either 'messageId' or 'desc'.`);
|
|
750
|
+
}
|
|
751
|
+
node_assert_1.default.ok((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'output'), `${suggestionPrefix} The "output" property is required.`);
|
|
752
|
+
const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [
|
|
753
|
+
actualSuggestion,
|
|
754
|
+
]).output;
|
|
755
|
+
// Verify if suggestion fix makes a syntax error or not.
|
|
756
|
+
const errorMessageInSuggestion = this.#linter
|
|
757
|
+
.verify(codeWithAppliedSuggestion, (0, omitCustomConfigProperties_1.omitCustomConfigProperties)(result.config), result.filename)
|
|
758
|
+
.find(m => m.fatal);
|
|
759
|
+
(0, node_assert_1.default)(!errorMessageInSuggestion, [
|
|
760
|
+
'A fatal parsing error occurred in suggestion fix.',
|
|
761
|
+
`Error: ${errorMessageInSuggestion?.message}`,
|
|
762
|
+
'Suggestion output:',
|
|
763
|
+
codeWithAppliedSuggestion,
|
|
764
|
+
].join('\n'));
|
|
765
|
+
node_assert_1.default.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
|
|
766
|
+
node_assert_1.default.notStrictEqual(expectedSuggestion.output, item.code, `The output of a suggestion should differ from the original source code for suggestion at index: ${index} on error with message: "${message.message}"`);
|
|
767
|
+
});
|
|
629
768
|
}
|
|
630
769
|
else {
|
|
631
|
-
node_assert_1.default.
|
|
632
|
-
}
|
|
633
|
-
if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'output')) {
|
|
634
|
-
const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
|
|
635
|
-
node_assert_1.default.strictEqual(codeWithAppliedSuggestion, expectedSuggestion.output, `Expected the applied suggestion fix to match the test suggestion output for suggestion at index: ${index} on error with message: "${message.message}"`);
|
|
770
|
+
node_assert_1.default.fail("Test error object property 'suggestions' should be an array or a number");
|
|
636
771
|
}
|
|
637
|
-
}
|
|
772
|
+
}
|
|
638
773
|
}
|
|
639
774
|
}
|
|
775
|
+
else {
|
|
776
|
+
// Message was an unexpected type
|
|
777
|
+
node_assert_1.default.fail(`Error should be a string, object, or RegExp, but found (${node_util_1.default.inspect(message)})`);
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'output')) {
|
|
782
|
+
if (item.output == null) {
|
|
783
|
+
if (result.outputs.length) {
|
|
784
|
+
node_assert_1.default.strictEqual(result.outputs[0], item.code, 'Expected no autofixes to be suggested.');
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
else if (typeof item.output === 'string') {
|
|
788
|
+
(0, node_assert_1.default)(result.outputs.length > 0, 'Expected autofix to be suggested.');
|
|
789
|
+
node_assert_1.default.strictEqual(result.outputs[0], item.output, 'Output is incorrect.');
|
|
790
|
+
if (result.outputs.length) {
|
|
791
|
+
node_assert_1.default.deepStrictEqual(result.outputs, [item.output], 'Multiple autofixes are required due to overlapping fix ranges - please use the array form of output to declare all of the expected autofix passes.');
|
|
792
|
+
}
|
|
640
793
|
}
|
|
641
794
|
else {
|
|
642
|
-
|
|
643
|
-
node_assert_1.default.
|
|
795
|
+
(0, node_assert_1.default)(result.outputs.length > 0, 'Expected autofix to be suggested.');
|
|
796
|
+
node_assert_1.default.deepStrictEqual(result.outputs, item.output, 'Outputs do not match.');
|
|
644
797
|
}
|
|
645
798
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
if (item.output == null) {
|
|
649
|
-
node_assert_1.default.strictEqual(result.output, item.code, 'Expected no autofixes to be suggested');
|
|
799
|
+
else if (result.outputs.length) {
|
|
800
|
+
node_assert_1.default.strictEqual(result.outputs[0], item.code, "The rule fixed the code. Please add 'output' property.");
|
|
650
801
|
}
|
|
651
|
-
|
|
652
|
-
node_assert_1.default.strictEqual(result.output, item.output, 'Output is incorrect.');
|
|
653
|
-
}
|
|
654
|
-
}
|
|
655
|
-
else {
|
|
656
|
-
node_assert_1.default.strictEqual(result.output, item.code, "The rule fixed the code. Please add 'output' property.");
|
|
802
|
+
assertASTDidntChange(result.beforeAST, result.afterAST);
|
|
657
803
|
}
|
|
658
|
-
|
|
659
|
-
|
|
804
|
+
}
|
|
805
|
+
exports.RuleTester = RuleTester;
|
|
660
806
|
/**
|
|
661
807
|
* Check if the AST was changed
|
|
662
808
|
*/
|
|
663
809
|
function assertASTDidntChange(beforeAST, afterAST) {
|
|
664
810
|
node_assert_1.default.deepStrictEqual(beforeAST, afterAST, 'Rule should not modify AST.');
|
|
665
811
|
}
|
|
812
|
+
/**
|
|
813
|
+
* Check if this test case is a duplicate of one we have seen before.
|
|
814
|
+
*/
|
|
815
|
+
function checkDuplicateTestCase(item, seenTestCases) {
|
|
816
|
+
if (!(0, serialization_1.isSerializable)(item)) {
|
|
817
|
+
/*
|
|
818
|
+
* If we can't serialize a test case (because it contains a function, RegExp, etc), skip the check.
|
|
819
|
+
* This might happen with properties like: options, plugins, settings, languageOptions.parser, languageOptions.parserOptions.
|
|
820
|
+
*/
|
|
821
|
+
return;
|
|
822
|
+
}
|
|
823
|
+
const serializedTestCase = (0, json_stable_stringify_without_jsonify_1.default)(item);
|
|
824
|
+
(0, node_assert_1.default)(!seenTestCases.has(serializedTestCase), 'detected duplicate test case');
|
|
825
|
+
seenTestCases.add(serializedTestCase);
|
|
826
|
+
}
|
|
666
827
|
/**
|
|
667
828
|
* Asserts that the message matches its expected value. If the expected
|
|
668
829
|
* value is a regular expression, it is checked against the actual
|