Software zum Installieren eines Smart-Mirror Frameworks , zum Nutzen von hochschulrelevanten Informationen, auf einem Raspberry-Pi.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rule-tester.js 38KB

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