|
|
|
|
|
|
|
|
|
"use strict"; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const |
|
assert = require("assert"), |
|
path = require("path"), |
|
util = require("util"), |
|
merge = require("lodash.merge"), |
|
equal = require("fast-deep-equal"), |
|
Traverser = require("../../lib/shared/traverser"), |
|
{ getRuleOptionsSchema, validate } = require("../shared/config-validator"), |
|
{ Linter, SourceCodeFixer, interpolate } = require("../linter"), |
|
CodePath = require("../linter/code-path-analysis/code-path"); |
|
|
|
const ajv = require("../shared/ajv")({ strictDefaults: true }); |
|
|
|
const espreePath = require.resolve("espree"); |
|
const parserSymbol = Symbol.for("eslint.RuleTester.parser"); |
|
|
|
const { SourceCode } = require("../source-code"); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const testerDefaultConfig = { rules: {} }; |
|
let defaultConfig = { rules: {} }; |
|
|
|
|
|
|
|
|
|
|
|
const RuleTesterParameters = [ |
|
"name", |
|
"code", |
|
"filename", |
|
"options", |
|
"errors", |
|
"output", |
|
"only" |
|
]; |
|
|
|
|
|
|
|
|
|
const errorObjectParameters = new Set([ |
|
"message", |
|
"messageId", |
|
"data", |
|
"type", |
|
"line", |
|
"column", |
|
"endLine", |
|
"endColumn", |
|
"suggestions" |
|
]); |
|
const friendlyErrorObjectParameterList = `[${[...errorObjectParameters].map(key => `'${key}'`).join(", ")}]`; |
|
|
|
|
|
|
|
|
|
const suggestionObjectParameters = new Set([ |
|
"desc", |
|
"messageId", |
|
"data", |
|
"output" |
|
]); |
|
const friendlySuggestionObjectParameterList = `[${[...suggestionObjectParameters].map(key => `'${key}'`).join(", ")}]`; |
|
|
|
const forbiddenMethods = [ |
|
"applyInlineConfig", |
|
"applyLanguageOptions", |
|
"finalize" |
|
]; |
|
|
|
const hasOwnProperty = Function.call.bind(Object.hasOwnProperty); |
|
|
|
const DEPRECATED_SOURCECODE_PASSTHROUGHS = { |
|
getSource: "getText", |
|
getSourceLines: "getLines", |
|
getAllComments: "getAllComments", |
|
getNodeByRangeIndex: "getNodeByRangeIndex", |
|
|
|
|
|
getCommentsBefore: "getCommentsBefore", |
|
getCommentsAfter: "getCommentsAfter", |
|
getCommentsInside: "getCommentsInside", |
|
getJSDocComment: "getJSDocComment", |
|
getFirstToken: "getFirstToken", |
|
getFirstTokens: "getFirstTokens", |
|
getLastToken: "getLastToken", |
|
getLastTokens: "getLastTokens", |
|
getTokenAfter: "getTokenAfter", |
|
getTokenBefore: "getTokenBefore", |
|
getTokenByRangeStart: "getTokenByRangeStart", |
|
getTokens: "getTokens", |
|
getTokensAfter: "getTokensAfter", |
|
getTokensBefore: "getTokensBefore", |
|
getTokensBetween: "getTokensBetween", |
|
|
|
getScope: "getScope", |
|
getAncestors: "getAncestors", |
|
getDeclaredVariables: "getDeclaredVariables", |
|
markVariableAsUsed: "markVariableAsUsed" |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function cloneDeeplyExcludesParent(x) { |
|
if (typeof x === "object" && x !== null) { |
|
if (Array.isArray(x)) { |
|
return x.map(cloneDeeplyExcludesParent); |
|
} |
|
|
|
const retv = {}; |
|
|
|
for (const key in x) { |
|
if (key !== "parent" && hasOwnProperty(x, key)) { |
|
retv[key] = cloneDeeplyExcludesParent(x[key]); |
|
} |
|
} |
|
|
|
return retv; |
|
} |
|
|
|
return x; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function freezeDeeply(x) { |
|
if (typeof x === "object" && x !== null) { |
|
if (Array.isArray(x)) { |
|
x.forEach(freezeDeeply); |
|
} else { |
|
for (const key in x) { |
|
if (key !== "parent" && hasOwnProperty(x, key)) { |
|
freezeDeeply(x[key]); |
|
} |
|
} |
|
} |
|
Object.freeze(x); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function sanitize(text) { |
|
if (typeof text !== "string") { |
|
return ""; |
|
} |
|
return text.replace( |
|
/[\u0000-\u0009\u000b-\u001a]/gu, |
|
c => `\\u${c.codePointAt(0).toString(16).padStart(4, "0")}` |
|
); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function defineStartEndAsError(objName, node) { |
|
Object.defineProperties(node, { |
|
start: { |
|
get() { |
|
throw new Error(`Use ${objName}.range[0] instead of ${objName}.start`); |
|
}, |
|
configurable: true, |
|
enumerable: false |
|
}, |
|
end: { |
|
get() { |
|
throw new Error(`Use ${objName}.range[1] instead of ${objName}.end`); |
|
}, |
|
configurable: true, |
|
enumerable: false |
|
} |
|
}); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function defineStartEndAsErrorInTree(ast, visitorKeys) { |
|
Traverser.traverse(ast, { visitorKeys, enter: defineStartEndAsError.bind(null, "node") }); |
|
ast.tokens.forEach(defineStartEndAsError.bind(null, "token")); |
|
ast.comments.forEach(defineStartEndAsError.bind(null, "token")); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function wrapParser(parser) { |
|
|
|
if (typeof parser.parseForESLint === "function") { |
|
return { |
|
[parserSymbol]: parser, |
|
parseForESLint(...args) { |
|
const ret = parser.parseForESLint(...args); |
|
|
|
defineStartEndAsErrorInTree(ret.ast, ret.visitorKeys); |
|
return ret; |
|
} |
|
}; |
|
} |
|
|
|
return { |
|
[parserSymbol]: parser, |
|
parse(...args) { |
|
const ast = parser.parse(...args); |
|
|
|
defineStartEndAsErrorInTree(ast); |
|
return ast; |
|
} |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function getCommentsDeprecation() { |
|
throw new Error( |
|
"`SourceCode#getComments()` is deprecated and will be removed in a future major version. Use `getCommentsBefore()`, `getCommentsAfter()`, and `getCommentsInside()` instead." |
|
); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function throwForbiddenMethodError(methodName) { |
|
return () => { |
|
throw new Error( |
|
`\`SourceCode#${methodName}()\` cannot be called inside a rule.` |
|
); |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function emitLegacyRuleAPIWarning(ruleName) { |
|
if (!emitLegacyRuleAPIWarning[`warned-${ruleName}`]) { |
|
emitLegacyRuleAPIWarning[`warned-${ruleName}`] = true; |
|
process.emitWarning( |
|
`"${ruleName}" rule is using the deprecated function-style format and will stop working in ESLint v9. Please use object-style format: https://eslint.org/docs/latest/extend/custom-rules`, |
|
"DeprecationWarning" |
|
); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function emitMissingSchemaWarning(ruleName) { |
|
if (!emitMissingSchemaWarning[`warned-${ruleName}`]) { |
|
emitMissingSchemaWarning[`warned-${ruleName}`] = true; |
|
process.emitWarning( |
|
`"${ruleName}" rule has options but is missing the "meta.schema" property and will stop working in ESLint v9. Please add a schema: https://eslint.org/docs/latest/extend/custom-rules#options-schemas`, |
|
"DeprecationWarning" |
|
); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function emitDeprecatedContextMethodWarning(ruleName, methodName) { |
|
if (!emitDeprecatedContextMethodWarning[`warned-${ruleName}-${methodName}`]) { |
|
emitDeprecatedContextMethodWarning[`warned-${ruleName}-${methodName}`] = true; |
|
process.emitWarning( |
|
`"${ruleName}" rule is using \`context.${methodName}()\`, which is deprecated and will be removed in ESLint v9. Please use \`sourceCode.${DEPRECATED_SOURCECODE_PASSTHROUGHS[methodName]}()\` instead.`, |
|
"DeprecationWarning" |
|
); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function emitCodePathCurrentSegmentsWarning(ruleName) { |
|
if (!emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`]) { |
|
emitCodePathCurrentSegmentsWarning[`warned-${ruleName}`] = true; |
|
process.emitWarning( |
|
`"${ruleName}" rule uses CodePath#currentSegments and will stop working in ESLint v9. Please read the documentation for how to update your code: https://eslint.org/docs/latest/extend/code-path-analysis#usage-examples`, |
|
"DeprecationWarning" |
|
); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
function emitParserServicesWarning(ruleName) { |
|
if (!emitParserServicesWarning[`warned-${ruleName}`]) { |
|
emitParserServicesWarning[`warned-${ruleName}`] = true; |
|
process.emitWarning( |
|
`"${ruleName}" rule is using \`context.parserServices\`, which is deprecated and will be removed in ESLint v9. Please use \`sourceCode.parserServices\` instead.`, |
|
"DeprecationWarning" |
|
); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
const DESCRIBE = Symbol("describe"); |
|
const IT = Symbol("it"); |
|
const IT_ONLY = Symbol("itOnly"); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function itDefaultHandler(text, method) { |
|
try { |
|
return method.call(this); |
|
} catch (err) { |
|
if (err instanceof assert.AssertionError) { |
|
err.message += ` (${util.inspect(err.actual)} ${err.operator} ${util.inspect(err.expected)})`; |
|
} |
|
throw err; |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function describeDefaultHandler(text, method) { |
|
return method.call(this); |
|
} |
|
|
|
|
|
|
|
|
|
class RuleTester { |
|
|
|
|
|
|
|
|
|
|
|
constructor(testerConfig) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
this.testerConfig = merge( |
|
{}, |
|
defaultConfig, |
|
testerConfig, |
|
{ rules: { "rule-tester/validate-ast": "error" } } |
|
); |
|
|
|
|
|
|
|
|
|
|
|
this.rules = {}; |
|
this.linter = new Linter(); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
static setDefaultConfig(config) { |
|
if (typeof config !== "object" || config === null) { |
|
throw new TypeError("RuleTester.setDefaultConfig: config must be an object"); |
|
} |
|
defaultConfig = config; |
|
|
|
|
|
defaultConfig.rules = defaultConfig.rules || {}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
static getDefaultConfig() { |
|
return defaultConfig; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static resetDefaultConfig() { |
|
defaultConfig = merge({}, testerDefaultConfig); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
static get describe() { |
|
return ( |
|
this[DESCRIBE] || |
|
(typeof describe === "function" ? describe : describeDefaultHandler) |
|
); |
|
} |
|
|
|
static set describe(value) { |
|
this[DESCRIBE] = value; |
|
} |
|
|
|
static get it() { |
|
return ( |
|
this[IT] || |
|
(typeof it === "function" ? it : itDefaultHandler) |
|
); |
|
} |
|
|
|
static set it(value) { |
|
this[IT] = value; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
static only(item) { |
|
if (typeof item === "string") { |
|
return { code: item, only: true }; |
|
} |
|
|
|
return { ...item, only: true }; |
|
} |
|
|
|
static get itOnly() { |
|
if (typeof this[IT_ONLY] === "function") { |
|
return this[IT_ONLY]; |
|
} |
|
if (typeof this[IT] === "function" && typeof this[IT].only === "function") { |
|
return Function.bind.call(this[IT].only, this[IT]); |
|
} |
|
if (typeof it === "function" && typeof it.only === "function") { |
|
return Function.bind.call(it.only, it); |
|
} |
|
|
|
if (typeof this[DESCRIBE] === "function" || typeof this[IT] === "function") { |
|
throw new Error( |
|
"Set `RuleTester.itOnly` to use `only` with a custom test framework.\n" + |
|
"See https://eslint.org/docs/latest/integrate/nodejs-api#customizing-ruletester for more." |
|
); |
|
} |
|
if (typeof it === "function") { |
|
throw new Error("The current test framework does not support exclusive tests with `only`."); |
|
} |
|
throw new Error("To use `only`, use RuleTester with a test framework that provides `it.only()` like Mocha."); |
|
} |
|
|
|
static set itOnly(value) { |
|
this[IT_ONLY] = value; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
defineRule(name, rule) { |
|
if (typeof rule === "function") { |
|
emitLegacyRuleAPIWarning(name); |
|
} |
|
this.rules[name] = rule; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
run(ruleName, rule, test) { |
|
|
|
const testerConfig = this.testerConfig, |
|
requiredScenarios = ["valid", "invalid"], |
|
scenarioErrors = [], |
|
linter = this.linter; |
|
|
|
if (!test || typeof test !== "object") { |
|
throw new TypeError(`Test Scenarios for rule ${ruleName} : Could not find test scenario object`); |
|
} |
|
|
|
requiredScenarios.forEach(scenarioType => { |
|
if (!test[scenarioType]) { |
|
scenarioErrors.push(`Could not find any ${scenarioType} test scenarios`); |
|
} |
|
}); |
|
|
|
if (scenarioErrors.length > 0) { |
|
throw new Error([ |
|
`Test Scenarios for rule ${ruleName} is invalid:` |
|
].concat(scenarioErrors).join("\n")); |
|
} |
|
|
|
if (typeof rule === "function") { |
|
emitLegacyRuleAPIWarning(ruleName); |
|
} |
|
|
|
linter.defineRule(ruleName, Object.assign({}, rule, { |
|
|
|
|
|
create(context) { |
|
freezeDeeply(context.options); |
|
freezeDeeply(context.settings); |
|
freezeDeeply(context.parserOptions); |
|
|
|
|
|
const newContext = Object.create( |
|
context, |
|
Object.fromEntries(Object.keys(DEPRECATED_SOURCECODE_PASSTHROUGHS).map(methodName => [ |
|
methodName, |
|
{ |
|
value(...args) { |
|
|
|
|
|
emitDeprecatedContextMethodWarning(ruleName, methodName); |
|
|
|
|
|
return context[methodName].call(this, ...args); |
|
}, |
|
enumerable: true |
|
} |
|
])) |
|
); |
|
|
|
|
|
const parserServices = context.parserServices; |
|
|
|
Object.defineProperty(newContext, "parserServices", { |
|
get() { |
|
emitParserServicesWarning(ruleName); |
|
return parserServices; |
|
} |
|
}); |
|
|
|
Object.freeze(newContext); |
|
|
|
return (typeof rule === "function" ? rule : rule.create)(newContext); |
|
} |
|
})); |
|
|
|
linter.defineRules(this.rules); |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function runRuleForItem(item) { |
|
let config = merge({}, testerConfig), |
|
code, filename, output, beforeAST, afterAST; |
|
|
|
if (typeof item === "string") { |
|
code = item; |
|
} else { |
|
code = item.code; |
|
|
|
|
|
|
|
|
|
|
|
const itemConfig = { ...item }; |
|
|
|
for (const parameter of RuleTesterParameters) { |
|
delete itemConfig[parameter]; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
config = merge( |
|
config, |
|
itemConfig |
|
); |
|
} |
|
|
|
if (item.filename) { |
|
filename = item.filename; |
|
} |
|
|
|
if (hasOwnProperty(item, "options")) { |
|
assert(Array.isArray(item.options), "options must be an array"); |
|
if ( |
|
item.options.length > 0 && |
|
typeof rule === "object" && |
|
( |
|
!rule.meta || (rule.meta && (typeof rule.meta.schema === "undefined" || rule.meta.schema === null)) |
|
) |
|
) { |
|
emitMissingSchemaWarning(ruleName); |
|
} |
|
config.rules[ruleName] = [1].concat(item.options); |
|
} else { |
|
config.rules[ruleName] = 1; |
|
} |
|
|
|
const schema = getRuleOptionsSchema(rule); |
|
|
|
|
|
|
|
|
|
|
|
|
|
linter.defineRule("rule-tester/validate-ast", { |
|
create() { |
|
return { |
|
Program(node) { |
|
beforeAST = cloneDeeplyExcludesParent(node); |
|
}, |
|
"Program:exit"(node) { |
|
afterAST = node; |
|
} |
|
}; |
|
} |
|
}); |
|
|
|
if (typeof config.parser === "string") { |
|
assert(path.isAbsolute(config.parser), "Parsers provided as strings to RuleTester must be absolute paths"); |
|
} else { |
|
config.parser = espreePath; |
|
} |
|
|
|
linter.defineParser(config.parser, wrapParser(require(config.parser))); |
|
|
|
if (schema) { |
|
ajv.validateSchema(schema); |
|
|
|
if (ajv.errors) { |
|
const errors = ajv.errors.map(error => { |
|
const field = error.dataPath[0] === "." ? error.dataPath.slice(1) : error.dataPath; |
|
|
|
return `\t${field}: ${error.message}`; |
|
}).join("\n"); |
|
|
|
throw new Error([`Schema for rule ${ruleName} is invalid:`, errors]); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
try { |
|
ajv.compile(schema); |
|
} catch (err) { |
|
throw new Error(`Schema for rule ${ruleName} is invalid: ${err.message}`); |
|
} |
|
} |
|
|
|
validate(config, "rule-tester", id => (id === ruleName ? rule : null)); |
|
|
|
|
|
const { getComments, applyLanguageOptions, applyInlineConfig, finalize } = SourceCode.prototype; |
|
const originalCurrentSegments = Object.getOwnPropertyDescriptor(CodePath.prototype, "currentSegments"); |
|
let messages; |
|
|
|
try { |
|
SourceCode.prototype.getComments = getCommentsDeprecation; |
|
Object.defineProperty(CodePath.prototype, "currentSegments", { |
|
get() { |
|
emitCodePathCurrentSegmentsWarning(ruleName); |
|
return originalCurrentSegments.get.call(this); |
|
} |
|
}); |
|
|
|
forbiddenMethods.forEach(methodName => { |
|
SourceCode.prototype[methodName] = throwForbiddenMethodError(methodName); |
|
}); |
|
|
|
messages = linter.verify(code, config, filename); |
|
} finally { |
|
SourceCode.prototype.getComments = getComments; |
|
Object.defineProperty(CodePath.prototype, "currentSegments", originalCurrentSegments); |
|
SourceCode.prototype.applyInlineConfig = applyInlineConfig; |
|
SourceCode.prototype.applyLanguageOptions = applyLanguageOptions; |
|
SourceCode.prototype.finalize = finalize; |
|
} |
|
|
|
const fatalErrorMessage = messages.find(m => m.fatal); |
|
|
|
assert(!fatalErrorMessage, `A fatal parsing error occurred: ${fatalErrorMessage && fatalErrorMessage.message}`); |
|
|
|
|
|
if (messages.some(m => m.fix)) { |
|
output = SourceCodeFixer.applyFixes(code, messages).output; |
|
const errorMessageInFix = linter.verify(output, config, filename).find(m => m.fatal); |
|
|
|
assert(!errorMessageInFix, [ |
|
"A fatal parsing error occurred in autofix.", |
|
`Error: ${errorMessageInFix && errorMessageInFix.message}`, |
|
"Autofix output:", |
|
output |
|
].join("\n")); |
|
} else { |
|
output = code; |
|
} |
|
|
|
return { |
|
messages, |
|
output, |
|
beforeAST, |
|
afterAST: cloneDeeplyExcludesParent(afterAST) |
|
}; |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function assertASTDidntChange(beforeAST, afterAST) { |
|
if (!equal(beforeAST, afterAST)) { |
|
assert.fail("Rule should not modify AST."); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function testValidTemplate(item) { |
|
const code = typeof item === "object" ? item.code : item; |
|
|
|
assert.ok(typeof code === "string", "Test case must specify a string value for 'code'"); |
|
if (item.name) { |
|
assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string"); |
|
} |
|
|
|
const result = runRuleForItem(item); |
|
const messages = result.messages; |
|
|
|
assert.strictEqual(messages.length, 0, util.format("Should have no errors but had %d: %s", |
|
messages.length, |
|
util.inspect(messages))); |
|
|
|
assertASTDidntChange(result.beforeAST, result.afterAST); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function assertMessageMatches(actual, expected) { |
|
if (expected instanceof RegExp) { |
|
|
|
|
|
assert.ok( |
|
expected.test(actual), |
|
`Expected '${actual}' to match ${expected}` |
|
); |
|
} else { |
|
assert.strictEqual(actual, expected); |
|
} |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function testInvalidTemplate(item) { |
|
assert.ok(typeof item.code === "string", "Test case must specify a string value for 'code'"); |
|
if (item.name) { |
|
assert.ok(typeof item.name === "string", "Optional test case property 'name' must be a string"); |
|
} |
|
assert.ok(item.errors || item.errors === 0, |
|
`Did not specify errors for an invalid test of ${ruleName}`); |
|
|
|
if (Array.isArray(item.errors) && item.errors.length === 0) { |
|
assert.fail("Invalid cases must have at least one error"); |
|
} |
|
|
|
const ruleHasMetaMessages = hasOwnProperty(rule, "meta") && hasOwnProperty(rule.meta, "messages"); |
|
const friendlyIDList = ruleHasMetaMessages ? `[${Object.keys(rule.meta.messages).map(key => `'${key}'`).join(", ")}]` : null; |
|
|
|
const result = runRuleForItem(item); |
|
const messages = result.messages; |
|
|
|
if (typeof item.errors === "number") { |
|
|
|
if (item.errors === 0) { |
|
assert.fail("Invalid cases must have 'error' value greater than 0"); |
|
} |
|
|
|
assert.strictEqual(messages.length, item.errors, util.format("Should have %d error%s but had %d: %s", |
|
item.errors, |
|
item.errors === 1 ? "" : "s", |
|
messages.length, |
|
util.inspect(messages))); |
|
} else { |
|
assert.strictEqual( |
|
messages.length, item.errors.length, util.format( |
|
"Should have %d error%s but had %d: %s", |
|
item.errors.length, |
|
item.errors.length === 1 ? "" : "s", |
|
messages.length, |
|
util.inspect(messages) |
|
) |
|
); |
|
|
|
const hasMessageOfThisRule = messages.some(m => m.ruleId === ruleName); |
|
|
|
for (let i = 0, l = item.errors.length; i < l; i++) { |
|
const error = item.errors[i]; |
|
const message = messages[i]; |
|
|
|
assert(hasMessageOfThisRule, "Error rule name should be the same as the name of the rule being tested"); |
|
|
|
if (typeof error === "string" || error instanceof RegExp) { |
|
|
|
|
|
assertMessageMatches(message.message, error); |
|
} else if (typeof error === "object" && error !== null) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Object.keys(error).forEach(propertyName => { |
|
assert.ok( |
|
errorObjectParameters.has(propertyName), |
|
`Invalid error property name '${propertyName}'. Expected one of ${friendlyErrorObjectParameterList}.` |
|
); |
|
}); |
|
|
|
if (hasOwnProperty(error, "message")) { |
|
assert.ok(!hasOwnProperty(error, "messageId"), "Error should not specify both 'message' and a 'messageId'."); |
|
assert.ok(!hasOwnProperty(error, "data"), "Error should not specify both 'data' and 'message'."); |
|
assertMessageMatches(message.message, error.message); |
|
} else if (hasOwnProperty(error, "messageId")) { |
|
assert.ok( |
|
ruleHasMetaMessages, |
|
"Error can not use 'messageId' if rule under test doesn't define 'meta.messages'." |
|
); |
|
if (!hasOwnProperty(rule.meta.messages, error.messageId)) { |
|
assert(false, `Invalid messageId '${error.messageId}'. Expected one of ${friendlyIDList}.`); |
|
} |
|
assert.strictEqual( |
|
message.messageId, |
|
error.messageId, |
|
`messageId '${message.messageId}' does not match expected messageId '${error.messageId}'.` |
|
); |
|
if (hasOwnProperty(error, "data")) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
const unformattedOriginalMessage = rule.meta.messages[error.messageId]; |
|
const rehydratedMessage = interpolate(unformattedOriginalMessage, error.data); |
|
|
|
assert.strictEqual( |
|
message.message, |
|
rehydratedMessage, |
|
`Hydrated message "${rehydratedMessage}" does not match "${message.message}"` |
|
); |
|
} |
|
} |
|
|
|
assert.ok( |
|
hasOwnProperty(error, "data") ? hasOwnProperty(error, "messageId") : true, |
|
"Error must specify 'messageId' if 'data' is used." |
|
); |
|
|
|
if (error.type) { |
|
assert.strictEqual(message.nodeType, error.type, `Error type should be ${error.type}, found ${message.nodeType}`); |
|
} |
|
|
|
if (hasOwnProperty(error, "line")) { |
|
assert.strictEqual(message.line, error.line, `Error line should be ${error.line}`); |
|
} |
|
|
|
if (hasOwnProperty(error, "column")) { |
|
assert.strictEqual(message.column, error.column, `Error column should be ${error.column}`); |
|
} |
|
|
|
if (hasOwnProperty(error, "endLine")) { |
|
assert.strictEqual(message.endLine, error.endLine, `Error endLine should be ${error.endLine}`); |
|
} |
|
|
|
if (hasOwnProperty(error, "endColumn")) { |
|
assert.strictEqual(message.endColumn, error.endColumn, `Error endColumn should be ${error.endColumn}`); |
|
} |
|
|
|
if (hasOwnProperty(error, "suggestions")) { |
|
|
|
|
|
if (!error.suggestions || (Array.isArray(error.suggestions) && error.suggestions.length === 0)) { |
|
if (Array.isArray(message.suggestions) && message.suggestions.length > 0) { |
|
assert.fail(`Error should have no suggestions on error with message: "${message.message}"`); |
|
} |
|
} else { |
|
assert.strictEqual(Array.isArray(message.suggestions), true, `Error should have an array of suggestions. Instead received "${message.suggestions}" on error with message: "${message.message}"`); |
|
assert.strictEqual(message.suggestions.length, error.suggestions.length, `Error should have ${error.suggestions.length} suggestions. Instead found ${message.suggestions.length} suggestions`); |
|
|
|
error.suggestions.forEach((expectedSuggestion, index) => { |
|
assert.ok( |
|
typeof expectedSuggestion === "object" && expectedSuggestion !== null, |
|
"Test suggestion in 'suggestions' array must be an object." |
|
); |
|
Object.keys(expectedSuggestion).forEach(propertyName => { |
|
assert.ok( |
|
suggestionObjectParameters.has(propertyName), |
|
`Invalid suggestion property name '${propertyName}'. Expected one of ${friendlySuggestionObjectParameterList}.` |
|
); |
|
}); |
|
|
|
const actualSuggestion = message.suggestions[index]; |
|
const suggestionPrefix = `Error Suggestion at index ${index} :`; |
|
|
|
if (hasOwnProperty(expectedSuggestion, "desc")) { |
|
assert.ok( |
|
!hasOwnProperty(expectedSuggestion, "data"), |
|
`${suggestionPrefix} Test should not specify both 'desc' and 'data'.` |
|
); |
|
assert.strictEqual( |
|
actualSuggestion.desc, |
|
expectedSuggestion.desc, |
|
`${suggestionPrefix} desc should be "${expectedSuggestion.desc}" but got "${actualSuggestion.desc}" instead.` |
|
); |
|
} |
|
|
|
if (hasOwnProperty(expectedSuggestion, "messageId")) { |
|
assert.ok( |
|
ruleHasMetaMessages, |
|
`${suggestionPrefix} Test can not use 'messageId' if rule under test doesn't define 'meta.messages'.` |
|
); |
|
assert.ok( |
|
hasOwnProperty(rule.meta.messages, expectedSuggestion.messageId), |
|
`${suggestionPrefix} Test has invalid messageId '${expectedSuggestion.messageId}', the rule under test allows only one of ${friendlyIDList}.` |
|
); |
|
assert.strictEqual( |
|
actualSuggestion.messageId, |
|
expectedSuggestion.messageId, |
|
`${suggestionPrefix} messageId should be '${expectedSuggestion.messageId}' but got '${actualSuggestion.messageId}' instead.` |
|
); |
|
if (hasOwnProperty(expectedSuggestion, "data")) { |
|
const unformattedMetaMessage = rule.meta.messages[expectedSuggestion.messageId]; |
|
const rehydratedDesc = interpolate(unformattedMetaMessage, expectedSuggestion.data); |
|
|
|
assert.strictEqual( |
|
actualSuggestion.desc, |
|
rehydratedDesc, |
|
`${suggestionPrefix} Hydrated test desc "${rehydratedDesc}" does not match received desc "${actualSuggestion.desc}".` |
|
); |
|
} |
|
} else { |
|
assert.ok( |
|
!hasOwnProperty(expectedSuggestion, "data"), |
|
`${suggestionPrefix} Test must specify 'messageId' if 'data' is used.` |
|
); |
|
} |
|
|
|
if (hasOwnProperty(expectedSuggestion, "output")) { |
|
const codeWithAppliedSuggestion = SourceCodeFixer.applyFixes(item.code, [actualSuggestion]).output; |
|
|
|
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}"`); |
|
} |
|
}); |
|
} |
|
} |
|
} else { |
|
|
|
|
|
assert.fail(`Error should be a string, object, or RegExp, but found (${util.inspect(message)})`); |
|
} |
|
} |
|
} |
|
|
|
if (hasOwnProperty(item, "output")) { |
|
if (item.output === null) { |
|
assert.strictEqual( |
|
result.output, |
|
item.code, |
|
"Expected no autofixes to be suggested" |
|
); |
|
} else { |
|
assert.strictEqual(result.output, item.output, "Output is incorrect."); |
|
} |
|
} else { |
|
assert.strictEqual( |
|
result.output, |
|
item.code, |
|
"The rule fixed the code. Please add 'output' property." |
|
); |
|
} |
|
|
|
assertASTDidntChange(result.beforeAST, result.afterAST); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
this.constructor.describe(ruleName, () => { |
|
if (test.valid.length > 0) { |
|
this.constructor.describe("valid", () => { |
|
test.valid.forEach(valid => { |
|
this.constructor[valid.only ? "itOnly" : "it"]( |
|
sanitize(typeof valid === "object" ? valid.name || valid.code : valid), |
|
() => { |
|
testValidTemplate(valid); |
|
} |
|
); |
|
}); |
|
}); |
|
} |
|
|
|
if (test.invalid.length > 0) { |
|
this.constructor.describe("invalid", () => { |
|
test.invalid.forEach(invalid => { |
|
this.constructor[invalid.only ? "itOnly" : "it"]( |
|
sanitize(invalid.name || invalid.code), |
|
() => { |
|
testInvalidTemplate(invalid); |
|
} |
|
); |
|
}); |
|
}); |
|
} |
|
}); |
|
} |
|
} |
|
|
|
RuleTester[DESCRIBE] = RuleTester[IT] = RuleTester[IT_ONLY] = null; |
|
|
|
module.exports = RuleTester; |
|
|