Skip to content

Commit f27b589

Browse files
committed
fix(analyze): quote-aware tokenizing, report-step failure honesty
Self-review of the script-form coverage fix found two more ways to misreport. 1. Tokenizing on whitespace shredded quoted arguments: the tests gate runs the command through a shell where -k "not slow" is ONE argument, but the coverage run received -k, "not, slow", silently changing which tests executed and therefore what was measured. Tokenizing now honors single and double quotes. 2. A failing 'coverage json' step, or an unreadable report, left measurementFailed false and returned an empty covered set, which reads as 'nothing is covered'. Both now set the failure reason, so the verdict says coverage could not be determined.
1 parent 646abb1 commit f27b589

2 files changed

Lines changed: 94 additions & 3 deletions

File tree

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

Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,41 @@ const SHELL_COMPOSITE_RE = /&&|\|\||[;|`<>]|\$\(/;
4444
/** How to hand `testCmd` to `coverage run`. Module form needs `-m`; a script
4545
* path must be passed positionally, or coverage tries to import a module by
4646
* 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+
4779
export function toCoverageRunArgs(testCmd: string): string[] | null {
4880
if (SHELL_COMPOSITE_RE.test(testCmd)) return null;
49-
const tokens = testCmd.trim().split(/\s+/).filter(Boolean);
81+
const tokens = tokenizeCommand(testCmd);
5082
if (tokens.length === 0) return null;
5183

5284
// Drop a leading interpreter: `python3 -m pytest` and `python3 script.py`
@@ -161,12 +193,17 @@ export async function reportCoverage(input: CoverageReportInput): Promise<Covera
161193
// without the flag `coverage json` exits non-zero and writes NOTHING,
162194
// silently zeroing coverage for every real file. Phantom entries are
163195
// dropped; real files keep their data.
164-
await runCmd(
196+
const emit = await runCmd(
165197
pythonBin,
166198
['-m', 'coverage', 'json', '--ignore-errors', '--data-file', dataFile, '-o', jsonFile],
167199
input.projectRoot,
168200
env,
169201
);
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+
}
170207

171208
// 3) Parse.
172209
try {
@@ -184,7 +221,11 @@ export async function reportCoverage(input: CoverageReportInput): Promise<Covera
184221
}
185222
}
186223
} catch {
187-
// 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+
}
188229
}
189230
} finally {
190231
await fs.rm(tmp, { recursive: true, force: true });

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,56 @@ describe('python-line-coverage reporter', () => {
126126
expect(result.coveredLines.size).toBe(0);
127127
});
128128

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+
129179
it('refuses to guess at shell-composite commands', async () => {
130180
if (!pythonHasCoverage()) return;
131181
const result = await reportCoverage({

0 commit comments

Comments
 (0)