2 * @fileoverview Mocha test wrapper
7 /* global describe, it */
10 * This is a wrapper around mocha to allow for DRY unittests for eslint
12 * RuleTester.run("{ruleName}", {
15 * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} }
18 * { code: "{code}", errors: {numErrors} },
19 * { code: "{code}", errors: ["{errorMessage}"] },
20 * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings}, errors: [{ message: "{errorMessage}", type: "{errorNodeType}"}] }
25 * {code} - String that represents the code to be tested
26 * {options} - Arguments that are passed to the configurable rules.
27 * {globals} - An object representing a list of variables that are
28 * registered as globals
29 * {parser} - String representing the parser to use
30 * {settings} - An object representing global settings for all rules
31 * {numErrors} - If failing case doesn't need to check error message,
32 * this integer will specify how many errors should be
34 * {errorMessage} - Message that is returned by the rule on failure
35 * {errorNodeType} - AST node type that is returned by they rule as
36 * a cause of the failure.
39 //------------------------------------------------------------------------------
41 //------------------------------------------------------------------------------
44 assert = require("assert"),
45 path = require("path"),
46 util = require("util"),
47 lodash = require("lodash"),
48 { getRuleOptionsSchema, validate } = require("../shared/config-validator"),
49 { Linter, SourceCodeFixer, interpolate } = require("../linter");
51 const ajv = require("../shared/ajv")({ strictDefaults: true });
53 //------------------------------------------------------------------------------
55 //------------------------------------------------------------------------------
58 * testerDefaultConfig must not be modified as it allows to reset the tester to
59 * the initial default configuration
61 const testerDefaultConfig = { rules: {} };
62 let defaultConfig = { rules: {} };
65 * List every parameters possible on a test case that are not related to eslint
68 const RuleTesterParameters = [
76 const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
79 * Clones a given value deeply.
80 * Note: This ignores `parent` property.
81 * @param {any} x A value to clone.
82 * @returns {any} A cloned value.
84 function cloneDeeplyExcludesParent(x) {
85 if (typeof x === "object" && x !== null) {
86 if (Array.isArray(x)) {
87 return x.map(cloneDeeplyExcludesParent);
92 for (const key in x) {
93 if (key !== "parent" && hasOwnProperty(x, key)) {
94 retv[key] = cloneDeeplyExcludesParent(x[key]);
105 * Freezes a given value deeply.
106 * @param {any} x A value to freeze.
109 function freezeDeeply(x) {
110 if (typeof x === "object" && x !== null) {
111 if (Array.isArray(x)) {
112 x.forEach(freezeDeeply);
114 for (const key in x) {
115 if (key !== "parent" && hasOwnProperty(x, key)) {
116 freezeDeeply(x[key]);
125 * Replace control characters by `\u00xx` form.
126 * @param {string} text The text to sanitize.
127 * @returns {string} The sanitized text.
129 function sanitize(text) {
131 /[\u0000-\u0009|\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
132 c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
136 //------------------------------------------------------------------------------
138 //------------------------------------------------------------------------------
140 // default separators for testing
141 const DESCRIBE = Symbol("describe");
142 const IT = Symbol("it");
145 * This is `it` default handler if `it` don't exist.
147 * @param {string} text The description of the test case.
148 * @param {Function} method The logic of the test case.
149 * @returns {any} Returned value of `method`.
151 function itDefaultHandler(text, method) {
153 return method.call(this);
155 if (err instanceof assert.AssertionError) {
156 err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
163 * This is `describe` default handler if `describe` don't exist.
165 * @param {string} text The description of the test case.
166 * @param {Function} method The logic of the test case.
167 * @returns {any} Returned value of `method`.
169 function describeDefaultHandler(text, method) {
170 return method.call(this);
176 * Creates a new instance of RuleTester.
177 * @param {Object} [testerConfig] Optional, extra configuration for the tester
179 constructor(testerConfig) {
182 * The configuration to use for this tester. Combination of the tester
183 * configuration and the default configuration.
186 this.testerConfig = lodash.merge(
188 // we have to clone because merge uses the first argument for recipient
189 lodash.cloneDeep(defaultConfig),
191 { rules: { "rule-tester/validate-ast": "error" } }
195 * Rule definitions to define before tests.
199 this.linter = new Linter();
203 * Set the configuration to use for all future tests
204 * @param {Object} config the configuration to use.
207 static setDefaultConfig(config) {
208 if (typeof config !== "object") {
209 throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
211 defaultConfig = config;
213 // Make sure the rules object exists since it is assumed to exist later
214 defaultConfig.rules = defaultConfig.rules || {};
218 * Get the current configuration used for all tests
219 * @returns {Object} the current configuration
221 static getDefaultConfig() {
222 return defaultConfig;
226 * Reset the configuration to the initial configuration of the tester removing
227 * any changes made until now.
230 static resetDefaultConfig() {
231 defaultConfig = lodash.cloneDeep(testerDefaultConfig);
236 * If people use `mocha test.js --watch` command, `describe` and `it` function
237 * instances are different for each execution. So `describe` and `it` should get fresh instance
240 static get describe() {
243 (typeof describe === "function" ? describe : describeDefaultHandler)
247 static set describe(value) {
248 this[DESCRIBE] = value;
254 (typeof it === "function" ? it : itDefaultHandler)
258 static set it(value) {
263 * Define a rule for one particular run of tests.
264 * @param {string} name The name of the rule to define.
265 * @param {Function} rule The rule definition.
268 defineRule(name, rule) {
269 this.rules[name] = rule;
273 * Adds a new rule test to execute.
274 * @param {string} ruleName The name of the rule to run.
275 * @param {Function} rule The rule to test.
276 * @param {Object} test The collection of tests to run.
279 run(ruleName, rule, test) {
281 const testerConfig = this.testerConfig,
282 requiredScenarios = ["valid", "invalid"],
284 linter = this.linter;
286 if (lodash.isNil(test) || typeof test !== "object") {
287 throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
290 requiredScenarios.forEach(scenarioType => {
291 if (lodash.isNil(test[scenarioType])) {
292 scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
296 if (scenarioErrors.length > 0) {
298 `Test Scenarios for rule ${ruleName} is invalid:`
299 ].concat(scenarioErrors).join("\n"));
303 linter.defineRule(ruleName, Object.assign({}, rule, {
305 // Create a wrapper rule that freezes the `context` properties.
307 freezeDeeply(context.options);
308 freezeDeeply(context.settings);
309 freezeDeeply(context.parserOptions);
311 return (typeof rule === "function" ? rule : rule.create)(context);
315 linter.defineRules(this.rules);
318 * Run the rule for the given item
319 * @param {string|Object} item Item to run the rule against
320 * @returns {Object} Eslint run result
323 function runRuleForItem(item) {
324 let config = lodash.cloneDeep(testerConfig),
325 code, filename, output, beforeAST, afterAST;
327 if (typeof item === "string") {
333 * Assumes everything on the item is a config except for the
334 * parameters used by this tester
336 const itemConfig = lodash.omit(item, RuleTesterParameters);
339 * Create the config object from the tester config and this item
340 * specific configurations.
342 config = lodash.merge(
349 filename = item.filename;
352 if (hasOwnProperty(item, "options")) {
353 assert(Array.isArray(item.options), "options must be an array");
354 config.rules[ruleName] = [1].concat(item.options);
356 config.rules[ruleName] = 1;
359 const schema = getRuleOptionsSchema(rule);
363 * The goal is to check whether or not AST was modified when
364 * running the rule under test.
366 linter.defineRule("rule-tester/validate-ast", () => ({
368 beforeAST = cloneDeeplyExcludesParent(node);
370 "Program:exit"(node) {
375 if (typeof config.parser === "string") {
376 assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths");
377 linter.defineParser(config.parser, require(config.parser));
381 ajv.validateSchema(schema);
384 const errors = ajv.errors.map(error => {
385 const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
387 return `\t${field}: ${error.message}`;
390 throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
394 * `ajv.validateSchema` checks for errors in the structure of the schema (by comparing the schema against a "meta-schema"),
395 * and it reports those errors individually. However, there are other types of schema errors that only occur when compiling
396 * 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,
397 * the schema is compiled here separately from checking for `validateSchema` errors.
402 throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
406 validate(config, "rule-tester", id => (id === ruleName ? rule : null));
409 const messages = linter.verify(code, config, filename);
411 // Ignore syntax errors for backward compatibility if `errors` is a number.
412 if (typeof item.errors !== "number") {
413 const errorMessage = messages.find(m => m.fatal);
415 assert(!errorMessage, `A fatal parsing error occurred: ${errorMessage && errorMessage.message}`);
418 // Verify if autofix makes a syntax error or not.
419 if (messages.some(m => m.fix)) {
420 output = SourceCodeFixer.applyFixes(code, messages).output;
421 const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal);
423 assert(!errorMessageInFix, `A fatal parsing error occurred in autofix: ${errorMessageInFix && errorMessageInFix.message}`);
432 afterAST: cloneDeeplyExcludesParent(afterAST)
437 * Check if the AST was changed
438 * @param {ASTNode} beforeAST AST node before running
439 * @param {ASTNode} afterAST AST node after running
443 function assertASTDidntChange(beforeAST, afterAST) {
444 if (!lodash.isEqual(beforeAST, afterAST)) {
445 assert.fail("Rule should not modify AST.");
450 * Check if the template is valid or not
451 * all valid cases go through this
452 * @param {string|Object} item Item to run the rule against
456 function testValidTemplate(item) {
457 const result = runRuleForItem(item);
458 const messages = result.messages;
460 assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
461 messages.length, util.inspect(messages)));
463 assertASTDidntChange(result.beforeAST, result.afterAST);
467 * Asserts that the message matches its expected value. If the expected
468 * value is a regular expression, it is checked against the actual
470 * @param {string} actual Actual value
471 * @param {string|RegExp} expected Expected value
475 function assertMessageMatches(actual, expected) {
476 if (expected instanceof RegExp) {
478 // assert.js doesn't have a built-in RegExp match function
480 expected.test(actual),
481 `Expected '${actual}' to match ${expected}`
484 assert.strictEqual(actual, expected);
489 * Check if the template is invalid or not
490 * all invalid cases go through this.
491 * @param {string|Object} item Item to run the rule against
495 function testInvalidTemplate(item) {
496 assert.ok(item.errors || item.errors === 0,
497 `Did not specify errors for an invalid test of ${ruleName}`);
499 const result = runRuleForItem(item);
500 const messages = result.messages;
503 if (typeof item.errors === "number") {
504 assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s",
505 item.errors, item.errors === 1 ? "" : "s", messages.length, util.inspect(messages)));
508 messages.length, item.errors.length,
510 "Should have %d error%s but had %d: %s",
511 item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages)
515 const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
517 for (let i = 0, l = item.errors.length; i < l; i++) {
518 const error = item.errors[i];
519 const message = messages[i];
521 assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
523 if (typeof error === "string" || error instanceof RegExp) {
525 // Just an error message.
526 assertMessageMatches(message.message, error);
527 } else if (typeof error === "object") {
531 * This may have a message, messageId, data, node type, line, and/or
534 if (hasOwnProperty(error, "message")) {
535 assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'.");
536 assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'.");
537 assertMessageMatches(message.message, error.message);
538 } else if (hasOwnProperty(error, "messageId")) {
540 hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"),
541 "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
543 if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
544 const friendlyIDList = `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]`;
546 assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
551 `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
553 if (hasOwnProperty(error, "data")) {
556 * if data was provided, then directly compare the returned message to a synthetic
557 * interpolated message using the same message ID and data provided in the test.
558 * See https://github.com/eslint/eslint/issues/9890 for context.
560 const unformattedOriginalMessage = rule.meta.messages[error.messageId];
561 const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
566 `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
572 hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
573 "Error must specify 'messageId' if 'data' is used."
577 assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
580 if (hasOwnProperty(error, "line")) {
581 assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
584 if (hasOwnProperty(error, "column")) {
585 assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
588 if (hasOwnProperty(error, "endLine")) {
589 assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
592 if (hasOwnProperty(error, "endColumn")) {
593 assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
596 if (hasOwnProperty(error, "suggestions")) {
598 // Support asserting there are no suggestions
599 if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) {
600 if (Array.isArray(message.suggestions) && message.suggestions.length > 0) {
601 assert.fail(`Error should have no suggestions on error with message: "${message.message}"`);
604 assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
605 assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
607 error.suggestions.forEach((expectedSuggestion, index) => {
608 const actualSuggestion = message.suggestions[index];
611 * Tests equality of a suggestion key if that key is defined in the expected output.
612 * @param {string} key Key to validate from the suggestion object
615 function assertSuggestionKeyEquals(key) {
616 if (hasOwnProperty(expectedSuggestion, key)) {
617 assert.deepStrictEqual(actualSuggestion[key], expectedSuggestion[key], `Error suggestion at index: ${index} should have desc of: "${actualSuggestion[key]}"`);
620 assertSuggestionKeyEquals("desc");
621 assertSuggestionKeyEquals("messageId");
623 if (hasOwnProperty(expectedSuggestion, "output")) {
624 const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
626 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}"`);
633 // Message was an unexpected type
634 assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
639 if (hasOwnProperty(item, "output")) {
640 if (item.output === null) {
644 "Expected no autofixes to be suggested"
647 assert.strictEqual(result.output, item.output, "Output is incorrect.");
651 assertASTDidntChange(result.beforeAST, result.afterAST);
655 * This creates a mocha test suite and pipes all supplied info through
656 * one of the templates above.
658 RuleTester.describe(ruleName, () => {
659 RuleTester.describe("valid", () => {
660 test.valid.forEach(valid => {
661 RuleTester.it(sanitize(typeof valid === "object" ? valid.code : valid), () => {
662 testValidTemplate(valid);
667 RuleTester.describe("invalid", () => {
668 test.invalid.forEach(invalid => {
669 RuleTester.it(sanitize(invalid.code), () => {
670 testInvalidTemplate(invalid);
678 RuleTester[DESCRIBE] = RuleTester[IT] = null;
680 module.exports = RuleTester;