@typescript-eslint/rule-tester 8.0.0-alpha.4 → 8.0.0-alpha.41

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 (47) hide show
  1. package/dist/RuleTester.d.ts +2 -2
  2. package/dist/RuleTester.d.ts.map +1 -1
  3. package/dist/RuleTester.js +418 -303
  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/ValidTestCase.d.ts +1 -1
  10. package/dist/types/ValidTestCase.d.ts.map +1 -1
  11. package/dist/types/index.d.ts +2 -2
  12. package/dist/types/index.d.ts.map +1 -1
  13. package/dist/utils/SourceCodeFixer.d.ts +6 -5
  14. package/dist/utils/SourceCodeFixer.d.ts.map +1 -1
  15. package/dist/utils/SourceCodeFixer.js +1 -2
  16. package/dist/utils/SourceCodeFixer.js.map +1 -1
  17. package/dist/utils/ajv.js +1 -2
  18. package/dist/utils/ajv.js.map +1 -1
  19. package/dist/utils/cloneDeeplyExcludesParent.js +2 -3
  20. package/dist/utils/cloneDeeplyExcludesParent.js.map +1 -1
  21. package/dist/utils/config-validator.js +1 -2
  22. package/dist/utils/config-validator.js.map +1 -1
  23. package/dist/utils/dependencyConstraints.d.ts.map +1 -1
  24. package/dist/utils/dependencyConstraints.js +4 -3
  25. package/dist/utils/dependencyConstraints.js.map +1 -1
  26. package/dist/utils/deprecation-warnings.js +1 -2
  27. package/dist/utils/deprecation-warnings.js.map +1 -1
  28. package/dist/utils/freezeDeeply.js +2 -3
  29. package/dist/utils/freezeDeeply.js.map +1 -1
  30. package/dist/utils/getRuleOptionsSchema.js +1 -2
  31. package/dist/utils/getRuleOptionsSchema.js.map +1 -1
  32. package/dist/utils/hasOwnProperty.d.ts.map +1 -1
  33. package/dist/utils/hasOwnProperty.js +1 -1
  34. package/dist/utils/hasOwnProperty.js.map +1 -1
  35. package/dist/utils/interpolate.d.ts +4 -0
  36. package/dist/utils/interpolate.d.ts.map +1 -1
  37. package/dist/utils/interpolate.js +10 -3
  38. package/dist/utils/interpolate.js.map +1 -1
  39. package/dist/utils/isReadonlyArray.js +1 -2
  40. package/dist/utils/isReadonlyArray.js.map +1 -1
  41. package/dist/utils/serialization.d.ts +7 -0
  42. package/dist/utils/serialization.d.ts.map +1 -0
  43. package/dist/utils/serialization.js +43 -0
  44. package/dist/utils/serialization.js.map +1 -0
  45. package/dist/utils/validationHelpers.js +6 -6
  46. package/dist/utils/validationHelpers.js.map +1 -1
  47. package/package.json +12 -6
@@ -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 isReadonlyArray_1 = require("./utils/isReadonlyArray");
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
- __classPrivateFieldSet(this, _RuleTester_testerConfig, (0, lodash_merge_1.default)({}, defaultConfig, testerConfig, {
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
- }), "f");
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
- __classPrivateFieldGet(this, _RuleTester_rules, "f")[name] = rule;
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 (__classPrivateFieldGet(this, _RuleTester_testerConfig, "f").dependencyConstraints &&
157
- !(0, dependencyConstraints_1.satisfiesAllDependencyConstraints)(__classPrivateFieldGet(this, _RuleTester_testerConfig, "f").dependencyConstraints)) {
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,12 @@ 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
- __classPrivateFieldGet(this, _RuleTester_linter, "f").defineRule(ruleName, Object.assign({}, rule, {
306
+ this.#linter.defineRule(ruleName, Object.assign({}, rule, {
188
307
  // Create a wrapper rule that freezes the `context` properties.
189
308
  create(context) {
190
309
  (0, freezeDeeply_1.freezeDeeply)(context.options);
@@ -193,8 +312,8 @@ class RuleTester extends TestFramework_1.TestFramework {
193
312
  return (typeof rule === 'function' ? rule : rule.create)(context);
194
313
  },
195
314
  }));
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);
315
+ this.#linter.defineRules(this.#rules);
316
+ const normalizedTests = this.#normalizeTests(test);
198
317
  function getTestMethod(test) {
199
318
  if (test.skip) {
200
319
  return 'itSkip';
@@ -219,7 +338,7 @@ class RuleTester extends TestFramework_1.TestFramework {
219
338
  return valid.name;
220
339
  })();
221
340
  constructor[getTestMethod(valid)]((0, validationHelpers_1.sanitize)(testName), () => {
222
- __classPrivateFieldGet(this, _RuleTester_instances, "m", _RuleTester_testValidTemplate).call(this, ruleName, rule, valid);
341
+ this.#testValidTemplate(ruleName, rule, valid, seenValidTestCases);
223
342
  });
224
343
  });
