rule-tester.js 39 KB

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