eslint-plugin-sonarjs
Version:
397 lines (396 loc) • 16.7 kB
JavaScript
;
/*
* SonarQube JavaScript Plugin
* Copyright (C) SonarSource Sàrl
* mailto:info AT sonarsource DOT com
*
* You can redistribute and/or modify this program under the terms of
* the Sonar Source-Available License Version 1, as published by SonarSource Sàrl.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the Sonar Source-Available License for more details.
*
* You should have received a copy of the Sonar Source-Available License
* along with this program; if not, see https://sonarsource.com/license/ssal/
*/
// https://sonarsource.github.io/rspec/#/rspec/S8754/javascript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.rule = void 0;
const ast_js_1 = require("../helpers/ast.js");
const ancestor_js_1 = require("../helpers/ancestor.js");
const generate_meta_js_1 = require("../helpers/generate-meta.js");
const location_js_1 = require("../helpers/location.js");
const module_js_1 = require("../helpers/module.js");
const mocha_style_test_frameworks_js_1 = require("../helpers/testing/mocha-style-test-frameworks.js");
const meta = __importStar(require("./generated-meta.js"));
const PLAYWRIGHT_DISABLED_DESCRIBE_MODIFIERS = new Set(['skip', 'fixme']);
const MESSAGE = 'Rename this test title to make it unique within the suite.';
const MESSAGE_ID = 'renameDuplicateTitle';
exports.rule = {
meta: (0, generate_meta_js_1.generateMeta)(meta, {
messages: {
[MESSAGE_ID]: MESSAGE,
},
}),
create(context) {
if (!(0, module_js_1.importsOrDependsOnModule)(context, mocha_style_test_frameworks_js_1.SUPPORTED_TEST_FRAMEWORKS, mocha_style_test_frameworks_js_1.SUPPORTED_TEST_FRAMEWORKS)) {
return {};
}
const state = {
context,
classifications: new WeakMap(),
helperSummaries: new Map(),
helperExpansionPath: new Map(),
checkedHelperSuites: new Set(),
reportedDuplicates: new WeakMap(),
};
let suiteStack = [createSuiteFrame()];
const pushedSuiteCalls = new Set();
const concreteSuiteCallbacks = new Set();
// Calls nested in a concrete test body cannot declare collected tests or suites, so they are
// skipped entirely until the outermost test call exits.
let activeTest;
let ignoredSuiteNesting = 0;
let functionNesting = 0;
let concreteSuiteCallbackNesting = 0;
return {
CallExpression(node) {
if (activeTest !== undefined) {
return;
}
const classification = classify(state, node);
if (classification.ignoredSuite) {
ignoredSuiteNesting++;
}
else if (classification.suite) {
pushedSuiteCalls.add(node);
const callback = getCallback(node);
if (callback !== undefined) {
concreteSuiteCallbacks.add(callback);
}
suiteStack.push(createSuiteFrame());
}
const currentSuiteFrame = suiteStack.at(-1);
if (currentSuiteFrame !== undefined &&
ignoredSuiteNesting === 0 &&
isInConcreteCollectionCallback(functionNesting, concreteSuiteCallbackNesting)) {
if (classification.test) {
checkTestTitle(state, node, currentSuiteFrame);
}
else {
checkHelperDefinedTests(state, node, currentSuiteFrame);
}
}
if (classification.concreteTest) {
activeTest = node;
}
},
'CallExpression:exit'(node) {
if (activeTest !== undefined) {
if (activeTest === node) {
activeTest = undefined;
}
return;
}
if (classify(state, node).ignoredSuite) {
ignoredSuiteNesting--;
}
if (pushedSuiteCalls.delete(node)) {
suiteStack.pop();
}
},
':function'(node) {
functionNesting++;
if (concreteSuiteCallbacks.has(node)) {
concreteSuiteCallbackNesting++;
}
},
':function:exit'(node) {
if (concreteSuiteCallbacks.delete(node)) {
concreteSuiteCallbackNesting--;
}
functionNesting--;
},
'Program:exit'() {
suiteStack = [createSuiteFrame()];
pushedSuiteCalls.clear();
concreteSuiteCallbacks.clear();
state.helperSummaries.clear();
state.helperExpansionPath.clear();
state.checkedHelperSuites.clear();
activeTest = undefined;
ignoredSuiteNesting = 0;
functionNesting = 0;
concreteSuiteCallbackNesting = 0;
},
};
},
};
function createSuiteFrame() {
return { titles: new Map(), expandedHelpers: new Map() };
}
function checkTestTitle(state, node, suiteFrame) {
const titleNode = node.arguments[0];
const title = titleNode && (0, mocha_style_test_frameworks_js_1.getStaticTitle)(titleNode);
if (title === undefined) {
return;
}
const originalTitleNode = suiteFrame.titles.get(title);
if (originalTitleNode) {
// Repeated helper expansion can reach the same declaration many times. One issue for each
// primary/secondary location pair is sufficient, including a helper's self-duplicate.
let originals = state.reportedDuplicates.get(titleNode);
if (originals?.has(originalTitleNode)) {
return;
}
if (originals === undefined) {
originals = new WeakSet();
state.reportedDuplicates.set(titleNode, originals);
}
originals.add(originalTitleNode);
(0, location_js_1.report)(state.context, {
node: titleNode,
messageId: MESSAGE_ID,
message: MESSAGE,
}, [(0, location_js_1.toSecondaryLocation)(originalTitleNode, 'Original test title.')]);
return;
}
suiteFrame.titles.set(title, titleNode);
}
function checkHelperDefinedTests(state, node, suiteFrame) {
const helper = getLocalHelperFunction(state.context, node);
if (helper !== undefined) {
expandHelper(state, helper, suiteFrame);
}
}
function expandHelper(state, helper, suiteFrame) {
const cycleDepth = state.helperExpansionPath.get(helper);
if (cycleDepth !== undefined) {
return { tests: new Set(), cycleDepth };
}
const cached = suiteFrame.expandedHelpers.get(helper);
if (cached !== undefined) {
// Replay only the distinct declarations reached by this helper, rather than re-expanding
// its call graph. Rechecking titles is needed when the same helper is invoked twice.
for (const test of cached.tests) {
checkTestTitle(state, test, suiteFrame);
}
return cached;
}
const depth = state.helperExpansionPath.size;
state.helperExpansionPath.set(helper, depth);
const expansion = replayHelperEvents(state, getHelperSummary(state, helper), suiteFrame);
state.helperExpansionPath.delete(helper);
// A cycle closing on this helper or a descendant is contained in its expansion. A cycle
// reaching an active ancestor truncates the result according to the caller's path instead.
if (expansion.cycleDepth >= depth) {
expansion.cycleDepth = Infinity;
suiteFrame.expandedHelpers.set(helper, expansion);
}
return expansion;
}
function replayHelperEvents(state, events, suiteFrame) {
const expansion = { tests: new Set(), cycleDepth: Infinity };
for (const event of events) {
switch (event.kind) {
case 'test':
checkTestTitle(state, event.node, suiteFrame);
expansion.tests.add(event.node);
break;
case 'suite': {
expansion.cycleDepth = Math.min(expansion.cycleDepth, checkHelperSuite(state, event));
break;
}
case 'helper': {
const nested = expandHelper(state, event.helper, suiteFrame);
expansion.cycleDepth = Math.min(expansion.cycleDepth, nested.cycleDepth);
for (const test of nested.tests) {
expansion.tests.add(test);
}
break;
}
}
}
return expansion;
}
function checkHelperSuite(state, event) {
// Helper-defined suites have their own title frame, so their diagnostics do not depend
// on the caller's suite unless recursion truncates their expansion along the current path.
if (state.checkedHelperSuites.has(event)) {
return Infinity;
}
const nested = replayHelperEvents(state, event.events, createSuiteFrame());
if (nested.cycleDepth === Infinity) {
state.checkedHelperSuites.add(event);
}
return nested.cycleDepth;
}
function getHelperSummary(state, helper) {
let events = state.helperSummaries.get(helper);
if (events === undefined) {
events = [];
collectHelperEvents(state, helper.body, events);
state.helperSummaries.set(helper, events);
}
return events;
}
function collectHelperEvents(state, node, events) {
if (node.type === 'CallExpression') {
const classification = classify(state, node);
if (classification.ignoredSuite) {
return;
}
if (classification.suite) {
const nestedEvents = [];
const callback = getCallback(node);
if (callback !== undefined) {
collectHelperEvents(state, callback.body, nestedEvents);
}
events.push({ kind: 'suite', events: nestedEvents });
return;
}
if (classification.test) {
events.push({ kind: 'test', node });
return;
}
const helper = getLocalHelperFunction(state.context, node);
if (helper !== undefined) {
events.push({ kind: 'helper', helper });
}
}
for (const child of (0, ancestor_js_1.childrenOf)(node, state.context.sourceCode.visitorKeys)) {
if (!ast_js_1.FUNCTION_NODES.includes(child.type)) {
collectHelperEvents(state, child, events);
}
}
}
function classify(state, node) {
let classification = state.classifications.get(node);
if (classification === undefined) {
classification = computeClassification(state.context, node);
state.classifications.set(node, classification);
}
return classification;
}
function computeClassification(context, node) {
const mocha = getMochaClassification(context, node.callee);
const playwrightTestQualifiers = (0, mocha_style_test_frameworks_js_1.getPlaywrightTestQualifiers)(context, node.callee);
const playwrightDescribe = getPlaywrightDescribeClassification(playwrightTestQualifiers ?? (0, mocha_style_test_frameworks_js_1.getPlaywrightDescribeQualifiers)(node.callee));
const concreteTest = mocha.test && (0, mocha_style_test_frameworks_js_1.hasCallback)(node);
return {
ignoredSuite: mocha.nonConcreteSuite || playwrightDescribe === 'ignored',
suite: mocha.suite || playwrightDescribe === 'concrete',
test: concreteTest || isPlaywrightTest(playwrightTestQualifiers, node),
concreteTest,
};
}
function getMochaClassification(context, callee) {
const calleeParts = (0, mocha_style_test_frameworks_js_1.getMochaCalleeParts)(callee);
if (calleeParts === undefined) {
return { suite: false, nonConcreteSuite: false, test: false };
}
const { constructName, modifiers } = (0, mocha_style_test_frameworks_js_1.getMochaConstructAndModifiers)(context, calleeParts);
const isSuite = constructName !== undefined && mocha_style_test_frameworks_js_1.SUITE_FUNCTION_NAMES.includes(constructName);
const isTest = constructName !== undefined && mocha_style_test_frameworks_js_1.TEST_FUNCTION_NAMES.includes(constructName);
if (!isSuite && !isTest) {
return { suite: false, nonConcreteSuite: false, test: false };
}
const concrete = modifiers.every(modifier => (0, mocha_style_test_frameworks_js_1.isConcreteMochaTestModifier)(context, modifier));
return {
suite: isSuite && concrete,
nonConcreteSuite: isSuite && !concrete,
test: isTest && concrete,
};
}
function getCallback(node) {
return node.arguments.find(isCallbackFunctionNode);
}
function isCallbackFunctionNode(node) {
return node.type === 'FunctionExpression' || node.type === 'ArrowFunctionExpression';
}
function isFunctionNode(node) {
return ast_js_1.FUNCTION_NODES.includes(node.type);
}
function getLocalHelperFunction(context, node) {
if (node.callee.type !== 'Identifier') {
return undefined;
}
const variable = (0, ast_js_1.getVariableFromScope)(context.sourceCode.getScope(node.callee), node.callee.name);
const definition = variable?.defs.find(isLocalFunctionDefinition);
if (definition?.node.type === 'FunctionDeclaration') {
return definition.node;
}
if (definition?.node.type === 'VariableDeclarator' &&
definition.node.init != null &&
isFunctionNode(definition.node.init)) {
return definition.node.init;
}
return undefined;
}
function isLocalFunctionDefinition(definition) {
if (definition.type === 'FunctionName') {
return true;
}
return (definition.type === 'Variable' &&
definition.node.type === 'VariableDeclarator' &&
definition.node.init != null &&
isFunctionNode(definition.node.init));
}
function isInConcreteCollectionCallback(functionNesting, concreteSuiteCallbackNesting) {
return functionNesting === concreteSuiteCallbackNesting;
}
function isPlaywrightTest(qualifiers, node) {
if (qualifiers === undefined) {
return false;
}
return (qualifiers.every(qualifier => mocha_style_test_frameworks_js_1.PLAYWRIGHT_TEST_MODIFIERS.has(qualifier)) &&
(!qualifiers.includes('fail') || (0, mocha_style_test_frameworks_js_1.hasCallback)(node)));
}
function getPlaywrightDescribeClassification(qualifiers) {
if (qualifiers?.[0] !== 'describe') {
return 'unknown';
}
const modifiers = qualifiers.slice(1);
if (modifiers.some(modifier => PLAYWRIGHT_DISABLED_DESCRIBE_MODIFIERS.has(modifier))) {
return 'ignored';
}
const runnableModifiers = modifiers.at(-1) === mocha_style_test_frameworks_js_1.PLAYWRIGHT_DESCRIBE_FOCUS_MODIFIER ? modifiers.slice(0, -1) : modifiers;
return runnableModifiers.every(modifier => mocha_style_test_frameworks_js_1.PLAYWRIGHT_DESCRIBE_MODIFIERS.has(modifier))
? 'concrete'
: 'unknown';
}