225
344
  });
@@ -234,7 +353,7 @@ class RuleTester extends TestFramework_1.TestFramework {
234
353
  return invalid.name;
235
354
  })();
236
355
  constructor[getTestMethod(invalid)]((0, validationHelpers_1.sanitize)(name), () => {
237
- __classPrivateFieldGet(this, _RuleTester_instances, "m", _RuleTester_testInvalidTemplate).call(this, ruleName, rule, invalid);
356
+ this.#testInvalidTemplate(ruleName, rule, invalid, seenInvalidTestCases);
238
357
  });
239
358
  });
240
359
  });
@@ -247,10 +366,9 @@ class RuleTester extends TestFramework_1.TestFramework {
247
366
  * Use @private instead of #private to expose it for testing purposes
248
367
  */
249
368
  runRuleForItem(ruleName, rule, item) {
250
- let config = (0, lodash_merge_1.default)({}, __classPrivateFieldGet(this, _RuleTester_testerConfig, "f"));
369
+ let config = (0, lodash_merge_1.default)({}, this.#testerConfig);
251
370
  let code;
252
371
  let filename;
253
- let output;
254
372
  let beforeAST;
255
373
  let afterAST;
256
374
  if (typeof item === 'string') {
@@ -273,7 +391,11 @@ class RuleTester extends TestFramework_1.TestFramework {
273
391
  */
274
392
  config = (0, lodash_merge_1.default)(config, itemConfig);
275
393
  }
276
- if (item.filename) {
394
+ if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'only')) {
395
+ node_assert_1.default.ok(typeof item.only === 'boolean', "Optional test case property 'only' must be a boolean");
396
+ }
397
+ if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'filename')) {
398
+ node_assert_1.default.ok(typeof item.filename === 'string', "Optional test case property 'filename' must be a string");
277
399
  filename = item.filename;
278
400
  }
279
401
  if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'options')) {
@@ -294,7 +416,7 @@ class RuleTester extends TestFramework_1.TestFramework {
294
416
  * The goal is to check whether or not AST was modified when
295
417
  * running the rule under test.
296
418
  */
297
- __classPrivateFieldGet(this, _RuleTester_linter, "f").defineRule('rule-tester/validate-ast', {
419
+ this.#linter.defineRule('rule-tester/validate-ast', {
298
420
  create() {
299
421
  return {
300
422
  Program(node) {
@@ -312,7 +434,9 @@ class RuleTester extends TestFramework_1.TestFramework {
312
434
  else {
313
435
  config.parser = require.resolve(TYPESCRIPT_ESLINT_PARSER);
314
436
  }
315
- __classPrivateFieldGet(this, _RuleTester_linter, "f").defineParser(config.parser, (0, validationHelpers_1.wrapParser)(require(config.parser)));
437
+ this.#linter.defineParser(config.parser,
438
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
439
+ (0, validationHelpers_1.wrapParser)(require(config.parser)));
316
440
  if (schema) {
317
441
  ajv.validateSchema(schema);
318
442
  if (ajv.errors) {
@@ -345,37 +469,52 @@ class RuleTester extends TestFramework_1.TestFramework {
345
469
  // Verify the code.
346
470
  // @ts-expect-error -- we don't define deprecated members on our types
347
471
  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)
472
+ let initialMessages = null;
473
+ let messages = null;
474
+ let fixedResult = null;
475
+ let passNumber = 0;
476
+ const outputs = [];
477
+ do {
478
+ passNumber++;
479
+ try {
480
+ // @ts-expect-error -- we don't define deprecated members on our types
481
+ eslint_1.SourceCode.prototype.getComments = validationHelpers_1.getCommentsDeprecation;
482
+ messages = this.#linter.verify(code, config, filename);
483
+ if (!initialMessages) {
484
+ initialMessages = messages;
485
+ }
486
+ }
487
+ finally {
488
+ // @ts-expect-error -- we don't define deprecated members on our types
489
+ eslint_1.SourceCode.prototype.getComments = getComments;
490
+ }
491
+ if (messages.length === 0) {
492
+ break;
493
+ }
494
+ const fatalErrorMessage = messages.find(m => m.fatal);
495
+ (0, node_assert_1.default)(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage?.message}`);
496
+ fixedResult = SourceCodeFixer.applyFixes(code, messages);
497
+ if (fixedResult.output === code) {
498
+ break;
499
+ }
500
+ code = fixedResult.output;
501
+ outputs.push(code);
502
+ // Verify if autofix makes a syntax error or not.
503
+ const errorMessageInFix = this.#linter
504
+ .verify(fixedResult.output, config, filename)
365
505
  .find(m => m.fatal);
366
506
  (0, node_assert_1.default)(!errorMessageInFix, [
367
507
  'A fatal parsing error occurred in autofix.',
368
508
  `Error: ${errorMessageInFix?.message}`,
369
509
  'Autofix output:',
370
- output,
510
+ fixedResult.output,
371
511
  ].join('\n'));
372
- }
373
- else {
374
- output = code;
375
- }
512
+ } while (fixedResult.fixed && passNumber < 10);
376
513
  return {
377
- messages,
378
- output,
514
+ config,
515
+ filename,
516
+ messages: initialMessages,
517
+ outputs,
379
518
  // is definitely assigned within the `rule-tester/validate-ast` rule
380
519
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
381
520
  beforeAST: beforeAST,
@@ -384,285 +523,261 @@ class RuleTester extends TestFramework_1.TestFramework {
384
523
  afterAST: (0, cloneDeeplyExcludesParent_1.cloneDeeplyExcludesParent)(afterAST),
385
524
  };
386
525
  }
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);
526
+ /**
527
+ * Check if the template is valid or not
528
+ * all valid cases go through this
529
+ */
530
+ #testValidTemplate(ruleName, rule, itemIn, seenValidTestCases) {
531
+ const item = typeof itemIn === 'object' ? itemIn : { code: itemIn };
532
+ node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
533
+ if (item.name) {
534
+ node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
404
535
  }
405
- return filename;
406
- };
407
- const normalizeTest = (test) => {
408
- if (test.parser === TYPESCRIPT_ESLINT_PARSER) {
409
- throw new Error(DUPLICATE_PARSER_ERROR_MESSAGE);
536
+ checkDuplicateTestCase(item, seenValidTestCases);
537
+ const result = this.runRuleForItem(ruleName, rule, item);
538
+ const messages = result.messages;
539
+ 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)));
540
+ assertASTDidntChange(result.beforeAST, result.afterAST);
541
+ }
542
+ /**
543
+ * Check if the template is invalid or not
544
+ * all invalid cases go through this.
545
+ */
546
+ #testInvalidTemplate(ruleName, rule, item, seenInvalidTestCases) {
547
+ node_assert_1.default.ok(typeof item.code === 'string', "Test case must specify a string value for 'code'");
548
+ if (item.name) {
549
+ node_assert_1.default.ok(typeof item.name === 'string', "Optional test case property 'name' must be a string");
410
550
  }
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
- }
551
+ node_assert_1.default.ok(item.errors || item.errors === 0, `Did not specify errors for an invalid test of ${ruleName}`);
552
+ if (Array.isArray(item.errors) && item.errors.length === 0) {
553
+ node_assert_1.default.fail('Invalid cases must have at least one error');
449
554
  }
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;
555
+ checkDuplicateTestCase(item, seenInvalidTestCases);
556
+ const ruleHasMetaMessages = (0, hasOwnProperty_1.hasOwnProperty)(rule, 'meta') && (0, hasOwnProperty_1.hasOwnProperty)(rule.meta, 'messages');
557
+ const friendlyIDList = ruleHasMetaMessages
558
+ ? `[${Object.keys(rule.meta.messages)
559
+ .map(key => `'${key}'`)
560
+ .join(', ')}]`
561
+ : null;
562
+ const result = this.runRuleForItem(ruleName, rule, item);
563
+ const messages = result.messages;
564
+ for (const message of messages) {
565
+ if ((0, hasOwnProperty_1.hasOwnProperty)(message, 'suggestions')) {
566
+ const seenMessageIndices = new Map();
567
+ for (let i = 0; i < message.suggestions.length; i += 1) {
568
+ const suggestionMessage = message.suggestions[i].desc;
569
+ const previous = seenMessageIndices.get(suggestionMessage);
570
+ 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.`);
571
+ seenMessageIndices.set(suggestionMessage, i);
572
+ }
462
573
  }
463
574
  }
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);
575
+ if (typeof item.errors === 'number') {
576
+ if (item.errors === 0) {
577
+ node_assert_1.default.fail("Invalid cases must have 'error' value greater than 0");
519
578
  }
579
+ 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
580
  }
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);
581
+ else {
582
+ 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)));
583
+ const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
584
+ for (let i = 0, l = item.errors.length; i < l; i++) {
585
+ const error = item.errors[i];
586
+ const message = messages[i];
587
+ (0, node_assert_1.default)(hasMessageOfThisRule, 'Error rule name should be the same as the name of the rule being tested');
588
+ if (typeof error === 'string' || error instanceof RegExp) {
589
+ // Just an error message.
590
+ assertMessageMatches(message.message, error);
591
+ 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
592
  }
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}"`);
593
+ else if (typeof error === 'object' && error != null) {
594
+ /*
595
+ * Error object.
596
+ * This may have a message, messageId, data, node type, line, and/or
597
+ * column.
598
+ */
599
+ Object.keys(error).forEach(propertyName => {
600
+ 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}.`);
601
+ });
602
+ // @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
603
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'message')) {
604
+ node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId'), "Error should not specify both 'message' and a 'messageId'.");
605
+ node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(error, 'data'), "Error should not specify both 'data' and 'message'.");
606
+ assertMessageMatches(message.message,
607
+ // @ts-expect-error -- we purposely don't define `message` on our types as the current standard is `messageId`
608
+ error.message);
571
609
  }
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}"`);
610
+ else if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'messageId')) {
611
+ node_assert_1.default.ok(ruleHasMetaMessages, "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'.");
612
+ if (!(0, hasOwnProperty_1.hasOwnProperty)(rule.meta.messages, error.messageId)) {
613
+ (0, node_assert_1.default)(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
614
+ }
615
+ node_assert_1.default.strictEqual(message.messageId, error.messageId, `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`);
616
+ const unsubstitutedPlaceholders = getUnsubstitutedMessagePlaceholders(message.message, rule.meta.messages[message.messageId], error.data);
617
+ 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.`);
618
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'data')) {
619
+ /*
620
+ * if data was provided, then directly compare the returned message to a synthetic
621
+ * interpolated message using the same message ID and data provided in the test.
622
+ * See https://github.com/eslint/eslint/issues/9890 for context.
623
+ */
624
+ const unformattedOriginalMessage = rule.meta.messages[error.messageId];
625
+ const rehydratedMessage = (0, interpolate_1.interpolate)(unformattedOriginalMessage, error.data);
626
+ node_assert_1.default.strictEqual(message.message, rehydratedMessage, `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`);
599
627
  }
600
628
  }
601
629
  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}"`);
630
+ node_assert_1.default.fail("Test error must specify either a 'messageId' or 'message'.");
631
+ }
632
+ if (error.type) {
633
+ node_assert_1.default.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
634
+ }
635
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'line')) {
636
+ node_assert_1.default.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
637
+ }
638
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'column')) {
639
+ node_assert_1.default.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
640
+ }
641
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'endLine')) {
642
+ node_assert_1.default.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
643
+ }
644
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'endColumn')) {
645
+ node_assert_1.default.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
646
+ }
647
+ 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.`);
648
+ if ((0, hasOwnProperty_1.hasOwnProperty)(error, 'suggestions')) {
649
+ // Support asserting there are no suggestions
650
+ const expectsSuggestions = Array.isArray(error.suggestions)
651
+ ? error.suggestions.length > 0
652
+ : Boolean(error.suggestions);
653
+ const hasSuggestions = message.suggestions !== void 0;
654
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
603
655
  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.`);
