@blundergoat/gruff-ts 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
package/src/test-block-rules.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
1
|
+
// Evaluates test-quality rules on each parsed `test(...)` or `it(...)` block in a project scan.
|
|
2
|
+
//
|
|
3
|
+
// Checks for unlabeled loops inside tests and overly broad test structure patterns while exempting clear table-driven tests.
|
|
4
|
+
// Called by the block orchestrator whenever a discovered callable is flagged as a test registration.
|
|
5
5
|
import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion } from "./blocks.ts";
|
|
6
6
|
import { type SourceFile } from "./discovery.ts";
|
|
7
7
|
import { escapeRegex } from "./findings-helpers.ts";
|
|
8
8
|
import { pushStaticAnalysisRedundantTestFindings, type StaticAnalysisSourceContext } from "./static-analysis-redundant-rules.ts";
|
|
9
|
-
import { countMatches } from "./text-scans.ts";
|
|
9
|
+
import { countMatches, matchingCloseParen } from "./text-scans.ts";
|
|
10
10
|
import type { Finding, Severity } from "./types.ts";
|
|
11
11
|
|
|
12
12
|
// Provisional rule output gathered during a test-block walk. Built before the surrounding context
|
|
@@ -17,17 +17,14 @@ interface TestBlockCheck {
|
|
|
17
17
|
severity: Severity;
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
/*
|
|
29
|
-
* Reached when `block.isTest` is true. Four sub-passes in a stable, deterministic order: assertion
|
|
30
|
-
* quality, mock quality, global-state-mutation, structural rules.
|
|
20
|
+
/**
|
|
21
|
+
* Check a test block in stable order: assertion quality, mock quality, shared-state mutation, and loop structure.
|
|
22
|
+
*
|
|
23
|
+
* @param file - source file used to locate findings
|
|
24
|
+
* @param block - test block whose executable text and location the checks use
|
|
25
|
+
* @param findings - caller's list that receives findings from every check
|
|
26
|
+
* @param staticContext - surrounding source for assertion analysis; omission limits it to the block's own source and starting line
|
|
27
|
+
* @returns Nothing. Appends the findings from this test block to the supplied list.
|
|
31
28
|
*/
|
|
32
29
|
export function analyseTestBlock(file: SourceFile, block: FunctionBlock, findings: Finding[], staticContext?: StaticAnalysisSourceContext): void {
|
|
33
30
|
const body = block.codeBody;
|
|
@@ -38,55 +35,49 @@ export function analyseTestBlock(file: SourceFile, block: FunctionBlock, finding
|
|
|
38
35
|
analyseTestStructureChecks(file, block, body, findings);
|
|
39
36
|
}
|
|
40
37
|
|
|
41
|
-
|
|
42
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Checks the test body for assertion-quality problems and static-analysis redundancy.
|
|
40
|
+
* Uses the block's original text and staticContext to assess whether static evidence makes an assertion redundant.
|
|
41
|
+
*
|
|
42
|
+
* @param file - source file used to anchor stable findings
|
|
43
|
+
* @param block - test block providing original text and location metadata for findings
|
|
44
|
+
* @param body - masked test body scanned by assertion-quality checks
|
|
45
|
+
* @param staticContext - surrounding source context used to evaluate redundant assertions
|
|
46
|
+
* @param findings - caller's list that receives findings from both checks
|
|
47
|
+
* @returns Nothing. Appends stable findings from both assertion-quality checks to the supplied list.
|
|
48
|
+
*/
|
|
43
49
|
function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
|
|
44
50
|
for (const check of assertionQualityChecks(block, body)) {
|
|
45
51
|
findings.push(blockFinding({ ruleId: check.ruleId, message: check.message, file, block, severity: check.severity, pillar: "test-quality" }));
|
|
46
52
|
}
|
|
47
|
-
pushMagicNumberAssertionFindings(file, block, body, findings);
|
|
48
53
|
pushStaticAnalysisRedundantTestFindings(file, block, block.body, body, staticContext, findings);
|
|
49
54
|
}
|
|
50
55
|
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
/**
|
|
57
|
+
* Return active assertion-quality checks for the masked test body.
|
|
58
|
+
* Predicates are evaluated before filtering, and retained checks keep their declared emission order.
|
|
59
|
+
*
|
|
60
|
+
* @param block - test block whose name appears in emitted check messages
|
|
61
|
+
* @param body - masked test body scanned for trivial assertions
|
|
62
|
+
* @returns Matched assertion-quality checks in declared order, or an empty list when none matched.
|
|
63
|
+
*/
|
|
53
64
|
function assertionQualityChecks(block: FunctionBlock, body: string): TestBlockCheck[] {
|
|
54
65
|
const testName = block.name;
|
|
55
66
|
const checks: Array<TestBlockCheck & { active: boolean }> = [
|
|
56
|
-
{ active: !hasAssertion(body), ruleId: "test-quality.no-assertions", message: `Test \`${testName}\` does not appear to make an assertion.`, severity: "warning" },
|
|
57
67
|
{ active: hasTrivialAssertion(body), ruleId: "test-quality.trivial-assertion", message: `Test \`${testName}\` contains an assertion that compares a value to itself.`, severity: "warning" },
|
|
58
|
-
{ active: isSnapshotOnlyTest(body), ruleId: "test-quality.snapshot-only-test", message: `Test \`${testName}\` relies only on snapshot assertions.`, severity: "advisory" },
|
|
59
|
-
{ active: isNoThrowOnlyTest(body), ruleId: "test-quality.no-throw-only-test", message: `Test \`${testName}\` only verifies that code does not throw.`, severity: "advisory" },
|
|
60
|
-
{ active: hasExceptionTypeOnlyAssertion(body), ruleId: "test-quality.exception-type-only", message: `Test \`${testName}\` checks only the exception type.`, severity: "advisory" },
|
|
61
68
|
];
|
|
62
69
|
return checks.filter((check) => check.active).map(({ active: _active, ...check }) => check);
|
|
63
70
|
}
|
|
64
71
|
|
|
65
|
-
|
|
66
|
-
*
|
|
67
|
-
*
|
|
72
|
+
/**
|
|
73
|
+
* Checks the test body for unused mock variables.
|
|
74
|
+
*
|
|
75
|
+
* @param file - source file used to locate each advisory
|
|
76
|
+
* @param block - test block used to anchor each advisory
|
|
77
|
+
* @param body - masked test body scanned for unused mock declarations
|
|
78
|
+
* @param findings - caller's list that receives one advisory per unused mock
|
|
79
|
+
* @returns Nothing. Appends one stable test-quality.unused-mock finding with the mock name to the supplied list for each match.
|
|
68
80
|
*/
|
|
69
|
-
function pushMagicNumberAssertionFindings(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
70
|
-
if (isConstantContractTestName(block.name)) {
|
|
71
|
-
return;
|
|
72
|
-
}
|
|
73
|
-
for (const assertion of magicNumberAssertions(body)) {
|
|
74
|
-
findings.push(
|
|
75
|
-
blockFindingWithMetadata({
|
|
76
|
-
ruleId: "test-quality.magic-number-assertion",
|
|
77
|
-
message: `Test \`${block.name}\` asserts against unexplained numeric literal ${assertion.value}.`,
|
|
78
|
-
file,
|
|
79
|
-
block,
|
|
80
|
-
severity: "advisory",
|
|
81
|
-
pillar: "test-quality",
|
|
82
|
-
metadata: { value: assertion.value },
|
|
83
|
-
}),
|
|
84
|
-
);
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// Two distinct findings emitted from one walk: per-unused-mock and a single mock-only flag.
|
|
89
|
-
// Reports `test-quality.unused-mock` / `test-quality.mock-only-test` with stable test-block metadata.
|
|
90
81
|
function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
91
82
|
const unusedMocks = unusedMockVariables(body);
|
|
92
83
|
for (const mock of unusedMocks) {
|
|
@@ -102,45 +93,44 @@ function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string
|
|
|
102
93
|
}),
|
|
103
94
|
);
|
|
104
95
|
}
|
|
105
|
-
if (isMockOnlyTest(body)) {
|
|
106
|
-
findings.push(blockFinding({ ruleId: "test-quality.mock-only-test", message: `Test \`${block.name}\` only verifies mock interaction.`, file, block, severity: "advisory", pillar: "test-quality" }));
|
|
107
|
-
}
|
|
108
96
|
}
|
|
109
97
|
|
|
110
|
-
|
|
98
|
+
/**
|
|
99
|
+
* Checks the test body for changes to process or runtime state that other tests may share.
|
|
100
|
+
*
|
|
101
|
+
* @param file - source file used to locate the warning
|
|
102
|
+
* @param block - test block used to anchor and name the warning
|
|
103
|
+
* @param body - masked test body checked for shared-state assignments
|
|
104
|
+
* @param findings - caller's list that receives the warning when a mutation matches
|
|
105
|
+
* @returns Nothing. On a match, appends a stable test-quality.global-state-mutation warning for the supplied file and block to findings.
|
|
106
|
+
*/
|
|
111
107
|
function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
112
108
|
if (hasGlobalStateMutation(body)) {
|
|
113
109
|
findings.push(blockFinding({ ruleId: "test-quality.global-state-mutation", message: `Test \`${block.name}\` mutates global process or runtime state.`, file, block, severity: "warning", pillar: "test-quality" }));
|
|
114
110
|
}
|
|
115
111
|
}
|
|
116
112
|
|
|
117
|
-
|
|
118
|
-
|
|
113
|
+
/**
|
|
114
|
+
* Flag loops that may hide which test iteration failed. Confidence is medium because the label heuristic can miss indirect messages.
|
|
115
|
+
*
|
|
116
|
+
* @param file - source file used to locate the advisory
|
|
117
|
+
* @param block - test block used to anchor and name the advisory
|
|
118
|
+
* @param body - test code checked for loops the heuristic considers reportable
|
|
119
|
+
* @param findings - caller's list that receives the advisory
|
|
120
|
+
* @returns Nothing. Appends a stable test-quality.loop-in-test finding when the heuristic matches.
|
|
121
|
+
*/
|
|
119
122
|
function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic that hides which iteration failed."],
|
|
123
|
-
["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
|
|
124
|
-
["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
|
|
125
|
-
];
|
|
126
|
-
for (const [ruleId, active, message] of checks) {
|
|
127
|
-
if (!active) {
|
|
128
|
-
continue;
|
|
129
|
-
}
|
|
130
|
-
// Loop findings report at medium confidence: parametrized tests are a legitimate pattern and
|
|
131
|
-
// the label heuristic cannot see every message shape (multi-line assertion calls, helpers).
|
|
132
|
-
if (ruleId === "test-quality.loop-in-test") {
|
|
133
|
-
findings.push(blockFindingWithMetadata({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
|
|
134
|
-
continue;
|
|
135
|
-
}
|
|
136
|
-
findings.push(blockFinding({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality" }));
|
|
123
|
+
if (controlFlowContainsNonFixtureLoop(body)) {
|
|
124
|
+
findings.push(blockFindingWithMetadata({ ruleId: "test-quality.loop-in-test", message: "Test contains loop logic that hides which iteration failed.", file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
|
|
137
125
|
}
|
|
138
126
|
}
|
|
139
127
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
128
|
+
/**
|
|
129
|
+
* Checks whether masked source contains a reportable for or while loop with an assertion.
|
|
130
|
+
*
|
|
131
|
+
* @param source - masked test body scanned for loop segments
|
|
132
|
+
* @returns True when a loop with an assertion is exempt by neither fixture nor labeled-case checks; false otherwise.
|
|
133
|
+
*/
|
|
144
134
|
function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
145
135
|
for (const match of source.matchAll(/\b(?:for|while)\b/g)) {
|
|
146
136
|
const start = match.index ?? 0;
|
|
@@ -159,50 +149,163 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
|
159
149
|
return false;
|
|
160
150
|
}
|
|
161
151
|
|
|
162
|
-
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
152
|
+
/**
|
|
153
|
+
* Checks whether a loop can skip the loop-in-test finding because its recognized assertions identify the failed case.
|
|
154
|
+
* A multiline message can mention the label. A supported expected operand must equal the label name after trimming.
|
|
155
|
+
* A label can be a loop binding or a const whose initializer mentions that binding directly.
|
|
156
|
+
*
|
|
157
|
+
* @param segment - masked loop text containing the header and body to check
|
|
158
|
+
* @returns True if each recognized chain has a label. False for an unrecognized loop, an unsafe branch, or missing bindings or recognized calls.
|
|
167
159
|
*/
|
|
168
160
|
function isLabeledCaseLoop(segment: string): boolean {
|
|
169
161
|
const parts = loopSegmentParts(segment);
|
|
170
162
|
if (!parts) {
|
|
171
163
|
return false;
|
|
172
164
|
}
|
|
165
|
+
if (hasUnsafeFixtureLoopBranch("", parts.body)) {
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
173
168
|
const boundNames = loopBoundNames(parts.header);
|
|
174
169
|
if (boundNames.length === 0) {
|
|
175
170
|
return false;
|
|
176
171
|
}
|
|
177
|
-
|
|
178
|
-
if (
|
|
172
|
+
// Reject the exemption when the loop mixes in assertion forms (`should.be`, `.resolves`/`.rejects`) that have no verified per-case label.
|
|
173
|
+
if (/\.\s*should\s*\.\s*be\s*\./.test(parts.body) || /\.\s*(?:rejects|resolves)\b/.test(parts.body)) {
|
|
179
174
|
return false;
|
|
180
175
|
}
|
|
181
|
-
|
|
176
|
+
const assertionCalls = assertionCallChains(parts.body);
|
|
177
|
+
if (assertionCalls.length === 0) {
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
const labelNames = [...boundNames, ...loopDerivedLocalNames(parts.body, boundNames)];
|
|
181
|
+
return assertionCalls.every((call) => hasLoopCaseLabel(call, labelNames));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Only call forms with supported per-case label arguments can clear a loop warning; `.should.be` matchers have no proved label form.
|
|
185
|
+
const ASSERTION_CALL_OPENER = /\b(?:assert(?:\.[A-Za-z]+|[A-Z][A-Za-z0-9_$]*)?|expect(?:\.(?:assertions|hasAssertions)|[A-Z][A-Za-z0-9_$]*)?|[A-Za-z_$][A-Za-z0-9_$]*Check)\s*(?:<(?!\s)(?:(?!&&|\|\|)[^;\r\n])+>\s*)?\(/g;
|
|
186
|
+
// One chained call such as `.toBe(` after a closed call.
|
|
187
|
+
const CHAINED_CALL_LINK = /^\s*\.\s*[A-Za-z_$][A-Za-z0-9_$]*\s*(?:<[^;]*?>\s*)?\(/;
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Return recognized assertion-chain slices from the masked loop body, including nested assertion calls inside outer assertion arguments.
|
|
191
|
+
* Skip an unmatched opening call or member-chained property call; if a later chained call is unclosed, retain the complete prefix already measured.
|
|
192
|
+
*
|
|
193
|
+
* @param body - masked loop body scanned for assertion openers and chained calls
|
|
194
|
+
* @returns Matched assertion-chain slices in source order, or an empty list when no opener can be matched.
|
|
195
|
+
*/
|
|
196
|
+
function assertionCallChains(body: string): string[] {
|
|
197
|
+
const calls: string[] = [];
|
|
198
|
+
for (const match of body.matchAll(ASSERTION_CALL_OPENER)) {
|
|
199
|
+
const start = match.index ?? 0;
|
|
200
|
+
// Skip member calls chained onto an earlier expression (such as `foo.expectCheck(`), while keeping nested standalone assertions checked.
|
|
201
|
+
if (start > 0 && body[start - 1] === ".") {
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
let close = matchingCloseParen(body, start + match[0].length - 1);
|
|
205
|
+
if (close === undefined) {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
for (let link = body.slice(close + 1).match(CHAINED_CALL_LINK); link; link = body.slice(close + 1).match(CHAINED_CALL_LINK)) {
|
|
209
|
+
const linkClose = matchingCloseParen(body, close + link[0].length);
|
|
210
|
+
if (linkClose === undefined) {
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
close = linkClose;
|
|
214
|
+
}
|
|
215
|
+
calls.push(body.slice(start, close + 1));
|
|
216
|
+
}
|
|
217
|
+
return calls;
|
|
182
218
|
}
|
|
183
219
|
|
|
184
|
-
|
|
185
|
-
|
|
220
|
+
/**
|
|
221
|
+
* Return const-local names whose initializer text in body has a whole-word match from boundNames, for use as assertion labels.
|
|
222
|
+
* Follow one level only; locals derived solely from other derived locals and unmatched declarations are excluded.
|
|
223
|
+
*
|
|
224
|
+
* @param body - masked loop body searched for const declarations
|
|
225
|
+
* @param boundNames - loop-bound identifier names tested against each const initializer
|
|
226
|
+
* @returns Derived local names eligible as assertion labels.
|
|
227
|
+
*/
|
|
228
|
+
function loopDerivedLocalNames(body: string, boundNames: string[]): string[] {
|
|
229
|
+
const derived: string[] = [];
|
|
230
|
+
for (const match of body.matchAll(/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*([^;\n]+)/g)) {
|
|
231
|
+
const initializer = match[2] ?? "";
|
|
232
|
+
if (boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(initializer))) {
|
|
233
|
+
derived.push(match[1] ?? "");
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return derived.filter(Boolean);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Extract identifier names bound by for-of, for-in or C-style headers.
|
|
241
|
+
* While-loops bind nothing here, so they never take the labeled opt-out.
|
|
242
|
+
*
|
|
243
|
+
* @param header - loop header text preceding the body brace
|
|
244
|
+
* @returns Bound identifier names from the loop header, or an empty list when none are declared.
|
|
245
|
+
*/
|
|
186
246
|
function loopBoundNames(header: string): string[] {
|
|
187
|
-
const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+of\b/)?.[1]
|
|
247
|
+
const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+(?:of|in)\b/)?.[1]
|
|
248
|
+
?? header.match(/\b(?:let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/)?.[1]
|
|
249
|
+
?? "";
|
|
188
250
|
return [...binding.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)].map((match) => match[0] ?? "").filter(Boolean);
|
|
189
251
|
}
|
|
190
252
|
|
|
191
|
-
|
|
192
|
-
|
|
253
|
+
/**
|
|
254
|
+
* Return whether the assertion call text in statement labels a case with one of the loop bindings or derived locals.
|
|
255
|
+
* Looks for a whole-word match in argument three for binary assert calls or argument two otherwise, plus bare expected operands.
|
|
256
|
+
*
|
|
257
|
+
* @param statement - recognized assertion-chain text from a loop body
|
|
258
|
+
* @param boundNames - loop bindings and derived local names accepted as case labels
|
|
259
|
+
* @returns True when the assertion message or expected operand matches a label name; false otherwise.
|
|
260
|
+
*/
|
|
193
261
|
function hasLoopCaseLabel(statement: string, boundNames: string[]): boolean {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
262
|
+
const argumentsList = assertionArguments(statement);
|
|
263
|
+
const isBinaryAssert = /^assert\.(?:(?:not)?(?:strictEqual|deepStrictEqual|equal|deepEqual)|throws|rejects|match|doesNotMatch)\b/i.test(statement);
|
|
264
|
+
const isExpect = /^expect\s*\(/.test(statement);
|
|
265
|
+
const message = argumentsList[isBinaryAssert ? 2 : 1] ?? "";
|
|
266
|
+
const matcher = isExpect ? statement.slice((matchingCloseParen(statement, statement.indexOf("(")) ?? statement.length) + 1) : "";
|
|
267
|
+
const expected = isBinaryAssert ? argumentsList[1] ?? "" : isExpect ? assertionArguments(matcher)[0] ?? "" : "";
|
|
268
|
+
return boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(message) || expected.trim() === name);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Return comma-separated argument slices from statement's outer call; strings and comments must already be masked.
|
|
273
|
+
* Nested delimiters stay within a slice.
|
|
274
|
+
*
|
|
275
|
+
* @param statement - masked call expression whose outer argument list is split
|
|
276
|
+
* @returns Argument slices from the outer call (retaining an interior slice on an empty call), or an empty list if parentheses are unmatched.
|
|
277
|
+
*/
|
|
278
|
+
function assertionArguments(statement: string): string[] {
|
|
279
|
+
const open = statement.indexOf("(");
|
|
280
|
+
const close = matchingCloseParen(statement, open);
|
|
281
|
+
if (open < 0 || close === undefined) {
|
|
282
|
+
return [];
|
|
283
|
+
}
|
|
284
|
+
const argumentsList: string[] = [];
|
|
285
|
+
let depth = 0;
|
|
286
|
+
let start = open + 1;
|
|
287
|
+
for (let index = start; index < close; index += 1) {
|
|
288
|
+
const character = statement[index] ?? "";
|
|
289
|
+
if ("([{".includes(character)) depth += 1;
|
|
290
|
+
else if (")]}".includes(character)) depth -= 1;
|
|
291
|
+
else if (character === "," && depth === 0) {
|
|
292
|
+
argumentsList.push(statement.slice(start, index));
|
|
293
|
+
start = index + 1;
|
|
198
294
|
}
|
|
199
295
|
}
|
|
200
|
-
|
|
296
|
+
argumentsList.push(statement.slice(start, close));
|
|
297
|
+
return argumentsList;
|
|
201
298
|
}
|
|
202
299
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
300
|
+
/**
|
|
301
|
+
* Return whether segment has an accepted fixture iterable and a final non-ignored statement starting with a recognized assertion.
|
|
302
|
+
* Switch, case, or default markers disqualify the loop; an assertion-bearing if disqualifies it unless matched as a fixture guard.
|
|
303
|
+
*
|
|
304
|
+
* @param source - masked source surrounding the loop for preceding declaration lookup
|
|
305
|
+
* @param start - character offset in source where the loop keyword begins
|
|
306
|
+
* @param segment - bounded loop text containing header and body
|
|
307
|
+
* @returns True when the loop iterates an accepted fixture table safely and ends with a recognized assertion; false otherwise.
|
|
308
|
+
*/
|
|
206
309
|
function isFixtureLoop(source: string, start: number, segment: string): boolean {
|
|
207
310
|
const parts = loopSegmentParts(segment);
|
|
208
311
|
if (!parts || !hasFixtureIterable(source, start, parts.header)) {
|
|
@@ -211,16 +314,19 @@ function isFixtureLoop(source: string, start: number, segment: string): boolean
|
|
|
211
314
|
if (hasUnsafeFixtureLoopBranch(source.slice(0, start + parts.bodyBraceIndex + 1), parts.body)) {
|
|
212
315
|
return false;
|
|
213
316
|
}
|
|
214
|
-
//
|
|
215
|
-
// terminal action; `void call()` still counts as a real trailing statement.
|
|
317
|
+
// A bare void-name marker can follow the terminal assertion without disqualifying the loop. A void-wrapped call still counts.
|
|
216
318
|
const statements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement) && !/^void\s+[A-Za-z_$][A-Za-z0-9_$]*$/.test(statement));
|
|
217
319
|
const lastStatement = statements[statements.length - 1] ?? "";
|
|
218
320
|
return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
|
|
219
321
|
}
|
|
220
322
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
323
|
+
/**
|
|
324
|
+
* Splits a loop segment into header and body at the body-opening brace, walking past the header's balanced parentheses first
|
|
325
|
+
* so that a destructured binding such as `for (const { name } of rows)` does not end the header at the destructuring brace.
|
|
326
|
+
*
|
|
327
|
+
* @param segment - bounded loop text beginning at the loop keyword
|
|
328
|
+
* @returns Header slice, body interior slice, and body-brace offset, or undefined for braceless or unclosed headers.
|
|
329
|
+
*/
|
|
224
330
|
function loopSegmentParts(segment: string): { header: string; body: string; bodyBraceIndex: number } | undefined {
|
|
225
331
|
const parenIndex = segment.indexOf("(");
|
|
226
332
|
if (parenIndex === -1) {
|
|
@@ -237,8 +343,13 @@ function loopSegmentParts(segment: string): { header: string; body: string; body
|
|
|
237
343
|
return { header: segment.slice(0, bodyBraceIndex), body: segment.slice(bodyBraceIndex + 1, segment.length - 1), bodyBraceIndex };
|
|
238
344
|
}
|
|
239
345
|
|
|
240
|
-
|
|
241
|
-
|
|
346
|
+
/**
|
|
347
|
+
* Find the closing-parenthesis index for the loop-header opener at parenIndex in segment, counting nested parentheses.
|
|
348
|
+
*
|
|
349
|
+
* @param segment - loop text containing the header parentheses
|
|
350
|
+
* @param parenIndex - offset of the header's opening parenthesis inside segment
|
|
351
|
+
* @returns Closing-parenthesis offset in segment, or undefined if the outer group does not close before segment ends.
|
|
352
|
+
*/
|
|
242
353
|
function matchingHeaderCloseParen(segment: string, parenIndex: number): number | undefined {
|
|
243
354
|
let depth = 0;
|
|
244
355
|
for (let index = parenIndex; index < segment.length; index += 1) {
|
|
@@ -255,8 +366,14 @@ function matchingHeaderCloseParen(segment: string, parenIndex: number): number |
|
|
|
255
366
|
return undefined;
|
|
256
367
|
}
|
|
257
368
|
|
|
258
|
-
|
|
259
|
-
|
|
369
|
+
/**
|
|
370
|
+
* Return whether loop body contains a switch-like construct or an assertion-bearing if segment without a recognized fixture-membership guard.
|
|
371
|
+
* Other if segments without assertions do not reject the fixture loop.
|
|
372
|
+
*
|
|
373
|
+
* @param sourceBeforeLoopBody - preceding source text supplying declarations for fixture guard lookup
|
|
374
|
+
* @param body - loop body text checked for switch markers and conditional assertions
|
|
375
|
+
* @returns True when an unsafe switch or unguarded assertion branch is found; false otherwise.
|
|
376
|
+
*/
|
|
260
377
|
function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
|
|
261
378
|
if (/\bswitch\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
|
|
262
379
|
return true;
|
|
@@ -272,9 +389,14 @@ function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string):
|
|
|
272
389
|
return false;
|
|
273
390
|
}
|
|
274
391
|
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
392
|
+
/**
|
|
393
|
+
* Return whether header looks like an inline fixture iterable or names a recognized fixture constant or const-bound table.
|
|
394
|
+
*
|
|
395
|
+
* @param source - masked source providing preceding declarations for const-bound lookup
|
|
396
|
+
* @param start - character offset in source where the loop begins
|
|
397
|
+
* @param header - loop header text inspected for an inline or named fixture iterable
|
|
398
|
+
* @returns True when the header iterates a recognized fixture iterable; false when no accepted shape was found.
|
|
399
|
+
*/
|
|
278
400
|
function hasFixtureIterable(source: string, start: number, header: string): boolean {
|
|
279
401
|
if (/\bof\s*\[/.test(header) || /\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
|
|
280
402
|
return true;
|
|
@@ -283,8 +405,14 @@ function hasFixtureIterable(source: string, start: number, header: string): bool
|
|
|
283
405
|
return iterableName !== "" && (isFixtureConstantIterableName(iterableName) || hasConstBoundFixtureIterable(source.slice(0, start), iterableName));
|
|
284
406
|
}
|
|
285
407
|
|
|
286
|
-
|
|
287
|
-
|
|
408
|
+
/**
|
|
409
|
+
* Return whether iterableName has fixture vocabulary and a const assignment in sourceBeforeLoop with an accepted initializer shape.
|
|
410
|
+
* The assignment text must reach a semicolon at the end of the prefix; arrays, Object.entries/keys/values, or discovery calls qualify.
|
|
411
|
+
*
|
|
412
|
+
* @param sourceBeforeLoop - source prefix preceding the loop header
|
|
413
|
+
* @param iterableName - identifier bound by the loop's `of` clause
|
|
414
|
+
* @returns True when the identifier matches fixture vocabulary and an accepted const initializer; false otherwise.
|
|
415
|
+
*/
|
|
288
416
|
function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: string): boolean {
|
|
289
417
|
if (!isFixtureIterableName(iterableName)) {
|
|
290
418
|
return false;
|
|
@@ -294,41 +422,58 @@ function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: st
|
|
|
294
422
|
return initializer.startsWith("[") || /^Object\.(?:entries|keys|values)\s*\(/.test(initializer) || isFixtureDiscoveryCall(initializer);
|
|
295
423
|
}
|
|
296
424
|
|
|
297
|
-
|
|
425
|
+
/**
|
|
426
|
+
* Check whether an identifier carries a recognized fixture-table suffix for the loop-exemption heuristic.
|
|
427
|
+
*
|
|
428
|
+
* @param name - identifier name from a loop iterable
|
|
429
|
+
* @returns True when the name ends with an accepted fixture-table suffix; false otherwise.
|
|
430
|
+
*/
|
|
298
431
|
function isFixtureIterableName(name: string): boolean {
|
|
299
432
|
return /(?:agents|cases|checks|entries|examples|fixtures|files|ids|paths|records|scenarios|scores|snapshots)$/i.test(name);
|
|
300
433
|
}
|
|
301
434
|
|
|
302
|
-
|
|
435
|
+
/**
|
|
436
|
+
* Check whether an identifier uses only uppercase letters, digits and underscores and has a fixture suffix; no local declaration is required.
|
|
437
|
+
*
|
|
438
|
+
* @param name - identifier name from a loop iterable
|
|
439
|
+
* @returns True when the name matches constant-case naming and a fixture suffix; false otherwise.
|
|
440
|
+
*/
|
|
303
441
|
function isFixtureConstantIterableName(name: string): boolean {
|
|
304
442
|
return /^[A-Z0-9_]+$/.test(name) && isFixtureIterableName(name);
|
|
305
443
|
}
|
|
306
444
|
|
|
307
|
-
|
|
445
|
+
/**
|
|
446
|
+
* Check whether initializer contains a call named glob, globSync, readdir, readdirSync, or beginning with discover, find or list.
|
|
447
|
+
* This name heuristic does not verify where the function was declared or whether it discovers fixtures.
|
|
448
|
+
*
|
|
449
|
+
* @param initializer - trimmed initializer expression from a const fixture binding
|
|
450
|
+
* @returns True when a recognized discovery call pattern appears in the initializer; false otherwise.
|
|
451
|
+
*/
|
|
308
452
|
function isFixtureDiscoveryCall(initializer: string): boolean {
|
|
309
453
|
return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
|
|
310
454
|
}
|
|
311
455
|
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
}
|
|
322
|
-
return false;
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
// Accepts guard conditionals whose assertion proves a shared invariant rather than branch policy.
|
|
456
|
+
/**
|
|
457
|
+
* Check whether segment's condition matches the fixture-membership guard heuristic using source text before offset start.
|
|
458
|
+
* The invariant heuristic checks text before the first opening brace as the condition; with no brace, the guard cannot qualify.
|
|
459
|
+
*
|
|
460
|
+
* @param source - preceding source text containing declarations visible before the conditional
|
|
461
|
+
* @param start - character offset in source where the conditional segment starts
|
|
462
|
+
* @param segment - conditional segment text beginning at `if`
|
|
463
|
+
* @returns True when the condition matches the fixture-membership guard heuristic; false otherwise.
|
|
464
|
+
*/
|
|
326
465
|
function isInvariantAssertionConditional(source: string, start: number, segment: string): boolean {
|
|
327
466
|
const condition = segment.slice(0, Math.max(0, segment.indexOf("{"))).trim();
|
|
328
467
|
return isFixtureMembershipGuard(source.slice(0, start), condition);
|
|
329
468
|
}
|
|
330
469
|
|
|
331
|
-
|
|
470
|
+
/**
|
|
471
|
+
* Check whether condition's first has/includes target is declared as a const with a new Set or array initializer in sourceBeforeCondition.
|
|
472
|
+
*
|
|
473
|
+
* @param sourceBeforeCondition - source prefix preceding the conditional statement
|
|
474
|
+
* @param condition - conditional header text before the opening brace
|
|
475
|
+
* @returns True when the guarded target is declared as a const Set or array; false when the target or declaration cannot be matched.
|
|
476
|
+
*/
|
|
332
477
|
function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: string): boolean {
|
|
333
478
|
const guardTarget = condition.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\.(?:has|includes)\s*\(/)?.[1] ?? "";
|
|
334
479
|
if (!guardTarget) {
|
|
@@ -337,7 +482,14 @@ function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: stri
|
|
|
337
482
|
return new RegExp(`\\bconst\\s+${escapeRegex(guardTarget)}\\s*=\\s*(?:new\\s+Set\\s*\\(|\\[)`).test(sourceBeforeCondition);
|
|
338
483
|
}
|
|
339
484
|
|
|
340
|
-
|
|
485
|
+
/**
|
|
486
|
+
* Extract bounded control-flow text in masked source beginning at keyword offset start for assertion detection.
|
|
487
|
+
* With no same-line body brace, returns the rest of that line; an unmatched brace limits the result to the header and opening brace.
|
|
488
|
+
*
|
|
489
|
+
* @param source - masked source text containing the control-flow construct
|
|
490
|
+
* @param start - character offset in source where the control-flow keyword begins
|
|
491
|
+
* @returns Bounded control-flow slice starting at the keyword offset.
|
|
492
|
+
*/
|
|
341
493
|
function controlFlowSegment(source: string, start: number): string {
|
|
342
494
|
const lineEnd = source.indexOf("\n", start);
|
|
343
495
|
const openBrace = controlFlowBodyBraceIndex(source, start, lineEnd);
|
|
@@ -348,9 +500,14 @@ function controlFlowSegment(source: string, start: number): string {
|
|
|
348
500
|
return source.slice(start, closeBrace === undefined ? openBrace + 1 : closeBrace + 1);
|
|
349
501
|
}
|
|
350
502
|
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
503
|
+
/**
|
|
504
|
+
* In masked source, scan from the keyword offset start up to lineEnd for the first opening brace outside parentheses.
|
|
505
|
+
*
|
|
506
|
+
* @param source - masked source text being scanned
|
|
507
|
+
* @param start - character offset of the control-flow keyword
|
|
508
|
+
* @param lineEnd - end-of-line offset bounding the scan, or -1 to scan to the end of source
|
|
509
|
+
* @returns Offset of the first body-opening brace outside parentheses, or undefined if none is found.
|
|
510
|
+
*/
|
|
354
511
|
function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: number): number | undefined {
|
|
355
512
|
const limit = lineEnd === -1 ? source.length : lineEnd;
|
|
356
513
|
let parenDepth = 0;
|
|
@@ -367,7 +524,13 @@ function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: numbe
|
|
|
367
524
|
return undefined;
|
|
368
525
|
}
|
|
369
526
|
|
|
370
|
-
|
|
527
|
+
/**
|
|
528
|
+
* Find the closing-brace index for the opening-brace offset openBrace in masked source, to bound a loop or conditional body.
|
|
529
|
+
*
|
|
530
|
+
* @param source - masked source text containing the braced block
|
|
531
|
+
* @param openBrace - offset of the opening brace in source
|
|
532
|
+
* @returns Offset of the matching closing brace, or undefined when the braces never balance before source ends.
|
|
533
|
+
*/
|
|
371
534
|
function matchingCloseBrace(source: string, openBrace: number): number | undefined {
|
|
372
535
|
let depth = 0;
|
|
373
536
|
for (let index = openBrace; index < source.length; index += 1) {
|
|
@@ -384,16 +547,22 @@ function matchingCloseBrace(source: string, openBrace: number): number | undefin
|
|
|
384
547
|
return undefined;
|
|
385
548
|
}
|
|
386
549
|
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
550
|
+
/**
|
|
551
|
+
* Check whether the test source contains assert.ok(true) or matching operands in supported assert or expect equality checks.
|
|
552
|
+
*
|
|
553
|
+
* @param source - masked test body scanned for trivial assertions
|
|
554
|
+
* @returns True when a trivial assertion form matches; false when none match, so the caller can skip `test-quality.trivial-assertion`.
|
|
555
|
+
*/
|
|
390
556
|
function hasTrivialAssertion(source: string): boolean {
|
|
391
557
|
return hasLiteralTrivialAssertion(source) || hasRepeatedAssertArgument(source) || hasRepeatedExpectArgument(source);
|
|
392
558
|
}
|
|
393
559
|
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
560
|
+
/**
|
|
561
|
+
* Check for supported assert.ok(true) or identical-literal equality patterns in source.
|
|
562
|
+
*
|
|
563
|
+
* @param source - masked test body scanned for literal trivial assertions
|
|
564
|
+
* @returns True when a literal trivial assertion matches; false otherwise.
|
|
565
|
+
*/
|
|
397
566
|
function hasLiteralTrivialAssertion(source: string): boolean {
|
|
398
567
|
return (
|
|
399
568
|
/\bassert\.ok\s*\(\s*true\s*\)/.test(source) ||
|
|
@@ -401,9 +570,13 @@ function hasLiteralTrivialAssertion(source: string): boolean {
|
|
|
401
570
|
);
|
|
402
571
|
}
|
|
403
572
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
573
|
+
/**
|
|
574
|
+
* Walks every `assert.equal(a, b)` call and normalises both arguments before comparison so that
|
|
575
|
+
* `foo;` and `foo` collapse to the same key, because mirrored expressions pass regardless of behaviour.
|
|
576
|
+
*
|
|
577
|
+
* @param source - masked test body scanned for repeated assert arguments
|
|
578
|
+
* @returns True when an assert equality call compares identical normalized arguments; false otherwise.
|
|
579
|
+
*/
|
|
407
580
|
function hasRepeatedAssertArgument(source: string): boolean {
|
|
408
581
|
for (const match of source.matchAll(/\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*([^,\n)]+?)(?:\s*,|\s*\))/g)) {
|
|
409
582
|
if (normalizeAssertionExpression(match[1] ?? "") === normalizeAssertionExpression(match[2] ?? "")) {
|
|
@@ -413,9 +586,13 @@ function hasRepeatedAssertArgument(source: string): boolean {
|
|
|
413
586
|
return false;
|
|
414
587
|
}
|
|
415
588
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
589
|
+
/**
|
|
590
|
+
* Check whether source contains a direct expect equality call using toBe, toEqual or toStrictEqual with identical normalized argument text.
|
|
591
|
+
* Async and negated matcher chains do not match.
|
|
592
|
+
*
|
|
593
|
+
* @param source - masked test body scanned for repeated expect arguments
|
|
594
|
+
* @returns True when a direct expect equality call has identical normalized operands; false means no supported pair was found.
|
|
595
|
+
*/
|
|
419
596
|
function hasRepeatedExpectArgument(source: string): boolean {
|
|
420
597
|
for (const match of source.matchAll(/\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*to(?:Be|Equal|StrictEqual)\s*\(\s*([^)]+?)\s*\)/g)) {
|
|
421
598
|
if (normalizeAssertionExpression(match[1] ?? "") === normalizeAssertionExpression(match[2] ?? "")) {
|
|
@@ -425,94 +602,23 @@ function hasRepeatedExpectArgument(source: string): boolean {
|
|
|
425
602
|
return false;
|
|
426
603
|
}
|
|
427
604
|
|
|
428
|
-
|
|
429
|
-
|
|
605
|
+
/**
|
|
606
|
+
* Build expression's comparison key after trimming surrounding whitespace and one trailing semicolon, so mirrored arguments compare equally.
|
|
607
|
+
*
|
|
608
|
+
* @param expression - raw operand text captured from an assertion call
|
|
609
|
+
* @returns Normalized comparison key for the assertion operand.
|
|
610
|
+
*/
|
|
430
611
|
function normalizeAssertionExpression(expression: string): string {
|
|
431
612
|
return expression.trim().replace(/;$/, "");
|
|
432
613
|
}
|
|
433
614
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
const withoutSnapshots = source
|
|
442
|
-
.replace(/\bexpect\s*\([\s\S]*?\)\s*\.\s*toMatch(?:Inline)?Snapshot\s*\([^)]*\)\s*;?/g, "")
|
|
443
|
-
.replace(/\bexpect\.(?:assertions|hasAssertions)\s*\([^)]*\)\s*;?/g, "");
|
|
444
|
-
return !hasAssertion(withoutSnapshots);
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
// Same shape as `isSnapshotOnlyTest` but for `doesNotThrow` / `not.toThrow`. A test that asserts
|
|
448
|
-
// only the absence of an exception is weak - `test-quality.no-throw-only-test` reports it so
|
|
449
|
-
// authors can add a real behaviour assertion alongside.
|
|
450
|
-
function isNoThrowOnlyTest(source: string): boolean {
|
|
451
|
-
if (!/\bassert\.doesNotThrow\s*\(|\.\s*not\s*\.\s*toThrow\s*\(/.test(source)) {
|
|
452
|
-
return false;
|
|
453
|
-
}
|
|
454
|
-
const withoutNoThrow = source
|
|
455
|
-
.replace(/\bassert\.doesNotThrow\s*\([\s\S]*?\)\s*;?/g, "")
|
|
456
|
-
.replace(/\bexpect\s*\([\s\S]*?\)\s*\.\s*not\s*\.\s*toThrow\s*\([^)]*\)\s*;?/g, "")
|
|
457
|
-
.replace(/\bexpect\.(?:assertions|hasAssertions)\s*\([^)]*\)\s*;?/g, "");
|
|
458
|
-
return !hasAssertion(withoutNoThrow);
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
// Pulls every numeric expected value out of `expect(...).toBe(n)` and `assert.equal(actual, n)`
|
|
462
|
-
// shapes. Small cardinalities and length/count matchers are excluded because the literal often is
|
|
463
|
-
// the test contract; larger opaque values still surface for naming or rationale.
|
|
464
|
-
function magicNumberAssertions(source: string): Array<{ value: number }> {
|
|
465
|
-
return MAGIC_NUMBER_ASSERTION_PATTERNS.flatMap((candidate) => magicNumberAssertionMatches(source, candidate));
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
const MAGIC_NUMBER_ASSERTION_PATTERNS: MagicNumberAssertionPattern[] = [
|
|
469
|
-
{ pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*(to(?:Be|Equal|HaveLength|HaveCount))\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, matcherIndex: 2, valueIndex: 3 },
|
|
470
|
-
{ pattern: /\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*(-?\d+(?:\.\d+)?)(?:\s*,|\s*\))/g, expressionIndex: 1, valueIndex: 2 },
|
|
471
|
-
];
|
|
472
|
-
|
|
473
|
-
// Extracts reportable numeric literals for one assertion grammar while keeping HTTP statuses quiet.
|
|
474
|
-
function magicNumberAssertionMatches(source: string, candidate: MagicNumberAssertionPattern): Array<{ value: number }> {
|
|
475
|
-
const results: Array<{ value: number }> = [];
|
|
476
|
-
for (const match of source.matchAll(candidate.pattern)) {
|
|
477
|
-
const expression = match[candidate.expressionIndex] ?? "";
|
|
478
|
-
const matcher = candidate.matcherIndex === undefined ? "" : match[candidate.matcherIndex] ?? "";
|
|
479
|
-
const expectedNumber = Number(match[candidate.valueIndex] ?? "0");
|
|
480
|
-
if (!isIgnoredMagicNumberAssertion(expression, matcher, expectedNumber)) {
|
|
481
|
-
results.push({ value: expectedNumber });
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
return results;
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
// Centralises the rule's non-findings so cardinal, count, and HTTP-status exemptions stay aligned.
|
|
488
|
-
function isIgnoredMagicNumberAssertion(expression: string, matcher: string, expectedNumber: number): boolean {
|
|
489
|
-
return isSmallCardinal(expectedNumber) || isLengthOrCountMatcher(matcher) || isHttpStatusAssertion(expression, expectedNumber);
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
// Small integer cardinals usually express the expected case count directly.
|
|
493
|
-
function isSmallCardinal(cardinal: number): boolean {
|
|
494
|
-
return Number.isInteger(cardinal) && cardinal >= -1 && cardinal <= 3;
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
// Length/count matchers already name the measurement, so the numeric literal is the assertion.
|
|
498
|
-
function isLengthOrCountMatcher(matcher: string): boolean {
|
|
499
|
-
return matcher === "toHaveLength" || matcher === "toHaveCount";
|
|
500
|
-
}
|
|
501
|
-
|
|
502
|
-
// Contract-named tests may assert the documented number directly; the name supplies the rationale.
|
|
503
|
-
function isConstantContractTestName(name: string): boolean {
|
|
504
|
-
return /\b(?:constant|threshold|limit|budget|default|contract)\b/i.test(name);
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
// HTTP response status codes are intentionally numeric at assertion sites; naming every 200/404
|
|
508
|
-
// would add ceremony without making the test clearer.
|
|
509
|
-
function isHttpStatusAssertion(expression: string, expectedNumber: number): boolean {
|
|
510
|
-
return Number.isInteger(expectedNumber) && expectedNumber >= 100 && expectedNumber <= 599 && /\b(?:status|statusCode)\b/.test(expression);
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
// `const mockX = vi.fn(...)` declarations whose binding appears only once in the body - that one
|
|
514
|
-
// occurrence is the declaration itself, so the mock is created but never wired in. Reports the
|
|
515
|
-
// names for `test-quality.unused-mock` to anchor on.
|
|
615
|
+
/**
|
|
616
|
+
* Find `const mockX = vi.fn(...)` declarations whose binding appears only once in the body,
|
|
617
|
+
* because that single occurrence is the declaration itself and the mock is never wired in.
|
|
618
|
+
*
|
|
619
|
+
* @param source - masked test body scanned for mock variable declarations and references
|
|
620
|
+
* @returns Unused mock variable names for `test-quality.unused-mock` to anchor on.
|
|
621
|
+
*/
|
|
516
622
|
function unusedMockVariables(source: string): string[] {
|
|
517
623
|
const names: string[] = [];
|
|
518
624
|
for (const match of source.matchAll(/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:(?:vi|jest)\.fn|sinon\.stub|createMock|mock)\s*\(/g)) {
|
|
@@ -527,29 +633,13 @@ function unusedMockVariables(source: string): string[] {
|
|
|
527
633
|
return names;
|
|
528
634
|
}
|
|
529
635
|
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
if (!/\.(?:toHaveBeenCalled|toHaveBeenCalledWith|toHaveBeenNthCalledWith|toBeCalled|toBeCalledWith)\s*\(/.test(source)) {
|
|
538
|
-
return false;
|
|
539
|
-
}
|
|
540
|
-
const targets = [...source.matchAll(/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\)/g)].map((match) => match[1] ?? "");
|
|
541
|
-
return targets.length > 0 && targets.every((target) => /(?:mock|stub|spy)$/i.test(target));
|
|
542
|
-
}
|
|
543
|
-
|
|
544
|
-
// `toThrow(Error)` / `assert.throws(fn, Error)` constrain only the constructor, not the message
|
|
545
|
-
// or properties. Reports `test-quality.exception-type-only` so authors tighten the assertion.
|
|
546
|
-
function hasExceptionTypeOnlyAssertion(source: string): boolean {
|
|
547
|
-
return /\.toThrow\s*\(\s*(?:Error|[A-Z][A-Za-z0-9_$]*Error)\s*\)/.test(source) || /\bassert\.throws\s*\([^,\n]+,\s*(?:Error|[A-Z][A-Za-z0-9_$]*Error)\s*\)/.test(source);
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
// Three known anti-patterns: writing to `process.env`, writing to `globalThis.*`, or reassigning
|
|
551
|
-
// `Date.now` / `Math.random`. Each leaks state across tests; reports
|
|
552
|
-
// `test-quality.global-state-mutation` so the author isolates the fixture.
|
|
636
|
+
/**
|
|
637
|
+
* Check whether source matches the supported process.env, globalThis, Date.now or Math.random assignment patterns.
|
|
638
|
+
* This textual check does not establish whether state is restored.
|
|
639
|
+
*
|
|
640
|
+
* @param source - masked test body scanned for shared-state assignments
|
|
641
|
+
* @returns True when a supported shared-state assignment pattern matches, used to report possible mutation; false otherwise.
|
|
642
|
+
*/
|
|
553
643
|
function hasGlobalStateMutation(source: string): boolean {
|
|
554
644
|
return /\bprocess\.env\.[A-Za-z0-9_]+\s*=/.test(source) || /\bglobalThis\.[A-Za-z0-9_$]+\s*=/.test(source) || /\b(?:Date\.now|Math\.random)\s*=/.test(source);
|
|
555
645
|
}
|