massive update, probably broken
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / eslint / lib / rule-tester / rule-tester.js
1 /**
2  * @fileoverview Mocha test wrapper
3  * @author Ilya Volodin
4  */
5 "use strict";
6
7 /* global describe, it */
8
9 /*
10  * This is a wrapper around mocha to allow for DRY unittests for eslint
11  * Format:
12  * RuleTester.run("{ruleName}", {
13  *      valid: [
14  *          "{code}",
15  *          { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} }
16  *      ],
17  *      invalid: [
18  *          { code: "{code}", errors: {numErrors} },
19  *          { code: "{code}", errors: ["{errorMessage}"] },
20  *          { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] }
21  *      ]
22  *  });
23  *
24  * Variables:
25  * {code} - String that represents the code to be tested
26  * {options} - Arguments that are passed to the configurable rules.
27  * {globals} - An object representing a list of variables that are
28  *             registered as globals
29  * {parser} - String representing the parser to use
30  * {settings} - An object representing global settings for all rules
31  * {numErrors} - If failing case doesn't need to check error message,
32  *               this integer will specify how many errors should be
33  *               received
34  * {errorMessage} - Message that is returned by the rule on failure
35  * {errorNodeType} - AST node type that is returned by they rule as
36  *                   a cause of the failure.
37  */
38
39 //------------------------------------------------------------------------------
40 // Requirements
41 //------------------------------------------------------------------------------
42
43 const
44     assert = require("assert"),
45     path = require("path"),
46     util = require("util"),
47     merge = require("lodash.merge"),
48     equal = require("fast-deep-equal"),
49     Traverser = require("../../lib/shared/traverser"),
50     { getRuleOptionsSchema, validate } = require("../shared/config-validator"),
51     { Linter, SourceCodeFixer, interpolate } = require("../linter");
52
53 const ajv = require("../shared/ajv")({ strictDefaults: true });
54
55 const espreePath = require.resolve("espree");
56 const parserSymbol = Symbol.for("eslint.RuleTester.parser");
57
58 //------------------------------------------------------------------------------
59 // Typedefs
60 //------------------------------------------------------------------------------
61
62 /** @typedef {import("../shared/types").Parser} Parser */
63
64 /**
65  * A test case that is expected to pass lint.
66  * @typedef {Object} ValidTestCase
67  * @property {string} code Code for the test case.
68  * @property {any[]} [options] Options for the test case.
69  * @property {{ [name: string]: any }} [settings] Settings for the test case.
70  * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
71  * @property {string} [parser] The absolute path for the parser.
72  * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
73  * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
74  * @property {{ [name: string]: boolean }} [env] Environments for the test case.
75  * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
76  */
77
78 /**
79  * A test case that is expected to fail lint.
80  * @typedef {Object} InvalidTestCase
81  * @property {string} code Code for the test case.
82  * @property {number | Array<TestCaseError | string | RegExp>} errors Expected errors.
83  * @property {string | null} [output] The expected code after autofixes are applied. If set to `null`, the test runner will assert that no autofix is suggested.
84  * @property {any[]} [options] Options for the test case.
85  * @property {{ [name: string]: any }} [settings] Settings for the test case.
86  * @property {string} [filename] The fake filename for the test case. Useful for rules that make assertion about filenames.
87  * @property {string} [parser] The absolute path for the parser.
88  * @property {{ [name: string]: any }} [parserOptions] Options for the parser.
89  * @property {{ [name: string]: "readonly" | "writable" | "off" }} [globals] The additional global variables.
90  * @property {{ [name: string]: boolean }} [env] Environments for the test case.
91  * @property {boolean} [only] Run only this test case or the subset of test cases with this property.
92  */
93
94 /**
95  * A description of a reported error used in a rule tester test.
96  * @typedef {Object} TestCaseError
97  * @property {string | RegExp} [message] Message.
98  * @property {string} [messageId] Message ID.
99  * @property {string} [type] The type of the reported AST node.
100  * @property {{ [name: string]: string }} [data] The data used to fill the message template.
101  * @property {number} [line] The 1-based line number of the reported start location.
102  * @property {number} [column] The 1-based column number of the reported start location.
103  * @property {number} [endLine] The 1-based line number of the reported end location.
104  * @property {number} [endColumn] The 1-based column number of the reported end location.
105  */
106
107 //------------------------------------------------------------------------------
108 // Private Members
109 //------------------------------------------------------------------------------
110
111 /*
112  * testerDefaultConfig must not be modified as it allows to reset the tester to
113  * the initial default configuration
114  */
115 const testerDefaultConfig = { rules: {} };
116 let defaultConfig = { rules: {} };
117
118 /*
119  * List every parameters possible on a test case that are not related to eslint
120  * configuration
121  */
122 const RuleTesterParameters = [
123     "code",
124     "filename",
125     "options",
126     "errors",
127     "output",
128     "only"
129 ];
130
131 /*
132  * All allowed property names in error objects.
133  */
134 const errorObjectParameters = new Set([
135     "message",
136     "messageId",
137     "data",
138     "type",
139     "line",
140     "column",
141     "endLine",
142     "endColumn",
143     "suggestions"
144 ]);
145 const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`;
146
147 /*
148  * All allowed property names in suggestion objects.
149  */
150 const suggestionObjectParameters = new Set([
151     "desc",
152     "messageId",
153     "data",
154     "output"
155 ]);
156 const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`;
157
158 const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
159
160 /**
161  * Clones a given value deeply.
162  * Note: This ignores `parent` property.
163  * @param {any} x A value to clone.
164  * @returns {any} A cloned value.
165  */
166 function cloneDeeplyExcludesParent(x) {
167     if (typeof x === "object" && x !== null) {
168         if (Array.isArray(x)) {
169             return x.map(cloneDeeplyExcludesParent);
170         }
171
172         const retv = {};
173
174         for (const key in x) {
175             if (key !== "parent" && hasOwnProperty(x, key)) {
176                 retv[key] = cloneDeeplyExcludesParent(x[key]);
177             }
178         }
179
180         return retv;
181     }
182
183     return x;
184 }
185
186 /**
187  * Freezes a given value deeply.
188  * @param {any} x A value to freeze.
189  * @returns {void}
190  */
191 function freezeDeeply(x) {
192     if (typeof x === "object" && x !== null) {
193         if (Array.isArray(x)) {
194             x.forEach(freezeDeeply);
195         } else {
196             for (const key in x) {
197                 if (key !== "parent" && hasOwnProperty(x, key)) {
198                     freezeDeeply(x[key]);
199                 }
200             }
201         }
202         Object.freeze(x);
203     }
204 }
205
206 /**
207  * Replace control characters by `\u00xx` form.
208  * @param {string} text The text to sanitize.
209  * @returns {string} The sanitized text.
210  */
211 function sanitize(text) {
212     return text.replace(
213         /[\u0000-\u0009\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
214         c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
215     );
216 }
217
218 /**
219  * Define `start`/`end` properties as throwing error.
220  * @param {string} objName Object name used for error messages.
221  * @param {ASTNode} node The node to define.
222  * @returns {void}
223  */
224 function defineStartEndAsError(objName, node) {
225     Object.defineProperties(node, {
226         start: {
227             get() {
228                 throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`);
229             },
230             configurable: true,
231             enumerable: false
232         },
233         end: {
234             get() {
235                 throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`);
236             },
237             configurable: true,
238             enumerable: false
239         }
240     });
241 }
242
243
244 /**
245  * Define `start`/`end` properties of all nodes of the given AST as throwing error.
246  * @param {ASTNode} ast The root node to errorize `start`/`end` properties.
247  * @param {Object} [visitorKeys] Visitor keys to be used for traversing the given ast.
248  * @returns {void}
249  */
250 function defineStartEndAsErrorInTree(ast, visitorKeys) {
251     Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") });
252     ast.tokens.forEach(defineStartEndAsError.bind(null, "token"));
253     ast.comments.forEach(defineStartEndAsError.bind(null, "token"));
254 }
255
256 /**
257  * Wraps the given parser in order to intercept and modify return values from the `parse` and `parseForESLint` methods, for test purposes.
258  * In particular, to modify ast nodes, tokens and comments to throw on access to their `start` and `end` properties.
259  * @param {Parser} parser Parser object.
260  * @returns {Parser} Wrapped parser object.
261  */
262 function wrapParser(parser) {
263
264     if (typeof parser.parseForESLint === "function") {
265         return {
266             [parserSymbol]: parser,
267             parseForESLint(...args) {
268                 const ret = parser.parseForESLint(...args);
269
270                 defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys);
271                 return ret;
272             }
273         };
274     }
275
276     return {
277         [parserSymbol]: parser,
278         parse(...args) {
279             const ast = parser.parse(...args);
280
281             defineStartEndAsErrorInTree(ast);
282             return ast;
283         }
284     };
285 }
286
287 //------------------------------------------------------------------------------
288 // Public Interface
289 //------------------------------------------------------------------------------
290
291 // default separators for testing
292 const DESCRIBE = Symbol("describe");
293 const IT = Symbol("it");
294 const IT_ONLY = Symbol("itOnly");
295
296 /**
297  * This is `it` default handler if `it` don't exist.
298  * @this {Mocha}
299  * @param {string} text The description of the test case.
300  * @param {Function} method The logic of the test case.
301  * @returns {any} Returned value of `method`.
302  */
303 function itDefaultHandler(text, method) {
304     try {
305         return method.call(this);
306     } catch (err) {
307         if (err instanceof assert.AssertionError) {
308             err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
309         }
310         throw err;
311     }
312 }
313
314 /**
315  * This is `describe` default handler if `describe` don't exist.
316  * @this {Mocha}
317  * @param {string} text The description of the test case.
318  * @param {Function} method The logic of the test case.
319  * @returns {any} Returned value of `method`.
320  */
321 function describeDefaultHandler(text, method) {
322     return method.call(this);
323 }
324
325 class RuleTester {
326
327     /**
328      * Creates a new instance of RuleTester.
329      * @param {Object} [testerConfig] Optional, extra configuration for the tester
330      */
331     constructor(testerConfig) {
332
333         /**
334          * The configuration to use for this tester. Combination of the tester
335          * configuration and the default configuration.
336          * @type {Object}
337          */
338         this.testerConfig = merge(
339             {},
340             defaultConfig,
341             testerConfig,
342             { rules: { "rule-tester/validate-ast": "error" } }
343         );
344
345         /**
346          * Rule definitions to define before tests.
347          * @type {Object}
348          */
349         this.rules = {};
350         this.linter = new Linter();
351     }
352
353     /**
354      * Set the configuration to use for all future tests
355      * @param {Object} config the configuration to use.
356      * @returns {void}
357      */
358     static setDefaultConfig(config) {
359         if (typeof config !== "object") {
360             throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
361         }
362         defaultConfig = config;
363
364         // Make sure the rules object exists since it is assumed to exist later
365         defaultConfig.rules = defaultConfig.rules || {};
366     }
367
368     /**
369      * Get the current configuration used for all tests
370      * @returns {Object} the current configuration
371      */
372     static getDefaultConfig() {
373         return defaultConfig;
374     }
375
376     /**
377      * Reset the configuration to the initial configuration of the tester removing
378      * any changes made until now.
379      * @returns {void}
380      */
381     static resetDefaultConfig() {
382         defaultConfig = merge({}, testerDefaultConfig);
383     }
384
385
386     /*
387      * If people use `mocha test.js --watch` command, `describe` and `it` function
388      * instances are different for each execution. So `describe` and `it` should get fresh instance
389      * always.
390      */
391     static get describe() {
392         return (
393             this[DESCRIBE] ||
394             (typeof describe === "function" ? describe : describeDefaultHandler)
395         );
396     }
397
398     static set describe(value) {
399         this[DESCRIBE] = value;
400     }
401
402     static get it() {
403         return (
404             this[IT] ||
405             (typeof it === "function" ? it : itDefaultHandler)
406         );
407     }
408
409     static set it(value) {
410         this[IT] = value;
411     }
412
413     /**
414      * Adds the `only` property to a test to run it in isolation.
415      * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
416      * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
417      */
418     static only(item) {
419         if (typeof item === "string") {
420             return { code: item, only: true };
421         }
422
423         return { ...item, only: true };
424     }
425
426     static get itOnly() {
427         if (typeof this[IT_ONLY] === "function") {
428             return this[IT_ONLY];
429         }
430         if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
431             return Function.bind.call(this[IT].only, this[IT]);
432         }
433         if (typeof it === "function" && typeof it.only === "function") {
434             return Function.bind.call(it.only, it);
435         }
436
437         if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
438             throw new Error(
439                 "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
440                 "See https://eslint.org/docs/developer-guide/nodejs-api#customizing-ruletester for more."
441             );
442         }
443         if (typeof it === "function") {
444             throw new Error("The current test framework does not support exclusive tests with `only`.");
445         }
446         throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
447     }
448
449     static set itOnly(value) {
450         this[IT_ONLY] = value;
451     }
452
453     /**
454      * Define a rule for one particular run of tests.
455      * @param {string} name The name of the rule to define.
456      * @param {Function} rule The rule definition.
457      * @returns {void}
458      */
459     defineRule(name, rule) {
460         this.rules[name] = rule;
461     }
462
463     /**
464      * Adds a new rule test to execute.
465      * @param {string} ruleName The name of the rule to run.
466      * @param {Function} rule The rule to test.
467      * @param {{
468      *   valid: (ValidTestCase | string)[],
469      *   invalid: InvalidTestCase[]
470      * }} test The collection of tests to run.
471      * @returns {void}
472      */
473     run(ruleName, rule, test) {
474
475         const testerConfig = this.testerConfig,
476             requiredScenarios = ["valid", "invalid"],
477             scenarioErrors = [],
478             linter = this.linter;
479
480         if (!test || typeof test !== "object") {
481             throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
482         }
483
484         requiredScenarios.forEach(scenarioType => {
485             if (!test[scenarioType]) {
486                 scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
487             }
488         });
489
490         if (scenarioErrors.length > 0) {
491             throw new Error([
492                 `Test Scenarios for rule ${ruleName} is invalid:`
493             ].concat(scenarioErrors).join("\n"));
494         }
495
496
497         linter.defineRule(ruleName, Object.assign({}, rule, {
498
499             // Create a wrapper rule that freezes the `context` properties.
500             create(context) {
501                 freezeDeeply(context.options);
502                 freezeDeeply(context.settings);
503                 freezeDeeply(context.parserOptions);
504
505                 return (typeof rule === "function" ? rule : rule.create)(context);
506             }
507         }));
508
509         linter.defineRules(this.rules);
510
511         /**
512          * Run the rule for the given item
513          * @param {string|Object} item Item to run the rule against
514          * @returns {Object} Eslint run result
515          * @private
516          */
517         function runRuleForItem(item) {
518             let config = merge({}, testerConfig),
519                 code, filename, output, beforeAST, afterAST;
520
521             if (typeof item === "string") {
522                 code = item;
523             } else {
524                 code = item.code;
525
526                 /*
527                  * Assumes everything on the item is a config except for the
528                  * parameters used by this tester
529                  */
530                 const itemConfig = { ...item };
531
532                 for (const parameter of RuleTesterParameters) {
533                     delete itemConfig[parameter];
534                 }
535
536                 /*
537                  * Create the config object from the tester config and this item
538                  * specific configurations.
539                  */
540                 config = merge(
541                     config,
542                     itemConfig
543                 );
544             }
545
546             if (item.filename) {
547                 filename = item.filename;
548             }
549
550             if (hasOwnProperty(item, "options")) {
551                 assert(Array.isArray(item.options), "options must be an array");
552                 config.rules[ruleName] = [1].concat(item.options);
553             } else {
554                 config.rules[ruleName] = 1;
555             }
556
557             const schema = getRuleOptionsSchema(rule);
558
559             /*
560              * Setup AST getters.
561              * The goal is to check whether or not AST was modified when
562              * running the rule under test.
563              */
564             linter.defineRule("rule-tester/validate-ast", () => ({
565                 Program(node) {
566                     beforeAST = cloneDeeplyExcludesParent(node);
567                 },
568                 "Program:exit"(node) {
569                     afterAST = node;
570                 }
571             }));
572
573             if (typeof config.parser === "string") {
574                 assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
575             } else {
576                 config.parser = espreePath;
577             }
578
579             linter.defineParser(config.parser, wrapParser(require(config.parser)));
580
581             if (schema) {
582                 ajv.validateSchema(schema);
583
584                 if (ajv.errors) {
585                     const errors = ajv.errors.map(error => {
586                         const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
587
588                         return `\t${field}: ${error.message}`;
589                     }).join("\n");
590
591                     throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
592                 }
593
594                 /*
595                  * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
596                  * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
597                  * the schema (e.g. using invalid defaults in a schema), and only one of these errors can be reported at a time. As a result,
598                  * the schema is compiled here separately from checking for `validateSchema` errors.
599                  */
600                 try {
601                     ajv.compile(schema);
602                 } catch (err) {
603                     throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
604                 }
605             }
606
607             validate(config, "rule-tester", id => (id === ruleName ? rule : null));
608
609             // Verify the code.
610             const messages = linter.verify(code, config, filename);
611             const fatalErrorMessage = messages.find(m => m.fatal);
612
613             assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
614
615             // Verify if autofix makes a syntax error or not.
616             if (messages.some(m => m.fix)) {
617                 output = SourceCodeFixer.applyFixes(code, messages).output;
618                 const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
619
620                 assert(!errorMessageInFix, [
621                     "A fatal parsing error occurred in autofix.",
622                     `Error: ${errorMessageInFix && errorMessageInFix.message}`,
623                     "Autofix output:",
624                     output
625                 ].join("\n"));
626             } else {
627                 output = code;
628             }
629
630             return {
631                 messages,
632                 output,
633                 beforeAST,
634                 afterAST: cloneDeeplyExcludesParent(afterAST)
635             };
636         }
637
638         /**
639          * Check if the AST was changed
640          * @param {ASTNode} beforeAST AST node before running
641          * @param {ASTNode} afterAST AST node after running
642          * @returns {void}
643          * @private
644          */
645         function assertASTDidntChange(beforeAST, afterAST) {
646             if (!equal(beforeAST, afterAST)) {
647                 assert.fail("Rule should not modify AST.");
648             }
649         }
650
651         /**
652          * Check if the template is valid or not
653          * all valid cases go through this
654          * @param {string|Object} item Item to run the rule against
655          * @returns {void}
656          * @private
657          */
658         function testValidTemplate(item) {
659             const result = runRuleForItem(item);
660             const messages = result.messages;
661
662             assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
663                 messages.length,
664                 util.inspect(messages)));
665
666             assertASTDidntChange(result.beforeAST, result.afterAST);
667         }
668
669         /**
670          * Asserts that the message matches its expected value. If the expected
671          * value is a regular expression, it is checked against the actual
672          * value.
673          * @param {string} actual Actual value
674          * @param {string|RegExp} expected Expected value
675          * @returns {void}
676          * @private
677          */
678         function assertMessageMatches(actual, expected) {
679             if (expected instanceof RegExp) {
680
681                 // assert.js doesn't have a built-in RegExp match function
682                 assert.ok(
683                     expected.test(actual),
684                     `Expected '${actual}' to match ${expected}`
685                 );
686             } else {
687                 assert.strictEqual(actual, expected);
688             }
689         }
690
691         /**
692          * Check if the template is invalid or not
693          * all invalid cases go through this.
694          * @param {string|Object} item Item to run the rule against
695          * @returns {void}
696          * @private
697          */
698         function testInvalidTemplate(item) {
699             assert.ok(item.errors || item.errors === 0,
700                 `Did not specify errors for an invalid test of ${ruleName}`);
701
702             if (Array.isArray(item.errors) && item.errors.length === 0) {
703                 assert.fail("Invalid cases must have at least one error");
704             }
705
706             const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
707             const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;
708
709             const result = runRuleForItem(item);
710             const messages = result.messages;
711
712             if (typeof item.errors === "number") {
713
714                 if (item.errors === 0) {
715                     assert.fail("Invalid cases must have 'error' value greater than 0");
716                 }
717
718                 assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
719                     item.errors,
720                     item.errors === 1 ? "" : "s",
721                     messages.length,
722                     util.inspect(messages)));
723             } else {
724                 assert.strictEqual(
725                     messages.length, item.errors.length, util.format(
726                         "Should have %d error%s but had %d: %s",
727                         item.errors.length,
728                         item.errors.length === 1 ? "" : "s",
729                         messages.length,
730                         util.inspect(messages)
731                     )
732                 );
733
734                 const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
735
736                 for (let i = 0, l = item.errors.length; i < l; i++) {
737                     const error = item.errors[i];
738                     const message = messages[i];
739
740                     assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
741
742                     if (typeof error === "string" || error instanceof RegExp) {
743
744                         // Just an error message.
745                         assertMessageMatches(message.message, error);
746                     } else if (typeof error === "object" && error !== null) {
747
748                         /*
749                          * Error object.
750                          * This may have a message, messageId, data, node type, line, and/or
751                          * column.
752                          */
753
754                         Object.keys(error).forEach(propertyName => {
755                             assert.ok(
756                                 errorObjectParameters.has(propertyName),
757                                 `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
758                             );
759                         });
760
761                         if (hasOwnProperty(error, "message")) {
762                             assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
763                             assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
764                             assertMessageMatches(message.message, error.message);
765                         } else if (hasOwnProperty(error, "messageId")) {
766                             assert.ok(
767                                 ruleHasMetaMessages,
768                                 "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
769                             );
770                             if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
771                                 assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
772                             }
773                             assert.strictEqual(
774                                 message.messageId,
775                                 error.messageId,
776                                 `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
777                             );
778                             if (hasOwnProperty(error, "data")) {
779
780                                 /*
781                                  *  if data was provided, then directly compare the returned message to a synthetic
782                                  *  interpolated message using the same message ID and data provided in the test.
783                                  *  See https://github.com/eslint/eslint/issues/9890 for context.
784                                  */
785                                 const unformattedOriginalMessage = rule.meta.messages[error.messageId];
786                                 const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
787
788                                 assert.strictEqual(
789                                     message.message,
790                                     rehydratedMessage,
791                                     `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
792                                 );
793                             }
794                         }
795
796                         assert.ok(
797                             hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
798                             "Error must specify 'messageId' if 'data' is used."
799                         );
800
801                         if (error.type) {
802                             assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
803                         }
804
805                         if (hasOwnProperty(error, "line")) {
806                             assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
807                         }
808
809                         if (hasOwnProperty(error, "column")) {
810                             assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
811                         }
812
813                         if (hasOwnProperty(error, "endLine")) {
814                             assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
815                         }
816
817                         if (hasOwnProperty(error, "endColumn")) {
818                             assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
819                         }
820
821                         if (hasOwnProperty(error, "suggestions")) {
822
823                             // Support asserting there are no suggestions
824                             if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
825                                 if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
826                                     assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
827                                 }
828                             } else {
829                                 assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
830                                 assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
831
832                                 error.suggestions.forEach((expectedSuggestion, index) => {
833                                     assert.ok(
834                                         typeof expectedSuggestion === "object" && expectedSuggestion !== null,
835                                         "Test suggestion in 'suggestions' array must be an object."
836                                     );
837                                     Object.keys(expectedSuggestion).forEach(propertyName => {
838                                         assert.ok(
839                                             suggestionObjectParameters.has(propertyName),
840                                             `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
841                                         );
842                                     });
843
844                                     const actualSuggestion = message.suggestions[index];
845                                     const suggestionPrefix = `Error Suggestion at index ${index} :`;
846
847                                     if (hasOwnProperty(expectedSuggestion, "desc")) {
848                                         assert.ok(
849                                             !hasOwnProperty(expectedSuggestion, "data"),
850                                             `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
851                                         );
852                                         assert.strictEqual(
853                                             actualSuggestion.desc,
854                                             expectedSuggestion.desc,
855                                             `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
856                                         );
857                                     }
858
859                                     if (hasOwnProperty(expectedSuggestion, "messageId")) {
860                                         assert.ok(
861                                             ruleHasMetaMessages,
862                                             `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
863                                         );
864                                         assert.ok(
865                                             hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
866                                             `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
867                                         );
868                                         assert.strictEqual(
869                                             actualSuggestion.messageId,
870                                             expectedSuggestion.messageId,
871                                             `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
872                                         );
873                                         if (hasOwnProperty(expectedSuggestion, "data")) {
874                                             const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
875                                             const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);
876
877                                             assert.strictEqual(
878                                                 actualSuggestion.desc,
879                                                 rehydratedDesc,
880                                                 `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
881                                             );
882                                         }
883                                     } else {
884                                         assert.ok(
885                                             !hasOwnProperty(expectedSuggestion, "data"),
886                                             `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
887                                         );
888                                     }
889
890                                     if (hasOwnProperty(expectedSuggestion, "output")) {
891                                         const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
892
893                                         assert.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}"`);
894                                     }
895                                 });
896                             }
897                         }
898                     } else {
899
900                         // Message was an unexpected type
901                         assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
902                     }
903                 }
904             }
905
906             if (hasOwnProperty(item, "output")) {
907                 if (item.output === null) {
908                     assert.strictEqual(
909                         result.output,
910                         item.code,
911                         "Expected no autofixes to be suggested"
912                     );
913                 } else {
914                     assert.strictEqual(result.output, item.output, "Output is incorrect.");
915                 }
916             } else {
917                 assert.strictEqual(
918                     result.output,
919                     item.code,
920                     "The rule fixed the code. Please add 'output' property."
921                 );
922             }
923
924             // Rules that produce fixes must have `meta.fixable` property.
925             if (result.output !== item.code) {
926                 assert.ok(
927                     hasOwnProperty(rule, "meta"),
928                     "Fixable rules should export a `meta.fixable` property."
929                 );
930
931                 // Linter throws if a rule that produced a fix has `meta` but doesn't have `meta.fixable`.
932             }
933
934             assertASTDidntChange(result.beforeAST, result.afterAST);
935         }
936
937         /*
938          * This creates a mocha test suite and pipes all supplied info through
939          * one of the templates above.
940          */
941         RuleTester.describe(ruleName, () => {
942             RuleTester.describe("valid", () => {
943                 test.valid.forEach(valid => {
944                     RuleTester[valid.only ? "itOnly" : "it"](
945                         sanitize(typeof valid === "object" ? valid.code : valid),
946                         () => {
947                             testValidTemplate(valid);
948                         }
949                     );
950                 });
951             });
952
953             RuleTester.describe("invalid", () => {
954                 test.invalid.forEach(invalid => {
955                     RuleTester[invalid.only ? "itOnly" : "it"](
956                         sanitize(invalid.code),
957                         () => {
958                             testInvalidTemplate(invalid);
959                         }
960                     );
961                 });
962             });
963         });
964     }
965 }
966
967 RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
968
969 module.exports = RuleTester;