656
+ if (!hasSuggestions && expectsSuggestions) {
657
+ node_assert_1.default.ok(!error.suggestions, `Error should have suggestions on error with message: "${message.message}"`);
658
+ }
659
+ else if (hasSuggestions) {
660
+ node_assert_1.default.ok(expectsSuggestions, `Error should have no suggestions on error with message: "${message.message}"`);
661
+ if (typeof error.suggestions === 'number') {
662
+ node_assert_1.default.strictEqual(messageSuggestions.length, error.suggestions,
663
+ // It is possible that error.suggestions is a number
664
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
665
+ `Error should have ${error.suggestions} suggestions. Instead found ${messageSuggestions.length} suggestions`);
619
666
  }
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
- }
667
+ else if (Array.isArray(error.suggestions)) {
668
+ node_assert_1.default.strictEqual(messageSuggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${messageSuggestions.length} suggestions`);
669
+ error.suggestions.forEach((expectedSuggestion, index) => {
670
+ node_assert_1.default.ok(typeof expectedSuggestion === 'object' &&
671
+ expectedSuggestion != null, "Test suggestion in 'suggestions' array must be an object.");
672
+ Object.keys(expectedSuggestion).forEach(propertyName => {
673
+ 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}.`);
674
+ });
675
+ const actualSuggestion = messageSuggestions[index];
676
+ const suggestionPrefix = `Error Suggestion at index ${index}:`;
677
+ // @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
678
+ if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'desc')) {
679
+ // @ts-expect-error -- we purposely don't define `desc` on our types as the current standard is `messageId`
680
+ const expectedDesc = expectedSuggestion.desc;
681
+ node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data'), `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`);
682
+ node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'messageId'), `${suggestionPrefix} Test should not specify both 'desc' and 'messageId'.`);
683
+ node_assert_1.default.strictEqual(actualSuggestion.desc, expectedDesc, `${suggestionPrefix} desc should be "${expectedDesc}" but got "${actualSuggestion.desc}" instead.`);
684
+ }
685
+ else if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'messageId')) {
686
+ node_assert_1.default.ok(ruleHasMetaMessages, `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`);
687
+ 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}.`);
688
+ node_assert_1.default.strictEqual(actualSuggestion.messageId, expectedSuggestion.messageId, `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`);
689
+ const unsubstitutedPlaceholders = getUnsubstitutedMessagePlaceholders(actualSuggestion.desc, rule.meta.messages[expectedSuggestion.messageId], expectedSuggestion.data);
690
+ 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.`);
691
+ if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data')) {
692
+ const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
693
+ const rehydratedDesc = (0, interpolate_1.interpolate)(unformattedMetaMessage, expectedSuggestion.data);
694
+ node_assert_1.default.strictEqual(actualSuggestion.desc, rehydratedDesc, `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`);
695
+ }
696
+ }
697
+ else if ((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data')) {
698
+ node_assert_1.default.fail(`${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`);
699
+ }
700
+ else {
701
+ node_assert_1.default.fail(`${suggestionPrefix} Test must specify either 'messageId' or 'desc'.`);
702
+ }
703
+ node_assert_1.default.ok((0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'output'), `${suggestionPrefix} The "output" property is required.`);
704
+ const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [
705
+ actualSuggestion,
706
+ ]).output;
707
+ // Verify if suggestion fix makes a syntax error or not.
708
+ const errorMessageInSuggestion = this.#linter
709
+ .verify(codeWithAppliedSuggestion, result.config, result.filename)
710
+ .find(m => m.fatal);
711
+ (0, node_assert_1.default)(!errorMessageInSuggestion, [
712
+ 'A fatal parsing error occurred in suggestion fix.',
713
+ `Error: ${errorMessageInSuggestion?.message}`,
714
+ 'Suggestion output:',
715
+ codeWithAppliedSuggestion,
716
+ ].join('\n'));
717
+ 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}"`);
718
+ 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}"`);
719
+ });
629
720
  }
