项目原始demo,不改动
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
Ce dépôt est archivé. Vous pouvez voir les fichiers et le cloner, mais vous ne pouvez pas pousser ni ouvrir de ticket/demande d'ajout.

rule-tester.js 20 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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.apply(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.apply(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. // Not using directly to avoid performance problem in node 6.1.0. See #6111
  342. // eslint-disable-next-line no-restricted-properties
  343. assert.deepEqual(beforeAST, afterAST, "Rule should not modify AST.");
  344. }
  345. }
  346. /**
  347. * Check if the template is valid or not
  348. * all valid cases go through this
  349. * @param {string|Object} item Item to run the rule against
  350. * @returns {void}
  351. * @private
  352. */
  353. function testValidTemplate(item) {
  354. const result = runRuleForItem(item);
  355. const messages = result.messages;
  356. assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
  357. messages.length, util.inspect(messages)));
  358. assertASTDidntChange(result.beforeAST, result.afterAST);
  359. }
  360. /**
  361. * Asserts that the message matches its expected value. If the expected
  362. * value is a regular expression, it is checked against the actual
  363. * value.
  364. * @param {string} actual Actual value
  365. * @param {string|RegExp} expected Expected value
  366. * @returns {void}
  367. * @private
  368. */
  369. function assertMessageMatches(actual, expected) {
  370. if (expected instanceof RegExp) {
  371. // assert.js doesn't have a built-in RegExp match function
  372. assert.ok(
  373. expected.test(actual),
  374. `Expected '${actual}' to match ${expected}`
  375. );
  376. } else {
  377. assert.strictEqual(actual, expected);
  378. }
  379. }
  380. /**
  381. * Check if the template is invalid or not
  382. * all invalid cases go through this.
  383. * @param {string|Object} item Item to run the rule against
  384. * @returns {void}
  385. * @private
  386. */
  387. function testInvalidTemplate(item) {
  388. assert.ok(item.errors || item.errors === 0,
  389. `Did not specify errors for an invalid test of ${ruleName}`);
  390. const result = runRuleForItem(item);
  391. const messages = result.messages;
  392. if (typeof item.errors === "number") {
  393. assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
  394. item.errors, item.errors === 1 ? "" : "s", messages.length, util.inspect(messages)));
  395. } else {
  396. assert.strictEqual(
  397. messages.length, item.errors.length,
  398. util.format(
  399. "Should have %d error%s but had %d: %s",
  400. item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages)
  401. )
  402. );
  403. const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
  404. for (let i = 0, l = item.errors.length; i < l; i++) {
  405. const error = item.errors[i];
  406. const message = messages[i];
  407. assert(!message.fatal, `A fatal parsing error occurred: ${message.message}`);
  408. assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
  409. if (typeof error === "string" || error instanceof RegExp) {
  410. // Just an error message.
  411. assertMessageMatches(message.message, error);
  412. } else if (typeof error === "object") {
  413. /*
  414. * Error object.
  415. * This may have a message, node type, line, and/or
  416. * column.
  417. */
  418. if (error.message) {
  419. assertMessageMatches(message.message, error.message);
  420. }
  421. if (error.messageId) {
  422. const hOP = Object.hasOwnProperty.call.bind(Object.hasOwnProperty);
  423. // verify that `error.message` is `undefined`
  424. assert.strictEqual(error.message, void 0, "Error should not specify both a message and a messageId.");
  425. if (!hOP(rule, "meta") || !hOP(rule.meta, "messages")) {
  426. assert.fail("Rule must specify a messages hash in `meta`");
  427. }
  428. if (!hOP(rule.meta.messages, error.messageId)) {
  429. const friendlyIDList = `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]`;
  430. assert.fail(`Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
  431. }
  432. let expectedMessage = rule.meta.messages[error.messageId];
  433. if (error.data) {
  434. expectedMessage = interpolate(expectedMessage, error.data);
  435. }
  436. assertMessageMatches(message.message, expectedMessage);
  437. }
  438. if (error.type) {
  439. assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
  440. }
  441. if (error.hasOwnProperty("line")) {
  442. assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
  443. }
  444. if (error.hasOwnProperty("column")) {
  445. assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
  446. }
  447. if (error.hasOwnProperty("endLine")) {
  448. assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
  449. }
  450. if (error.hasOwnProperty("endColumn")) {
  451. assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
  452. }
  453. } else {
  454. // Message was an unexpected type
  455. assert.fail(message, null, "Error should be a string, object, or RegExp.");
  456. }
  457. }
  458. }
  459. if (item.hasOwnProperty("output")) {
  460. if (item.output === null) {
  461. assert.strictEqual(
  462. messages.filter(message => message.fix).length,
  463. 0,
  464. "Expected no autofixes to be suggested"
  465. );
  466. } else {
  467. const fixResult = SourceCodeFixer.applyFixes(item.code, messages);
  468. // eslint-disable-next-line no-restricted-properties
  469. assert.equal(fixResult.output, item.output, "Output is incorrect.");
  470. }
  471. }
  472. assertASTDidntChange(result.beforeAST, result.afterAST);
  473. }
  474. /*
  475. * This creates a mocha test suite and pipes all supplied info through
  476. * one of the templates above.
  477. */
  478. RuleTester.describe(ruleName, () => {
  479. RuleTester.describe("valid", () => {
  480. test.valid.forEach(valid => {
  481. RuleTester.it(typeof valid === "object" ? valid.code : valid, () => {
  482. testValidTemplate(valid);
  483. });
  484. });
  485. });
  486. RuleTester.describe("invalid", () => {
  487. test.invalid.forEach(invalid => {
  488. RuleTester.it(invalid.code, () => {
  489. testInvalidTemplate(invalid);
  490. });
  491. });
  492. });
  493. });
  494. }
  495. }
  496. RuleTester[DESCRIBE] = RuleTester[IT] = null;
  497. module.exports = RuleTester;