@typescript-eslint/rule-tester 8.0.0-alpha.6 → 8.0.0-alpha.60

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