630
721
  else {
631
- node_assert_1.default.ok(!(0, hasOwnProperty_1.hasOwnProperty)(expectedSuggestion, 'data'), `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`);
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}"`);
722
+ node_assert_1.default.fail("Test error object property 'suggestions' should be an array or a number");
636
723
  }
637
- });
724
+ }
638
725
  }
639
726
  }
727
+ else {
728
+ // Message was an unexpected type
729
+ node_assert_1.default.fail(`Error should be a string, object, or RegExp, but found (${node_util_1.default.inspect(message)})`);
730
+ }
731
+ }
732
+ }
733
+ if ((0, hasOwnProperty_1.hasOwnProperty)(item, 'output')) {
734
+ if (item.output == null) {
735
+ if (result.outputs.length) {
736
+ node_assert_1.default.strictEqual(result.outputs[0], item.code, 'Expected no autofixes to be suggested.');
737
+ }
738
+ }
739
+ else if (typeof item.output === 'string') {
740
+ (0, node_assert_1.default)(result.outputs.length > 0, 'Expected autofix to be suggested.');
741
+ node_assert_1.default.strictEqual(result.outputs[0], item.output, 'Output is incorrect.');
742
+ if (result.outputs.length) {
743
+ 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.');
744
+ }
640
745
  }
641
746
  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)})`);
747
+ (0, node_assert_1.default)(result.outputs.length > 0, 'Expected autofix to be suggested.');
748
+ node_assert_1.default.deepStrictEqual(result.outputs, item.output, 'Outputs do not match.');
644
749
  }
645
750
  }
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
751
  else {
652
- node_assert_1.default.strictEqual(result.output, item.output, 'Output is incorrect.');
752
+ if (result.outputs.length) {
753
+ node_assert_1.default.strictEqual(result.outputs[0], item.code, "The rule fixed the code. Please add 'output' property.");
754
+ }
653
755
  }
756
+ assertASTDidntChange(result.beforeAST, result.afterAST);
654
757
  }
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
- };
758
+ }
759
+ exports.RuleTester = RuleTester;
660
760
  /**
661
761
  * Check if the AST was changed
662
762
  */
663
763
  function assertASTDidntChange(beforeAST, afterAST) {
664
764
  node_assert_1.default.deepStrictEqual(beforeAST, afterAST, 'Rule should not modify AST.');
665
765
  }
766
+ /**
767
+ * Check if this test case is a duplicate of one we have seen before.
768
+ */
769
+ function checkDuplicateTestCase(item, seenTestCases) {
770
+ if (!(0, serialization_1.isSerializable)(item)) {
771
+ /*
772
+ * If we can't serialize a test case (because it contains a function, RegExp, etc), skip the check.
773
+ * This might happen with properties like: options, plugins, settings, languageOptions.parser, languageOptions.parserOptions.
774
+ */
775
+ return;
776
+ }
777
+ const serializedTestCase = (0, json_stable_stringify_without_jsonify_1.default)(item);
778
+ (0, node_assert_1.default)(!seenTestCases.has(serializedTestCase), 'detected duplicate test case');
779
+ seenTestCases.add(serializedTestCase);
780
+ }
666
781
  /**
667
782
  * Asserts that the message matches its expected value. If the expected
668
783
  * value is a regular expression, it is checked against the actual