rule-tester.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. create() {
  559. return {
  560. Program(node) {
  561. beforeAST = cloneDeeplyExcludesParent(node);
  562. },
  563. "Program:exit"(node) {
  564. afterAST = node;
  565. }
  566. };
  567. }
  568. });
  569. if (typeof config.parser === "string") {
  570. assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
  571. } else {
  572. config.parser = espreePath;
  573. }
  574. linter.defineParser(config.parser, wrapParser(require(config.parser)));
  575. if (schema) {
  576. ajv.validateSchema(schema);
  577. if (ajv.errors) {
  578. const errors = ajv.errors.map(error => {
  579. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  580. return `\t${field}: ${error.message}`;
  581. }).join("\n");
  582. throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
  583. }
  584. /*
  585. * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
  586. * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
  587. * 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,
  588. * the schema is compiled here separately from checking for `validateSchema` errors.
  589. */
  590. try {
  591. ajv.compile(schema);
  592. } catch (err) {
  593. throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
  594. }
  595. }
  596. validate(config, "rule-tester", id => (id === ruleName ? rule : null));
  597. // Verify the code.
  598. const { getComments } = SourceCode.prototype;
  599. let messages;
  600. try {
  601. SourceCode.prototype.getComments = getCommentsDeprecation;
  602. messages = linter.verify(code, config, filename);
  603. } finally {
  604. SourceCode.prototype.getComments = getComments;
  605. }
  606. const fatalErrorMessage = messages.find(m => m.fatal);
  607. assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`);
  608. // Verify if autofix makes a syntax error or not.
  609. if (messages.some(m => m.fix)) {
  610. output = SourceCodeFixer.applyFixes(code, messages).output;
  611. const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
  612. assert(!errorMessageInFix, [
  613. "A fatal parsing error occurred in autofix.",
  614. `Error: ${errorMessageInFix && errorMessageInFix.message}`,
  615. "Autofix output:",
  616. output
  617. ].join("\n"));
  618. } else {
  619. output = code;
  620. }
  621. return {
  622. messages,
  623. output,
  624. beforeAST,
  625. afterAST: cloneDeeplyExcludesParent(afterAST)
  626. };
  627. }
  628. /**
  629. * Check if the AST was changed
  630. * @param {ASTNode} beforeAST AST node before running
  631. * @param {ASTNode} afterAST AST node after running
  632. * @returns {void}
  633. * @private
  634. */
  635. function assertASTDidntChange(beforeAST, afterAST) {
  636. if (!equal(beforeAST, afterAST)) {
  637. assert.fail("Rule should not modify AST.");
  638. }
  639. }
  640. /**
  641. * Check if the template is valid or not
  642. * all valid cases go through this
  643. * @param {string|Object} item Item to run the rule against
  644. * @returns {void}
  645. * @private
  646. */
  647. function testValidTemplate(item) {
  648. const code = typeof item === "object" ? item.code : item;
  649. assert.ok(typeof code === "string", "Test case must specify a string value for 'code'");
  650. if (item.name) {
  651. assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
  652. }
  653. const result = runRuleForItem(item);
  654. const messages = result.messages;
  655. assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
  656. messages.length,
  657. util.inspect(messages)));
  658. assertASTDidntChange(result.beforeAST, result.afterAST);
  659. }
  660. /**
  661. * Asserts that the message matches its expected value. If the expected
  662. * value is a regular expression, it is checked against the actual
  663. * value.
  664. * @param {string} actual Actual value
  665. * @param {string|RegExp} expected Expected value
  666. * @returns {void}
  667. * @private
  668. */
  669. function assertMessageMatches(actual, expected) {
  670. if (expected instanceof RegExp) {
  671. // assert.js doesn't have a built-in RegExp match function
  672. assert.ok(
  673. expected.test(actual),
  674. `Expected '${actual}' to match ${expected}`
  675. );
  676. } else {
  677. assert.strictEqual(actual, expected);
  678. }
  679. }
  680. /**
  681. * Check if the template is invalid or not
  682. * all invalid cases go through this.
  683. * @param {string|Object} item Item to run the rule against
  684. * @returns {void}
  685. * @private
  686. */
  687. function testInvalidTemplate(item) {
  688. assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'");
  689. if (item.name) {
  690. assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string");
  691. }
  692. assert.ok(item.errors || item.errors === 0,
  693. `Did not specify errors for an invalid test of ${ruleName}`);
  694. if (Array.isArray(item.errors) && item.errors.length === 0) {
  695. assert.fail("Invalid cases must have at least one error");
  696. }
  697. const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages");
  698. const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null;
  699. const result = runRuleForItem(item);
  700. const messages = result.messages;
  701. if (typeof item.errors === "number") {
  702. if (item.errors === 0) {
  703. assert.fail("Invalid cases must have 'error' value greater than 0");
  704. }
  705. assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
  706. item.errors,
  707. item.errors === 1 ? "" : "s",
  708. messages.length,
  709. util.inspect(messages)));
  710. } else {
  711. assert.strictEqual(
  712. messages.length, item.errors.length, util.format(
  713. "Should have %d error%s but had %d: %s",
  714. item.errors.length,
  715. item.errors.length === 1 ? "" : "s",
  716. messages.length,
  717. util.inspect(messages)
  718. )
  719. );
  720. const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
  721. for (let i = 0, l = item.errors.length; i < l; i++) {
  722. const error = item.errors[i];
  723. const message = messages[i];
  724. assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
  725. if (typeof error === "string" || error instanceof RegExp) {
  726. // Just an error message.
  727. assertMessageMatches(message.message, error);
  728. } else if (typeof error === "object" && error !== null) {
  729. /*
  730. * Error object.
  731. * This may have a message, messageId, data, node type, line, and/or
  732. * column.
  733. */
  734. Object.keys(error).forEach(propertyName => {
  735. assert.ok(
  736. errorObjectParameters.has(propertyName),
  737. `Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.`
  738. );
  739. });
  740. if (hasOwnProperty(error, "message")) {
  741. assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
  742. assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
  743. assertMessageMatches(message.message, error.message);
  744. } else if (hasOwnProperty(error, "messageId")) {
  745. assert.ok(
  746. ruleHasMetaMessages,
  747. "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
  748. );
  749. if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
  750. assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
  751. }
  752. assert.strictEqual(
  753. message.messageId,
  754. error.messageId,
  755. `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
  756. );
  757. if (hasOwnProperty(error, "data")) {
  758. /*
  759. * if data was provided, then directly compare the returned message to a synthetic
  760. * interpolated message using the same message ID and data provided in the test.
  761. * See https://github.com/eslint/eslint/issues/9890 for context.
  762. */
  763. const unformattedOriginalMessage = rule.meta.messages[error.messageId];
  764. const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
  765. assert.strictEqual(
  766. message.message,
  767. rehydratedMessage,
  768. `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
  769. );
  770. }
  771. }
  772. assert.ok(
  773. hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
  774. "Error must specify 'messageId' if 'data' is used."
  775. );
  776. if (error.type) {
  777. assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
  778. }
  779. if (hasOwnProperty(error, "line")) {
  780. assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
  781. }
  782. if (hasOwnProperty(error, "column")) {
  783. assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
  784. }
  785. if (hasOwnProperty(error, "endLine")) {
  786. assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
  787. }
  788. if (hasOwnProperty(error, "endColumn")) {
  789. assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
  790. }
  791. if (hasOwnProperty(error, "suggestions")) {
  792. // Support asserting there are no suggestions
  793. if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
  794. if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
  795. assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
  796. }
  797. } else {
  798. assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
  799. assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
  800. error.suggestions.forEach((expectedSuggestion, index) => {
  801. assert.ok(
  802. typeof expectedSuggestion === "object" && expectedSuggestion !== null,
  803. "Test suggestion in 'suggestions' array must be an object."
  804. );
  805. Object.keys(expectedSuggestion).forEach(propertyName => {
  806. assert.ok(
  807. suggestionObjectParameters.has(propertyName),
  808. `Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.`
  809. );
  810. });
  811. const actualSuggestion = message.suggestions[index];
  812. const suggestionPrefix = `Error Suggestion at index ${index} :`;
  813. if (hasOwnProperty(expectedSuggestion, "desc")) {
  814. assert.ok(
  815. !hasOwnProperty(expectedSuggestion, "data"),
  816. `${suggestionPrefix} Test should not specify both 'desc' and 'data'.`
  817. );
  818. assert.strictEqual(
  819. actualSuggestion.desc,
  820. expectedSuggestion.desc,
  821. `${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.`
  822. );
  823. }
  824. if (hasOwnProperty(expectedSuggestion, "messageId")) {
  825. assert.ok(
  826. ruleHasMetaMessages,
  827. `${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.`
  828. );
  829. assert.ok(
  830. hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId),
  831. `${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.`
  832. );
  833. assert.strictEqual(
  834. actualSuggestion.messageId,
  835. expectedSuggestion.messageId,
  836. `${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.`
  837. );
  838. if (hasOwnProperty(expectedSuggestion, "data")) {
  839. const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId];
  840. const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data);
  841. assert.strictEqual(
  842. actualSuggestion.desc,
  843. rehydratedDesc,
  844. `${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".`
  845. );
  846. }
  847. } else {
  848. assert.ok(
  849. !hasOwnProperty(expectedSuggestion, "data"),
  850. `${suggestionPrefix} Test must specify 'messageId' if 'data' is used.`
  851. );
  852. }
  853. if (hasOwnProperty(expectedSuggestion, "output")) {
  854. const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
  855. 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}"`);
  856. }
  857. });
  858. }
  859. }
  860. } else {
  861. // Message was an unexpected type
  862. assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
  863. }
  864. }
  865. }
  866. if (hasOwnProperty(item, "output")) {
  867. if (item.output === null) {
  868. assert.strictEqual(
  869. result.output,
  870. item.code,
  871. "Expected no autofixes to be suggested"
  872. );
  873. } else {
  874. assert.strictEqual(result.output, item.output, "Output is incorrect.");
  875. }
  876. } else {
  877. assert.strictEqual(
  878. result.output,
  879. item.code,
  880. "The rule fixed the code. Please add 'output' property."
  881. );
  882. }
  883. assertASTDidntChange(result.beforeAST, result.afterAST);
  884. }
  885. /*
  886. * This creates a mocha test suite and pipes all supplied info through
  887. * one of the templates above.
  888. */
  889. this.constructor.describe(ruleName, () => {
  890. this.constructor.describe("valid", () => {
  891. test.valid.forEach(valid => {
  892. this.constructor[valid.only ? "itOnly" : "it"](
  893. sanitize(typeof valid === "object" ? valid.name || valid.code : valid),
  894. () => {
  895. testValidTemplate(valid);
  896. }
  897. );
  898. });
  899. });
  900. this.constructor.describe("invalid", () => {
  901. test.invalid.forEach(invalid => {
  902. this.constructor[invalid.only ? "itOnly" : "it"](
  903. sanitize(invalid.name || invalid.code),
  904. () => {
  905. testInvalidTemplate(invalid);
  906. }
  907. );
  908. });
  909. });
  910. });
  911. }
  912. }
  913. RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null;
  914. module.exports = RuleTester;