您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

903 行
36 KiB

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