@blundergoat/gruff-ts 0.3.0 → 0.3.1
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 +6 -0
- package/README.md +3 -3
- package/docs/configuration.md +0 -3
- package/docs/rules.md +3 -4
- package/package.json +1 -1
- package/src/analyser.ts +5 -7
- package/src/blocks.ts +3 -3
- package/src/cli-program.ts +1 -1
- package/src/comment-rules.ts +1 -1
- package/src/constants.ts +1 -1
- package/src/findings.ts +10 -0
- package/src/fixture-purpose-rules.ts +7 -9
- 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 +1 -1
- package/src/rules.ts +1 -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 +1 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## v0.3.1 - 2026-06-03
|
|
4
|
+
|
|
5
|
+
- **JSON finding path alias and stable identity** - `analyse --format=json` and `report --format=json` now emit canonical `findings[].file` alongside the existing `findings[].filePath`; `filePath` is deprecated and will be removed in the next release. Findings also carry `stableIdentity`, a line-insensitive 16-hex identity for external diff tooling. Existing `fingerprint` values, baselines, SARIF fingerprints, dashboard data, and in-memory `filePath` consumers are unchanged.
|
|
6
|
+
- **Test-quality static-analysis redundancy rule and low-signal retirements** - adds `test-quality.static-analysis-redundant-test`, an advisory rule for tests that mostly assert statically knowable code shape instead of behaviour (for example `typeof exportedFunction === "function"`, direct `instanceof` construction, or non-null assertions against visible non-nullable return declarations). Findings include static-proof metadata and keep runtime payload/callable assertions quiet. The low-signal `test-quality.missing-nearby-test` project-layout rule and `test-quality.setup-bloat` setup-size rule are removed from the catalogue and config defaults; stale config entries are ignored. (`src/test-block-rules.ts`, `src/project-rules.ts`, `src/rules.ts`)
|
|
7
|
+
- **Per-rule `severity:` overrides now apply to the descriptor-driven line rules** - the `security.*`, `modernisation.*`, and `waste.*` regex line checks (for example `security.new-function`, `security.eval-call`) emitted findings with a hardcoded severity, so a project's `rules.<id>.severity` override in `.gruff-ts.yaml` was silently ignored. `pushPatternCheckFindings` now resolves severity through `ruleSeverity`, like every other pillar; the descriptor severity stays the default. A project running a legitimate `new Function`/eval shape (such as a transpile-then-execute test loader) can set `security.new-function: { severity: warning }` to keep the finding visible without failing an `--fail-on error` gate. No default severity, schema, or `Finding` shape change. (`src/line-rules.ts`, `src/security-and-config.test.ts`)
|
|
8
|
+
|
|
3
9
|
## v0.3.0 - 2026-05-30
|
|
4
10
|
|
|
5
11
|
0.3.0 release. Changes since 0.2.0: three breaking rule removals (`complexity.npath`; `size.stylesheet-length` with CSS dropped from scanned file types; and the `design.god-function` composite), region-scoped incremental analysis, authoritative `paths.ignore` with a new `check-ignore` command, sensitive-data PHI/GCP detection, named config profiles with `extends:` inheritance, and a documentation reframe around gruff's purpose - governing AI-generated code so a human who did not write it can sign off on it.
|
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ Used as a hook on an agent's output, gruff-ts is a forcing function rather than
|
|
|
24
24
|
| Runtime | Node.js `22+` |
|
|
25
25
|
| Package | `@blundergoat/gruff-ts` |
|
|
26
26
|
| Binary | `gruff-ts` |
|
|
27
|
-
| Rule catalogue |
|
|
27
|
+
| Rule catalogue | 122 rules across 11 pillars |
|
|
28
28
|
| Primary config | `.gruff-ts.yaml`; `.gruff.json`, `.gruff.yaml`, and `.gruff.yml` are fallback files |
|
|
29
29
|
| Analysis schema | `gruff.analysis.v2` |
|
|
30
30
|
| Baseline schema | `gruff.baseline.v1` |
|
|
@@ -223,7 +223,7 @@ Semantics:
|
|
|
223
223
|
|
|
224
224
|
## Rules And Pillars
|
|
225
225
|
|
|
226
|
-
The current catalogue contains
|
|
226
|
+
The current catalogue contains 122 rules:
|
|
227
227
|
|
|
228
228
|
| Pillar | Rules |
|
|
229
229
|
| --- | ---: |
|
|
@@ -237,7 +237,7 @@ The current catalogue contains 121 rules:
|
|
|
237
237
|
| `security` | 29 |
|
|
238
238
|
| `sensitive-data` | 10 |
|
|
239
239
|
| `size` | 3 |
|
|
240
|
-
| `test-quality` |
|
|
240
|
+
| `test-quality` | 16 |
|
|
241
241
|
|
|
242
242
|
Use `npx gruff-ts list-rules --format=json` for exact rule IDs, severities, confidence levels, remediation text, thresholds, and options.
|
|
243
243
|
|
package/docs/configuration.md
CHANGED
package/docs/rules.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Rules
|
|
2
2
|
|
|
3
|
-
`gruff-ts` exposes
|
|
3
|
+
`gruff-ts` exposes 122 rules across 11 pillars. This list is generated from the
|
|
4
4
|
public rule catalogue used by `gruff-ts list-rules`; severity, confidence,
|
|
5
5
|
thresholds, and option names are the defaults before project config overrides.
|
|
6
6
|
|
|
@@ -30,7 +30,7 @@ gruff-ts list-rules --format=json
|
|
|
30
30
|
- security: 29
|
|
31
31
|
- sensitive-data: 10
|
|
32
32
|
- size: 3
|
|
33
|
-
- test-quality:
|
|
33
|
+
- test-quality: 16
|
|
34
34
|
|
|
35
35
|
## Complexity
|
|
36
36
|
|
|
@@ -157,14 +157,13 @@ gruff-ts list-rules --format=json
|
|
|
157
157
|
- `test-quality.global-state-mutation` (warning; high confidence): Flags tests mutating process or global runtime state.
|
|
158
158
|
- `test-quality.loop-in-test` (advisory; high confidence): Flags loops inside test bodies.
|
|
159
159
|
- `test-quality.magic-number-assertion` (advisory; medium confidence): Flags assertions against unexplained numeric literals.
|
|
160
|
-
- `test-quality.missing-nearby-test` (advisory; medium confidence): Flags exported production files without nearby tests.
|
|
161
160
|
- `test-quality.mock-only-test` (advisory; high confidence): Flags tests that only verify mock interaction.
|
|
162
161
|
- `test-quality.no-assertions` (warning; high confidence): Flags tests without apparent assertions.
|
|
163
162
|
- `test-quality.no-throw-only-test` (advisory; high confidence): Flags tests that only assert code does not throw.
|
|
164
163
|
- `test-quality.only-skip` (advisory; high confidence): Flags focused or skipped test markers.
|
|
165
|
-
- `test-quality.setup-bloat` (advisory; medium confidence; threshold 12): Flags tests with too much setup before the first assertion.
|
|
166
164
|
- `test-quality.sleep-in-test` (advisory; high confidence): Flags sleeps in tests.
|
|
167
165
|
- `test-quality.snapshot-only-test` (advisory; high confidence): Flags tests that rely only on snapshots.
|
|
166
|
+
- `test-quality.static-analysis-redundant-test` (advisory; high confidence): Flags tests that primarily assert code shape rather than behavior.
|
|
168
167
|
- `test-quality.trivial-assertion` (warning; high confidence): Flags tautological assertions.
|
|
169
168
|
- `test-quality.unused-mock` (advisory; medium confidence): Flags mocks created but not used.
|
|
170
169
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blundergoat/gruff-ts",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Governs AI-generated code so a human can verify it: a TypeScript/JavaScript static analyzer - 119 rules across 11 quality pillars, SARIF output, baselines, and a local dashboard.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Matthew Hansen (https://www.blundergoat.com/about)",
|
package/src/analyser.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { absolutize, discoverSources, displayPath, type SourceFile } from "./dis
|
|
|
12
12
|
import { makeFinding } from "./findings.ts";
|
|
13
13
|
import { finding } from "./findings-helpers.ts";
|
|
14
14
|
import { commentRecords } from "./comment-scanner.ts";
|
|
15
|
-
import { analyseArchitectureRules,
|
|
15
|
+
import { analyseArchitectureRules, buildProjectIndex, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
|
|
16
16
|
import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks, parameterNames } from "./blocks.ts";
|
|
17
17
|
import { analyseClassRules, analyseAcronymCase, analyseInconsistentCasing, analyseInterfaceFields, collectDeclaredIdentifiers } from "./class-rules.ts";
|
|
18
18
|
import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
|
|
@@ -178,8 +178,7 @@ function shouldRetainProjectSource(file: SourceFile, source: string): boolean {
|
|
|
178
178
|
function projectSource(file: SourceFile, source: string): ProjectSource {
|
|
179
179
|
const lines = source.split(/\r?\n/);
|
|
180
180
|
const templateMaskedLines = hasImportSyntaxCandidate(source) ? maskTemplateLiteralBodies(source).split(/\r?\n/) : lines;
|
|
181
|
-
|
|
182
|
-
return { file, lines, templateMaskedLines, ...(surface ? { exportedSurface: surface } : {}) };
|
|
181
|
+
return { file, lines, templateMaskedLines };
|
|
183
182
|
}
|
|
184
183
|
|
|
185
184
|
// Cheap prefilter for files that might contain real import/export edges or fixture strings that
|
|
@@ -284,7 +283,6 @@ function analyseProjectIndex(projectSources: ProjectSource[], config: Config): F
|
|
|
284
283
|
const index = buildProjectIndex(projectSources);
|
|
285
284
|
const findings: Finding[] = [];
|
|
286
285
|
analyseArchitectureRules(index, config, findings);
|
|
287
|
-
analyseTestAdequacyRules(index, findings);
|
|
288
286
|
return findings;
|
|
289
287
|
}
|
|
290
288
|
|
|
@@ -334,7 +332,7 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
|
|
|
334
332
|
const blocks = functionBlocks(source, codeSource);
|
|
335
333
|
const comments = commentRecords(source);
|
|
336
334
|
analyseFileOverviewDoc(file, source, findings);
|
|
337
|
-
analyseBlocks(file, blocks, config, findings);
|
|
335
|
+
analyseBlocks(file, source, codeSource, blocks, config, findings);
|
|
338
336
|
analyseUnusedImports(file, codeSource, source, findings);
|
|
339
337
|
analyseLineRules(file, source, codeSource, config, findings);
|
|
340
338
|
analyseSecurityFlow(file, source, findings);
|
|
@@ -355,13 +353,13 @@ function analyseTypeScriptRules(file: SourceFile, source: string, config: Config
|
|
|
355
353
|
// separately so blocks.ts can stay independent of the naming-pusher and test-block-rule modules;
|
|
356
354
|
// the per-rule emission order from `analyseBlockRules` is the stable fingerprint contract every
|
|
357
355
|
// Finding depends on for deterministic baseline matching.
|
|
358
|
-
function analyseBlocks(file: SourceFile, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
|
|
356
|
+
function analyseBlocks(file: SourceFile, source: string, codeSource: string, blocks: FunctionBlock[], config: Config, findings: Finding[]): void {
|
|
359
357
|
for (const block of blocks) {
|
|
360
358
|
const context = blockRuleContext(file, block, config, findings);
|
|
361
359
|
analyseBlockRules(context);
|
|
362
360
|
pushParameterNamingFindings(context);
|
|
363
361
|
if (block.isTest) {
|
|
364
|
-
analyseTestBlock(file, block,
|
|
362
|
+
analyseTestBlock(file, block, findings, { source, codeSource, startLine: 1 });
|
|
365
363
|
}
|
|
366
364
|
}
|
|
367
365
|
}
|
package/src/blocks.ts
CHANGED
|
@@ -669,9 +669,9 @@ export function hasAssertion(source: string): boolean {
|
|
|
669
669
|
return false;
|
|
670
670
|
}
|
|
671
671
|
|
|
672
|
-
//
|
|
673
|
-
//
|
|
674
|
-
//
|
|
672
|
+
// Counts non-ignorable lines preceding the first assertion in a test body. Stops as soon as an
|
|
673
|
+
// assertion appears, so the value never overshoots the actual prologue length. Used by
|
|
674
|
+
// `docs.fixture-purpose-missing` to size test-setup fixtures.
|
|
675
675
|
export function setupLineCount(source: string): number {
|
|
676
676
|
let count = 0;
|
|
677
677
|
for (const line of functionBodyContent(source).split(/\r?\n/)) {
|
package/src/cli-program.ts
CHANGED
|
@@ -126,7 +126,7 @@ function configureRootProgram(program: Command): void {
|
|
|
126
126
|
.name("gruff-ts")
|
|
127
127
|
.usage("command [options] [arguments]")
|
|
128
128
|
.helpOption("-h, --help", "Display help for the given command. When no command is given display help for the list command")
|
|
129
|
-
.version(VERSION
|
|
129
|
+
.version(`gruff-ts ${VERSION}`, "-V, --version", "Display this application version")
|
|
130
130
|
.option("--silent", "Do not output any message")
|
|
131
131
|
.option("-q, --quiet", "Only errors are displayed. All other output is suppressed")
|
|
132
132
|
.option("--ansi", "Force ANSI output")
|
package/src/comment-rules.ts
CHANGED
|
@@ -59,7 +59,7 @@ export function analyseCommentQualityRules(input: CommentQualityRuleInput): void
|
|
|
59
59
|
analyseCommentedDeclarationQuality(file, lines, comments, declarations, findings);
|
|
60
60
|
analyseFunctionContextCommentQuality({ file, lines, comments, blocks, config, findings });
|
|
61
61
|
pushMagicThresholdFindings(file, lines, codeSource, comments, findings);
|
|
62
|
-
pushFixturePurposeFindings({ file, source, codeSource, lines, comments, blocks,
|
|
62
|
+
pushFixturePurposeFindings({ file, source, codeSource, lines, comments, blocks, findings });
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
/*
|
package/src/constants.ts
CHANGED
package/src/findings.ts
CHANGED
|
@@ -39,7 +39,17 @@ function makeFinding(input: FindingInput): Finding {
|
|
|
39
39
|
...(input.remediation ? { remediation: input.remediation } : {}),
|
|
40
40
|
metadata: input.metadata ?? {},
|
|
41
41
|
fingerprint,
|
|
42
|
+
stableIdentity: stableIdentityFor(input),
|
|
42
43
|
};
|
|
43
44
|
}
|
|
44
45
|
|
|
46
|
+
// Stable, line-insensitive identity for external diff tooling; fingerprint remains line-sensitive.
|
|
47
|
+
function stableIdentityFor(input: FindingInput): string {
|
|
48
|
+
const symbolOrMessage = input.symbol && input.symbol.length > 0 ? input.symbol : input.message;
|
|
49
|
+
return createHash("sha256")
|
|
50
|
+
.update([input.ruleId, input.filePath, symbolOrMessage].join("\0"))
|
|
51
|
+
.digest("hex")
|
|
52
|
+
.slice(0, 16);
|
|
53
|
+
}
|
|
54
|
+
|
|
45
55
|
export { makeFinding };
|
|
@@ -3,11 +3,10 @@
|
|
|
3
3
|
// reports `docs.fixture-purpose-missing` for each candidate without a nearby explanation comment.
|
|
4
4
|
import { type FunctionBlock, setupLineCount } from "./blocks.ts";
|
|
5
5
|
import { type CommentRecord } from "./comment-scanner.ts";
|
|
6
|
-
import { threshold } from "./config.ts";
|
|
7
6
|
import { type SourceFile } from "./discovery.ts";
|
|
8
7
|
import { makeFinding } from "./findings.ts";
|
|
9
8
|
import { isFixtureLikePath, isTestPath } from "./project-rules.ts";
|
|
10
|
-
import type {
|
|
9
|
+
import type { Finding } from "./types.ts";
|
|
11
10
|
|
|
12
11
|
// Below 12 lines, a fixture is short enough to read at a glance - requiring a purpose header
|
|
13
12
|
// would just be noise; above this threshold, the next reader needs the intent spelled out.
|
|
@@ -34,18 +33,17 @@ export interface FixturePurposeInput {
|
|
|
34
33
|
lines: string[];
|
|
35
34
|
comments: CommentRecord[];
|
|
36
35
|
blocks: FunctionBlock[];
|
|
37
|
-
config: Config;
|
|
38
36
|
findings: Finding[];
|
|
39
37
|
}
|
|
40
38
|
|
|
41
39
|
// Test/fixture paths only - gated up front so production source never reports fixture-purpose
|
|
42
40
|
// findings. Reports the stable `docs.fixture-purpose-missing` finding for each candidate.
|
|
43
41
|
export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
|
|
44
|
-
const { file, source, codeSource, lines, comments, blocks,
|
|
42
|
+
const { file, source, codeSource, lines, comments, blocks, findings } = input;
|
|
45
43
|
if (!isTestPath(file.displayPath) && !isFixtureLikePath(file.displayPath)) {
|
|
46
44
|
return;
|
|
47
45
|
}
|
|
48
|
-
for (const candidate of fixturePurposeCandidates(source, codeSource, blocks
|
|
46
|
+
for (const candidate of fixturePurposeCandidates(source, codeSource, blocks)) {
|
|
49
47
|
if (hasFixturePurposeComment(lines, comments, candidate.line)) {
|
|
50
48
|
continue;
|
|
51
49
|
}
|
|
@@ -71,7 +69,7 @@ export function pushFixturePurposeFindings(input: FixturePurposeInput): void {
|
|
|
71
69
|
|
|
72
70
|
// Three candidate kinds collected in one pass: template-literal fixtures, generated array fixtures,
|
|
73
71
|
// and test setup blocks. `occupiedLines` tracks the first two so the third doesn't double-report.
|
|
74
|
-
function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]
|
|
72
|
+
function fixturePurposeCandidates(source: string, codeSource: string, blocks: FunctionBlock[]): FixturePurposeCandidate[] {
|
|
75
73
|
if (!hasFixturePurposeCandidateSignal(codeSource, blocks)) {
|
|
76
74
|
return [];
|
|
77
75
|
}
|
|
@@ -96,7 +94,7 @@ function fixturePurposeCandidates(source: string, codeSource: string, blocks: Fu
|
|
|
96
94
|
}
|
|
97
95
|
});
|
|
98
96
|
|
|
99
|
-
for (const candidate of fixtureTestBlockCandidates(blocks,
|
|
97
|
+
for (const candidate of fixtureTestBlockCandidates(blocks, occupiedLines)) {
|
|
100
98
|
pushUniqueFixturePurposeCandidate(candidates, seen, candidate);
|
|
101
99
|
}
|
|
102
100
|
|
|
@@ -178,14 +176,14 @@ function generatedFixtureCandidate(rawLine: string, codeLine: string, lineNumber
|
|
|
178
176
|
|
|
179
177
|
// Test blocks with high setup-line counts AND a fixture-shape signal. Excludes blocks whose setup
|
|
180
178
|
// already produced a template-literal or generated-array candidate at the same line.
|
|
181
|
-
function fixtureTestBlockCandidates(blocks: FunctionBlock[],
|
|
179
|
+
function fixtureTestBlockCandidates(blocks: FunctionBlock[], occupiedLines: Set<number>): FixturePurposeCandidate[] {
|
|
182
180
|
const candidates: FixturePurposeCandidate[] = [];
|
|
183
181
|
for (const block of blocks) {
|
|
184
182
|
if (!block.isTest || fixtureLineInsideBlock(block, occupiedLines)) {
|
|
185
183
|
continue;
|
|
186
184
|
}
|
|
187
185
|
const setupLines = setupLineCount(block.codeBody);
|
|
188
|
-
if (setupLines <=
|
|
186
|
+
if (setupLines <= FIXTURE_PURPOSE_MIN_LINES || !hasFixtureSetupSignal(block.codeBody)) {
|
|
189
187
|
continue;
|
|
190
188
|
}
|
|
191
189
|
candidates.push({
|
package/src/line-rules.ts
CHANGED
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
|
|
5
5
|
// invoked by the cli orchestrator before/after this module so the stable per-line emission order
|
|
6
6
|
// stays a single contract.
|
|
7
|
+
import { ruleSeverity } from "./config.ts";
|
|
7
8
|
import { type SourceFile } from "./discovery.ts";
|
|
8
9
|
import { makeFinding } from "./findings.ts";
|
|
9
10
|
import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
|
|
@@ -256,13 +257,14 @@ function pushStringTimerFinding(context: LineRuleContext): void {
|
|
|
256
257
|
}
|
|
257
258
|
}
|
|
258
259
|
|
|
259
|
-
// Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks
|
|
260
|
-
//
|
|
261
|
-
//
|
|
260
|
+
// Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks use
|
|
261
|
+
// `rawPatternStartsInCode` to confirm a match starts in real code, not inside a comment. Each finding's
|
|
262
|
+
// severity is resolved through `ruleSeverity`, so a project's per-rule `severity:` override applies.
|
|
263
|
+
// Reports each matching rule's stable, line-anchored finding; the descriptor severity is the default.
|
|
262
264
|
function pushPatternCheckFindings(context: LineRuleContext): void {
|
|
263
265
|
for (const check of context.codeChecks) {
|
|
264
266
|
if (check.pattern.test(context.codeLine)) {
|
|
265
|
-
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: check.severity, pillar: check.pillar }));
|
|
267
|
+
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
|
|
266
268
|
}
|
|
267
269
|
}
|
|
268
270
|
for (const check of context.literalChecks) {
|
|
@@ -270,7 +272,7 @@ function pushPatternCheckFindings(context: LineRuleContext): void {
|
|
|
270
272
|
continue;
|
|
271
273
|
}
|
|
272
274
|
if (rawPatternStartsInCode(context.line, context.codeLine, check.globalPattern ?? check.pattern)) {
|
|
273
|
-
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: check.severity, pillar: check.pillar }));
|
|
275
|
+
context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
|
|
274
276
|
}
|
|
275
277
|
}
|
|
276
278
|
}
|
package/src/profiles.ts
CHANGED
package/src/project-rules.ts
CHANGED
|
@@ -1,23 +1,14 @@
|
|
|
1
|
-
// Cross-file architecture rules (deep imports, cycles, large-module concentration)
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
|
|
5
|
-
import { basename, dirname as dirnamePath, extname, join } from "node:path";
|
|
1
|
+
// Cross-file architecture rules (deep imports, cycles, large-module concentration) and the
|
|
2
|
+
// path-classification helpers (isTestPath, isFixtureLikePath, etc.) every rule pass shares. Pulls the
|
|
3
|
+
// project-index types and the rules that consume them out of cli.ts so the orchestrator stays lean.
|
|
4
|
+
import { dirname as dirnamePath, extname, join } from "node:path";
|
|
6
5
|
import { isString } from "./config-parse.ts";
|
|
7
6
|
import { optionNumber, ruleSeverity, threshold } from "./config.ts";
|
|
8
7
|
import { type SourceFile } from "./discovery.ts";
|
|
9
8
|
import { makeFinding } from "./findings.ts";
|
|
10
9
|
import { fileBaseName } from "./findings-helpers.ts";
|
|
11
|
-
import { byteLine } from "./text-scans.ts";
|
|
12
10
|
import type { Config, Finding, Severity } from "./types.ts";
|
|
13
11
|
|
|
14
|
-
// First exported callable/value in a production file. Missing-nearby-test only needs this compact
|
|
15
|
-
// surface, so the project index does not retain full source bodies after per-file analysis.
|
|
16
|
-
export interface ProjectExportedSurface {
|
|
17
|
-
symbol: string;
|
|
18
|
-
line: number;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
12
|
// Read-once snapshot of a discovered file. Lines are cached because cross-file project rules
|
|
22
13
|
// scan each source repeatedly - splitting once amortises the cost across rule passes.
|
|
23
14
|
// `templateMaskedLines` mirrors `lines` but blanks out `` ` `` template-literal body characters
|
|
@@ -27,7 +18,6 @@ export interface ProjectSource {
|
|
|
27
18
|
file: SourceFile;
|
|
28
19
|
lines: string[];
|
|
29
20
|
templateMaskedLines: string[];
|
|
30
|
-
exportedSurface?: ProjectExportedSurface;
|
|
31
21
|
}
|
|
32
22
|
|
|
33
23
|
// Project-wide aggregate built once per scan and reused by every architecture rule (cycle detection,
|
|
@@ -107,12 +97,6 @@ export function analyseArchitectureRules(index: ProjectIndex, config: Config, fi
|
|
|
107
97
|
analyseLargeModuleConcentration(index, config, findings);
|
|
108
98
|
}
|
|
109
99
|
|
|
110
|
-
// Container for test-adequacy rules. Just one rule today; existing as a stable shape so additions
|
|
111
|
-
// inherit the same project-index contract without each touching the entry point.
|
|
112
|
-
export function analyseTestAdequacyRules(index: ProjectIndex, findings: Finding[]): void {
|
|
113
|
-
analyseMissingNearbyTests(index, findings);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
100
|
/*
|
|
117
101
|
* Reports imports that climb more than `maxParentSegments` `../` hops, anchored at the edge line
|
|
118
102
|
* in the importing file. The double loop exists intentionally because `..` and `../foo` look
|
|
@@ -426,102 +410,6 @@ export function isProductionSourcePath(path: string): boolean {
|
|
|
426
410
|
return !isTestPath(path) && !isDeclarationPath(path) && !isFixtureLikePath(path) && !path.split("/").includes("generated");
|
|
427
411
|
}
|
|
428
412
|
|
|
429
|
-
/*
|
|
430
|
-
* Reports exported callables whose file has no neighbouring `.test.ts` / `.spec.ts`. The stable
|
|
431
|
-
* neighbour rules (`hasNearbyTest`) define what counts - false positives are likelier than missed
|
|
432
|
-
* cases, so the rule is intentionally conservative.
|
|
433
|
-
*/
|
|
434
|
-
function analyseMissingNearbyTests(index: ProjectIndex, findings: Finding[]): void {
|
|
435
|
-
const testSources = index.scriptSources.filter((source) => isTestPath(source.file.displayPath));
|
|
436
|
-
const testPaths = new Set(testSources.map((source) => source.file.displayPath));
|
|
437
|
-
for (const source of index.scriptSources.filter((candidate) => isProductionSourcePath(candidate.file.displayPath))) {
|
|
438
|
-
const exported = source.exportedSurface;
|
|
439
|
-
if (!exported || hasNearbyTest(source.file.displayPath, testPaths) || hasCentralTestImport(source.file.displayPath, testSources, index.importsByFile)) {
|
|
440
|
-
continue;
|
|
441
|
-
}
|
|
442
|
-
findings.push(
|
|
443
|
-
makeFinding({
|
|
444
|
-
ruleId: "test-quality.missing-nearby-test",
|
|
445
|
-
message: `Exported source file \`${source.file.displayPath}\` has no nearby test file.`,
|
|
446
|
-
filePath: source.file.displayPath,
|
|
447
|
-
line: exported.line,
|
|
448
|
-
severity: "advisory",
|
|
449
|
-
pillar: "test-quality",
|
|
450
|
-
confidence: "medium",
|
|
451
|
-
symbol: exported.symbol,
|
|
452
|
-
remediation: "Add a focused test beside the source file or under a nearby __tests__/tests directory.",
|
|
453
|
-
metadata: { expectedTestBase: fileBaseName(source.file.displayPath) },
|
|
454
|
-
}),
|
|
455
|
-
);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
// Centralized `test/unit` or `test/integration` suites often import the source directly instead
|
|
460
|
-
// of matching filenames. Treat that import edge as nearby enough to avoid layout false positives.
|
|
461
|
-
function hasCentralTestImport(sourcePath: string, testSources: ProjectSource[], importsByFile: Map<string, ImportEdge[]>): boolean {
|
|
462
|
-
return testSources.some((testSource) => (importsByFile.get(testSource.file.displayPath) ?? []).some((edge) => edge.targetPath === sourcePath));
|
|
463
|
-
}
|
|
464
|
-
|
|
465
|
-
// Returns the first exported callable/value seen - one finding per file is sufficient because
|
|
466
|
-
// the rule's signal is "this file ships an API surface", not "every export is untested".
|
|
467
|
-
export function exportedSurface(source: string): ProjectExportedSurface | undefined {
|
|
468
|
-
const match = source.match(/\bexport\s+(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|enum|const|let|var)\s+([A-Za-z_$][A-Za-z0-9_$]*)/);
|
|
469
|
-
if (!match?.[1]) {
|
|
470
|
-
return undefined;
|
|
471
|
-
}
|
|
472
|
-
return { symbol: match[1], line: byteLine(source, match.index ?? 0) };
|
|
473
|
-
}
|
|
474
|
-
|
|
475
|
-
// True when a same-name test file exists alongside the source, in a sibling `__tests__`/`tests`
|
|
476
|
-
// directory, or anywhere under a top-level `test`/`tests` tree. Mirrors common project layouts;
|
|
477
|
-
// expanding this list widens what counts as "tested".
|
|
478
|
-
function hasNearbyTest(sourcePath: string, testPaths: Set<string>): boolean {
|
|
479
|
-
const sourceBase = stripSourceExtension(sourcePath);
|
|
480
|
-
const sourceName = basename(sourceBase);
|
|
481
|
-
const sourceDir = displayDir(sourcePath);
|
|
482
|
-
const nearbyDirs = new Set([sourceDir, joinDisplay(sourceDir, "__tests__"), joinDisplay(sourceDir, "tests"), "test", "tests"]);
|
|
483
|
-
for (const testPath of testPaths) {
|
|
484
|
-
const testBase = stripTestMarker(stripSourceExtension(testPath));
|
|
485
|
-
if (basename(testBase) !== sourceName) {
|
|
486
|
-
continue;
|
|
487
|
-
}
|
|
488
|
-
if (testBase === sourceBase || nearbyDirs.has(displayDir(testPath)) || isTopLevelTestPath(testPath)) {
|
|
489
|
-
return true;
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
return false;
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
// Top-level `test/` and `tests/` trees are common central suite layouts. This helper is separate
|
|
496
|
-
// from `isTestPath` because nearby-test matching still requires basename agreement.
|
|
497
|
-
function isTopLevelTestPath(path: string): boolean {
|
|
498
|
-
return path.startsWith("test/") || path.startsWith("tests/");
|
|
499
|
-
}
|
|
500
|
-
|
|
501
|
-
// Drops the trailing `.ts`/`.tsx`/`.js`/`.jsx`/`.mts`/`.cjs`/`.mjs` extension so source-and-test
|
|
502
|
-
// filename comparison is extension-agnostic. Used together with `stripTestMarker`.
|
|
503
|
-
function stripSourceExtension(path: string): string {
|
|
504
|
-
return path.replace(/\.[cm]?[tj]sx?$/, "");
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
// Drops the conventional `.test` / `.spec` suffix before comparing a test path to a source path.
|
|
508
|
-
function stripTestMarker(path: string): string {
|
|
509
|
-
return path.replace(/\.(?:test|spec)$/, "");
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// Collapses a path's directory portion to the empty string at the project root so
|
|
513
|
-
// `hasNearbyTest`'s nearbyDirs lookup uses one canonical key for root-level files.
|
|
514
|
-
function displayDir(path: string): string {
|
|
515
|
-
const dir = normalizeDisplayPath(dirnamePath(path));
|
|
516
|
-
return dir === "." ? "" : dir;
|
|
517
|
-
}
|
|
518
|
-
|
|
519
|
-
// POSIX-style join that handles the empty-prefix case so `joinDisplay("", "x")` returns `"x"`,
|
|
520
|
-
// not `"/x"` - needed for paths that live directly at the project root.
|
|
521
|
-
function joinDisplay(left: string, right: string): string {
|
|
522
|
-
return left ? `${left}/${right}` : right;
|
|
523
|
-
}
|
|
524
|
-
|
|
525
413
|
// `__tests__/` and `tests/` directories, plus `.test.ts` / `.spec.ts` filename suffix. The same
|
|
526
414
|
// patterns drive the production-source filter, so adding a layout here widens every test-aware rule.
|
|
527
415
|
export function isTestPath(path: string): boolean {
|
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
|
@@ -152,7 +152,7 @@ function renderConsoleList(shouldUseAnsi = false): string {
|
|
|
152
152
|
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
153
|
"",
|
|
154
154
|
ansiWrap("Available commands:", ANSI_YELLOW, shouldUseAnsi),
|
|
155
|
-
...CONSOLE_COMMANDS.map((command) => formatConsoleRow(command.name, command.description,
|
|
155
|
+
...CONSOLE_COMMANDS.map((command) => formatConsoleRow(command.name, command.description, 15, shouldUseAnsi)),
|
|
156
156
|
].join("\n") + "\n";
|
|
157
157
|
}
|
|
158
158
|
|
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." },
|
|
@@ -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 {
|
package/src/test-fixtures.ts
CHANGED
|
@@ -608,6 +608,10 @@ ${"test"}("magic assertion", () => {
|
|
|
608
608
|
expect(total).toBe(42);
|
|
609
609
|
});
|
|
610
610
|
|
|
611
|
+
${"test"}("static shape assertion", () => {
|
|
612
|
+
assert.equal(typeof renderCatalogue, "function");
|
|
613
|
+
});
|
|
614
|
+
|
|
611
615
|
${"test"}("unused mock", () => {
|
|
612
616
|
const unusedMock = jest.fn();
|
|
613
617
|
assert.ok(true);
|
|
@@ -658,7 +662,6 @@ function catalogueCoverageOptions(): AnalyseProjectOptions {
|
|
|
658
662
|
"size.file-length": { threshold: 8, severity: "warning" },
|
|
659
663
|
"size.function-length": { threshold: 8, severity: "warning" },
|
|
660
664
|
"size.parameter-count": { threshold: 3, severity: "warning" },
|
|
661
|
-
"test-quality.setup-bloat": { threshold: 2, severity: "advisory" },
|
|
662
665
|
},
|
|
663
666
|
},
|
|
664
667
|
};
|
package/src/types.ts
CHANGED