rule-tester.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  1. /**
  2. * @fileoverview Mocha test wrapper
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. /* globals describe, it -- Mocha globals */
  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. * Emit a deprecation warning if function-style format is being used.
  275. * @param {string} ruleName Name of the rule.
  276. * @returns {void}
  277. */
  278. function emitLegacyRuleAPIWarning(ruleName) {
  279. if (!emitLegacyRuleAPIWarning[`warned-${ruleName}`]) {
  280. emitLegacyRuleAPIWarning[`warned-${ruleName}`] = true;
  281. process.emitWarning(
  282. `"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/developer-guide/working-with-rules`,
  283. "DeprecationWarning"
  284. );
  285. }
  286. }
  287. /**
  288. * Emit a deprecation warning if rule has options but is missing the "meta.schema" property
  289. * @param {string} ruleName Name of the rule.
  290. * @returns {void}
  291. */
  292. function emitMissingSchemaWarning(ruleName) {
  293. if (!emitMissingSchemaWarning[`warned-${ruleName}`]) {
  294. emitMissingSchemaWarning[`warned-${ruleName}`] = true;
  295. process.emitWarning(
  296. `"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/developer-guide/working-with-rules#options-schemas`,
  297. "DeprecationWarning"
  298. );
  299. }
  300. }
  301. //------------------------------------------------------------------------------
  302. // Public Interface
  303. //------------------------------------------------------------------------------
  304. // default separators for testing
  305. const DESCRIBE = Symbol("describe");
  306. const IT = Symbol("it");
  307. const IT_ONLY = Symbol("itOnly");
  308. /**
  309. * This is `it` default handler if `it` don't exist.
  310. * @this {Mocha}
  311. * @param {string} text The description of the test case.
  312. * @param {Function} method The logic of the test case.
  313. * @throws {Error} Any error upon execution of `method`.
  314. * @returns {any} Returned value of `method`.
  315. */
  316. function itDefaultHandler(text, method) {
  317. try {
  318. return method.call(this);
  319. } catch (err) {
  320. if (err instanceof assert.AssertionError) {
  321. err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
  322. }
  323. throw err;
  324. }
  325. }
  326. /**
  327. * This is `describe` default handler if `describe` don't exist.
  328. * @this {Mocha}
  329. * @param {string} text The description of the test case.
  330. * @param {Function} method The logic of the test case.
  331. * @returns {any} Returned value of `method`.
  332. */
  333. function describeDefaultHandler(text, method) {
  334. return method.call(this);
  335. }
  336. /**
  337. * Mocha test wrapper.
  338. */
  339. class RuleTester {
  340. /**
  341. * Creates a new instance of RuleTester.
  342. * @param {Object} [testerConfig] Optional, extra configuration for the tester
  343. */
  344. constructor(testerConfig) {
  345. /**
  346. * The configuration to use for this tester. Combination of the tester
  347. * configuration and the default configuration.
  348. * @type {Object}
  349. */
  350. this.testerConfig = merge(
  351. {},
  352. defaultConfig,
  353. testerConfig,
  354. { rules: { "rule-tester/validate-ast": "error" } }
  355. );
  356. /**
  357. * Rule definitions to define before tests.
  358. * @type {Object}
  359. */
  360. this.rules = {};
  361. this.linter = new Linter();
  362. }
  363. /**
  364. * Set the configuration to use for all future tests
  365. * @param {Object} config the configuration to use.
  366. * @throws {TypeError} If non-object config.
  367. * @returns {void}
  368. */
  369. static setDefaultConfig(config) {
  370. if (typeof config !== "object") {
  371. throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
  372. }
  373. defaultConfig = config;
  374. // Make sure the rules object exists since it is assumed to exist later
  375. defaultConfig.rules = defaultConfig.rules || {};
  376. }
  377. /**
  378. * Get the current configuration used for all tests
  379. * @returns {Object} the current configuration
  380. */
  381. static getDefaultConfig() {
  382. return defaultConfig;
  383. }
  384. /**
  385. * Reset the configuration to the initial configuration of the tester removing
  386. * any changes made until now.
  387. * @returns {void}
  388. */
  389. static resetDefaultConfig() {
  390. defaultConfig = merge({}, testerDefaultConfig);
  391. }
  392. /*
  393. * If people use `mocha test.js --watch` command, `describe` and `it` function
  394. * instances are different for each execution. So `describe` and `it` should get fresh instance
  395. * always.
  396. */
  397. static get describe() {
  398. return (
  399. this[DESCRIBE] ||
  400. (typeof describe === "function" ? describe : describeDefaultHandler)
  401. );
  402. }
  403. static set describe(value) {
  404. this[DESCRIBE] = value;
  405. }
  406. static get it() {
  407. return (
  408. this[IT] ||
  409. (typeof it === "function" ? it : itDefaultHandler)
  410. );
  411. }
  412. static set it(value) {
  413. this[IT] = value;
  414. }
  415. /**
  416. * Adds the `only` property to a test to run it in isolation.
  417. * @param {string | ValidTestCase | InvalidTestCase} item A single test to run by itself.
  418. * @returns {ValidTestCase | InvalidTestCase} The test with `only` set.
  419. */
  420. static only(item) {
  421. if (typeof item === "string") {
  422. return { code: item, only: true };
  423. }
  424. return { ...item, only: true };
  425. }
  426. static get itOnly() {
  427. if (typeof this[IT_ONLY] === "function") {
  428. return this[IT_ONLY];
  429. }
  430. if (typeof this[IT] === "function" && typeof this[IT].only === "function") {
  431. return Function.bind.call(this[IT].only, this[IT]);
  432. }
  433. if (typeof it === "function" && typeof it.only === "function") {
  434. return Function.bind.call(it.only, it);
  435. }
  436. if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") {
  437. throw new Error(
  438. "Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" +
  439. "See https://eslint.org/docs/developer-guide/nodejs-api#customizing-ruletester for more."
  440. );
  441. }
  442. if (typeof it === "function") {
  443. throw new Error("The current test framework does not support exclusive tests with `only`.");
  444. }
  445. throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha.");
  446. }
  447. static set itOnly(value) {
  448. this[IT_ONLY] = value;
  449. }
  450. /**
  451. * Define a rule for one particular run of tests.
  452. * @param {string} name The name of the rule to define.
  453. * @param {Function} rule The rule definition.
  454. * @returns {void}
  455. */
  456. defineRule(name, rule) {
  457. this.rules[name] = rule;
  458. }
  459. /**
  460. * Adds a new rule test to execute.
  461. * @param {string} ruleName The name of the rule to run.
  462. * @param {Function} rule The rule to test.
  463. * @param {{
  464. * valid: (ValidTestCase | string)[],
  465. * invalid: InvalidTestCase[]
  466. * }} test The collection of tests to run.
  467. * @throws {TypeError|Error} If non-object `test`, or if a required
  468. * scenario of the given type is missing.
  469. * @returns {void}
  470. */
  471. run(ruleName, rule, test) {
  472. const testerConfig = this.testerConfig,
  473. requiredScenarios = ["valid", "invalid"],
  474. scenarioErrors = [],
  475. linter = this.linter;
  476. if (!test || typeof test !== "object") {
  477. throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
  478. }
  479. requiredScenarios.forEach(scenarioType => {
  480. if (!test[scenarioType]) {
  481. scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
  482. }
  483. });
  484. if (scenarioErrors.length > 0) {
  485. throw new Error([
  486. `Test Scenarios for rule ${ruleName} is invalid:`
  487. ].concat(scenarioErrors).join("\n"));
  488. }
  489. if (typeof rule === "function") {
  490. emitLegacyRuleAPIWarning(ruleName);
  491. }
  492. linter.defineRule(ruleName, Object.assign({}, rule, {
  493. // Create a wrapper rule that freezes the `context` properties.
  494. create(context) {
  495. freezeDeeply(context.options);
  496. freezeDeeply(context.settings);
  497. freezeDeeply(context.parserOptions);
  498. return (typeof rule === "function" ? rule : rule.create)(context);
  499. }
  500. }));
  501. linter.defineRules(this.rules);
  502. /**
  503. * Run the rule for the given item
  504. * @param {string|Object} item Item to run the rule against
  505. * @throws {Error} If an invalid schema.
  506. * @returns {Object} Eslint run result
  507. * @private
  508. */
  509. function runRuleForItem(item) {
  510. let config = merge({}, testerConfig),
  511. code, filename, output, beforeAST, afterAST;
  512. if (typeof item === "string") {
  513. code = item;
  514. } else {
  515. code = item.code;
  516. /*
  517. * Assumes everything on the item is a config except for the
  518. * parameters used by this tester
  519. */
  520. const itemConfig = { ...item };
  521. for (const parameter of RuleTesterParameters) {
  522. delete itemConfig[parameter];
  523. }
  524. /*
  525. * Create the config object from the tester config and this item
  526. * specific configurations.
  527. */
  528. config = merge(
  529. config,
  530. itemConfig
  531. );
  532. }
  533. if (item.filename) {
  534. filename = item.filename;
  535. }
  536. if (hasOwnProperty(item, "options")) {
  537. assert(Array.isArray(item.options), "options must be an array");
  538. if (
  539. item.options.length > 0 &&
  540. typeof rule === "object" &&
  541. (
  542. !rule.meta || (rule.meta && (typeof rule.meta.schema === "undefined" || rule.meta.schema === null))
  543. )
  544. ) {
  545. emitMissingSchemaWarning(ruleName);
  546. }
  547. config.rules[ruleName] = [1].concat(item.options);
  548. } else {
  549. config.rules[ruleName] = 1;
  550. }
  551. const schema = getRuleOptionsSchema(rule);
  552. /*
  553. * Setup AST getters.
  554. * The goal is to check whether or not AST was modified when
  555. * running the rule under test.
  556. */
  557. linter.defineRule("rule-tester/validate-ast", () => ({
  558. Program(node) {
  559. beforeAST = cloneDeeplyExcludesParent(node);
  560. },
  561. "Program:exit"(node) {
  562. afterAST = node;
  563. }
  564. }));
  565. if (typeof config.parser === "string") {
  566. assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
  567. } else {
  568. config.parser = espreePath;
  569. }
  570. linter.defineParser(config.parser, wrapParser(require(config.parser)));
  571. if (schema) {
  572. ajv.validateSchema(schema);
  573. if (ajv.errors) {
  574. const errors = ajv.errors.map(error => {
  575. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  576. return `\t${field}: ${error.message}`;
  577. }).join("\n");
  578. throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
  579. }
  580. /*
  581. * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
  582. * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
  583. * 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,
  584. * the schema is compiled here separately from checking for `validateSchema` errors.
  585. */
  586. try {
  587. ajv.compile(schema);
  588. } catch (err) {
  589. throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
  590. }
  591. }
  592. validate(config, "rule-tester", id => (id === ruleName ? rule : null));
  593. // Verify the code.
  594. const { getComments } = SourceCode.prototype;
  595. let messages;
  596. try {
  597. SourceCode.prototype.getComments = getCommentsDeprecation;
  598. messages = linter.verify(code, config, filename);
  599. } finally {
  600. SourceCode.prototype.getComments = getComments;
  601. }
  602. const fatalErrorMessage = messages.find(m => m.fatal);
  603. assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
  604. // Verify if autofix makes a syntax error or not.
  605. if (messages.some(m => m.fix)) {
  606. output = SourceCodeFixer.applyFixes(code, messages).output;
  607. const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
  608. assert(!errorMessageInFix, [
  609. "A fatal parsing error occurred in autofix.",
  610. `Error: ${errorMessageInFix && errorMessageInFix.message}`,
  611. "Autofix output:",
  612. output
  613. ].join("\n"));
  614. } else {
  615. output = code;
  616. }
  617. return {
  618. messages,
  619. output,
  620. beforeAST,
  621. afterAST: cloneDeeplyExcludesParent(afterAST)
  622. };
  623. }
  624. /**
  625. * Check if the AST was changed
  626. * @param {ASTNode} beforeAST AST node before running
  627. * @param {ASTNode} afterAST AST node after running
  628. * @returns {void}
  629. * @private
  630. */
  631. function assertASTDidntChange(beforeAST, afterAST) {
  632. if (!equal(beforeAST, afterAST)) {
  633. assert.fail("Rule should not modify AST.");
  634. }
  635. }
  636. /**
  637. * Check if the template is valid or not
  638. * all valid cases go through this
  639. * @param {string|Object} item Item to run the rule against
  640. * @returns {void}
  641. * @private
  642. */
  643. function testValidTemplate(item) {
  644. const code = typeof item === "object" ? item.code : item;
  645. assert.ok(typeof code === "string", "Test case must specify a string value for 'code'");
  646. if (item.name) {
  647. assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
  648. }
  649. const result = runRuleForItem(item);
  650. const messages = result.messages;
  651. assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
  652. messages.length,
  653. util.inspect(messages)));
  654. assertASTDidntChange(result.beforeAST, result.afterAST);
  655. }
  656. /**
  657. * Asserts that the message matches its expected value. If the expected
  658. * value is a regular expression, it is checked against the actual
  659. * value.
  660. * @param {string} actual Actual value
  661. * @param {string|RegExp} expected Expected value
  662. * @returns {void}
  663. * @private
  664. */
  665. function assertMessageMatches(actual, expected) {
  666. if (expected instanceof RegExp) {
  667. // assert.js doesn't have a built-in RegExp match function
  668. assert.ok(
  669. expected.test(actual),
  670. `Expected '${actual}' to match ${expected}`
  671. );
  672. } else {
  673. assert.strictEqual(actual, expected);
  674. }
  675. }
  676. /**
  677. * Check if the template is invalid or not
  678. * all invalid cases go through this.
  679. * @param {string|Object} item Item to run the rule against
  680. * @returns {void}
  681. * @private
  682. */
  683. function testInvalidTemplate(item) {
  684. assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'");
  685. if (item.name) {
  686. assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
  687. }
  688. assert.ok(item.errors || item.errors === 0,
  689. `Did not specify errors for an invalid test of ${ruleName}`);
  690. if (Array.isArray(item.errors) && item.errors.length === 0) {
  691. assert.fail("Invalid cases must have at least one error");
  692. }
  693. const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
  694. const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;
  695. const result = runRuleForItem(item);
  696. const messages = result.messages;
  697. if (typeof item.errors === "number") {
  698. if (item.errors === 0) {
  699. assert.fail("Invalid cases must have 'error' value greater than 0");
  700. }
  701. assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
  702. item.errors,
  703. item.errors === 1 ? "" : "s",
  704. messages.length,
  705. util.inspect(messages)));
  706. } else {
  707. assert.strictEqual(
  708. messages.length, item.errors.length, util.format(
  709. "Should have %d error%s but had %d: %s",
  710. item.errors.length,
  711. item.errors.length === 1 ? "" : "s",
  712. messages.length,
  713. util.inspect(messages)
  714. )
  715. );
  716. const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
  717. for (let i = 0, l = item.errors.length; i < l; i++) {
  718. const error = item.errors[i];
  719. const message = messages[i];
  720. assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
  721. if (typeof error === "string" || error instanceof RegExp) {
  722. // Just an error message.
  723. assertMessageMatches(message.message, error);
  724. } else if (typeof error === "object" && error !== null) {
  725. /*
  726. * Error object.
  727. * This may have a message, messageId, data, node type, line, and/or
  728. * column.
  729. */
  730. Object.keys(error).forEach(propertyName => {
  731. assert.ok(
  732. errorObjectParameters.has(propertyName),
  733. `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
  734. );
  735. });
  736. if (hasOwnProperty(error, "message")) {
  737. assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
  738. assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
  739. assertMessageMatches(message.message, error.message);
  740. } else if (hasOwnProperty(error, "messageId")) {
  741. assert.ok(
  742. ruleHasMetaMessages,
  743. "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
  744. );
  745. if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
  746. assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
  747. }
  748. assert.strictEqual(
  749. message.messageId,
  750. error.messageId,
  751. `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
  752. );
  753. if (hasOwnProperty(error, "data")) {
  754. /*
  755. * if data was provided, then directly compare the returned message to a synthetic
  756. * interpolated message using the same message ID and data provided in the test.
  757. * See https://github.com/eslint/eslint/issues/9890 for context.
  758. */
  759. const unformattedOriginalMessage = rule.meta.messages[error.messageId];
  760. const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
  761. assert.strictEqual(
  762. message.message,
  763. rehydratedMessage,
  764. `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
  765. );
  766. }
  767. }
  768. assert.ok(
  769. hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
  770. "Error must specify 'messageId' if 'data' is used."
  771. );
  772. if (error.type) {
  773. assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
  774. }
  775. if (hasOwnProperty(error, "line")) {
  776. assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
  777. }
  778. if (hasOwnProperty(error, "column")) {
  779. assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
  780. }
  781. if (hasOwnProperty(error, "endLine")) {
  782. assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
  783. }
  784. if (hasOwnProperty(error, "endColumn")) {
  785. assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
  786. }
  787. if (hasOwnProperty(error, "suggestions")) {
  788. // Support asserting there are no suggestions
  789. if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
  790. if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
  791. assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
  792. }
  793. } else {
  794. assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
  795. assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
  796. error.suggestions.forEach((expectedSuggestion, index) => {
  797. assert.ok(
  798. typeof expectedSuggestion === "object" && expectedSuggestion !== null,
  799. "Test suggestion in 'suggestions' array must be an object."
  800. );
  801. Object.keys(expectedSuggestion).forEach(propertyName => {
  802. assert.ok(
  803. suggestionObjectParameters.has(propertyName),
  804. `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
  805. );
  806. });
  807. const actualSuggestion = message.suggestions[index];
  808. const suggestionPrefix = `Error Suggestion at index ${index} :`;
  809. if (hasOwnProperty(expectedSuggestion, "desc")) {
  810. assert.ok(
  811. !hasOwnProperty(expectedSuggestion, "data"),
  812. `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
  813. );
  814. assert.strictEqual(
  815. actualSuggestion.desc,
  816. expectedSuggestion.desc,
  817. `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
  818. );
  819. }
  820. if (hasOwnProperty(expectedSuggestion, "messageId")) {
  821. assert.ok(
  822. ruleHasMetaMessages,
  823. `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
  824. );
  825. assert.ok(
  826. hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
  827. `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
  828. );
  829. assert.strictEqual(
  830. actualSuggestion.messageId,
  831. expectedSuggestion.messageId,
  832. `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
  833. );
  834. if (hasOwnProperty(expectedSuggestion, "data")) {
  835. const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
  836. const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);
  837. assert.strictEqual(
  838. actualSuggestion.desc,
  839. rehydratedDesc,
  840. `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
  841. );
  842. }
  843. } else {
  844. assert.ok(
  845. !hasOwnProperty(expectedSuggestion, "data"),
  846. `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
  847. );
  848. }
  849. if (hasOwnProperty(expectedSuggestion, "output")) {
  850. const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
  851. 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}"`);
  852. }
  853. });
  854. }
  855. }
  856. } else {
  857. // Message was an unexpected type
  858. assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
  859. }
  860. }
  861. }
  862. if (hasOwnProperty(item, "output")) {
  863. if (item.output === null) {
  864. assert.strictEqual(
  865. result.output,
  866. item.code,
  867. "Expected no autofixes to be suggested"
  868. );
  869. } else {
  870. assert.strictEqual(result.output, item.output, "Output is incorrect.");
  871. }
  872. } else {
  873. assert.strictEqual(
  874. result.output,
  875. item.code,
  876. "The rule fixed the code. Please add 'output' property."
  877. );
  878. }
  879. assertASTDidntChange(result.beforeAST, result.afterAST);
  880. }
  881. /*
  882. * This creates a mocha test suite and pipes all supplied info through
  883. * one of the templates above.
  884. */
  885. this.constructor.describe(ruleName, () => {
  886. this.constructor.describe("valid", () => {
  887. test.valid.forEach(valid => {
  888. this.constructor[valid.only ? "itOnly" : "it"](
  889. sanitize(typeof valid === "object" ? valid.name || valid.code : valid),
  890. () => {
  891. testValidTemplate(valid);
  892. }
  893. );
  894. });
  895. });
  896. this.constructor.describe("invalid", () => {
  897. test.invalid.forEach(invalid => {
  898. this.constructor[invalid.only ? "itOnly" : "it"](
  899. sanitize(invalid.name || invalid.code),
  900. () => {
  901. testInvalidTemplate(invalid);
  902. }
  903. );
  904. });
  905. });
  906. });
  907. }
  908. }
  909. RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
  910. module.exports = RuleTester;