flat-rule-tester.js 44 KB

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