Skip to content

Commit cc2b29e

Browse files
authored
Merge pull request #84 from Refactron-ai/fix/r4-script-form-coverage
fix(analyze): script-form coverage, honest unknowns, shadow-bypass guard
2 parents bee3694 + f27b589 commit cc2b29e

3 files changed

Lines changed: 264 additions & 18 deletions

File tree

‎src/analyze/coverage/python-line-coverage.ts‎

Lines changed: 126 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,81 @@ export interface CoverageReportInput {
2121
export interface CoverageReport {
2222
coverageToolFound: boolean;
2323
coveredLines: Set<string>; // `${relPath}:${line}` (1-indexed)
24+
// Every file coverage.py MEASURED, whether or not any line ran. A changed
25+
// file missing from this set was never loaded by the suite at all, which is a
26+
// different claim from "its lines did not execute" and must not be reported
27+
// as one: the usual cause is the tests importing an installed copy of the
28+
// package instead of the tree under verification.
29+
measuredFiles: Set<string>;
2430
runDurationMs: number;
31+
// True when coverage.py exists but the measurement could not be performed
32+
// (unwrappable command, failed run, no data emitted). Callers MUST treat this
33+
// as "unknown coverage", never as "nothing is covered": claiming zero
34+
// coverage we never measured is a lie about the user's test suite.
35+
measurementFailed: boolean;
36+
measurementFailureReason?: string;
37+
}
38+
39+
// Shell metacharacters mean the command is a composite the coverage wrapper
40+
// cannot reliably wrap (`pytest && lint`, pipes, substitutions). Guessing here
41+
// risks measuring only part of the suite, so we decline and report unknown.
42+
const SHELL_COMPOSITE_RE = /&&|\|\||[;|`<>]|\$\(/;
43+
44+
/** How to hand `testCmd` to `coverage run`. Module form needs `-m`; a script
45+
* path must be passed positionally, or coverage tries to import a module by
46+
* that name (Django's `python3 tests/runtests.py` failed exactly this way). */
47+
/** Split a command into argv, honoring single and double quotes. The tests gate
48+
* hands the command to a shell, where `-k "not slow"` is ONE argument; a plain
49+
* whitespace split would pass `"not` and `slow"` and silently change which
50+
* tests run, so the measured coverage would not match the verified run. */
51+
function tokenizeCommand(cmd: string): string[] {
52+
const out: string[] = [];
53+
let cur = '';
54+
let quote: '"' | "'" | null = null;
55+
let started = false;
56+
for (const ch of cmd.trim()) {
57+
if (quote) {
58+
if (ch === quote) quote = null;
59+
else cur += ch;
60+
continue;
61+
}
62+
if (ch === '"' || ch === "'") {
63+
quote = ch;
64+
started = true;
65+
continue;
66+
}
67+
if (/\s/.test(ch)) {
68+
if (cur || started) out.push(cur);
69+
cur = '';
70+
started = false;
71+
continue;
72+
}
73+
cur += ch;
74+
}
75+
if (cur || started) out.push(cur);
76+
return out;
77+
}
78+
79+
export function toCoverageRunArgs(testCmd: string): string[] | null {
80+
if (SHELL_COMPOSITE_RE.test(testCmd)) return null;
81+
const tokens = tokenizeCommand(testCmd);
82+
if (tokens.length === 0) return null;
83+
84+
// Drop a leading interpreter: `python3 -m pytest` and `python3 script.py`
85+
// both describe what to run, not how to spawn it.
86+
let rest = tokens;
87+
if (/^python[0-9.]*$/.test(tokens[0] ?? '')) rest = tokens.slice(1);
88+
if (rest.length === 0) return null;
89+
90+
const head = rest[0] ?? '';
91+
if (head === '-m') {
92+
const mod = rest.slice(1);
93+
return mod.length > 0 ? ['-m', ...mod] : null;
94+
}
95+
// A script path (ends in .py, or is a path) runs positionally; anything else
96+
// is a console entry point we invoke as a module (pytest, vitest).
97+
if (head.endsWith('.py') || head.includes('/') || head.includes('\\')) return [...rest];
98+
return ['-m', ...rest];
2599
}
26100

27101
/** Probe whether `coverage.py` can actually RUN in the user's Python.
@@ -67,7 +141,25 @@ export async function reportCoverage(input: CoverageReportInput): Promise<Covera
67141

68142
const found = input._probeOverride ?? (await probeCoverage(pythonBin, input.projectRoot));
69143
if (!found) {
70-
return { coverageToolFound: false, coveredLines: new Set(), runDurationMs: 0 };
144+
return {
145+
coverageToolFound: false,
146+
coveredLines: new Set(),
147+
measuredFiles: new Set(),
148+
runDurationMs: 0,
149+
measurementFailed: false,
150+
};
151+
}
152+
153+
const cmdArgs = toCoverageRunArgs(testCmd);
154+
if (cmdArgs === null) {
155+
return {
156+
coverageToolFound: true,
157+
coveredLines: new Set(),
158+
measuredFiles: new Set(),
159+
runDurationMs: performance.now() - t0,
160+
measurementFailed: true,
161+
measurementFailureReason: `cannot wrap test command for coverage: ${testCmd}`,
162+
};
71163
}
72164

73165
const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'refactron-cov-'));
@@ -76,22 +168,42 @@ export async function reportCoverage(input: CoverageReportInput): Promise<Covera
76168
const env = { ...process.env, COVERAGE_FILE: dataFile };
77169

78170
const covered = new Set<string>();
171+
const measured = new Set<string>();
172+
let failureReason: string | undefined;
79173
try {
80-
// 1) Run tests under coverage.
81-
const runArgs = ['-m', 'coverage', 'run', '--data-file', dataFile, '-m', ...testCmd.split(' ')];
82-
await runCmd(pythonBin, runArgs, input.projectRoot, env);
174+
// 1) Run tests under coverage. A nonzero exit here is NOT itself a failure
175+
// (a red suite still produces valid coverage data); what matters is whether
176+
// a data file was written at all. A command coverage could not launch
177+
// leaves nothing behind, and that must read as unknown, not zero.
178+
const runArgs = ['-m', 'coverage', 'run', '--data-file', dataFile, ...cmdArgs];
179+
const run = await runCmd(pythonBin, runArgs, input.projectRoot, env);
180+
const wroteData = await fs
181+
.access(dataFile)
182+
.then(() => true)
183+
.catch(() => false);
184+
if (!wroteData) {
185+
failureReason =
186+
run.code === null
187+
? `coverage run could not be spawned: ${run.stderr.trim().slice(0, 200)}`
188+
: `coverage run produced no data (exit ${run.code}): ${run.stderr.trim().slice(0, 200)}`;
189+
}
83190

84191
// 2) Emit JSON. --ignore-errors: a suite that runs exec(compile(src,
85192
// "string", "exec")) leaves a measured "file" with no source on disk, and
86193
// without the flag `coverage json` exits non-zero and writes NOTHING,
87194
// silently zeroing coverage for every real file. Phantom entries are
88195
// dropped; real files keep their data.
89-
await runCmd(
196+
const emit = await runCmd(
90197
pythonBin,
91198
['-m', 'coverage', 'json', '--ignore-errors', '--data-file', dataFile, '-o', jsonFile],
92199
input.projectRoot,
93200
env,
94201
);
202+
if (failureReason === undefined && emit.code !== 0) {
203+
// Data exists but we could not turn it into a report. Reporting an empty
204+
// covered set here would be the same lie as a failed run: unknown, not zero.
205+
failureReason = `coverage json failed (exit ${emit.code ?? 'null'}): ${emit.stderr.trim().slice(0, 200)}`;
206+
}
95207

96208
// 3) Parse.
97209
try {
@@ -103,12 +215,17 @@ export async function reportCoverage(input: CoverageReportInput): Promise<Covera
103215
// relPath. Without this, coverage.json's `flask_appbuilder/foo.py`
104216
// never matches a detector lookup of `./flask_appbuilder/foo.py:42`.
105217
const normalized = normalizePath(relPath);
218+
measured.add(normalized);
106219
for (const line of fileData.executed_lines ?? []) {
107220
covered.add(`${normalized}:${line}`);
108221
}
109222
}
110223
} catch {
111-
// JSON missing/unparseable → return empty but still mark tool as found.
224+
// JSON missing or unparseable. We have no measurement, so say so rather
225+
// than returning an empty covered set that reads as "nothing is covered".
226+
if (failureReason === undefined) {
227+
failureReason = 'coverage report could not be read';
228+
}
112229
}
113230
} finally {
114231
await fs.rm(tmp, { recursive: true, force: true });
@@ -117,6 +234,9 @@ export async function reportCoverage(input: CoverageReportInput): Promise<Covera
117234
return {
118235
coverageToolFound: true,
119236
coveredLines: covered,
237+
measuredFiles: measured,
120238
runDurationMs: performance.now() - t0,
239+
measurementFailed: failureReason !== undefined,
240+
...(failureReason !== undefined ? { measurementFailureReason: failureReason } : {}),
121241
};
122242
}

‎src/verify/verify-diff.ts‎

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,11 @@ function toChanges(repoRoot: string, edits: FileEdit[]): FileChange[] {
3636
}));
3737
}
3838

39-
// The two consumers of `testCmd` disagree on shape. RefactronVerifier runs it as
40-
// a full shell command (`sh -c "<testCmd>"`), so it wants `python3 -m pytest -q`.
41-
// reportCoverage runs `python -m coverage run -m <testCmd tokens>`, so it wants
42-
// the module invocation *after* `python -m` (`pytest -q`). Strip a leading
43-
// `python[3] -m ` so the caller can pass one full command and both get the form
44-
// they expect.
45-
function toCoverageModuleCmd(testCmd: string): string {
46-
return testCmd.replace(/^\s*python[0-9.]*\s+-m\s+/, '');
47-
}
39+
// The caller passes ONE full shell command. RefactronVerifier runs it verbatim
40+
// via `sh -c`; reportCoverage decides for itself how to wrap it for `coverage
41+
// run` (see toCoverageRunArgs). This module deliberately does no pre-mangling:
42+
// the old `python -m ` strip destroyed script-form commands such as Django's
43+
// `python3 tests/runtests.py`, which then measured no coverage at all.
4844

4945
export async function verifyDiff(input: VerifyDiffInput): Promise<VerdictReport> {
5046
const edits =
@@ -91,15 +87,31 @@ async function assessCoverage(
9187
}
9288
const shadow = await createShadowTree(input.repoRoot, toChanges(input.repoRoot, edits));
9389
try {
94-
const covTestCmd = input.testCmd ? toCoverageModuleCmd(input.testCmd) : undefined;
9590
const report = await reportCoverage({
9691
projectRoot: shadow.path,
97-
...(covTestCmd ? { testCmd: covTestCmd } : {}),
92+
...(input.testCmd ? { testCmd: input.testCmd } : {}),
9893
});
99-
if (!report.coverageToolFound) {
94+
// No tool, or a measurement we could not actually perform, both mean the
95+
// same thing: coverage is UNKNOWN. Reporting an unmeasured empty set as
96+
// "not exercised by any test" would be a confident lie about the suite.
97+
if (!report.coverageToolFound || report.measurementFailed) {
10098
return { tool: 'none', changedLinesCovered: 'unknown', uncovered: [] };
10199
}
102100
const ranges = await changedLinesForEdits(input.repoRoot, pyEdits);
101+
// Shadow-bypass guard. If a changed file was never MEASURED at all, the
102+
// suite never loaded our copy of it. The usual cause is the project being
103+
// pip-installed (editable or not) so `import pkg` resolves to the installed
104+
// copy instead of the tree under verification, meaning the tests ran the
105+
// ORIGINAL code and this run proves nothing about the change. Proven on
106+
// django: without the shadow root on sys.path the same diff read UNPROVEN
107+
// while with it the auth suite caught the change. Report unknown, never
108+
// "not exercised by any test".
109+
const unmeasured = ranges.filter(
110+
(r) => r.lines.length > 0 && !report.measuredFiles.has(normalizePath(r.path)),
111+
);
112+
if (unmeasured.length > 0) {
113+
return { tool: 'none', changedLinesCovered: 'unknown', uncovered: [] };
114+
}
103115
const uncovered: Array<{ file: string; line: number }> = [];
104116
for (const r of ranges) {
105117
const rel = normalizePath(r.path);

‎tests/integration/coverage-reporter.test.ts‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,120 @@ describe('python-line-coverage reporter', () => {
7373
expect(result.coveredLines.size).toBe(0);
7474
});
7575

76+
// Script-form test commands (Django's `python3 tests/runtests.py`, manage.py
77+
// test, custom runners) are extremely common. The old code stripped only a
78+
// `python -m ` prefix and then unconditionally re-added `-m`, so it ran
79+
// `coverage run -m python3 tests/runtests.py`, tried to execute a MODULE named
80+
// "python3", failed, swallowed the failure, and returned an empty covered set:
81+
// covered Django code read as "not exercised by any test". Proven against
82+
// django/django during round-4 hardening.
83+
describe('test-command forms', () => {
84+
async function scriptRunnerFixture(): Promise<string> {
85+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cov-script-'));
86+
await fs.writeFile(
87+
path.join(dir, 'svc.py'),
88+
'def used():\n return 1\n\n\ndef unused():\n return 2\n',
89+
);
90+
await fs.writeFile(
91+
path.join(dir, 'runtests.py'),
92+
'import sys, os\nsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))\n' +
93+
'from svc import used\nassert used() == 1\nprint("ok")\n',
94+
);
95+
return dir;
96+
}
97+
98+
it('measures coverage for a SCRIPT-form test command', async () => {
99+
if (!pythonHasCoverage()) return;
100+
const dir = await scriptRunnerFixture();
101+
const result = await reportCoverage({ projectRoot: dir, testCmd: 'python3 runtests.py' });
102+
expect(result.coverageToolFound).toBe(true);
103+
expect(result.measurementFailed).toBe(false);
104+
expect(result.coveredLines.has('svc.py:2')).toBe(true); // used() return
105+
expect(result.coveredLines.has('svc.py:6')).toBe(false); // unused() return
106+
});
107+
108+
it('still measures coverage for module-form commands (regression guard)', async () => {
109+
if (!pythonHasCoverage()) return;
110+
for (const testCmd of ['python3 -m pytest -q', 'pytest -q']) {
111+
const result = await reportCoverage({ projectRoot: FIXTURE, testCmd });
112+
expect(result.measurementFailed).toBe(false);
113+
expect(result.coveredLines.has('svc_tested.py:2')).toBe(true);
114+
}
115+
});
116+
117+
it('reports measurementFailed when the coverage run cannot execute', async () => {
118+
if (!pythonHasCoverage()) return;
119+
const dir = await scriptRunnerFixture();
120+
const result = await reportCoverage({
121+
projectRoot: dir,
122+
testCmd: 'python3 no_such_runner_qq.py',
123+
});
124+
// Never claim zero coverage when we could not measure at all.
125+
expect(result.measurementFailed).toBe(true);
126+
expect(result.coveredLines.size).toBe(0);
127+
});
128+
129+
it('keeps quoted arguments intact when tokenizing', async () => {
130+
// The tests gate runs the command through a shell, so `-k "not slow"` is
131+
// ONE argument there. A naive whitespace split turns it into `"not` and
132+
// `slow"`, which changes which tests run and therefore what gets measured.
133+
const { toCoverageRunArgs } =
134+
await import('../../src/analyze/coverage/python-line-coverage.js');
135+
expect(toCoverageRunArgs('pytest tests/ -k "not slow"')).toEqual([
136+
'-m',
137+
'pytest',
138+
'tests/',
139+
'-k',
140+
'not slow',
141+
]);
142+
expect(toCoverageRunArgs("pytest -k 'a or b'")).toEqual(['-m', 'pytest', '-k', 'a or b']);
143+
expect(toCoverageRunArgs('python3 tests/runtests.py "my app"')).toEqual([
144+
'tests/runtests.py',
145+
'my app',
146+
]);
147+
});
148+
149+
it('reports measurementFailed when the report step fails after a good run', async () => {
150+
// A shim python that satisfies the probe and the `coverage run` (writing a
151+
// data file) but fails `coverage json`. The old code swallowed that and
152+
// returned an empty covered set as if measured: the same lie this module
153+
// exists to prevent.
154+
if (process.platform === 'win32') return;
155+
const shimDir = await fs.mkdtemp(path.join(os.tmpdir(), 'cov-jsonfail-'));
156+
const shim = path.join(shimDir, 'python-jsonfail');
157+
await fs.writeFile(
158+
shim,
159+
'#!/bin/sh\n' +
160+
'case "$*" in\n' +
161+
' *"coverage --version"*) exit 0 ;;\n' +
162+
' *"coverage run"*)\n' +
163+
' for a in "$@"; do case "$a" in *.coverage) : > "$a" ;; esac; done\n' +
164+
' exit 0 ;;\n' +
165+
' *"coverage json"*) echo "boom" >&2; exit 1 ;;\n' +
166+
' *) exit 0 ;;\n' +
167+
'esac\n',
168+
{ mode: 0o755 },
169+
);
170+
const result = await reportCoverage({
171+
projectRoot: FIXTURE,
172+
testCmd: 'pytest -q',
173+
pythonBin: shim,
174+
});
175+
expect(result.measurementFailed).toBe(true);
176+
expect(result.coveredLines.size).toBe(0);
177+
});
178+
179+
it('refuses to guess at shell-composite commands', async () => {
180+
if (!pythonHasCoverage()) return;
181+
const result = await reportCoverage({
182+
projectRoot: FIXTURE,
183+
testCmd: 'pytest -q && echo done',
184+
});
185+
expect(result.measurementFailed).toBe(true);
186+
expect(result.coveredLines.size).toBe(0);
187+
});
188+
});
189+
76190
it('still reports real files when the suite executes phantom-filename code', async () => {
77191
// A suite that runs exec(compile(src, "string", "exec")) makes coverage.py
78192
// record a measured "file" named `string` with no source on disk. Without

0 commit comments

Comments
 (0)