Ohm-Management - Projektarbeit B-ME
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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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 lodash = require("lodash"),
  40. assert = require("assert"),
  41. util = require("util"),
  42. validator = require("../config/config-validator"),
  43. ajv = require("../util/ajv"),
  44. Linter = require("../linter"),
  45. Environments = require("../config/environments"),
  46. SourceCodeFixer = require("../util/source-code-fixer"),
  47. interpolate = require("../util/interpolate");
  48. //------------------------------------------------------------------------------
  49. // Private Members
  50. //------------------------------------------------------------------------------
  51. /*
  52. * testerDefaultConfig must not be modified as it allows to reset the tester to
  53. * the initial default configuration
  54. */
  55. const testerDefaultConfig = { rules: {} };
  56. let defaultConfig = { rules: {} };
  57. /*
  58. * List every parameters possible on a test case that are not related to eslint
  59. * configuration
  60. */
  61. const RuleTesterParameters = [
  62. "code",
  63. "filename",
  64. "options",
  65. "errors",
  66. "output"
  67. ];
  68. const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
  69. /**
  70. * Clones a given value deeply.
  71. * Note: This ignores `parent` property.
  72. *
  73. * @param {any} x - A value to clone.
  74. * @returns {any} A cloned value.
  75. */
  76. function cloneDeeplyExcludesParent(x) {
  77. if (typeof x === "object" && x !== null) {
  78. if (Array.isArray(x)) {
  79. return x.map(cloneDeeplyExcludesParent);
  80. }
  81. const retv = {};
  82. for (const key in x) {
  83. if (key !== "parent" && hasOwnProperty(x, key)) {
  84. retv[key] = cloneDeeplyExcludesParent(x[key]);
  85. }
  86. }
  87. return retv;
  88. }
  89. return x;
  90. }
  91. /**
  92. * Freezes a given value deeply.
  93. *
  94. * @param {any} x - A value to freeze.
  95. * @returns {void}
  96. */
  97. function freezeDeeply(x) {
  98. if (typeof x === "object" && x !== null) {
  99. if (Array.isArray(x)) {
  100. x.forEach(freezeDeeply);
  101. } else {
  102. for (const key in x) {
  103. if (key !== "parent" && hasOwnProperty(x, key)) {
  104. freezeDeeply(x[key]);
  105. }
  106. }
  107. }
  108. Object.freeze(x);
  109. }
  110. }
  111. //------------------------------------------------------------------------------
  112. // Public Interface
  113. //------------------------------------------------------------------------------
  114. // default separators for testing
  115. const DESCRIBE = Symbol("describe");
  116. const IT = Symbol("it");
  117. /**
  118. * This is `it` default handler if `it` don't exist.
  119. * @this {Mocha}
  120. * @param {string} text - The description of the test case.
  121. * @param {Function} method - The logic of the test case.
  122. * @returns {any} Returned value of `method`.
  123. */
  124. function itDefaultHandler(text, method) {
  125. try {
  126. return method.call(this);
  127. } catch (err) {
  128. if (err instanceof assert.AssertionError) {
  129. err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
  130. }
  131. throw err;
  132. }
  133. }
  134. /**
  135. * This is `describe` default handler if `describe` don't exist.
  136. * @this {Mocha}
  137. * @param {string} text - The description of the test case.
  138. * @param {Function} method - The logic of the test case.
  139. * @returns {any} Returned value of `method`.
  140. */
  141. function describeDefaultHandler(text, method) {
  142. return method.call(this);
  143. }
  144. class RuleTester {
  145. /**
  146. * Creates a new instance of RuleTester.
  147. * @param {Object} [testerConfig] Optional, extra configuration for the tester
  148. * @constructor
  149. */
  150. constructor(testerConfig) {
  151. /**
  152. * The configuration to use for this tester. Combination of the tester
  153. * configuration and the default configuration.
  154. * @type {Object}
  155. */
  156. this.testerConfig = lodash.merge(
  157. // we have to clone because merge uses the first argument for recipient
  158. lodash.cloneDeep(defaultConfig),
  159. testerConfig,
  160. { rules: { "rule-tester/validate-ast": "error" } }
  161. );
  162. /**
  163. * Rule definitions to define before tests.
  164. * @type {Object}
  165. */
  166. this.rules = {};
  167. this.linter = new Linter();
  168. }
  169. /**
  170. * Set the configuration to use for all future tests
  171. * @param {Object} config the configuration to use.
  172. * @returns {void}
  173. */
  174. static setDefaultConfig(config) {
  175. if (typeof config !== "object") {
  176. throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
  177. }
  178. defaultConfig = config;
  179. // Make sure the rules object exists since it is assumed to exist later
  180. defaultConfig.rules = defaultConfig.rules || {};
  181. }
  182. /**
  183. * Get the current configuration used for all tests
  184. * @returns {Object} the current configuration
  185. */
  186. static getDefaultConfig() {
  187. return defaultConfig;
  188. }
  189. /**
  190. * Reset the configuration to the initial configuration of the tester removing
  191. * any changes made until now.
  192. * @returns {void}
  193. */
  194. static resetDefaultConfig() {
  195. defaultConfig = lodash.cloneDeep(testerDefaultConfig);
  196. }
  197. /*
  198. * If people use `mocha test.js --watch` command, `describe` and `it` function
  199. * instances are different for each execution. So `describe` and `it` should get fresh instance
  200. * always.
  201. */
  202. static get describe() {
  203. return (
  204. this[DESCRIBE] ||
  205. (typeof describe === "function" ? describe : describeDefaultHandler)
  206. );
  207. }
  208. static set describe(value) {
  209. this[DESCRIBE] = value;
  210. }
  211. static get it() {
  212. return (
  213. this[IT] ||
  214. (typeof it === "function" ? it : itDefaultHandler)
  215. );
  216. }
  217. static set it(value) {
  218. this[IT] = value;
  219. }
  220. /**
  221. * Define a rule for one particular run of tests.
  222. * @param {string} name The name of the rule to define.
  223. * @param {Function} rule The rule definition.
  224. * @returns {void}
  225. */
  226. defineRule(name, rule) {
  227. this.rules[name] = rule;
  228. }
  229. /**
  230. * Adds a new rule test to execute.
  231. * @param {string} ruleName The name of the rule to run.
  232. * @param {Function} rule The rule to test.
  233. * @param {Object} test The collection of tests to run.
  234. * @returns {void}
  235. */
  236. run(ruleName, rule, test) {
  237. const testerConfig = this.testerConfig,
  238. requiredScenarios = ["valid", "invalid"],
  239. scenarioErrors = [],
  240. linter = this.linter;
  241. if (lodash.isNil(test) || typeof test !== "object") {
  242. throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
  243. }
  244. requiredScenarios.forEach(scenarioType => {
  245. if (lodash.isNil(test[scenarioType])) {
  246. scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
  247. }
  248. });
  249. if (scenarioErrors.length > 0) {
  250. throw new Error([
  251. `Test Scenarios for rule ${ruleName} is invalid:`
  252. ].concat(scenarioErrors).join("\n"));
  253. }
  254. linter.defineRule(ruleName, Object.assign({}, rule, {
  255. // Create a wrapper rule that freezes the `context` properties.
  256. create(context) {
  257. freezeDeeply(context.options);
  258. freezeDeeply(context.settings);
  259. freezeDeeply(context.parserOptions);
  260. return (typeof rule === "function" ? rule : rule.create)(context);
  261. }
  262. }));
  263. linter.defineRules(this.rules);
  264. const ruleMap = linter.getRules();
  265. /**
  266. * Run the rule for the given item
  267. * @param {string|Object} item Item to run the rule against
  268. * @returns {Object} Eslint run result
  269. * @private
  270. */
  271. function runRuleForItem(item) {
  272. let config = lodash.cloneDeep(testerConfig),
  273. code, filename, beforeAST, afterAST;
  274. if (typeof item === "string") {
  275. code = item;
  276. } else {
  277. code = item.code;
  278. /*
  279. * Assumes everything on the item is a config except for the
  280. * parameters used by this tester
  281. */
  282. const itemConfig = lodash.omit(item, RuleTesterParameters);
  283. /*
  284. * Create the config object from the tester config and this item
  285. * specific configurations.
  286. */
  287. config = lodash.merge(
  288. config,
  289. itemConfig
  290. );
  291. }
  292. if (item.filename) {
  293. filename = item.filename;
  294. }
  295. if (Object.prototype.hasOwnProperty.call(item, "options")) {
  296. assert(Array.isArray(item.options), "options must be an array");
  297. config.rules[ruleName] = [1].concat(item.options);
  298. } else {
  299. config.rules[ruleName] = 1;
  300. }
  301. const schema = validator.getRuleOptionsSchema(rule);
  302. /*
  303. * Setup AST getters.
  304. * The goal is to check whether or not AST was modified when
  305. * running the rule under test.
  306. */
  307. linter.defineRule("rule-tester/validate-ast", () => ({
  308. Program(node) {
  309. beforeAST = cloneDeeplyExcludesParent(node);
  310. },
  311. "Program:exit"(node) {
  312. afterAST = node;
  313. }
  314. }));
  315. if (schema) {
  316. ajv.validateSchema(schema);
  317. if (ajv.errors) {
  318. const errors = ajv.errors.map(error => {
  319. const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
  320. return `\t${field}: ${error.message}`;
  321. }).join("\n");
  322. throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
  323. }
  324. }
  325. validator.validate(config, "rule-tester", ruleMap.get.bind(ruleMap), new Environments());
  326. return {
  327. messages: linter.verify(code, config, filename, true),
  328. beforeAST,
  329. afterAST: cloneDeeplyExcludesParent(afterAST)
  330. };
  331. }
  332. /**
  333. * Check if the AST was changed
  334. * @param {ASTNode} beforeAST AST node before running
  335. * @param {ASTNode} afterAST AST node after running
  336. * @returns {void}
  337. * @private
  338. */
  339. function assertASTDidntChange(beforeAST, afterAST) {
  340. if (!lodash.isEqual(beforeAST, afterAST)) {
  341. assert.fail("Rule should not modify AST.");
  342. }
  343. }
  344. /**
  345. * Check if the template is valid or not
  346. * all valid cases go through this
  347. * @param {string|Object} item Item to run the rule against
  348. * @returns {void}
  349. * @private
  350. */
  351. function testValidTemplate(item) {
  352. const result = runRuleForItem(item);
  353. const messages = result.messages;
  354. assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
  355. messages.length, util.inspect(messages)));
  356. assertASTDidntChange(result.beforeAST, result.afterAST);
  357. }
  358. /**
  359. * Asserts that the message matches its expected value. If the expected
  360. * value is a regular expression, it is checked against the actual
  361. * value.
  362. * @param {string} actual Actual value
  363. * @param {string|RegExp} expected Expected value
  364. * @returns {void}
  365. * @private
  366. */
  367. function assertMessageMatches(actual, expected) {
  368. if (expected instanceof RegExp) {
  369. // assert.js doesn't have a built-in RegExp match function
  370. assert.ok(
  371. expected.test(actual),
  372. `Expected '${actual}' to match ${expected}`
  373. );
  374. } else {
  375. assert.strictEqual(actual, expected);
  376. }
  377. }
  378. /**
  379. * Check if the template is invalid or not
  380. * all invalid cases go through this.
  381. * @param {string|Object} item Item to run the rule against
  382. * @returns {void}
  383. * @private
  384. */
  385. function testInvalidTemplate(item) {
  386. assert.ok(item.errors || item.errors === 0,
  387. `Did not specify errors for an invalid test of ${ruleName}`);
  388. const result = runRuleForItem(item);
  389. const messages = result.messages;
  390. if (typeof item.errors === "number") {
  391. assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
  392. item.errors, item.errors === 1 ? "" : "s", messages.length, util.inspect(messages)));
  393. } else {
  394. assert.strictEqual(
  395. messages.length, item.errors.length,
  396. util.format(
  397. "Should have %d error%s but had %d: %s",
  398. item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages)
  399. )
  400. );
  401. const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
  402. for (let i = 0, l = item.errors.length; i < l; i++) {
  403. const error = item.errors[i];
  404. const message = messages[i];
  405. assert(!message.fatal, `A fatal parsing error occurred: ${message.message}`);
  406. assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
  407. if (typeof error === "string" || error instanceof RegExp) {
  408. // Just an error message.
  409. assertMessageMatches(message.message, error);
  410. } else if (typeof error === "object") {
  411. /*
  412. * Error object.
  413. * This may have a message, messageId, data, node type, line, and/or
  414. * column.
  415. */
  416. if (hasOwnProperty(error, "message")) {
  417. assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
  418. assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
  419. assertMessageMatches(message.message, error.message);
  420. } else if (hasOwnProperty(error, "messageId")) {
  421. assert.ok(
  422. hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"),
  423. "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
  424. );
  425. if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
  426. const friendlyIDList = `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]`;
  427. assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
  428. }
  429. assert.strictEqual(
  430. error.messageId,
  431. message.messageId,
  432. `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
  433. );
  434. if (hasOwnProperty(error, "data")) {
  435. /*
  436. * if data was provided, then directly compare the returned message to a synthetic
  437. * interpolated message using the same message ID and data provided in the test.
  438. * See https://github.com/eslint/eslint/issues/9890 for context.
  439. */
  440. const unformattedOriginalMessage = rule.meta.messages[error.messageId];
  441. const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
  442. assert.strictEqual(
  443. message.message,
  444. rehydratedMessage,
  445. `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
  446. );
  447. }
  448. }
  449. assert.ok(
  450. hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
  451. "Error must specify 'messageId' if 'data' is used."
  452. );
  453. if (error.type) {
  454. assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
  455. }
  456. if (Object.prototype.hasOwnProperty.call(error, "line")) {
  457. assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
  458. }
  459. if (Object.prototype.hasOwnProperty.call(error, "column")) {
  460. assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
  461. }
  462. if (Object.prototype.hasOwnProperty.call(error, "endLine")) {
  463. assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
  464. }
  465. if (Object.prototype.hasOwnProperty.call(error, "endColumn")) {
  466. assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
  467. }
  468. } else {
  469. // Message was an unexpected type
  470. assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
  471. }
  472. }
  473. }
  474. if (Object.prototype.hasOwnProperty.call(item, "output")) {
  475. if (item.output === null) {
  476. assert.strictEqual(
  477. messages.filter(message => message.fix).length,
  478. 0,
  479. "Expected no autofixes to be suggested"
  480. );
  481. } else {
  482. const fixResult = SourceCodeFixer.applyFixes(item.code, messages);
  483. assert.strictEqual(fixResult.output, item.output, "Output is incorrect.");
  484. }
  485. }
  486. assertASTDidntChange(result.beforeAST, result.afterAST);
  487. }
  488. /*
  489. * This creates a mocha test suite and pipes all supplied info through
  490. * one of the templates above.
  491. */
  492. RuleTester.describe(ruleName, () => {
  493. RuleTester.describe("valid", () => {
  494. test.valid.forEach(valid => {
  495. RuleTester.it(typeof valid === "object" ? valid.code : valid, () => {
  496. testValidTemplate(valid);
  497. });
  498. });
  499. });
  500. RuleTester.describe("invalid", () => {
  501. test.invalid.forEach(invalid => {
  502. RuleTester.it(invalid.code, () => {
  503. testInvalidTemplate(invalid);
  504. });
  505. });
  506. });
  507. });
  508. }
  509. }
  510. RuleTester[DESCRIBE] = RuleTester[IT] = null;
  511. module.exports = RuleTester;