rule-tester.js 55 KB

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