UNPKG

26 kBJavaScriptView Raw
1/**
2 * @fileoverview Mocha test wrapper
3 * @author Ilya Volodin
4 */
5"use strict";
6
7/* global describe, it */
8
9/*
10 * This is a wrapper around mocha to allow for DRY unittests for eslint
11 * Format:
12 * RuleTester.run("{ruleName}", {
13 * valid: [
14 * "{code}",
15 * { code: "{code}", options: {options}, globals: {globals}, parser: "{parser}", settings: {settings} }
16 * ],
17 * invalid: [
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}"}] }
21 * ]
22 * });
23 *
24 * Variables:
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
33 * received
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.
37 */
38
39//------------------------------------------------------------------------------
40// Requirements
41//------------------------------------------------------------------------------
42
43const
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");
50
51const ajv = require("../shared/ajv")({ strictDefaults: true });
52
53//------------------------------------------------------------------------------
54// Private Members
55//------------------------------------------------------------------------------
56
57/*
58 * testerDefaultConfig must not be modified as it allows to reset the tester to
59 * the initial default configuration
60 */
61const testerDefaultConfig = { rules: {} };
62let defaultConfig = { rules: {} };
63
64/*
65 * List every parameters possible on a test case that are not related to eslint
66 * configuration
67 */
68const RuleTesterParameters = [
69 "code",
70 "filename",
71 "options",
72 "errors",
73 "output"
74];
75
76const hasOwnProperty = Function.call.bind(Object.hasOwnProperty);
77
78/**
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.
83 */
84function cloneDeeplyExcludesParent(x) {
85 if (typeof x === "object" && x !== null) {
86 if (Array.isArray(x)) {
87 return x.map(cloneDeeplyExcludesParent);
88 }
89
90 const retv = {};
91
92 for (const key in x) {
93 if (key !== "parent" && hasOwnProperty(x, key)) {
94 retv[key] = cloneDeeplyExcludesParent(x[key]);
95 }
96 }
97
98 return retv;
99 }
100
101 return x;
102}
103
104/**
105 * Freezes a given value deeply.
106 * @param {any} x A value to freeze.
107 * @returns {void}
108 */
109function freezeDeeply(x) {
110 if (typeof x === "object" && x !== null) {
111 if (Array.isArray(x)) {
112 x.forEach(freezeDeeply);
113 } else {
114 for (const key in x) {
115 if (key !== "parent" && hasOwnProperty(x, key)) {
116 freezeDeeply(x[key]);
117 }
118 }
119 }
120 Object.freeze(x);
121 }
122}
123
124/**
125 * Replace control characters by `\u00xx` form.
126 * @param {string} text The text to sanitize.
127 * @returns {string} The sanitized text.
128 */
129function sanitize(text) {
130 return text.replace(
131 /[\u0000-\u0009|\u000b-\u001a]/gu, // eslint-disable-line no-control-regex
132 c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}`
133 );
134}
135
136//------------------------------------------------------------------------------
137// Public Interface
138//------------------------------------------------------------------------------
139
140// default separators for testing
141const DESCRIBE = Symbol("describe");
142const IT = Symbol("it");
143
144/**
145 * This is `it` default handler if `it` don't exist.
146 * @this {Mocha}
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`.
150 */
151function itDefaultHandler(text, method) {
152 try {
153 return method.call(this);
154 } catch (err) {
155 if (err instanceof assert.AssertionError) {
156 err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`;
157 }
158 throw err;
159 }
160}
161
162/**
163 * This is `describe` default handler if `describe` don't exist.
164 * @this {Mocha}
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`.
168 */
169function describeDefaultHandler(text, method) {
170 return method.call(this);
171}
172
173class RuleTester {
174
175 /**
176 * Creates a new instance of RuleTester.
177 * @param {Object} [testerConfig] Optional, extra configuration for the tester
178 */
179 constructor(testerConfig) {
180
181 /**
182 * The configuration to use for this tester. Combination of the tester
183 * configuration and the default configuration.
184 * @type {Object}
185 */
186 this.testerConfig = lodash.merge(
187
188 // we have to clone because merge uses the first argument for recipient
189 lodash.cloneDeep(defaultConfig),
190 testerConfig,
191 { rules: { "rule-tester/validate-ast": "error" } }
192 );
193
194 /**
195 * Rule definitions to define before tests.
196 * @type {Object}
197 */
198 this.rules = {};
199 this.linter = new Linter();
200 }
201
202 /**
203 * Set the configuration to use for all future tests
204 * @param {Object} config the configuration to use.
205 * @returns {void}
206 */
207 static setDefaultConfig(config) {
208 if (typeof config !== "object") {
209 throw new TypeError("RuleTester.setDefaultConfig: config must be an object");
210 }
211 defaultConfig = config;
212
213 // Make sure the rules object exists since it is assumed to exist later
214 defaultConfig.rules = defaultConfig.rules || {};
215 }
216
217 /**
218 * Get the current configuration used for all tests
219 * @returns {Object} the current configuration
220 */
221 static getDefaultConfig() {
222 return defaultConfig;
223 }
224
225 /**
226 * Reset the configuration to the initial configuration of the tester removing
227 * any changes made until now.
228 * @returns {void}
229 */
230 static resetDefaultConfig() {
231 defaultConfig = lodash.cloneDeep(testerDefaultConfig);
232 }
233
234
235 /*
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
238 * always.
239 */
240 static get describe() {
241 return (
242 this[DESCRIBE] ||
243 (typeof describe === "function" ? describe : describeDefaultHandler)
244 );
245 }
246
247 static set describe(value) {
248 this[DESCRIBE] = value;
249 }
250
251 static get it() {
252 return (
253 this[IT] ||
254 (typeof it === "function" ? it : itDefaultHandler)
255 );
256 }
257
258 static set it(value) {
259 this[IT] = value;
260 }
261
262 /**
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.
266 * @returns {void}
267 */
268 defineRule(name, rule) {
269 this.rules[name] = rule;
270 }
271
272 /**
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.
277 * @returns {void}
278 */
279 run(ruleName, rule, test) {
280
281 const testerConfig = this.testerConfig,
282 requiredScenarios = ["valid", "invalid"],
283 scenarioErrors = [],
284 linter = this.linter;
285
286 if (lodash.isNil(test) || typeof test !== "object") {
287 throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`);
288 }
289
290 requiredScenarios.forEach(scenarioType => {
291 if (lodash.isNil(test[scenarioType])) {
292 scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`);
293 }
294 });
295
296 if (scenarioErrors.length > 0) {
297 throw new Error([
298 `Test Scenarios for rule ${ruleName} is invalid:`
299 ].concat(scenarioErrors).join("\n"));
300 }
301
302
303 linter.defineRule(ruleName, Object.assign({}, rule, {
304
305 // Create a wrapper rule that freezes the `context` properties.
306 create(context) {
307 freezeDeeply(context.options);
308 freezeDeeply(context.settings);
309 freezeDeeply(context.parserOptions);
310
311 return (typeof rule === "function" ? rule : rule.create)(context);
312 }
313 }));
314
315 linter.defineRules(this.rules);
316
317 /**
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
321 * @private
322 */
323 function runRuleForItem(item) {
324 let config = lodash.cloneDeep(testerConfig),
325 code, filename, output, beforeAST, afterAST;
326
327 if (typeof item === "string") {
328 code = item;
329 } else {
330 code = item.code;
331
332 /*
333 * Assumes everything on the item is a config except for the
334 * parameters used by this tester
335 */
336 const itemConfig = lodash.omit(item, RuleTesterParameters);
337
338 /*
339 * Create the config object from the tester config and this item
340 * specific configurations.
341 */
342 config = lodash.merge(
343 config,
344 itemConfig
345 );
346 }
347
348 if (item.filename) {
349 filename = item.filename;
350 }
351
352 if (hasOwnProperty(item, "options")) {
353 assert(Array.isArray(item.options), "options must be an array");
354 config.rules[ruleName] = [1].concat(item.options);
355 } else {
356 config.rules[ruleName] = 1;
357 }
358
359 const schema = getRuleOptionsSchema(rule);
360
361 /*
362 * Setup AST getters.
363 * The goal is to check whether or not AST was modified when
364 * running the rule under test.
365 */
366 linter.defineRule("rule-tester/validate-ast", () => ({
367 Program(node) {
368 beforeAST = cloneDeeplyExcludesParent(node);
369 },
370 "Program:exit"(node) {
371 afterAST = node;
372 }
373 }));
374
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));
378 }
379
380 if (schema) {
381 ajv.validateSchema(schema);
382
383 if (ajv.errors) {
384 const errors = ajv.errors.map(error => {
385 const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath;
386
387 return `\t${field}: ${error.message}`;
388 }).join("\n");
389
390 throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]);
391 }
392
393 /*
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.
398 */
399 try {
400 ajv.compile(schema);
401 } catch (err) {
402 throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`);
403 }
404 }
405
406 validate(config, "rule-tester", id => (id === ruleName ? rule : null));
407
408 // Verify the code.
409 const messages = linter.verify(code, config, filename);
410
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);
414
415 assert(!errorMessage, `A fatal parsing error occurred: ${errorMessage && errorMessage.message}`);
416 }
417
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);
422
423 assert(!errorMessageInFix, `A fatal parsing error occurred in autofix: ${errorMessageInFix && errorMessageInFix.message}`);
424 } else {
425 output = code;
426 }
427
428 return {
429 messages,
430 output,
431 beforeAST,
432 afterAST: cloneDeeplyExcludesParent(afterAST)
433 };
434 }
435
436 /**
437 * Check if the AST was changed
438 * @param {ASTNode} beforeAST AST node before running
439 * @param {ASTNode} afterAST AST node after running
440 * @returns {void}
441 * @private
442 */
443 function assertASTDidntChange(beforeAST, afterAST) {
444 if (!lodash.isEqual(beforeAST, afterAST)) {
445 assert.fail("Rule should not modify AST.");
446 }
447 }
448
449 /**
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
453 * @returns {void}
454 * @private
455 */
456 function testValidTemplate(item) {
457 const result = runRuleForItem(item);
458 const messages = result.messages;
459
460 assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s",
461 messages.length, util.inspect(messages)));
462
463 assertASTDidntChange(result.beforeAST, result.afterAST);
464 }
465
466 /**
467 * Asserts that the message matches its expected value. If the expected
468 * value is a regular expression, it is checked against the actual
469 * value.
470 * @param {string} actual Actual value
471 * @param {string|RegExp} expected Expected value
472 * @returns {void}
473 * @private
474 */
475 function assertMessageMatches(actual, expected) {
476 if (expected instanceof RegExp) {
477
478 // assert.js doesn't have a built-in RegExp match function
479 assert.ok(
480 expected.test(actual),
481 `Expected '${actual}' to match ${expected}`
482 );
483 } else {
484 assert.strictEqual(actual, expected);
485 }
486 }
487
488 /**
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
492 * @returns {void}
493 * @private
494 */
495 function testInvalidTemplate(item) {
496 assert.ok(item.errors || item.errors === 0,
497 `Did not specify errors for an invalid test of ${ruleName}`);
498
499 const result = runRuleForItem(item);
500 const messages = result.messages;
501
502
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)));
506 } else {
507 assert.strictEqual(
508 messages.length, item.errors.length,
509 util.format(
510 "Should have %d error%s but had %d: %s",
511 item.errors.length, item.errors.length === 1 ? "" : "s", messages.length, util.inspect(messages)
512 )
513 );
514
515 const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName);
516
517 for (let i = 0, l = item.errors.length; i < l; i++) {
518 const error = item.errors[i];
519 const message = messages[i];
520
521 assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested");
522
523 if (typeof error === "string" || error instanceof RegExp) {
524
525 // Just an error message.
526 assertMessageMatches(message.message, error);
527 } else if (typeof error === "object") {
528
529 /*
530 * Error object.
531 * This may have a message, messageId, data, node type, line, and/or
532 * column.
533 */
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")) {
539 assert.ok(
540 hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"),
541 "Error can not use 'messageId' if rule under test doesn't define 'meta.messages'."
542 );
543 if (!hasOwnProperty(rule.meta.messages, error.messageId)) {
544 const friendlyIDList = `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]`;
545
546 assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`);
547 }
548 assert.strictEqual(
549 message.messageId,
550 error.messageId,
551 `messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.`
552 );
553 if (hasOwnProperty(error, "data")) {
554
555 /*
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.
559 */
560 const unformattedOriginalMessage = rule.meta.messages[error.messageId];
561 const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data);
562
563 assert.strictEqual(
564 message.message,
565 rehydratedMessage,
566 `Hydrated message "${rehydratedMessage}" does not match "${message.message}"`
567 );
568 }
569 }
570
571 assert.ok(
572 hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true,
573 "Error must specify 'messageId' if 'data' is used."
574 );
575
576 if (error.type) {
577 assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`);
578 }
579
580 if (hasOwnProperty(error, "line")) {
581 assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`);
582 }
583
584 if (hasOwnProperty(error, "column")) {
585 assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`);
586 }
587
588 if (hasOwnProperty(error, "endLine")) {
589 assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`);
590 }
591
592 if (hasOwnProperty(error, "endColumn")) {
593 assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`);
594 }
595
596 if (hasOwnProperty(error, "suggestions")) {
597
598 // Support asserting there are no suggestions
599 if (!error.suggestions) {
600 assert.strictEqual(message.suggestions, error.suggestions, `Error should have no suggestions on error with message: "${message.message}"`);
601 } else {
602 assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`);
603 assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`);
604
605 error.suggestions.forEach((expectedSuggestion, index) => {
606 const actualSuggestion = message.suggestions[index];
607
608 /**
609 * Tests equality of a suggestion key if that key is defined in the expected output.
610 * @param {string} key Key to validate from the suggestion object
611 * @returns {void}
612 */
613 function assertSuggestionKeyEquals(key) {
614 if (hasOwnProperty(expectedSuggestion, key)) {
615 assert.deepStrictEqual(actualSuggestion[key], expectedSuggestion[key], `Error suggestion at index: ${index} should have desc of: "${actualSuggestion[key]}"`);
616 }
617 }
618 assertSuggestionKeyEquals("desc");
619 assertSuggestionKeyEquals("messageId");
620
621 if (hasOwnProperty(expectedSuggestion, "output")) {
622 const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output;
623
624 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}"`);
625 }
626 });
627 }
628 }
629 } else {
630
631 // Message was an unexpected type
632 assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`);
633 }
634 }
635 }
636
637 if (hasOwnProperty(item, "output")) {
638 if (item.output === null) {
639 assert.strictEqual(
640 result.output,
641 item.code,
642 "Expected no autofixes to be suggested"
643 );
644 } else {
645 assert.strictEqual(result.output, item.output, "Output is incorrect.");
646 }
647 }
648
649 assertASTDidntChange(result.beforeAST, result.afterAST);
650 }
651
652 /*
653 * This creates a mocha test suite and pipes all supplied info through
654 * one of the templates above.
655 */
656 RuleTester.describe(ruleName, () => {
657 RuleTester.describe("valid", () => {
658 test.valid.forEach(valid => {
659 RuleTester.it(sanitize(typeof valid === "object" ? valid.code : valid), () => {
660 testValidTemplate(valid);
661 });
662 });
663 });
664
665 RuleTester.describe("invalid", () => {
666 test.invalid.forEach(invalid => {
667 RuleTester.it(sanitize(invalid.code), () => {
668 testInvalidTemplate(invalid);
669 });
670 });
671 });
672 });
673 }
674}
675
676RuleTester[DESCRIBE] = RuleTester[IT] = null;
677
678module.exports = RuleTester;