@@ -21,7 +21,81 @@ export interface CoverageReportInput {
2121export 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 ( / ^ p y t h o n [ 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}
0 commit comments