@typescript-eslint/rule-tester 8.0.0-alpha.5 → 8.0.0-alpha.50
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 +2 -2
- package/dist/RuleTester.d.ts.map +1 -1
- package/dist/RuleTester.js +419 -305
- 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/ValidTestCase.d.ts +1 -1
- package/dist/types/ValidTestCase.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -2
- 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.js +1 -2
- 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/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/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/validationHelpers.js +6 -6
- package/dist/utils/validationHelpers.js.map +1 -1
- package/package.json +12 -6
package/dist/RuleTester.js
CHANGED
|
@@ -24,21 +24,9 @@ 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"));
|
|
@@ -49,6 +37,7 @@ const ts_eslint_1 = require("@typescript-eslint/utils/ts-eslint");
|
|
|
49
37
|
// we intentionally import from eslint here because we need to use the same class
|
|
50
38
|
// that ESLint uses, not our custom override typed version
|
|
51
39
|
const eslint_1 = require("eslint");
|
|
40
|
+
const json_stable_stringify_without_jsonify_1 = __importDefault(require("json-stable-stringify-without-jsonify"));
|
|
52
41
|
const lodash_merge_1 = __importDefault(require("lodash.merge"));
|
|
53
42
|
const TestFramework_1 = require("./TestFramework");
|
|
54
43
|
const ajv_1 = require("./utils/ajv");
|
|
@@ -59,7 +48,7 @@ const freezeDeeply_1 = require("./utils/freezeDeeply");
|
|
|
59
48
|
const getRuleOptionsSchema_1 = require("./utils/getRuleOptionsSchema");
|
|
60
49
|
const hasOwnProperty_1 = require("./utils/hasOwnProperty");
|
|
61
50
|
const interpolate_1 = require("./utils/interpolate");
|
|
62
|
-
const
|
|
51
|
+
const serialization_1 = require("./utils/serialization");
|
|
63
52
|
const SourceCodeFixer = __importStar(require("./utils/SourceCodeFixer"));
|
|
64
53
|
const validationHelpers_1 = require("./utils/validationHelpers");
|
|
65
54
|
const ajv = (0, ajv_1.ajvBuilder)({ strictDefaults: true });
|
|
@@ -75,27 +64,55 @@ const testerDefaultConfig = {
|
|
|
75
64
|
defaultFilenames: { ts: 'file.ts', tsx: 'react.tsx' },
|
|
76
65
|
};
|
|
77
66
|
let defaultConfig = (0, eslint_utils_1.deepMerge)({}, testerDefaultConfig);
|
|
67
|
+
/**
|
|
68
|
+
* Extracts names of {{ placeholders }} from the reported message.
|
|
69
|
+
* @param message Reported message
|
|
70
|
+
* @returns Array of placeholder names
|
|
71
|
+
*/
|
|
72
|
+
function getMessagePlaceholders(message) {
|
|
73
|
+
const matcher = (0, interpolate_1.getPlaceholderMatcher)();
|
|
74
|
+
return Array.from(message.matchAll(matcher), ([, name]) => name.trim());
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Returns the placeholders in the reported messages but
|
|
78
|
+
* only includes the placeholders available in the raw message and not in the provided data.
|
|
79
|
+
* @param message The reported message
|
|
80
|
+
* @param raw The raw message specified in the rule meta.messages
|
|
81
|
+
* @param data The passed
|
|
82
|
+
* @returns Missing placeholder names
|
|
83
|
+
*/
|
|
84
|
+
function getUnsubstitutedMessagePlaceholders(message, raw, data = {}) {
|
|
85
|
+
const unsubstituted = getMessagePlaceholders(message);
|
|
86
|
+
if (unsubstituted.length === 0) {
|
|
87
|
+
return [];
|
|
88
|
+
}
|
|
89
|
+
// 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
|
|
90
|
+
const known = getMessagePlaceholders(raw);
|
|
91
|
+
const provided = Object.keys(data);
|
|
92
|
+
return unsubstituted.filter(name => known.includes(name) && !provided.includes(name));
|
|
93
|
+
}
|
|
78
94
|
class RuleTester extends TestFramework_1.TestFramework {
|
|
95
|
+
#testerConfig;
|
|
96
|
+
#rules = {};
|
|
97
|
+
// `configType` is hardcoded to eslintrc until switch to flat config is complete
|
|
98
|
+
// We should look to support both eslintrc and flat config for consumers of RuleTester.
|
|
99
|
+
#linter = new ts_eslint_1.Linter({ configType: 'eslintrc' });
|
|
79
100
|
/**
|
|
80
101
|
* Creates a new instance of RuleTester.
|
|
81
102
|
*/
|
|
82
103
|
constructor(testerConfig) {
|
|
83
104
|
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
105
|
/**
|
|
89
106
|
* The configuration to use for this tester. Combination of the tester
|
|
90
107
|
* configuration and the default configuration.
|
|
91
108
|
*/
|
|
92
|
-
|
|
109
|
+
this.#testerConfig = (0, lodash_merge_1.default)({}, defaultConfig, testerConfig, {
|
|
93
110
|
rules: { 'rule-tester/validate-ast': 'error' },
|
|
94
111
|
// as of eslint 6 you have to provide an absolute path to the parser
|
|
95
112
|
// but that's not as clean to type, this saves us trying to manually enforce
|
|
96
113
|
// that contributors require.resolve everything
|
|
97
114
|
parser: require.resolve(testerConfig?.parser ?? defaultConfig.parser),
|
|
98
|
-
})
|
|
115
|
+
});
|
|
99
116
|
// make sure that the parser doesn't hold onto file handles between tests
|
|
100
117
|
// on linux (i.e. our CI env), there can be very a limited number of watch handles available
|
|
101
118
|
const constructor = this.constructor;
|
|
@@ -103,6 +120,7 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
103
120
|
try {
|
|
104
121
|
// instead of creating a hard dependency, just use a soft require
|
|
105
122
|
// a bit weird, but if they're using this tooling, it'll be installed
|
|
123
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
106
124
|
const parser = require(TYPESCRIPT_ESLINT_PARSER);
|
|
107
125
|
parser.clearCaches();
|
|
108
126
|
}
|
|
@@ -146,15 +164,114 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
146
164
|
* Define a rule for one particular run of tests.
|
|
147
165
|
*/
|
|
148
166
|
defineRule(name, rule) {
|
|
149
|
-
|
|
167
|
+
this.#rules[name] = rule;
|
|
168
|
+
}
|
|
169
|
+
#normalizeTests(rawTests) {
|
|
170
|
+
/*
|
|
171
|
+
Automatically add a filename to the tests to enable type-aware tests to "just work".
|
|
172
|
+
This saves users having to verbosely and manually add the filename to every
|
|
173
|
+
single test case.
|
|
174
|
+
Hugely helps with the string-based valid test cases as it means they don't
|
|
175
|
+
need to be made objects!
|
|
176
|
+
*/
|
|
177
|
+
const getFilename = (testOptions) => {
|
|
178
|
+
const resolvedOptions = (0, eslint_utils_1.deepMerge)(this.#testerConfig.parserOptions, testOptions);
|
|
179
|
+
const filename = resolvedOptions.ecmaFeatures?.jsx
|
|
180
|
+
? this.#testerConfig.defaultFilenames.tsx
|
|
181
|
+
: this.#testerConfig.defaultFilenames.ts;
|
|
182
|
+
if (resolvedOptions.project) {
|
|
183
|
+
return node_path_1.default.join(resolvedOptions.tsconfigRootDir ?? process.cwd(), filename);
|
|
184
|
+
}
|
|
185
|
+
return filename;
|
|
186
|
+
};
|
|
187
|
+
const normalizeTest = (test) => {
|
|
188
|
+
if (test.parser === TYPESCRIPT_ESLINT_PARSER) {
|
|
189
|
+
throw new Error(DUPLICATE_PARSER_ERROR_MESSAGE);
|
|
190
|
+
}
|
|
191
|
+
if (!test.filename) {
|
|
192
|
+
return {
|
|
193
|
+
...test,
|
|
194
|
+
filename: getFilename(test.parserOptions),
|
|
195
|
+
parserOptions: {
|
|
196
|
+
// Re-running simulates --fix mode, which implies an isolated program
|
|
197
|
+
// (i.e. parseAndGenerateServicesCalls[test.filename] > 1).
|
|
198
|
+
disallowAutomaticSingleRunInference: true,
|
|
199
|
+
...test.parserOptions,
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
return test;
|
|
204
|
+
};
|
|
205
|
+
const normalizedTests = {
|
|
206
|
+
valid: rawTests.valid
|
|
207
|
+
.map(test => {
|
|
208
|
+
if (typeof test === 'string') {
|
|
209
|
+
return { code: test };
|
|
210
|
+
}
|
|
211
|
+
return test;
|
|
212
|
+
})
|
|
213
|
+
.map(normalizeTest),
|
|
214
|
+
invalid: rawTests.invalid.map(normalizeTest),
|
|
215
|
+
};
|
|
216
|
+
// convenience iterator to make it easy to loop all tests without a concat
|
|
217
|
+
const allTestsIterator = {
|
|
218
|
+
*[Symbol.iterator]() {
|
|
219
|
+
for (const testCase of normalizedTests.valid) {
|
|
220
|
+
yield testCase;
|
|
221
|
+
}
|
|
222
|
+
for (const testCase of normalizedTests.invalid) {
|
|
223
|
+
yield testCase;
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
const hasOnly = (() => {
|
|
228
|
+
for (const test of allTestsIterator) {
|
|
229
|
+
if (test.only) {
|
|
230
|
+
return true;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
return false;
|
|
234
|
+
})();
|
|
235
|
+
if (hasOnly) {
|
|
236
|
+
// if there is an `only: true` - don't try apply constraints - assume that
|
|
237
|
+
// we are in "local development" mode rather than "CI validation" mode
|
|
238
|
+
return normalizedTests;
|
|
239
|
+
}
|
|
240
|
+
const hasConstraints = (() => {
|
|
241
|
+
for (const test of allTestsIterator) {
|
|
242
|
+
if (test.dependencyConstraints &&
|
|
243
|
+
Object.keys(test.dependencyConstraints).length > 0) {
|
|
244
|
+
return true;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
return false;
|
|
248
|
+
})();
|
|
249
|
+
if (!hasConstraints) {
|
|
250
|
+
return normalizedTests;
|
|
251
|
+
}
|
|
252
|
+
/*
|
|
253
|
+
Mark all unsatisfactory tests as `skip: true`.
|
|
254
|
+
We do this instead of just omitting the tests entirely because it gives the
|
|
255
|
+
test framework the opportunity to log the test as skipped rather than the test
|
|
256
|
+
just disappearing without a trace.
|
|
257
|
+
*/
|
|
258
|
+
const maybeMarkAsOnly = (test) => {
|
|
259
|
+
return {
|
|
260
|
+
...test,
|
|
261
|
+
skip: !(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(test.dependencyConstraints),
|
|
262
|
+
};
|
|
263
|
+
};
|
|
264
|
+
normalizedTests.valid = normalizedTests.valid.map(maybeMarkAsOnly);
|
|
265
|
+
normalizedTests.invalid = normalizedTests.invalid.map(maybeMarkAsOnly);
|
|
266
|
+
return normalizedTests;
|
|
150
267
|
}
|
|
151
268
|
/**
|
|
152
269
|
* Adds a new rule test to execute.
|
|
153
270
|
*/
|
|
154
271
|
run(ruleName, rule, test) {
|
|
155
272
|
const constructor = this.constructor;
|
|
156
|
-
if (
|
|
157
|
-
!(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(
|
|
273
|
+
if (this.#testerConfig.dependencyConstraints &&
|
|
274
|
+
!(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(this.#testerConfig.dependencyConstraints)) {
|
|
158
275
|
// for frameworks like mocha or jest that have a "skip" version of their function
|
|
159
276
|
// we can provide a nice skipped test!
|
|
160
277
|
constructor.describeSkip(ruleName, () => {
|
|
@@ -181,10 +298,13 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
181
298
|
...scenarioErrors,
|
|
182
299
|
].join('\n'));
|
|
183
300
|
}
|
|
301
|
+
const seenValidTestCases = new Set();
|
|
302
|
+
const seenInvalidTestCases = new Set();
|
|
184
303
|
if (typeof rule === 'function') {
|
|
185
304
|
(0, validationHelpers_1.emitLegacyRuleAPIWarning)(ruleName);
|
|
186
305
|
}
|
|
187
|
-
|
|
306
|
+
this.#linter.defineRule(ruleName, {
|
|
307
|
+
...rule,
|
|
188
308
|
// Create a wrapper rule that freezes the `context` properties.
|
|
189
309
|
create(context) {
|
|
190
310
|
(0, freezeDeeply_1.freezeDeeply)(context.options);
|
|
@@ -192,9 +312,9 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
192
312
|
(0, freezeDeeply_1.freezeDeeply)(context.parserOptions);
|
|
193
313
|
return (typeof rule === 'function' ? rule : rule.create)(context);
|
|
194
314
|
},
|
|
195
|
-
})
|
|
196
|
-
|
|
197
|
-
const normalizedTests =
|
|
315
|
+
});
|
|
316
|
+
this.#linter.defineRules(this.#rules);
|
|
317
|
+
const normalizedTests = this.#normalizeTests(test);
|
|
198
318
|
function getTestMethod(test) {
|
|
199
319
|
if (test.skip) {
|
|
200
320
|
return 'itSkip';
|
|
@@ -219,7 +339,7 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
219
339
|
return valid.name;
|
|
220
340
|
})();
|
|
221
341
|
constructor[getTestMethod(valid)]((0, validationHelpers_1.sanitize)(testName), () => {
|
|
222
|
-
|
|
342
|
+
this.#testValidTemplate(ruleName, rule, valid, seenValidTestCases);
|
|
223
343
|
});
|
|
224
344
|
});
|
|
225
345
|
});
|
|
@@ -234,7 +354,7 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
234
354
|
return invalid.name;
|
|
235
355
|
})();
|
|
236
356
|
constructor[getTestMethod(invalid)]((0, validationHelpers_1.sanitize)(name), () => {
|
|
237
|
-
|
|
357
|
+
this.#testInvalidTemplate(ruleName, rule, invalid, seenInvalidTestCases);
|
|
238
358
|
});
|
|
239
359
|
});
|
|
240
360
|
});
|
|
@@ -247,10 +367,9 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
247
367
|
* Use @private instead of #private to expose it for testing purposes
|
|
248
368
|
*/
|
|
249
369
|
runRuleForItem(ruleName, rule, item) {
|
|
250
|
-
let config = (0, lodash_merge_1.default)({},
|
|
370
|
+
let config = (0, lodash_merge_1.default)({}, this.#testerConfig);
|
|
251
371
|
let code;
|
|
252
372
|
let filename;
|
|
253
|
-
let output;
|
|
254
373
|
let beforeAST;
|
|
255
374
|
let afterAST;
|
|
256
375
|
if (typeof item === 'string') {
|
|
@@ -273,7 +392,11 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
273
392
|
*/
|
|
274
393
|
config = (0, lodash_merge_1.default)(config, itemConfig);
|
|
275
394
|
}
|
|
276
|
-
if (
|
|
395
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'only')) {
|
|
396
|
+
node_assert_1.default.ok(typeof item.only === 'boolean', "Optional test case property 'only' must be a boolean");
|
|
397
|
+
}
|
|
398
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'filename')) {
|
|
399
|
+
node_assert_1.default.ok(typeof item.filename === 'string', "Optional test case property 'filename' must be a string");
|
|
277
400
|
filename = item.filename;
|
|
278
401
|
}
|
|
279
402
|
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'options')) {
|
|
@@ -294,7 +417,7 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
294
417
|
* The goal is to check whether or not AST was modified when
|
|
295
418
|
* running the rule under test.
|
|
296
419
|
*/
|
|
297
|
-
|
|
420
|
+
this.#linter.defineRule('rule-tester/validate-ast', {
|
|
298
421
|
create() {
|
|
299
422
|
return {
|
|
300
423
|
Program(node) {
|
|
@@ -312,7 +435,9 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
312
435
|
else {
|
|
313
436
|
config.parser = require.resolve(TYPESCRIPT_ESLINT_PARSER);
|
|
314
437
|
}
|
|
315
|
-
|
|
438
|
+
this.#linter.defineParser(config.parser,
|
|
439
|
+
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
440
|
+
(0, validationHelpers_1.wrapParser)(require(config.parser)));
|
|
316
441
|
if (schema) {
|
|
317
442
|
ajv.validateSchema(schema);
|
|
318
443
|
if (ajv.errors) {
|
|
@@ -345,37 +470,52 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
345
470
|
// Verify the code.
|
|
346
471
|
// @ts-expect-error -- we don't define deprecated members on our types
|
|
347
472
|
const { getComments } = eslint_1.SourceCode.prototype;
|
|
348
|
-
let
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
473
|
+
let initialMessages = null;
|
|
474
|
+
let messages = null;
|
|
475
|
+
let fixedResult = null;
|
|
476
|
+
let passNumber = 0;
|
|
477
|
+
const outputs = [];
|
|
478
|
+
do {
|
|
479
|
+
passNumber++;
|
|
480
|
+
try {
|
|
481
|
+
// @ts-expect-error -- we don't define deprecated members on our types
|
|
482
|
+
eslint_1.SourceCode.prototype.getComments = validationHelpers_1.getCommentsDeprecation;
|
|
483
|
+
messages = this.#linter.verify(code, config, filename);
|
|
484
|
+
if (!initialMessages) {
|
|
485
|
+
initialMessages = messages;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
finally {
|
|
489
|
+
// @ts-expect-error -- we don't define deprecated members on our types
|
|
490
|
+
eslint_1.SourceCode.prototype.getComments = getComments;
|
|
491
|
+
}
|
|
492
|
+
if (messages.length === 0) {
|
|
493
|
+
break;
|
|
494
|
+
}
|
|
495
|
+
const fatalErrorMessage = messages.find(m => m.fatal);
|
|
496
|
+
(0, node_assert_1.default)(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage?.message}`);
|
|
497
|
+
fixedResult = SourceCodeFixer.applyFixes(code, messages);
|
|
498
|
+
if (fixedResult.output === code) {
|
|
499
|
+
break;
|
|
500
|
+
}
|
|
501
|
+
code = fixedResult.output;
|
|
502
|
+
outputs.push(code);
|
|
503
|
+
// Verify if autofix makes a syntax error or not.
|
|
504
|
+
const errorMessageInFix = this.#linter
|
|
505
|
+
.verify(fixedResult.output, config, filename)
|
|
365
506
|
.find(m => m.fatal);
|
|
366
507
|
(0, node_assert_1.default)(!errorMessageInFix, [
|
|
367
508
|
'A fatal parsing error occurred in autofix.',
|
|
368
509
|
`Error: ${errorMessageInFix?.message}`,
|
|
369
510
|
'Autofix output:',
|
|
370
|
-
output,
|
|
511
|
+
fixedResult.output,
|
|
371
512
|
].join('\n'));
|
|
372
|
-
}
|
|
373
|
-
else {
|
|
374
|
-
output = code;
|
|
375
|
-
}
|
|
513
|
+
} while (fixedResult.fixed && passNumber < 10);
|
|
376
514
|
return {
|
|
377
|
-
|
|
378
|
-
|
|
515
|
+
config,
|
|
516
|
+
filename,
|
|
517
|
+
messages: initialMessages,
|
|
518
|
+
outputs,
|
|
379
519
|
// is definitely assigned within the `rule-tester/validate-ast` rule
|
|
380
520
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
381
521
|
beforeAST: beforeAST,
|
|
@@ -384,285 +524,259 @@ class RuleTester extends TestFramework_1.TestFramework {
|
|
|
384
524
|
afterAST: (0, cloneDeeplyExcludesParent_1.cloneDeeplyExcludesParent)(afterAST),
|
|
385
525
|
};
|
|
386
526
|
}
|
|
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);
|
|
527
|
+
/**
|
|
528
|
+
* Check if the template is valid or not
|
|
529
|
+
* all valid cases go through this
|
|
530
|
+
*/
|
|
531
|
+
#testValidTemplate(ruleName, rule, itemIn, seenValidTestCases) {
|
|
532
|
+
const item = typeof itemIn === 'object' ? itemIn : { code: itemIn };
|
|
533
|
+
node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
|
|
534
|
+
if (item.name) {
|
|
535
|
+
node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
|
|
404
536
|
}
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
537
|
+
checkDuplicateTestCase(item, seenValidTestCases);
|
|
538
|
+
const result = this.runRuleForItem(ruleName, rule, item);
|
|
539
|
+
const messages = result.messages;
|
|
540
|
+
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)));
|
|
541
|
+
assertASTDidntChange(result.beforeAST, result.afterAST);
|
|
542
|
+
}
|
|
543
|
+
/**
|
|
544
|
+
* Check if the template is invalid or not
|
|
545
|
+
* all invalid cases go through this.
|
|
546
|
+
*/
|
|
547
|
+
#testInvalidTemplate(ruleName, rule, item, seenInvalidTestCases) {
|
|
548
|
+
node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
|
|
549
|
+
if (item.name) {
|
|
550
|
+
node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
|
|
410
551
|
}
|
|
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
|
-
}
|
|
552
|
+
node_assert_1.default.ok(item.errors || item.errors === 0, `Did not specify errors for an invalid test of ${ruleName}`);
|
|
553
|
+
if (Array.isArray(item.errors) && item.errors.length === 0) {
|
|
554
|
+
node_assert_1.default.fail('Invalid cases must have at least one error');
|
|
449
555
|
}
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
556
|
+
checkDuplicateTestCase(item, seenInvalidTestCases);
|
|
557
|
+
const ruleHasMetaMessages = (0, hasOwnProperty_1.hasOwnProperty)(rule, 'meta') && (0, hasOwnProperty_1.hasOwnProperty)(rule.meta, 'messages');
|
|
558
|
+
const friendlyIDList = ruleHasMetaMessages
|
|
559
|
+
? `[${Object.keys(rule.meta.messages)
|
|
560
|
+
.map(key => `'${key}'`)
|
|
561
|
+
.join(', ')}]`
|
|
562
|
+
: null;
|
|
563
|
+
const result = this.runRuleForItem(ruleName, rule, item);
|
|
564
|
+
const messages = result.messages;
|
|
565
|
+
for (const message of messages) {
|
|
566
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(message, 'suggestions')) {
|
|
567
|
+
const seenMessageIndices = new Map();
|
|
568
|
+
for (let i = 0; i < message.suggestions.length; i += 1) {
|
|
569
|
+
const suggestionMessage = message.suggestions[i].desc;
|
|
570
|
+
const previous = seenMessageIndices.get(suggestionMessage);
|
|
571
|
+
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.`);
|
|
572
|
+
seenMessageIndices.set(suggestionMessage, i);
|
|
573
|
+
}
|
|
462
574
|
}
|
|
463
575
|
}
|
|
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);
|
|
576
|
+
if (typeof item.errors === 'number') {
|
|
577
|
+
if (item.errors === 0) {
|
|
578
|
+
node_assert_1.default.fail("Invalid cases must have 'error' value greater than 0");
|
|
519
579
|
}
|
|
580
|
+
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
581
|
}
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
const error = item.errors[i];
|
|
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);
|
|
582
|
+
else {
|
|
583
|
+
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)));
|
|
584
|
+
const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
|
|
585
|
+
for (let i = 0, l = item.errors.length; i < l; i++) {
|
|
586
|
+
const error = item.errors[i];
|
|
587
|
+
const message = messages[i];
|
|
588
|
+
(0, node_assert_1.default)(hasMessageOfThisRule, 'Error rule name should be the same as the name of the rule being tested');
|
|
589
|
+
if (typeof error === 'string' || error instanceof RegExp) {
|
|
590
|
+
// Just an error message.
|
|
591
|
+
assertMessageMatches(message.message, error);
|
|
592
|
+
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
593
|
}
|
|
556
|
-
else if (
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
594
|
+
else if (typeof error === 'object' && error != null) {
|
|
595
|
+
/*
|
|
596
|
+
* Error object.
|
|
597
|
+
* This may have a message, messageId, data, node type, line, and/or
|
|
598
|
+
* column.
|
|
599
|
+
*/
|
|
600
|
+
Object.keys(error).forEach(propertyName => {
|
|
601
|
+
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}.`);
|
|
602
|
+
});
|
|
603
|
+
// @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
|
|
604
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'message')) {
|
|
605
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId'), "Error should not specify both 'message' and a 'messageId'.");
|
|
606
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'data'), "Error should not specify both 'data' and 'message'.");
|
|
607
|
+
assertMessageMatches(message.message,
|
|
608
|
+
// @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
|
|
609
|
+
error.message);
|
|
571
610
|
}
|
|
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}"`);
|
|
611
|
+
else if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId')) {
|
|
612
|
+
node_assert_1.default.ok(ruleHasMetaMessages, "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'.");
|
|
613
|
+
if (!(0, hasOwnProperty_1.hasOwnProperty)(rule.meta.messages, error.messageId)) {
|
|
614
|
+
(0, node_assert_1.default)(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
|
|
615
|
+
}
|
|
616
|
+
node_assert_1.default.strictEqual(message.messageId, error.messageId, `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`);
|
|
617
|
+
const unsubstitutedPlaceholders = getUnsubstitutedMessagePlaceholders(message.message, rule.meta.messages[message.messageId], error.data);
|
|
618
|
+
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.`);
|
|
619
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'data')) {
|
|
620
|
+
/*
|
|
621
|
+
* if data was provided, then directly compare the returned message to a synthetic
|
|
622
|
+
* interpolated message using the same message ID and data provided in the test.
|
|
623
|
+
* See https://github.com/eslint/eslint/issues/9890 for context.
|
|
624
|
+
*/
|
|
625
|
+
const unformattedOriginalMessage = rule.meta.messages[error.messageId];
|
|
626
|
+
const rehydratedMessage = (0, interpolate_1.interpolate)(unformattedOriginalMessage, error.data);
|
|
627
|
+
node_assert_1.default.strictEqual(message.message, rehydratedMessage, `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`);
|
|
599
628
|
}
|
|
600
629
|
}
|
|
601
630
|
else {
|
|
602
|
-
|
|
631
|
+
node_assert_1.default.fail("Test error must specify either a 'messageId' or 'message'.");
|
|
632
|
+
}
|
|
633
|
+
if (error.type) {
|
|
634
|
+
node_assert_1.default.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
|
|
635
|
+
}
|
|
636
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'line')) {
|
|
637
|
+
node_assert_1.default.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
|
|
638
|
+
}
|
|
639
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'column')) {
|
|
640
|
+
node_assert_1.default.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
|
|
641
|
+
}
|
|
642
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'endLine')) {
|
|
643
|
+
node_assert_1.default.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
|
|
644
|
+
}
|
|
645
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'endColumn')) {
|
|
646
|
+
node_assert_1.default.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
|
|
647
|
+
}
|
|
648
|
+
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.`);
|
|
649
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'suggestions')) {
|
|
650
|
+
// Support asserting there are no suggestions
|
|
651
|
+
const expectsSuggestions = Array.isArray(error.suggestions)
|
|
652
|
+
? error.suggestions.length > 0
|
|
653
|
+
: Boolean(error.suggestions);
|
|
654
|
+
const hasSuggestions = message.suggestions !== undefined;
|
|
655
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
603
656
|
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.`);
|
|
657
|
+
if (!hasSuggestions && expectsSuggestions) {
|
|
658
|
+
node_assert_1.default.ok(!error.suggestions, `Error should have suggestions on error with message: "${message.message}"`);
|
|
659
|
+
}
|
|
660
|
+
else if (hasSuggestions) {
|
|
661
|
+
node_assert_1.default.ok(expectsSuggestions, `Error should have no suggestions on error with message: "${message.message}"`);
|
|
662
|
+
if (typeof error.suggestions === 'number') {
|
|
663
|
+
node_assert_1.default.strictEqual(messageSuggestions.length, error.suggestions,
|
|
664
|
+
// It is possible that error.suggestions is a number
|
|
665
|
+
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
|
|
666
|
+
`Error should have ${error.suggestions} suggestions. Instead found ${messageSuggestions.length} suggestions`);
|
|
619
667
|
}
|
|
620
|
-
if ((
|
|
621
|
-
node_assert_1.default.
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
668
|
+
else if (Array.isArray(error.suggestions)) {
|
|
669
|
+
node_assert_1.default.strictEqual(messageSuggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${messageSuggestions.length} suggestions`);
|
|
670
|
+
error.suggestions.forEach((expectedSuggestion, index) => {
|
|
671
|
+
node_assert_1.default.ok(typeof expectedSuggestion === 'object' &&
|
|
672
|
+
expectedSuggestion != null, "Test suggestion in 'suggestions' array must be an object.");
|
|
673
|
+
Object.keys(expectedSuggestion).forEach(propertyName => {
|
|
674
|
+
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}.`);
|
|
675
|
+
});
|
|
676
|
+
const actualSuggestion = messageSuggestions[index];
|
|
677
|
+
const suggestionPrefix = `Error Suggestion at index ${index}:`;
|
|
678
|
+
// @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
|
|
679
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'desc')) {
|
|
680
|
+
// @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
|
|
681
|
+
const expectedDesc = expectedSuggestion.desc;
|
|
682
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data'), `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`);
|
|
683
|
+
node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'messageId'), `${suggestionPrefix} Test should not specify both 'desc' and 'messageId'.`);
|
|
684
|
+
node_assert_1.default.strictEqual(actualSuggestion.desc, expectedDesc, `${suggestionPrefix} desc should be "${expectedDesc}" but got "${actualSuggestion.desc}" instead.`);
|
|
685
|
+
}
|
|
686
|
+
else if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'messageId')) {
|
|
687
|
+
node_assert_1.default.ok(ruleHasMetaMessages, `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`);
|
|
688
|
+
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}.`);
|
|
689
|
+
node_assert_1.default.strictEqual(actualSuggestion.messageId, expectedSuggestion.messageId, `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`);
|
|
690
|
+
const unsubstitutedPlaceholders = getUnsubstitutedMessagePlaceholders(actualSuggestion.desc, rule.meta.messages[expectedSuggestion.messageId], expectedSuggestion.data);
|
|
691
|
+
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.`);
|
|
692
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data')) {
|
|
693
|
+
const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
|
|
694
|
+
const rehydratedDesc = (0, interpolate_1.interpolate)(unformattedMetaMessage, expectedSuggestion.data);
|
|
695
|
+
node_assert_1.default.strictEqual(actualSuggestion.desc, rehydratedDesc, `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
else if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data')) {
|
|
699
|
+
node_assert_1.default.fail(`${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`);
|
|
700
|
+
}
|
|
701
|
+
else {
|
|
702
|
+
node_assert_1.default.fail(`${suggestionPrefix} Test must specify either 'messageId' or 'desc'.`);
|
|
703
|
+
}
|
|
704
|
+
node_assert_1.default.ok((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'output'), `${suggestionPrefix} The "output" property is required.`);
|
|
705
|
+
const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [
|
|
706
|
+
actualSuggestion,
|
|
707
|
+
]).output;
|
|
708
|
+
// Verify if suggestion fix makes a syntax error or not.
|
|
709
|
+
const errorMessageInSuggestion = this.#linter
|
|
710
|
+
.verify(codeWithAppliedSuggestion, result.config, result.filename)
|
|
711
|
+
.find(m => m.fatal);
|
|
712
|
+
(0, node_assert_1.default)(!errorMessageInSuggestion, [
|
|
713
|
+
'A fatal parsing error occurred in suggestion fix.',
|
|
714
|
+
`Error: ${errorMessageInSuggestion?.message}`,
|
|
715
|
+
'Suggestion output:',
|
|
716
|
+
codeWithAppliedSuggestion,
|
|
717
|
+
].join('\n'));
|
|
718
|
+
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}"`);
|
|
719
|
+
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}"`);
|
|
720
|
+
});
|
|
629
721
|
}
|
|
630
722
|
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}"`);
|
|
723
|
+
node_assert_1.default.fail("Test error object property 'suggestions' should be an array or a number");
|
|
636
724
|
}
|
|
637
|
-
}
|
|
725
|
+
}
|
|
638
726
|
}
|
|
639
727
|
}
|
|
728
|
+
else {
|
|
729
|
+
// Message was an unexpected type
|
|
730
|
+
node_assert_1.default.fail(`Error should be a string, object, or RegExp, but found (${node_util_1.default.inspect(message)})`);
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'output')) {
|
|
735
|
+
if (item.output == null) {
|
|
736
|
+
if (result.outputs.length) {
|
|
737
|
+
node_assert_1.default.strictEqual(result.outputs[0], item.code, 'Expected no autofixes to be suggested.');
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
else if (typeof item.output === 'string') {
|
|
741
|
+
(0, node_assert_1.default)(result.outputs.length > 0, 'Expected autofix to be suggested.');
|
|
742
|
+
node_assert_1.default.strictEqual(result.outputs[0], item.output, 'Output is incorrect.');
|
|
743
|
+
if (result.outputs.length) {
|
|
744
|
+
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.');
|
|
745
|
+
}
|
|
640
746
|
}
|
|
641
747
|
else {
|
|
642
|
-
|
|
643
|
-
node_assert_1.default.
|
|
748
|
+
(0, node_assert_1.default)(result.outputs.length > 0, 'Expected autofix to be suggested.');
|
|
749
|
+
node_assert_1.default.deepStrictEqual(result.outputs, item.output, 'Outputs do not match.');
|
|
644
750
|
}
|
|
645
751
|
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
if (item.output == null) {
|
|
649
|
-
node_assert_1.default.strictEqual(result.output, item.code, 'Expected no autofixes to be suggested');
|
|
650
|
-
}
|
|
651
|
-
else {
|
|
652
|
-
node_assert_1.default.strictEqual(result.output, item.output, 'Output is incorrect.');
|
|
752
|
+
else if (result.outputs.length) {
|
|
753
|
+
node_assert_1.default.strictEqual(result.outputs[0], item.code, "The rule fixed the code. Please add 'output' property.");
|
|
653
754
|
}
|
|
755
|
+
assertASTDidntChange(result.beforeAST, result.afterAST);
|
|
654
756
|
}
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
}
|
|
658
|
-
assertASTDidntChange(result.beforeAST, result.afterAST);
|
|
659
|
-
};
|
|
757
|
+
}
|
|
758
|
+
exports.RuleTester = RuleTester;
|
|
660
759
|
/**
|
|
661
760
|
* Check if the AST was changed
|
|
662
761
|
*/
|
|
663
762
|
function assertASTDidntChange(beforeAST, afterAST) {
|
|
664
763
|
node_assert_1.default.deepStrictEqual(beforeAST, afterAST, 'Rule should not modify AST.');
|
|
665
764
|
}
|
|
765
|
+
/**
|
|
766
|
+
* Check if this test case is a duplicate of one we have seen before.
|
|
767
|
+
*/
|
|
768
|
+
function checkDuplicateTestCase(item, seenTestCases) {
|
|
769
|
+
if (!(0, serialization_1.isSerializable)(item)) {
|
|
770
|
+
/*
|
|
771
|
+
* If we can't serialize a test case (because it contains a function, RegExp, etc), skip the check.
|
|
772
|
+
* This might happen with properties like: options, plugins, settings, languageOptions.parser, languageOptions.parserOptions.
|
|
773
|
+
*/
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
const serializedTestCase = (0, json_stable_stringify_without_jsonify_1.default)(item);
|
|
777
|
+
(0, node_assert_1.default)(!seenTestCases.has(serializedTestCase), 'detected duplicate test case');
|
|
778
|
+
seenTestCases.add(serializedTestCase);
|
|
779
|
+
}
|
|
666
780
|
/**
|
|
667
781
|
* Asserts that the message matches its expected value. If the expected
|
|
668
782
|
* value is a regular expression, it is checked against the actual
|