@blundergoat/gruff-ts 0.3.0 → 0.3.2
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 +12 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +20 -5
- package/SECURITY.md +1 -1
- package/docs/README.md +0 -1
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +0 -3
- package/docs/rules.md +5 -5
- package/package.json +17 -2
- package/src/analyser.ts +18 -8
- package/src/blocks.ts +59 -12
- package/src/changed-regions.ts +25 -17
- package/src/cli-program.ts +100 -4
- package/src/comment-rules.ts +1 -1
- package/src/constants.ts +1 -1
- package/src/dashboard.ts +1 -1
- package/src/findings.ts +12 -0
- package/src/fixture-purpose-rules.ts +7 -9
- package/src/hook-contract.ts +435 -0
- package/src/line-rules.ts +7 -5
- package/src/profiles.ts +0 -1
- package/src/project-rules.ts +4 -116
- package/src/report-renderers.ts +40 -7
- package/src/rule-list.ts +2 -1
- package/src/rules.ts +1 -2
- package/src/sensitive-data-rules.ts +2 -2
- package/src/static-analysis-redundant-rules.ts +411 -0
- package/src/test-block-rules.ts +13 -42
- package/src/test-fixtures.ts +4 -1
- package/src/types.ts +2 -1
- package/docs/releasing.md +0 -106
- package/fixtures/sample.ts +0 -21
- package/scripts/bump-version.sh +0 -210
- package/scripts/check.sh +0 -4
- package/scripts/dependency-install.sh +0 -96
- package/scripts/dependency-update.sh +0 -177
- package/scripts/npm-publish.sh +0 -258
- package/scripts/preflight-checks.sh +0 -395
- package/scripts/start-dev.sh +0 -8
- package/scripts/test-performance.sh +0 -695
- package/src/fixtures/rule-catalogue-security-doctrine.ts +0 -160
package/src/report-renderers.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { severityGradeBreakdown } from "./scoring.ts";
|
|
|
18
18
|
function renderReport(report: AnalysisReport, format: OutputFormat): string {
|
|
19
19
|
switch (format) {
|
|
20
20
|
case "json":
|
|
21
|
-
return JSON.stringify(report, null, 2);
|
|
21
|
+
return JSON.stringify(toJsonReport(report), null, 2);
|
|
22
22
|
case "html":
|
|
23
23
|
return renderHtml(report);
|
|
24
24
|
case "markdown":
|
|
@@ -34,6 +34,38 @@ function renderReport(report: AnalysisReport, format: OutputFormat): string {
|
|
|
34
34
|
}
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
type JsonFinding = Finding & { file: string };
|
|
38
|
+
type JsonTopOffender = AnalysisReport["score"]["topOffenders"][number] & { file: string };
|
|
39
|
+
type JsonAnalysisReport = Omit<AnalysisReport, "findings" | "score"> & {
|
|
40
|
+
findings: JsonFinding[];
|
|
41
|
+
score: Omit<AnalysisReport["score"], "topOffenders"> & { topOffenders: JsonTopOffender[] };
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
// JSON boundary adapter: canonical `file` is emitted while legacy `filePath` stays for one release.
|
|
45
|
+
// Stable `gruff.analysis.v2` contract line kept adjacent to the function for the doc-context rule.
|
|
46
|
+
function toJsonReport(report: AnalysisReport): JsonAnalysisReport {
|
|
47
|
+
return {
|
|
48
|
+
...report,
|
|
49
|
+
findings: report.findings.map(jsonFinding),
|
|
50
|
+
score: {
|
|
51
|
+
...report.score,
|
|
52
|
+
topOffenders: report.score.topOffenders.map(jsonTopOffender),
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Maps one Finding into the JSON contract without mutating the native in-memory finding object.
|
|
58
|
+
function jsonFinding(finding: Finding): JsonFinding {
|
|
59
|
+
const { ruleId, message, filePath, ...rest } = finding;
|
|
60
|
+
return { ruleId, message, file: filePath, filePath, ...rest };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Maps one top offender into the JSON contract while preserving the legacy filePath alias.
|
|
64
|
+
function jsonTopOffender(offender: AnalysisReport["score"]["topOffenders"][number]): JsonTopOffender {
|
|
65
|
+
const { filePath, ...rest } = offender;
|
|
66
|
+
return { file: filePath, filePath, ...rest };
|
|
67
|
+
}
|
|
68
|
+
|
|
37
69
|
/*
|
|
38
70
|
* SARIF 2.1.0 output for GitHub code-scanning uploads. Kept as one large object literal because
|
|
39
71
|
* the SARIF schema demands a specific shape - splitting it up obscures which fields are required.
|
|
@@ -187,12 +219,12 @@ function renderSummary(report: AnalysisReport, elapsedMs?: number, pathLabel?: s
|
|
|
187
219
|
`gruff-ts ${report.tool.version} summary`,
|
|
188
220
|
`Path: ${pathLabel ?? report.run.projectRoot}`,
|
|
189
221
|
...(typeof elapsedMs === "number" ? [`Duration: ${formatSummaryDuration(elapsedMs)}`] : []),
|
|
190
|
-
`Composite: ${report.score.grade} (${report.score.composite.toFixed(
|
|
222
|
+
`Composite: ${report.score.grade} (${report.score.composite.toFixed(2)} / 100)`,
|
|
223
|
+
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
191
224
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
192
225
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
193
226
|
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
194
227
|
...renderComplexityClusterLines(report.findings, top),
|
|
195
|
-
`Findings: ${report.summary.total} total, ${report.summary.error} error, ${report.summary.warning} warning, ${report.summary.advisory} advisory`,
|
|
196
228
|
`Analysed files: ${report.paths.analysedFiles}`,
|
|
197
229
|
...(report.baseline ? [summaryBaselineLine(report.baseline)] : []),
|
|
198
230
|
];
|
|
@@ -382,8 +414,9 @@ function renderRankedCountRows<T extends string>(counts: Map<T, number>, limit?:
|
|
|
382
414
|
function renderText(report: AnalysisReport): string {
|
|
383
415
|
const breakdown = severityGradeBreakdown(report.findings);
|
|
384
416
|
const lines = [
|
|
385
|
-
`gruff-ts ${report.tool.version}`,
|
|
386
|
-
`Composite: ${report.score.grade} (${report.score.composite.toFixed(
|
|
417
|
+
`gruff-ts ${report.tool.version} analyse`,
|
|
418
|
+
`Composite: ${report.score.grade} (${report.score.composite.toFixed(2)} / 100)`,
|
|
419
|
+
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
387
420
|
` Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
388
421
|
` Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
389
422
|
` Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
@@ -415,13 +448,13 @@ function renderMarkdown(report: AnalysisReport): string {
|
|
|
415
448
|
return [
|
|
416
449
|
"# gruff-ts report",
|
|
417
450
|
"",
|
|
418
|
-
`Composite: **${report.score.grade} (${report.score.composite.toFixed(
|
|
451
|
+
`Composite: **${report.score.grade} (${report.score.composite.toFixed(2)} / 100)**`,
|
|
419
452
|
`- Errors: ${breakdown.error.grade} (${breakdown.error.count})`,
|
|
420
453
|
`- Warnings: ${breakdown.warning.grade} (${breakdown.warning.count})`,
|
|
421
454
|
`- Advisory: ${breakdown.advisory.grade} (${breakdown.advisory.count})`,
|
|
422
455
|
...renderMarkdownComplexityClusterLines(report.findings),
|
|
423
456
|
"",
|
|
424
|
-
`Findings: ${report.summary.
|
|
457
|
+
`Findings: ${report.summary.total} total · ${report.summary.error} error · ${report.summary.warning} warning · ${report.summary.advisory} advisory`,
|
|
425
458
|
"",
|
|
426
459
|
...renderMarkdownPillarsTable(buildPillarRows(report)),
|
|
427
460
|
"",
|
package/src/rule-list.ts
CHANGED
|
@@ -23,6 +23,7 @@ const CONSOLE_COMMANDS = [
|
|
|
23
23
|
{ name: "completion", description: "Dump the shell completion script" },
|
|
24
24
|
{ name: "dashboard", description: "Serve the local gruff dashboard." },
|
|
25
25
|
{ name: "help", description: "Display help for a command" },
|
|
26
|
+
{ name: "hook", description: "Run the gruff agent-hook contract." },
|
|
26
27
|
{ name: "init", description: "Write the default .gruff-ts.yaml to the current directory." },
|
|
27
28
|
{ name: "list", description: "List commands" },
|
|
28
29
|
{ name: "list-profiles", description: "List the built-in gruff profiles." },
|
|
@@ -152,7 +153,7 @@ function renderConsoleList(shouldUseAnsi = false): string {
|
|
|
152
153
|
formatConsoleRow("-v|vv|vvv, --verbose", "Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug", 22, shouldUseAnsi),
|
|
153
154
|
"",
|
|
154
155
|
ansiWrap("Available commands:", ANSI_YELLOW, shouldUseAnsi),
|
|
155
|
-
...CONSOLE_COMMANDS.map((command) => formatConsoleRow(command.name, command.description,
|
|
156
|
+
...CONSOLE_COMMANDS.map((command) => formatConsoleRow(command.name, command.description, 15, shouldUseAnsi)),
|
|
156
157
|
].join("\n") + "\n";
|
|
157
158
|
}
|
|
158
159
|
|
package/src/rules.ts
CHANGED
|
@@ -98,14 +98,13 @@ const RULE_DESCRIPTORS: readonly RuleDescriptor[] = [
|
|
|
98
98
|
{ ruleId: "test-quality.global-state-mutation", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests mutating process or global runtime state.", remediation: "Isolate state changes and restore them around the test." },
|
|
99
99
|
{ ruleId: "test-quality.loop-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags loops inside test bodies.", remediation: "Use table tests or separate named cases." },
|
|
100
100
|
{ ruleId: "test-quality.magic-number-assertion", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags assertions against unexplained numeric literals.", remediation: "Name expected values or assert domain-specific outcomes." },
|
|
101
|
-
{ ruleId: "test-quality.missing-nearby-test", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags exported production files without nearby tests.", remediation: "Add a focused test beside the source or in a nearby test directory." },
|
|
102
101
|
{ ruleId: "test-quality.mock-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only verify mock interaction.", remediation: "Assert observable behavior in addition to collaboration." },
|
|
103
102
|
{ ruleId: "test-quality.no-assertions", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tests without apparent assertions.", remediation: "Add assertions for observable behavior." },
|
|
104
103
|
{ ruleId: "test-quality.no-throw-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that only assert code does not throw.", remediation: "Assert the observable result or state change." },
|
|
105
104
|
{ ruleId: "test-quality.only-skip", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags focused or skipped test markers.", remediation: "Remove .only and either enable or delete skipped tests." },
|
|
106
|
-
{ ruleId: "test-quality.setup-bloat", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags tests with too much setup before the first assertion.", remediation: "Extract builders or reduce fixture setup. Or raise rules.test-quality.setup-bloat.threshold in .gruff-ts.yaml if the bound is wrong for this project.", threshold: 12 },
|
|
107
105
|
{ ruleId: "test-quality.sleep-in-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags sleeps in tests.", remediation: "Synchronize on behavior instead of wall-clock time." },
|
|
108
106
|
{ ruleId: "test-quality.snapshot-only-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that rely only on snapshots.", remediation: "Add targeted assertions for important behavior." },
|
|
107
|
+
{ ruleId: "test-quality.static-analysis-redundant-test", pillar: "test-quality", severity: "advisory", confidence: "high", description: "Flags tests that primarily assert code shape rather than behavior.", remediation: "Remove the redundant assertion, replace it with behavioral evidence, or document why runtime coverage matters." },
|
|
109
108
|
{ ruleId: "test-quality.trivial-assertion", pillar: "test-quality", severity: "warning", confidence: "high", description: "Flags tautological assertions.", remediation: "Assert a real result from the system under test." },
|
|
110
109
|
{ ruleId: "test-quality.unused-mock", pillar: "test-quality", severity: "advisory", confidence: "medium", description: "Flags mocks created but not used.", remediation: "Remove unused mocks or wire them into the behavior under test." },
|
|
111
110
|
{ ruleId: "waste.any-type", pillar: "maintainability", severity: "warning", confidence: "high", description: "Flags any type usage.", remediation: "Use unknown with validation or a precise type." },
|
|
@@ -140,7 +140,7 @@ function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: st
|
|
|
140
140
|
index + 1,
|
|
141
141
|
envValue.value,
|
|
142
142
|
"medium",
|
|
143
|
-
{ keyName: envValue.keyName, length: envValue.value.length },
|
|
143
|
+
{ keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
|
|
144
144
|
ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
|
|
145
145
|
);
|
|
146
146
|
}
|
|
@@ -165,7 +165,7 @@ function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, co
|
|
|
165
165
|
byteLine(source, match.index ?? 0),
|
|
166
166
|
raw,
|
|
167
167
|
"medium",
|
|
168
|
-
{ length: raw.length, detector: "high-entropy-string" },
|
|
168
|
+
{ length: raw.length, detector: "high-entropy-string", threshold: minLength },
|
|
169
169
|
ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
|
|
170
170
|
);
|
|
171
171
|
}
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
// Static-analysis-redundant assertion scanner for test blocks. It reports tests that only prove
|
|
2
|
+
// TypeScript-visible code shape, keeping the main per-test-block pass focused on orchestration.
|
|
3
|
+
import { type FunctionBlock } from "./blocks.ts";
|
|
4
|
+
import { type SourceFile } from "./discovery.ts";
|
|
5
|
+
import { makeFinding } from "./findings.ts";
|
|
6
|
+
import { lineOffset } from "./findings-helpers.ts";
|
|
7
|
+
import type { Confidence, Finding } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
// Candidate assertion contract promoted into a real Finding after its test-block line is known.
|
|
10
|
+
interface StaticAnalysisRedundantAssertion {
|
|
11
|
+
assertion: string;
|
|
12
|
+
staticFact: string;
|
|
13
|
+
sourceProof?: string;
|
|
14
|
+
confidence: Confidence;
|
|
15
|
+
recommendation: string;
|
|
16
|
+
index: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Non-nullable declaration evidence captured from a test block before assertion matching runs.
|
|
20
|
+
interface NonNullableReturnDeclaration {
|
|
21
|
+
name: string;
|
|
22
|
+
returnType: string;
|
|
23
|
+
lineOffset: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Full-file source context used to prove imports and declarations outside the current test body.
|
|
27
|
+
export interface StaticAnalysisSourceContext {
|
|
28
|
+
source: string;
|
|
29
|
+
codeSource: string;
|
|
30
|
+
startLine: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// One TypeScript-visible function fact and the line that proves it to reviewers.
|
|
34
|
+
interface StaticFunctionFact {
|
|
35
|
+
staticFact: string;
|
|
36
|
+
sourceProof: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Function facts are split by identifier and namespace import so member lookups stay explicit.
|
|
40
|
+
interface StaticFunctionFacts {
|
|
41
|
+
identifiers: Map<string, StaticFunctionFact>;
|
|
42
|
+
namespaceImports: Map<string, StaticFunctionFact>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const TYPEOF_FUNCTION_ASSERTION_PATTERNS = [
|
|
46
|
+
/\bassert\.(?:equal|strictEqual)\s*\(\s*typeof\s+([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*,\s*["']function["']\s*(?:,[^)]*)?\)/g,
|
|
47
|
+
/\bassert\.(?:equal|strictEqual)\s*\(\s*["']function["']\s*,\s*typeof\s+([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*(?:,[^)]*)?\)/g,
|
|
48
|
+
/\bexpect\s*\(\s*typeof\s+([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*\)\s*\.\s*to(?:Be|Equal|StrictEqual)\s*\(\s*["']function["']\s*\)/g,
|
|
49
|
+
] as const;
|
|
50
|
+
|
|
51
|
+
const DIRECT_CONSTRUCTION_ASSERTION_PATTERNS = [
|
|
52
|
+
/\bassert\.ok\s*\(\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s+instanceof\s+\1\s*(?:,[^)]*)?\)/g,
|
|
53
|
+
/\bassert\.(?:equal|strictEqual)\s*\(\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s+instanceof\s+\1\s*,\s*true\s*(?:,[^)]*)?\)/g,
|
|
54
|
+
/\bexpect\s*\(\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s*\)\s*\.\s*toBeInstanceOf\s*\(\s*\1\s*\)/g,
|
|
55
|
+
] as const;
|
|
56
|
+
|
|
57
|
+
const NON_NULLABLE_ASSERTION_PATTERNS = [
|
|
58
|
+
/\bassert\.not(?:Equal|StrictEqual)\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*,\s*(?:null|undefined)\s*(?:,[^)]*)?\)/g,
|
|
59
|
+
/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*\)\s*\.\s*toBeDefined\s*\(\s*\)/g,
|
|
60
|
+
/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*\)\s*\.\s*not\s*\.\s*toBeNull\s*\(\s*\)/g,
|
|
61
|
+
] as const;
|
|
62
|
+
|
|
63
|
+
const NON_NULLABLE_DECLARATION_PATTERNS = [
|
|
64
|
+
/\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*:\s*([A-Za-z_$][A-Za-z0-9_$<>,\s.[\]]*)\s*\{/g,
|
|
65
|
+
/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\([^)]*\)\s*:\s*([A-Za-z_$][A-Za-z0-9_$<>,\s.[\]]*)\s*=>/g,
|
|
66
|
+
] as const;
|
|
67
|
+
|
|
68
|
+
/*
|
|
69
|
+
* Reports stable `test-quality.static-analysis-redundant-test` findings. The contract keeps source
|
|
70
|
+
* proof and recommendation in metadata because reviewers need the assertion and proof side by side.
|
|
71
|
+
*/
|
|
72
|
+
export function pushStaticAnalysisRedundantTestFindings(file: SourceFile, block: FunctionBlock, rawBody: string, codeBody: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
|
|
73
|
+
for (const candidate of staticAnalysisRedundantAssertions(file, block, rawBody, codeBody, staticContext)) {
|
|
74
|
+
const line = block.startLine + lineOffset(rawBody, candidate.index);
|
|
75
|
+
findings.push(
|
|
76
|
+
makeFinding({
|
|
77
|
+
ruleId: "test-quality.static-analysis-redundant-test",
|
|
78
|
+
message: `Static-analysis-redundant candidate: ${candidate.confidence} confidence. Test \`${block.name}\` asserts code shape rather than behaviour: ${candidate.assertion}.`,
|
|
79
|
+
filePath: file.displayPath,
|
|
80
|
+
line,
|
|
81
|
+
severity: "advisory",
|
|
82
|
+
pillar: "test-quality",
|
|
83
|
+
confidence: candidate.confidence,
|
|
84
|
+
symbol: block.name,
|
|
85
|
+
remediation: candidate.recommendation,
|
|
86
|
+
metadata: {
|
|
87
|
+
testFile: file.displayPath,
|
|
88
|
+
testMethod: block.name,
|
|
89
|
+
assertion: candidate.assertion,
|
|
90
|
+
staticFact: candidate.staticFact,
|
|
91
|
+
sourceProof: candidate.sourceProof ?? `${file.displayPath}:${line}`,
|
|
92
|
+
confidence: candidate.confidence,
|
|
93
|
+
recommendation: candidate.recommendation,
|
|
94
|
+
},
|
|
95
|
+
}),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Runs the three static-shape detectors and preserves deterministic source-order emission.
|
|
101
|
+
function staticAnalysisRedundantAssertions(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, staticContext: StaticAnalysisSourceContext): StaticAnalysisRedundantAssertion[] {
|
|
102
|
+
return [
|
|
103
|
+
...typeofFunctionAssertions(file, rawSource, codeSource, staticContext),
|
|
104
|
+
...directConstructionInstanceAssertions(file, rawSource, codeSource),
|
|
105
|
+
...nonNullableReturnAssertions(file, block, rawSource, codeSource),
|
|
106
|
+
].sort((left, right) => left.index - right.index);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Detects `typeof x === "function"`-style assertions when TypeScript already proves the function.
|
|
110
|
+
function typeofFunctionAssertions(file: SourceFile, rawSource: string, codeSource: string, staticContext: StaticAnalysisSourceContext): StaticAnalysisRedundantAssertion[] {
|
|
111
|
+
const functionFacts = staticFunctionFacts(file, staticContext);
|
|
112
|
+
return TYPEOF_FUNCTION_ASSERTION_PATTERNS.flatMap((pattern) => typeofFunctionAssertionsForPattern(file, rawSource, codeSource, functionFacts, pattern));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Evaluates one typeof-function assertion grammar while keeping executable-source checks local.
|
|
116
|
+
function typeofFunctionAssertionsForPattern(file: SourceFile, rawSource: string, codeSource: string, functionFacts: StaticFunctionFacts, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
|
|
117
|
+
return [...rawSource.matchAll(pattern)]
|
|
118
|
+
.map((match) => typeofFunctionCandidateFromMatch(file, rawSource, codeSource, functionFacts, match))
|
|
119
|
+
.filter(isStaticAnalysisRedundantAssertion);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Builds one typeof-function candidate only when the expression has static declaration evidence.
|
|
123
|
+
function typeofFunctionCandidateFromMatch(file: SourceFile, rawSource: string, codeSource: string, functionFacts: StaticFunctionFacts, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
|
|
124
|
+
const index = match.index ?? 0;
|
|
125
|
+
if (!isExecutableAssertionAt(codeSource, index)) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const expression = match[1] ?? "";
|
|
129
|
+
const fact = staticFunctionFactForExpression(expression, functionFacts);
|
|
130
|
+
if (!fact) {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
return staticRedundantCandidate({
|
|
134
|
+
file,
|
|
135
|
+
source: rawSource,
|
|
136
|
+
index,
|
|
137
|
+
assertion: normalizedAssertionText(match[0] ?? ""),
|
|
138
|
+
staticFact: fact.staticFact,
|
|
139
|
+
sourceProof: fact.sourceProof,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Gathers declaration and import facts from the full source context once per test-block scan.
|
|
144
|
+
function staticFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext): StaticFunctionFacts {
|
|
145
|
+
const facts: StaticFunctionFacts = { identifiers: new Map(), namespaceImports: new Map() };
|
|
146
|
+
pushFunctionDeclarationFacts(file, context, facts.identifiers);
|
|
147
|
+
pushConstFunctionFacts(file, context, facts.identifiers);
|
|
148
|
+
pushImportFunctionFacts(file, context, facts);
|
|
149
|
+
return facts;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Adds facts for `function name()` declarations because comments and strings can mimic syntax.
|
|
153
|
+
function pushFunctionDeclarationFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
154
|
+
for (const match of context.source.matchAll(/\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
|
|
155
|
+
const index = match.index ?? 0;
|
|
156
|
+
if (!isExecutableFunctionDeclarationAt(context.codeSource, index)) {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const name = match[1] ?? "";
|
|
160
|
+
if (name) {
|
|
161
|
+
facts.set(name, {
|
|
162
|
+
staticFact: `\`${name}\` is declared as a function in this file.`,
|
|
163
|
+
sourceProof: sourceProof(file, context, index),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Adds facts for const-bound functions because these declarations are common test helper shapes.
|
|
170
|
+
function pushConstFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
171
|
+
const pattern = /\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?(?:function\b|(?:\([^)]*\)|[A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*[^=;]+?)?=>)/g;
|
|
172
|
+
for (const match of context.source.matchAll(pattern)) {
|
|
173
|
+
const index = match.index ?? 0;
|
|
174
|
+
if (!isExecutableFunctionDeclarationAt(context.codeSource, index)) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const name = match[1] ?? "";
|
|
178
|
+
if (name) {
|
|
179
|
+
facts.set(name, {
|
|
180
|
+
staticFact: `\`${name}\` is declared as a function-valued const in this file.`,
|
|
181
|
+
sourceProof: sourceProof(file, context, index),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Dispatches named and namespace import evidence into separate maps for later expression lookup.
|
|
188
|
+
function pushImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: StaticFunctionFacts): void {
|
|
189
|
+
pushNamedImportFunctionFacts(file, context, facts.identifiers);
|
|
190
|
+
pushNamespaceImportFunctionFacts(file, context, facts.namespaceImports);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Adds facts for static named imports, including aliases, when the import is executable code.
|
|
194
|
+
function pushNamedImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
195
|
+
for (const match of context.source.matchAll(/\bimport\s+(?!type\b)\{([^}]+)\}\s*from\b/g)) {
|
|
196
|
+
const index = match.index ?? 0;
|
|
197
|
+
if (!isExecutableImportAt(context.codeSource, index)) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const proof = sourceProof(file, context, index);
|
|
201
|
+
for (const importedName of namedImportLocals(match[1] ?? "")) {
|
|
202
|
+
facts.set(importedName, namedImportFunctionFact(importedName, proof));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Adds facts for namespace imports because `namespace.member` assertions need import-level proof.
|
|
208
|
+
function pushNamespaceImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
209
|
+
for (const match of context.source.matchAll(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/g)) {
|
|
210
|
+
const index = match.index ?? 0;
|
|
211
|
+
if (!isExecutableImportAt(context.codeSource, index)) {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const namespaceName = match[1] ?? "";
|
|
215
|
+
if (namespaceName) {
|
|
216
|
+
facts.set(namespaceName, {
|
|
217
|
+
staticFact: `\`${namespaceName}\` is a static ES module namespace import.`,
|
|
218
|
+
sourceProof: sourceProof(file, context, index),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Builds the reviewer-facing fact text for one named import.
|
|
225
|
+
function namedImportFunctionFact(importedName: string, proof: string): StaticFunctionFact {
|
|
226
|
+
return {
|
|
227
|
+
staticFact: `\`${importedName}\` is a static ES module named import, so TypeScript can validate the imported binding's declared function type without executing this test assertion.`,
|
|
228
|
+
sourceProof: proof,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Normalises `import { original as local }` clauses to the local binding names used in tests.
|
|
233
|
+
function namedImportLocals(importClause: string): string[] {
|
|
234
|
+
return importClause
|
|
235
|
+
.split(",")
|
|
236
|
+
.map((specifier) => namedImportLocal(specifier))
|
|
237
|
+
.filter((value): value is string => value !== undefined);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Returns the local binding name for one named import specifier, ignoring type-only entries.
|
|
241
|
+
function namedImportLocal(specifier: string): string | undefined {
|
|
242
|
+
const trimmed = specifier.trim();
|
|
243
|
+
if (trimmed === "" || /^type\b/.test(trimmed)) {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
const aliased = trimmed.match(/\bas\s+([A-Za-z_$][A-Za-z0-9_$]*)$/);
|
|
247
|
+
if (aliased) {
|
|
248
|
+
return aliased[1];
|
|
249
|
+
}
|
|
250
|
+
const direct = trimmed.match(/^([A-Za-z_$][A-Za-z0-9_$]*)$/);
|
|
251
|
+
return direct?.[1];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Looks up direct identifiers and namespace-member expressions against static import facts.
|
|
255
|
+
function staticFunctionFactForExpression(expression: string, facts: StaticFunctionFacts): StaticFunctionFact | undefined {
|
|
256
|
+
const direct = facts.identifiers.get(expression);
|
|
257
|
+
if (direct) {
|
|
258
|
+
return direct;
|
|
259
|
+
}
|
|
260
|
+
const namespaceMember = expression.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
|
|
261
|
+
if (!namespaceMember) {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
const namespaceName = namespaceMember[1] ?? "";
|
|
265
|
+
const memberName = namespaceMember[2] ?? "";
|
|
266
|
+
const namespaceFact = facts.namespaceImports.get(namespaceName);
|
|
267
|
+
if (!namespaceFact || !memberName) {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
return {
|
|
271
|
+
staticFact: `\`${expression}\` is a statically named member of the \`${namespaceName}\` namespace import, so TypeScript can validate that member's declared function type without executing this test assertion.`,
|
|
272
|
+
sourceProof: namespaceFact.sourceProof,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Converts a byte offset in the source context into the display path and 1-based proof line.
|
|
277
|
+
function sourceProof(file: SourceFile, context: StaticAnalysisSourceContext, index: number): string {
|
|
278
|
+
return `${file.displayPath}:${context.startLine + lineOffset(context.source, index)}`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Detects self-instance assertions where the constructor expression itself proves the relationship.
|
|
282
|
+
function directConstructionInstanceAssertions(file: SourceFile, rawSource: string, codeSource: string): StaticAnalysisRedundantAssertion[] {
|
|
283
|
+
return DIRECT_CONSTRUCTION_ASSERTION_PATTERNS.flatMap((pattern) => directConstructionInstanceAssertionsForPattern(file, rawSource, codeSource, pattern));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Evaluates one direct-construction assertion grammar against executable test code.
|
|
287
|
+
function directConstructionInstanceAssertionsForPattern(file: SourceFile, rawSource: string, codeSource: string, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
|
|
288
|
+
return [...rawSource.matchAll(pattern)]
|
|
289
|
+
.map((match) => directConstructionInstanceCandidate(file, rawSource, codeSource, match))
|
|
290
|
+
.filter(isStaticAnalysisRedundantAssertion);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Builds one direct-construction candidate with a source-order index for stable sorting.
|
|
294
|
+
function directConstructionInstanceCandidate(file: SourceFile, rawSource: string, codeSource: string, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
|
|
295
|
+
const index = match.index ?? 0;
|
|
296
|
+
if (!isExecutableAssertionAt(codeSource, index)) {
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
const className = match[1] ?? "";
|
|
300
|
+
return staticRedundantCandidate({
|
|
301
|
+
file,
|
|
302
|
+
source: rawSource,
|
|
303
|
+
index,
|
|
304
|
+
assertion: normalizedAssertionText(match[0] ?? ""),
|
|
305
|
+
staticFact: `\`new ${className}()\` constructs \`${className}\`, so the self-instance relationship is established by the expression shape.`,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Detects assertions that only check non-nullability already guaranteed by a return type.
|
|
310
|
+
function nonNullableReturnAssertions(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string): StaticAnalysisRedundantAssertion[] {
|
|
311
|
+
const declarations = nonNullableReturnDeclarations(rawSource, codeSource);
|
|
312
|
+
return NON_NULLABLE_ASSERTION_PATTERNS.flatMap((pattern) => nonNullableReturnAssertionsForPattern(file, block, rawSource, codeSource, declarations, pattern));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Evaluates one non-nullable assertion grammar against collected return-type declarations.
|
|
316
|
+
function nonNullableReturnAssertionsForPattern(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, declarations: Map<string, NonNullableReturnDeclaration>, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
|
|
317
|
+
return [...rawSource.matchAll(pattern)]
|
|
318
|
+
.map((match) => nonNullableReturnCandidate(file, block, rawSource, codeSource, declarations, match))
|
|
319
|
+
.filter(isStaticAnalysisRedundantAssertion);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Builds one non-nullable-return candidate only when declaration evidence exists.
|
|
323
|
+
function nonNullableReturnCandidate(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, declarations: Map<string, NonNullableReturnDeclaration>, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
|
|
324
|
+
const index = match.index ?? 0;
|
|
325
|
+
if (!isExecutableAssertionAt(codeSource, index)) {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
const declaration = declarations.get(match[1] ?? "");
|
|
329
|
+
if (!declaration) {
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
return staticRedundantCandidate({
|
|
333
|
+
file,
|
|
334
|
+
source: rawSource,
|
|
335
|
+
index,
|
|
336
|
+
assertion: normalizedAssertionText(match[0] ?? ""),
|
|
337
|
+
staticFact: `\`${declaration.name}()\` declares a non-nullable \`${declaration.returnType}\` return type.`,
|
|
338
|
+
sourceProof: `${file.displayPath}:${block.startLine + declaration.lineOffset}`,
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Collects function and const-arrow declarations whose return type excludes null and undefined.
|
|
343
|
+
function nonNullableReturnDeclarations(source: string, codeSource: string): Map<string, NonNullableReturnDeclaration> {
|
|
344
|
+
const declarations = new Map<string, NonNullableReturnDeclaration>();
|
|
345
|
+
for (const pattern of NON_NULLABLE_DECLARATION_PATTERNS) {
|
|
346
|
+
pushNonNullableReturnDeclarationsForPattern(declarations, source, codeSource, pattern);
|
|
347
|
+
}
|
|
348
|
+
return declarations;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Adds declaration evidence for one grammar while ignoring masked comments and strings.
|
|
352
|
+
function pushNonNullableReturnDeclarationsForPattern(declarations: Map<string, NonNullableReturnDeclaration>, source: string, codeSource: string, pattern: RegExp): void {
|
|
353
|
+
for (const match of source.matchAll(pattern)) {
|
|
354
|
+
if (!isExecutableFunctionDeclarationAt(codeSource, match.index ?? 0)) {
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
pushNonNullableReturnDeclaration(declarations, source, match.index ?? 0, match[1] ?? "", match[2] ?? "");
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Gives each static-shape candidate the shared confidence and remediation contract.
|
|
362
|
+
function staticRedundantCandidate(args: Omit<StaticAnalysisRedundantAssertion, "confidence" | "recommendation"> & { file: SourceFile; source: string }): StaticAnalysisRedundantAssertion {
|
|
363
|
+
const { file: _file, source: _source, ...candidate } = args;
|
|
364
|
+
return {
|
|
365
|
+
...candidate,
|
|
366
|
+
confidence: "high",
|
|
367
|
+
recommendation: "Remove this assertion if it is the only behavior being tested, or replace it with an assertion about the returned value or observable behavior.",
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Type guard used after optional candidate builders so callers keep precise arrays.
|
|
372
|
+
function isStaticAnalysisRedundantAssertion(candidate: StaticAnalysisRedundantAssertion | undefined): candidate is StaticAnalysisRedundantAssertion {
|
|
373
|
+
return candidate !== undefined;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Collapses whitespace so finding messages carry readable one-line assertion snippets.
|
|
377
|
+
function normalizedAssertionText(assertion: string): string {
|
|
378
|
+
return assertion.replace(/\s+/g, " ").trim();
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Checks masked code at the match offset so comment/string matches cannot create findings.
|
|
382
|
+
function isExecutableAssertionAt(codeSource: string, index: number): boolean {
|
|
383
|
+
return /\b(?:assert|expect)\b/.test(codeSource.slice(index, index + 12));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Checks masked code at the match offset so comment/string declarations are ignored.
|
|
387
|
+
function isExecutableFunctionDeclarationAt(codeSource: string, index: number): boolean {
|
|
388
|
+
return /\b(?:function|const)\b/.test(codeSource.slice(index, index + 12));
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Checks masked code at the match offset so commented import examples are ignored.
|
|
392
|
+
function isExecutableImportAt(codeSource: string, index: number): boolean {
|
|
393
|
+
return /\bimport\b/.test(codeSource.slice(index, index + 12));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Stores one declaration only when the name is present and the return type is non-nullable.
|
|
397
|
+
function pushNonNullableReturnDeclaration(declarations: Map<string, NonNullableReturnDeclaration>, source: string, index: number, name: string, returnType: string): void {
|
|
398
|
+
const normalizedReturnType = returnType.replace(/\s+/g, " ").trim();
|
|
399
|
+
if (!name || !isNonNullableReturnType(normalizedReturnType)) {
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
declarations.set(name, { name, returnType: normalizedReturnType, lineOffset: lineOffset(source, index) });
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Treats explicit nullable, unknown, and non-returning types as not useful static proof.
|
|
406
|
+
function isNonNullableReturnType(returnType: string): boolean {
|
|
407
|
+
if (returnType === "" || /^(?:any|unknown|void|null|undefined|never)$/.test(returnType)) {
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
return !/\b(?:null|undefined)\b/.test(returnType);
|
|
411
|
+
}
|
package/src/test-block-rules.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// Per-test-block rule pass: assertion quality (no-assertions, trivial, snapshot-only,
|
|
2
2
|
// no-throw-only, exception-type-only, magic-number), mock quality (unused-mock, mock-only-test),
|
|
3
|
-
//
|
|
3
|
+
// global-state-mutation, and structural checks (sleep/loop/conditional/only-skip).
|
|
4
4
|
// Invoked from the analyseBlocks orchestrator when `block.isTest` is true.
|
|
5
|
-
import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion
|
|
6
|
-
import { ruleSeverity, threshold } from "./config.ts";
|
|
5
|
+
import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion } from "./blocks.ts";
|
|
7
6
|
import { type SourceFile } from "./discovery.ts";
|
|
8
7
|
import { escapeRegex } from "./findings-helpers.ts";
|
|
8
|
+
import { pushStaticAnalysisRedundantTestFindings, type StaticAnalysisSourceContext } from "./static-analysis-redundant-rules.ts";
|
|
9
9
|
import { countMatches } from "./text-scans.ts";
|
|
10
|
-
import type {
|
|
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
|
|
13
13
|
// (file, line) is known, then promoted into a real Finding by the caller.
|
|
@@ -27,23 +27,25 @@ interface MagicNumberAssertionPattern {
|
|
|
27
27
|
|
|
28
28
|
/*
|
|
29
29
|
* Reached when `block.isTest` is true. Four sub-passes in a stable, deterministic order: assertion
|
|
30
|
-
* quality, mock quality,
|
|
30
|
+
* quality, mock quality, global-state-mutation, structural rules.
|
|
31
31
|
*/
|
|
32
|
-
export function analyseTestBlock(file: SourceFile, block: FunctionBlock,
|
|
32
|
+
export function analyseTestBlock(file: SourceFile, block: FunctionBlock, findings: Finding[], staticContext?: StaticAnalysisSourceContext): void {
|
|
33
33
|
const body = block.codeBody;
|
|
34
|
-
|
|
34
|
+
const sourceContext = staticContext ?? { source: block.body, codeSource: block.codeBody, startLine: block.startLine };
|
|
35
|
+
analyseAssertionQuality(file, block, body, sourceContext, findings);
|
|
35
36
|
analyseMockQuality(file, block, body, findings);
|
|
36
|
-
|
|
37
|
+
analyseGlobalStateMutation(file, block, body, findings);
|
|
37
38
|
analyseTestStructureChecks(file, block, body, findings);
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
// Five assertion-shape checks (no-assertions, trivial, snapshot-only, no-throw-only, exception-type-only)
|
|
41
42
|
// plus the magic-number sub-pass. Reports findings with stable test-block metadata.
|
|
42
|
-
function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
43
|
+
function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
|
|
43
44
|
for (const check of assertionQualityChecks(block, body)) {
|
|
44
45
|
findings.push(blockFinding({ ruleId: check.ruleId, message: check.message, file, block, severity: check.severity, pillar: "test-quality" }));
|
|
45
46
|
}
|
|
46
47
|
pushMagicNumberAssertionFindings(file, block, body, findings);
|
|
48
|
+
pushStaticAnalysisRedundantTestFindings(file, block, block.body, body, staticContext, findings);
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
// Lazy evaluation: only checks whose `active` predicate fired are returned. The five rule IDs are
|
|
@@ -105,30 +107,11 @@ function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string
|
|
|
105
107
|
}
|
|
106
108
|
}
|
|
107
109
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
* and `test-quality.setup-bloat` (threshold 12) for excessive arrange before the first assertion.
|
|
111
|
-
* Reports both with stable metadata so downstream tooling can track the setup-line counts.
|
|
112
|
-
*/
|
|
113
|
-
function analyseSetupBloat(file: SourceFile, block: FunctionBlock, body: string, config: Config, findings: Finding[]): void {
|
|
110
|
+
// Reports the stable `test-quality.global-state-mutation` finding contract for state leaks.
|
|
111
|
+
function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
114
112
|
if (hasGlobalStateMutation(body)) {
|
|
115
113
|
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" }));
|
|
116
114
|
}
|
|
117
|
-
const setupLines = setupLineCount(body);
|
|
118
|
-
const maxSetupLines = setupBloatThreshold(file, config);
|
|
119
|
-
if (setupLines > maxSetupLines) {
|
|
120
|
-
findings.push(
|
|
121
|
-
blockFindingWithMetadata({
|
|
122
|
-
ruleId: "test-quality.setup-bloat",
|
|
123
|
-
message: `Test \`${block.name}\` has ${setupLines} setup lines before its first assertion.`,
|
|
124
|
-
file,
|
|
125
|
-
block,
|
|
126
|
-
severity: ruleSeverity(config, "test-quality.setup-bloat", "advisory"),
|
|
127
|
-
pillar: "test-quality",
|
|
128
|
-
metadata: { setupLines, maxSetupLines },
|
|
129
|
-
}),
|
|
130
|
-
);
|
|
131
|
-
}
|
|
132
115
|
}
|
|
133
116
|
|
|
134
117
|
// Pattern-driven checks for sleep/loop/conditional logic plus the `.only`/`.skip` commit gate.
|
|
@@ -241,18 +224,6 @@ function isFixtureDiscoveryCall(initializer: string): boolean {
|
|
|
241
224
|
return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
|
|
242
225
|
}
|
|
243
226
|
|
|
244
|
-
// Integration, contract, smoke, and performance tests naturally need more environment setup than
|
|
245
|
-
// focused unit tests; keep the default strict for unit tests and double it for broad-flow suites.
|
|
246
|
-
function setupBloatThreshold(file: SourceFile, config: Config): number {
|
|
247
|
-
const baseThreshold = threshold(config, "test-quality.setup-bloat", 12);
|
|
248
|
-
return isBroadFlowTestPath(file.displayPath) ? baseThreshold * 2 : baseThreshold;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// Broad-flow tests exercise systems rather than one unit, so longer setup stays below the bloat line.
|
|
252
|
-
function isBroadFlowTestPath(path: string): boolean {
|
|
253
|
-
return /(?:^|\/)test\/(?:integration|contract|smoke|performance)\//.test(path);
|
|
254
|
-
}
|
|
255
|
-
|
|
256
227
|
// Structural loop/branch findings now require the control flow to wrap an assertion; setup-only
|
|
257
228
|
// conditionals and fixture-building loops are noisy but not direct test-quality failures.
|
|
258
229
|
function controlFlowContainsAssertion(source: string, pattern: RegExp): boolean {
|