rule-tester.js 36 KB

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