diff --git a/src/analyze/coverage/python-line-coverage.ts b/src/analyze/coverage/python-line-coverage.ts index d7ff501e..7bc96c69 100644 --- a/src/analyze/coverage/python-line-coverage.ts +++ b/src/analyze/coverage/python-line-coverage.ts @@ -1,5 +1,6 @@ import { spawn } from 'node:child_process'; import * as fs from 'node:fs/promises'; +import * as fsSync from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; @@ -13,7 +14,7 @@ export function normalizePath(p: string): string { export interface CoverageReportInput { projectRoot: string; - testCmd?: string; // default: 'pytest -q' + testCmd?: string; // default: 'python3 -m pytest -q' pythonBin?: string; // default: 'python3' _probeOverride?: boolean; // test-only injection point } @@ -69,6 +70,28 @@ export interface CoverageReport { // toCoverageRunArgs). Losing a measurement costs a verdict; losing equivalence // costs the truth of every verdict this module supports. // +// Equivalence may be ESTABLISHED in two ways, and only two: +// +// 1. By RECOGNITION. The command is already equivalent in both spawn shapes +// (`python3 -m pytest`, `python3 tests/runtests.py`). Nothing is rebuilt. +// +// 2. By CONSTRUCTION. We reproduce ONE bounded shell behaviour so the two +// spawns agree. Today that is PATH resolution of a console entry point, +// so sys.path[0] is the bin directory in both. A construction is admitted +// only when all three hold: +// a. TOTAL over its input: every case the shell handles we handle +// identically, or we decline. No "close enough". +// b. CHECKABLE against an observable, not an argument. Here the +// shadow-bypass guard independently tests whether coverage measured +// the copy the gate imported. +// c. Its failure is a DECLINE, never a fall back to a form already +// known to be non-equivalent. +// +// Clause (c) is written in blood: falling back to module form when resolution +// failed reintroduced the exact false SAFE the construction existed to remove, +// on every pyenv, asdf and nix setup, because their console scripts are shell +// shims rather than Python files. +// // So: new shell features get taught to this path only when equivalence can be // PROVEN, not when a bug report asks for them. @@ -122,12 +145,6 @@ const ASSIGNMENT_RE = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s; * PATH-like assignment value. */ const TILDE_EXPANDS_RE = /(^|:)~/; -/** Variables that can change WHICH copy of a module Python imports. When one of - * these is set, the interpreter's own sys.path[0] rule decides who wins, so a - * spawn-shape difference between the gate and this runner stops being cosmetic - * and starts selecting a different tree. See the entry-point note below. */ -const IMPORT_AFFECTING_RE = /^(PYTHON[A-Z0-9_]*|PATH|VIRTUAL_ENV|CONDA_PREFIX)$/; - /** What to hand `coverage run`, plus any environment the command carried. * The env is separate because `coverage run` takes argv, not a shell line. */ export interface CoverageRunPlan { @@ -135,7 +152,17 @@ export interface CoverageRunPlan { env: Record; } -export function toCoverageRunArgs(testCmd: string): CoverageRunPlan | null { +/** Resolves a console entry point (`pytest`) to the script file a shell would + * execute for it, or null when it cannot be resolved to a Python script we can + * hand to `coverage run` positionally. Injected so the classifier stays pure + * and testable, and REQUIRED so no call site can omit it and silently select a + * spawn shape the gate would not have used. */ +export type EntryPointResolver = (name: string, env: Record) => string | null; + +export function toCoverageRunArgs( + testCmd: string, + resolveEntryPoint: EntryPointResolver, +): CoverageRunPlan | null { if (SHELL_COMPOSITE_RE.test(testCmd)) return null; const tokens = tokenizeCommand(testCmd); if (tokens.length === 0) return null; @@ -183,29 +210,96 @@ export function toCoverageRunArgs(testCmd: string): CoverageRunPlan | null { return { args: [...rest], env }; } - // Console entry point, rewritten to module form. This rewrite is NOT - // equivalent to the gate's spawn when an import-affecting variable is set, - // and the difference silently selects a different copy of the code: + // Console entry point. Prefer to run the SAME file the gate's shell would + // run, positionally, so sys.path[0] is the bin directory in both spawns and + // neither run can import a copy the other did not. This is what lets the + // shadow-bypass guard work: when an editable install resolves imports to the + // ORIGINAL tree, coverage now measures that tree too, the shadow file is + // absent from measuredFiles, and the guard fires as designed. + const resolved = resolveEntryPoint(head, env); + if (resolved !== null) return { args: [resolved, ...rest.slice(1)], env }; + + // Unresolvable, so decline. There is deliberately no fallback to `-m` here. // - // gate sh -c "PYTHONPATH= pytest -q" console script: - // sys.path[0] is the bin - // dir, so PYTHONPATH wins - // this path coverage run -m pytest -q `-m` puts CWD FIRST, - // ahead of PYTHONPATH, so - // the shadow tree wins + // Module form is what shipped before, and it is the shape that produced the + // false SAFE: `-m` prepends CWD to sys.path while the console script the gate + // runs does not, so on any project where something else supplies the package + // (an editable install, a plain install, PYTHONPATH) the gate ran the ORIGINAL + // tree while coverage measured the SHADOW tree, and fusing those two true + // statements produced SAFE for a change that broke the suite. // - // The gate then proves the ORIGINAL tree green while coverage proves the - // SHADOW tree exercised, and fusing those two true statements yields SAFE for - // a change that breaks the suite. That is a false SAFE, reproduced on a flat - // layout with `PYTHONPATH= pytest -q`, and it is the reason the - // equivalence rule at the top of this file is written as a rule. + // Falling back to it would keep that hole open wherever resolution fails, and + // resolution fails on exactly the setups people use: pyenv and asdf install + // `#!/usr/bin/env bash` shims, nix wraps programs the same way, and Windows + // console scripts are native `.exe` launchers. That is not a corner, so the + // fallback is not a safety net; it is the bug with narrower reach. // - // Declining costs a measurement for this shape and nothing else: the form the - // docs teach, `PYTHONPATH=. python3 -m pytest -q`, is module form on BOTH - // sides and stays equivalent. Widening the decline can only lose capability; - // narrowing it loses soundness. - if (Object.keys(env).some((name) => IMPORT_AFFECTING_RE.test(name))) return null; - return { args: ['-m', ...rest], env }; + // The cost is bounded and honest. `python3 -m pytest -q`, which is what + // auto-detection produces and what every documented example teaches, is + // module form on BOTH sides and never reaches this branch. + return null; +} + +/** Find the file a shell would execute for a console entry point, and accept it + * only if it is a Python script we can hand to `coverage run` positionally. + * + * The shebang check is the whole safety argument. A Windows console script is + * an `.exe` launcher and a Unix one is a Python file with `#!.../python`; + * handing the former to `coverage run` would fail, so it is rejected here and + * the caller falls back to module form. Resolution uses the EFFECTIVE PATH, + * including any hoisted `PATH=` prefix, so it agrees with what the gate's + * shell would have resolved. */ +export function resolveConsoleScript(name: string, env: Record): string | null { + // A name containing a separator is a path, not a PATH lookup. The shell runs + // it relative to ITS cwd, which is the shadow root and not this process's cwd, + // so we cannot reproduce it here. + if (name.includes('/') || name.includes('\\')) return null; + + const search = env.PATH ?? process.env.PATH ?? ''; + for (const dir of search.split(path.delimiter)) { + // An empty element means cwd to a POSIX shell, and a relative element is + // resolved against the SHELL's cwd. Either way the shell would search a + // directory we cannot identify from here, and anything we found later on + // PATH might be shadowed by something in it. Decline rather than guess. + if (dir === '' || !path.isAbsolute(dir)) return null; + + const candidate = path.join(dir, name); + try { + // The shell skips a match it cannot execute and keeps searching, so this + // must too: a non-executable file earlier on PATH is invisible to it. + fsSync.accessSync(candidate, fsSync.constants.X_OK); + if (!fsSync.statSync(candidate).isFile()) continue; + } catch { + continue; // missing, not executable, or a directory: keep searching + } + + // This is the file the shell would run. It is the ONLY candidate we may + // consider: scanning past it to find a Python script further down would + // run a different program than the gate did, which is precisely the + // divergence this resolver exists to remove. + try { + const fd = fsSync.openSync(candidate, 'r'); + try { + const buf = Buffer.alloc(512); + const read = fsSync.readSync(fd, buf, 0, 512, 0); + const first = (buf.subarray(0, read).toString('utf8').split('\n')[0] ?? '').replace( + /\r$/, + '', + ); + // Only a Python script can be handed to `coverage run` positionally. + // A shim (`#!/usr/bin/env bash`, pyenv and asdf install these), a + // native launcher (Windows `.exe`), or a shebang we cannot read is not + // one, and the caller declines rather than substituting module form. + if (first.startsWith('#!') && /python/i.test(first)) return candidate; + } finally { + fsSync.closeSync(fd); + } + } catch { + // unreadable: treat as not resolvable + } + return null; + } + return null; } /** Probe whether `coverage.py` can actually RUN in the user's Python. @@ -247,7 +341,11 @@ function runCmd( export async function reportCoverage(input: CoverageReportInput): Promise { const t0 = performance.now(); const pythonBin = input.pythonBin ?? 'python3'; - const testCmd = input.testCmd ?? 'pytest -q'; + // Module form, matching what `detect.ts` auto-detects and what every + // documented example teaches. It is equivalent by recognition in both + // spawn shapes on every platform, whereas the bare console script it used + // to default to can only be made equivalent where it resolves. + const testCmd = input.testCmd ?? 'python3 -m pytest -q'; const found = input._probeOverride ?? (await probeCoverage(pythonBin, input.projectRoot)); if (!found) { @@ -262,7 +360,7 @@ export async function reportCoverage(input: CoverageReportInput): Promise r.lines.length > 0 && !report.measuredFiles.has(normalizePath(r.path)), ); if (unmeasured.length > 0) { - return unknownCoverage(); + // Say WHY, and say what fixes it. This is the dominant degradation path + // for a project whose tests import an installed copy, and a bare "could + // not be determined" leaves the user with no idea that a one-line change + // to their test command would give them a real verdict. The remedy is + // documented at verdicts.mdx "Make sure the tests run the code being + // verified", but nobody who lands here has a reason to go read it. + const names = unmeasured.map((r) => r.path).join(', '); + return unknownCoverage( + `the test run never imported ${names}, so the suite exercised a different copy ` + + `than the one being verified (usually an installed or editable package). ` + + `Put the verified tree first on sys.path, for example by prefixing the test ` + + `command with PYTHONPATH=. (or PYTHONPATH=src for a src layout).`, + ); } // Judge coverage on STATEMENTS, not physical lines, using real extents from // the Python AST. coverage.py only ever marks a statement's FIRST line, so a diff --git a/tests/integration/coverage-reporter.test.ts b/tests/integration/coverage-reporter.test.ts index cc837543..5fc7e7a8 100644 --- a/tests/integration/coverage-reporter.test.ts +++ b/tests/integration/coverage-reporter.test.ts @@ -34,13 +34,25 @@ const NO_COVERAGE = (() => { })(); describe('python-line-coverage reporter', () => { + // Two explicit worlds. Every classifier assertion says which one it is in, + // because the answer differs: a console entry point that resolves runs + // positionally, and one that does not is DECLINED rather than rewritten to + // module form. Passing the resolver is mandatory so no call site can silently + // pick a spawn shape the gate would not have used. + // Deliberately reads `env`, so a regression that stops forwarding the hoisted + // environment to the resolver shows up as a wrong path rather than passing + // silently. Without this the resolver would search the ambient PATH while the + // gate's shell searched the prefixed one, and pick a DIFFERENT executable. + const RESOLVES = (n: string, env: Record) => `${env.PATH ?? '/venv/bin'}/${n}`; + const UNRESOLVABLE = () => null; + it('returns covered lines for a tested function and skips untested', async () => { if (!pythonHasCoverage()) { // eslint-disable-next-line no-console console.warn('skipping: coverage.py not installed'); return; } - const result = await reportCoverage({ projectRoot: FIXTURE, testCmd: 'pytest -q' }); + const result = await reportCoverage({ projectRoot: FIXTURE, testCmd: 'python3 -m pytest -q' }); expect(result.coverageToolFound).toBe(true); expect(result.coveredLines.has('svc_tested.py:2')).toBe(true); // tested_function return expect(result.coveredLines.has('svc_tested.py:5')).toBe(false); // untested_function return @@ -58,7 +70,7 @@ describe('python-line-coverage reporter', () => { console.warn('skipping: coverage.py not installed'); return; } - const result = await reportCoverage({ projectRoot: FIXTURE, testCmd: 'pytest -q' }); + const result = await reportCoverage({ projectRoot: FIXTURE, testCmd: 'python3 -m pytest -q' }); const svc = result.executableLines.get('svc_tested.py'); expect(svc).toBeDefined(); // Both the executed `return 42` (line 2) and the missing `return 99` (line @@ -90,7 +102,7 @@ describe('python-line-coverage reporter', () => { return; } const pragma = path.resolve(__dirname, '../fixtures/verify-diff-pragma'); - const result = await reportCoverage({ projectRoot: pragma, testCmd: 'pytest -q' }); + const result = await reportCoverage({ projectRoot: pragma, testCmd: 'python3 -m pytest -q' }); const gated = result.executableLines.get('gated.py'); expect(gated).toBeDefined(); // `return "-".join(` at line 6 opens the pragma'd body: excluded, never @@ -111,7 +123,7 @@ describe('python-line-coverage reporter', () => { // For this test we assert the shape when probe fails. const result = await reportCoverage({ projectRoot: FIXTURE, - testCmd: 'pytest -q', + testCmd: 'python3 -m pytest -q', _probeOverride: false, // injected for test isolation }); expect(result.coverageToolFound).toBe(false); @@ -138,7 +150,7 @@ describe('python-line-coverage reporter', () => { await fs.writeFile(path.join(shimDir, 'python-ghost.bat'), '@echo off\r\nexit /b 1\r\n'); const result = await reportCoverage({ projectRoot: FIXTURE, - testCmd: 'pytest -q', + testCmd: 'python3 -m pytest -q', pythonBin: shim, }); expect(result.coverageToolFound).toBe(false); @@ -177,14 +189,33 @@ describe('python-line-coverage reporter', () => { expect(result.coveredLines.has('svc.py:6')).toBe(false); // unused() return }); - it('still measures coverage for module-form commands (regression guard)', async () => { - if (!pythonHasCoverage()) return; - for (const testCmd of ['python3 -m pytest -q', 'pytest -q']) { - const result = await reportCoverage({ projectRoot: FIXTURE, testCmd }); + it.skipIf(NO_COVERAGE)( + 'still measures coverage for module-form commands (regression guard)', + async () => { + // Equivalent by RECOGNITION: `python3 -m pytest` is module form on both + // sides, so this holds on every platform and must never regress. + const result = await reportCoverage({ + projectRoot: FIXTURE, + testCmd: 'python3 -m pytest -q', + }); expect(result.measurementFailed).toBe(false); expect(result.coveredLines.has('svc_tested.py:2')).toBe(true); - } - }); + }, + ); + + // Equivalent by CONSTRUCTION, and only where the construction is possible. + // Windows console scripts are native launchers with no Python shebang, so + // they cannot be handed to `coverage run` positionally and are declined + // instead of being rewritten to the module form that caused issue #98. + // Tracked in #100. + it.skipIf(NO_COVERAGE || process.platform === 'win32')( + 'measures a console-script command by resolving it (POSIX)', + async () => { + const result = await reportCoverage({ projectRoot: FIXTURE, testCmd: 'pytest -q' }); + expect(result.measurementFailed).toBe(false); + expect(result.coveredLines.has('svc_tested.py:2')).toBe(true); + }, + ); it('reports measurementFailed when the coverage run cannot execute', async () => { if (!pythonHasCoverage()) return; @@ -204,15 +235,15 @@ describe('python-line-coverage reporter', () => { // `slow"`, which changes which tests run and therefore what gets measured. const { toCoverageRunArgs } = await import('../../src/analyze/coverage/python-line-coverage.js'); - expect(toCoverageRunArgs('pytest tests/ -k "not slow"')).toEqual({ - args: ['-m', 'pytest', 'tests/', '-k', 'not slow'], + expect(toCoverageRunArgs('pytest tests/ -k "not slow"', RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', 'tests/', '-k', 'not slow'], env: {}, }); - expect(toCoverageRunArgs("pytest -k 'a or b'")).toEqual({ - args: ['-m', 'pytest', '-k', 'a or b'], + expect(toCoverageRunArgs("pytest -k 'a or b'", RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', '-k', 'a or b'], env: {}, }); - expect(toCoverageRunArgs('python3 tests/runtests.py "my app"')).toEqual({ + expect(toCoverageRunArgs('python3 tests/runtests.py "my app"', RESOLVES)).toEqual({ args: ['tests/runtests.py', 'my app'], env: {}, }); @@ -228,32 +259,32 @@ describe('python-line-coverage reporter', () => { const { toCoverageRunArgs } = await import('../../src/analyze/coverage/python-line-coverage.js'); - expect(toCoverageRunArgs('PYTHONPATH=. python3 -m pytest -q')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH=. python3 -m pytest -q', RESOLVES)).toEqual({ args: ['-m', 'pytest', '-q'], env: { PYTHONPATH: '.' }, }); - expect(toCoverageRunArgs('PYTHONPATH=src python3 -m pytest -q')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH=src python3 -m pytest -q', RESOLVES)).toEqual({ args: ['-m', 'pytest', '-q'], env: { PYTHONPATH: 'src' }, }); // The slash used to divert this one into the script-form branch, so it // failed differently but just as silently. - expect(toCoverageRunArgs('PYTHONPATH=./src python3 -m pytest -q')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH=./src python3 -m pytest -q', RESOLVES)).toEqual({ args: ['-m', 'pytest', '-q'], env: { PYTHONPATH: './src' }, }); - expect(toCoverageRunArgs('COVERAGE_CORE=sysmon python3 -m pytest')).toEqual({ + expect(toCoverageRunArgs('COVERAGE_CORE=sysmon python3 -m pytest', RESOLVES)).toEqual({ args: ['-m', 'pytest'], env: { COVERAGE_CORE: 'sysmon' }, }); // Several assignments in a row, and the remainder still classifies as // script form rather than module form. - expect(toCoverageRunArgs('A=1 B=2 python3 tests/runtests.py')).toEqual({ + expect(toCoverageRunArgs('A=1 B=2 python3 tests/runtests.py', RESOLVES)).toEqual({ args: ['tests/runtests.py'], env: { A: '1', B: '2' }, }); // An empty value is a legitimate assignment (`FOO= cmd` unsets in shell). - expect(toCoverageRunArgs('PYTHONPATH= python3 -m pytest')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH= python3 -m pytest', RESOLVES)).toEqual({ args: ['-m', 'pytest'], env: { PYTHONPATH: '' }, }); @@ -309,29 +340,29 @@ describe('python-line-coverage reporter', () => { const { toCoverageRunArgs } = await import('../../src/analyze/coverage/python-line-coverage.js'); - expect(toCoverageRunArgs('pytest -k a=b')).toEqual({ - args: ['-m', 'pytest', '-k', 'a=b'], + expect(toCoverageRunArgs('pytest -k a=b', RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', '-k', 'a=b'], env: {}, }); // A non-import-affecting prefix still hoists onto a console entry point, // so the hoist-stop is exercised here rather than short-circuited by the // import-affecting decline. - expect(toCoverageRunArgs('FOO=1 pytest -k a=b')).toEqual({ - args: ['-m', 'pytest', '-k', 'a=b'], + expect(toCoverageRunArgs('FOO=1 pytest -k a=b', RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', '-k', 'a=b'], env: { FOO: '1' }, }); - expect(toCoverageRunArgs('PYTHONPATH=. python3 -m pytest -k a=b')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH=. python3 -m pytest -k a=b', RESOLVES)).toEqual({ args: ['-m', 'pytest', '-k', 'a=b'], env: { PYTHONPATH: '.' }, }); // A leading token that is not a valid shell identifier is not an // assignment: `-k=v` is a flag, and `1BAD=x` cannot be an env name. - expect(toCoverageRunArgs('pytest --opt=1')).toEqual({ - args: ['-m', 'pytest', '--opt=1'], + expect(toCoverageRunArgs('pytest --opt=1', RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', '--opt=1'], env: {}, }); // Nothing left to run once the assignments are removed. - expect(toCoverageRunArgs('PYTHONPATH=.')).toBeNull(); + expect(toCoverageRunArgs('PYTHONPATH=.', RESOLVES)).toBeNull(); }); it('declines a hoisted value the shell would expand', async () => { @@ -343,21 +374,21 @@ describe('python-line-coverage reporter', () => { const { toCoverageRunArgs } = await import('../../src/analyze/coverage/python-line-coverage.js'); - expect(toCoverageRunArgs('PYTHONPATH=$HOME/x python3 -m pytest')).toBeNull(); - expect(toCoverageRunArgs('PYTHONPATH=$PWD python3 -m pytest')).toBeNull(); + expect(toCoverageRunArgs('PYTHONPATH=$HOME/x python3 -m pytest', RESOLVES)).toBeNull(); + expect(toCoverageRunArgs('PYTHONPATH=$PWD python3 -m pytest', RESOLVES)).toBeNull(); // `sh` expands a tilde at the start of the value AND after each `:`, // because expansion applies per segment of a PATH-like value. - expect(toCoverageRunArgs('PYTHONPATH=~/x python3 -m pytest')).toBeNull(); - expect(toCoverageRunArgs('PYTHONPATH=a:~/y python3 -m pytest')).toBeNull(); + expect(toCoverageRunArgs('PYTHONPATH=~/x python3 -m pytest', RESOLVES)).toBeNull(); + expect(toCoverageRunArgs('PYTHONPATH=a:~/y python3 -m pytest', RESOLVES)).toBeNull(); // A tilde that is not at a segment boundary is literal to the shell too. - expect(toCoverageRunArgs('PYTHONPATH=a~b python3 -m pytest')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH=a~b python3 -m pytest', RESOLVES)).toEqual({ args: ['-m', 'pytest'], env: { PYTHONPATH: 'a~b' }, }); // A literal `$` in an ARGUMENT is not our problem to expand and was never // hoisted, so it keeps classifying as before. - expect(toCoverageRunArgs('pytest -k "cost$"')).toEqual({ - args: ['-m', 'pytest', '-k', 'cost$'], + expect(toCoverageRunArgs('pytest -k "cost$"', RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', '-k', 'cost$'], env: {}, }); }); @@ -374,13 +405,13 @@ describe('python-line-coverage reporter', () => { // Quote removal. A value class of `\S*` would stop matching here, the // token would classify as a COMMAND, and we would be back to issue #95 // with a different first token. - expect(toCoverageRunArgs('PYTHONPATH="a b" python3 -m pytest -q')).toEqual({ + expect(toCoverageRunArgs('PYTHONPATH="a b" python3 -m pytest -q', RESOLVES)).toEqual({ args: ['-m', 'pytest', '-q'], env: { PYTHONPATH: 'a b' }, }); // A shell applies assignments left to right, so the last one wins. - expect(toCoverageRunArgs('A=1 A=2 python3 -m pytest -q')).toEqual({ + expect(toCoverageRunArgs('A=1 A=2 python3 -m pytest -q', RESOLVES)).toEqual({ args: ['-m', 'pytest', '-q'], env: { A: '2' }, }); @@ -388,50 +419,188 @@ describe('python-line-coverage reporter', () => { // A shell reads `1BAD=x` as a COMMAND name, not an assignment, because // the name is not a valid identifier. Hoisting it would make the coverage // run succeed against a command the tests gate could never have run. - expect(toCoverageRunArgs('1BAD=x python3 -m pytest -q')?.env).toEqual({}); - expect(toCoverageRunArgs('-k=v python3 -m pytest -q')?.env).toEqual({}); + expect(toCoverageRunArgs('1BAD=x python3 -m pytest -q', RESOLVES)?.env).toEqual({}); + expect(toCoverageRunArgs('-k=v python3 -m pytest -q', RESOLVES)?.env).toEqual({}); // The default testCmd. `src/analyze/engine.ts` calls reportCoverage with // no testCmd at all, so 'pytest -q' is a second production caller of this // classifier and must keep classifying exactly as it did before hoisting. - expect(toCoverageRunArgs('pytest -q')).toEqual({ args: ['-m', 'pytest', '-q'], env: {} }); + expect(toCoverageRunArgs('pytest -q', RESOLVES)).toEqual({ + args: ['/venv/bin/pytest', '-q'], + env: {}, + }); }); - it('declines an import-affecting prefix on a console entry point', async () => { - // The false SAFE. Rewriting a console script to module form is not - // equivalent to the gate's spawn: `-m` puts CWD first on sys.path, ahead - // of PYTHONPATH, while the console script the gate runs does not. With an - // import-affecting variable set, that difference selects a DIFFERENT COPY - // of the code, so the gate proves the original tree green while coverage - // proves the shadow tree exercised, and the fusion reads SAFE for a change - // that breaks the suite. Reproduced end to end before this decline existed. + it('runs a resolvable console entry point positionally, as the gate does (issue #98)', async () => { + // `coverage run -m pytest` puts CWD on sys.path ahead of everything the + // environment supplies, while the console script the gate runs does not. + // On an editable install that difference made coverage measure the SHADOW + // tree while the gate ran the INSTALLED one, and fusing those produced a + // false SAFE for a change that broke the suite. Running the same file the + // gate runs, positionally, puts sys.path[0] in the same place for both. const { toCoverageRunArgs } = await import('../../src/analyze/coverage/python-line-coverage.js'); - expect(toCoverageRunArgs('PYTHONPATH=/elsewhere pytest -q')).toBeNull(); - expect(toCoverageRunArgs('PYTHONPATH=src pytest -q')).toBeNull(); - expect(toCoverageRunArgs('PYTHONHOME=/opt/py pytest')).toBeNull(); - expect(toCoverageRunArgs('PATH=/custom/bin pytest')).toBeNull(); - expect(toCoverageRunArgs('VIRTUAL_ENV=/venv pytest')).toBeNull(); - - // Module form is equivalent on BOTH sides (`-m` there, `-m` here), so the - // form the docs actually teach keeps working. This is the whole point of - // declining narrowly rather than declining every prefixed command. - expect(toCoverageRunArgs('PYTHONPATH=. python3 -m pytest -q')).toEqual({ + const resolves = (name: string) => `/venv/bin/${name}`; + expect(toCoverageRunArgs('pytest -q', resolves)).toEqual({ + args: ['/venv/bin/pytest', '-q'], + env: {}, + }); + // The prefix is hoisted and the entry point still resolves, so this is + // measurable rather than declined: both spawns now agree. + expect(toCoverageRunArgs('PYTHONPATH=src pytest -q', resolves)).toEqual({ + args: ['/venv/bin/pytest', '-q'], + env: { PYTHONPATH: 'src' }, + }); + // Explicit module form is already equivalent on both sides and must NOT + // be rewritten: the gate runs `python3 -m pytest` too. + expect(toCoverageRunArgs('python3 -m pytest -q', resolves)).toEqual({ args: ['-m', 'pytest', '-q'], - env: { PYTHONPATH: '.' }, + env: {}, }); - // Script form is equivalent too: sys.path[0] is the script's directory in - // both spawns. - expect(toCoverageRunArgs('PYTHONPATH=. python3 tests/runtests.py')).toEqual({ + // A script path is already positional and must not be touched. + expect(toCoverageRunArgs('python3 tests/runtests.py', resolves)).toEqual({ args: ['tests/runtests.py'], - env: { PYTHONPATH: '.' }, + env: {}, + }); + }); + + it('resolves an entry point exactly as a shell would (issue #98)', async () => { + // The real resolver, not a stub. Everything the safety argument rests on + // lives here: once a console entry point resolves, the classifier stops + // consulting anything else, so a resolution that disagrees with the shell + // IS a wrong verdict rather than a wrong measurement. + const { resolveConsoleScript } = + await import('../../src/analyze/coverage/python-line-coverage.js'); + + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cov-path-')); + const a = path.join(root, 'a'); + const b = path.join(root, 'b'); + await fs.mkdir(a); + await fs.mkdir(b); + const PATHV = [a, b].join(path.delimiter); + + // The exec-bit case lives in its own POSIX-only test below: `chmod` is a + // no-op on Windows, where every readable file reports executable, so the + // property cannot be expressed there. + await fs.writeFile(path.join(a, 'tool'), '#!/usr/bin/env python3\nprint(1)\n', { + mode: 0o755, }); - // A variable that cannot change module resolution is still hoisted onto a - // console entry point. - expect(toCoverageRunArgs('COVERAGE_CORE=sysmon pytest -q')).toEqual({ + expect(resolveConsoleScript('tool', { PATH: PATHV })).toBe(path.join(a, 'tool')); + + // The FIRST executable match wins, and if it is not a Python script we + // decline instead of looking further down PATH. A pyenv or asdf shim is + // exactly this shape. + await fs.writeFile(path.join(a, 'shim'), '#!/usr/bin/env bash\nexec real "$@"\n', { + mode: 0o755, + }); + await fs.writeFile(path.join(b, 'shim'), '#!/usr/bin/env python3\nprint(3)\n', { + mode: 0o755, + }); + expect(resolveConsoleScript('shim', { PATH: PATHV })).toBeNull(); + + // A directory named like the entry point is not a match. + await fs.mkdir(path.join(a, 'adir')); + expect(resolveConsoleScript('adir', { PATH: PATHV })).toBeNull(); + + // A relative or empty PATH element is resolved against the SHELL's cwd, + // which is the shadow root and not this process's cwd. We cannot know + // what it holds, and it could shadow a later match, so decline. + expect(resolveConsoleScript('tool', { PATH: `relative${path.delimiter}${b}` })).toBeNull(); + expect(resolveConsoleScript('tool', { PATH: `${path.delimiter}${b}` })).toBeNull(); + + // A name with a separator is a path, run relative to the shell's cwd. + expect(resolveConsoleScript('bin/tool', { PATH: PATHV })).toBeNull(); + + // Nothing on PATH at all. + expect(resolveConsoleScript('absent', { PATH: PATHV })).toBeNull(); + + // A CRLF shebang still names python. + await fs.writeFile(path.join(a, 'crlf'), '#!/usr/bin/env python3\r\nprint(4)\r\n', { + mode: 0o755, + }); + expect(resolveConsoleScript('crlf', { PATH: PATHV })).toBe(path.join(a, 'crlf')); + + // A long venv shebang beyond the old 128-byte read window. + const deep = '/' + 'd'.repeat(200) + '/bin/python3'; + await fs.writeFile(path.join(a, 'deep'), `#!${deep}\nprint(5)\n`, { mode: 0o755 }); + expect(resolveConsoleScript('deep', { PATH: PATHV })).toBe(path.join(a, 'deep')); + + // A binary with no shebang (the Windows `.exe` shape) is not runnable by + // `coverage run`. + await fs.writeFile(path.join(a, 'native'), Buffer.from([0x4d, 0x5a, 0x90, 0x00]), { + mode: 0o755, + }); + expect(resolveConsoleScript('native', { PATH: PATHV })).toBeNull(); + }); + + it.skipIf(process.platform === 'win32')( + 'skips a PATH match it cannot execute, as a shell does (POSIX)', + async () => { + // A shell skips a non-executable match and keeps searching. Taking it + // anyway, or scanning past it to a Python script further down, would run + // a different program than the gate did. Both were real defects: the + // first attempt at this resolver did exactly that and reintroduced the + // false SAFE it was written to remove. + const { resolveConsoleScript } = + await import('../../src/analyze/coverage/python-line-coverage.js'); + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cov-exec-')); + const a = path.join(root, 'a'); + const b = path.join(root, 'b'); + await fs.mkdir(a); + await fs.mkdir(b); + const PATHV = [a, b].join(path.delimiter); + + await fs.writeFile(path.join(a, 'tool'), '#!/usr/bin/env python3\nprint(1)\n', { + mode: 0o644, + }); + await fs.writeFile(path.join(b, 'tool'), '#!/usr/bin/env python3\nprint(2)\n', { + mode: 0o755, + }); + expect(resolveConsoleScript('tool', { PATH: PATHV })).toBe(path.join(b, 'tool')); + }, + ); + + it('DECLINES an entry point it cannot resolve, never falling back (issue #98)', async () => { + // There is deliberately no fallback to module form. `-m` prepends CWD to + // sys.path while the console script the gate runs does not, so on any + // project where something else supplies the package the two spawns import + // different copies and a change that breaks the suite can read SAFE. + // + // Resolution fails on the setups people actually use: pyenv and asdf + // install `#!/usr/bin/env bash` shims, nix wraps programs the same way, + // and Windows console scripts are native `.exe` launchers. A fallback + // would therefore keep the false SAFE alive almost everywhere it started. + const { toCoverageRunArgs } = + await import('../../src/analyze/coverage/python-line-coverage.js'); + + expect(toCoverageRunArgs('pytest -q', UNRESOLVABLE)).toBeNull(); + expect(toCoverageRunArgs('PYTHONPATH=src pytest -q', UNRESOLVABLE)).toBeNull(); + // No import-affecting variable is needed to make this unsafe: an editable + // install supplies the competing copy on its own. That is why the decline + // is unconditional rather than keyed on the environment. + expect(toCoverageRunArgs('COVERAGE_CORE=sysmon pytest -q', UNRESOLVABLE)).toBeNull(); + + // A hoisted PATH must reach the resolver: `sh -c "PATH=/custom/bin pytest"` + // searches /custom/bin, so this must too. + expect(toCoverageRunArgs('PATH=/custom/bin pytest -q', RESOLVES)).toEqual({ + args: ['/custom/bin/pytest', '-q'], + env: { PATH: '/custom/bin' }, + }); + + // Forms that are equivalent by RECOGNITION never consult the resolver and + // are unaffected, which is what keeps the documented command working. + expect(toCoverageRunArgs('python3 -m pytest -q', UNRESOLVABLE)).toEqual({ args: ['-m', 'pytest', '-q'], - env: { COVERAGE_CORE: 'sysmon' }, + env: {}, + }); + expect(toCoverageRunArgs('PYTHONPATH=. python3 -m pytest -q', UNRESOLVABLE)).toEqual({ + args: ['-m', 'pytest', '-q'], + env: { PYTHONPATH: '.' }, + }); + expect(toCoverageRunArgs('python3 tests/runtests.py', UNRESOLVABLE)).toEqual({ + args: ['tests/runtests.py'], + env: {}, }); }); @@ -458,7 +627,7 @@ describe('python-line-coverage reporter', () => { ); const result = await reportCoverage({ projectRoot: FIXTURE, - testCmd: 'pytest -q', + testCmd: 'python3 -m pytest -q', pythonBin: shim, }); expect(result.measurementFailed).toBe(true); @@ -488,7 +657,7 @@ describe('python-line-coverage reporter', () => { return; } const phantom = path.resolve(__dirname, '../fixtures/coverage-phantom'); - const result = await reportCoverage({ projectRoot: phantom, testCmd: 'pytest -q' }); + const result = await reportCoverage({ projectRoot: phantom, testCmd: 'python3 -m pytest -q' }); expect(result.coverageToolFound).toBe(true); expect(result.coveredLines.has('svc.py:2')).toBe(true); // covered_function return }); diff --git a/tests/integration/verify-diff.test.ts b/tests/integration/verify-diff.test.ts index 8b641461..f174ff20 100644 --- a/tests/integration/verify-diff.test.ts +++ b/tests/integration/verify-diff.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, afterEach } from 'vitest'; import { execSync } from 'node:child_process'; import * as fs from 'node:fs/promises'; import * as os from 'node:os'; @@ -131,6 +131,16 @@ const REORDERED_PKG = 'def add(a, b):\n return b + a\n\n\ndef unused_helper(a, b):\n return a - b\n'; describe('verifyDiff with a NAME=VALUE prefix on testCmd (issue #95)', () => { + // Restored in afterEach, NOT in a finally inside the test body. vitest marks a + // timed-out test failed and moves on WITHOUT waiting for the awaited call to + // settle, so an in-body finally never runs and the value leaks into every + // later test in this file. Measured: the next test observed the leaked path. + const ORIGINAL_PYTHONPATH = process.env.PYTHONPATH; + afterEach(() => { + if (ORIGINAL_PYTHONPATH === undefined) delete process.env.PYTHONPATH; + else process.env.PYTHONPATH = ORIGINAL_PYTHONPATH; + }); + it.skipIf(NO_COVERAGE)( 'PYTHONPATH= prefix still measures coverage and can reach SAFE', async () => { @@ -209,6 +219,10 @@ describe('verifyDiff with a NAME=VALUE prefix on testCmd (issue #95)', () => { // delivers is discarding the measurement as UNKNOWN... expect(intoOriginal.coverage.tool).toBe('none'); expect(intoOriginal.coverage.changedLinesCovered).toBe('unknown'); + // This case is module form on both sides, so it degrades through the + // guard on every platform. That makes it the right place to pin the + // remedy wording: a user who lands here must be told what to change. + expect(String(intoOriginal.coverage.unknownReason)).toContain('PYTHONPATH'); // ...instead of telling the user their suite failed to exercise code it // was never given the chance to load. That sentence would be a confident // lie, and it is what this assertion pins. @@ -253,10 +267,83 @@ describe('verifyDiff with a NAME=VALUE prefix on testCmd (issue #95)', () => { expect(viaModuleForm.verdict).toBe('UNSAFE'); // So no command shape may call it SAFE. expect(viaConsoleScript.verdict).not.toBe('SAFE'); - // And it degrades for the stated reason: the wrapper refused a command it - // could not run equivalently, rather than measuring the wrong tree. + // It degrades through the shadow-bypass guard, not through a decline. + // Once #98 gave the coverage run the gate's spawn shape, both runs import + // the same copy, so this command is measurable again: coverage measures + // the tree the gate actually ran, the shadow file is absent from + // measuredFiles, and the guard discards the measurement as unknown. The + // decline below it survives only for spawns we cannot make equivalent. expect(viaConsoleScript.coverage.tool).toBe('none'); - expect(String(viaConsoleScript.coverage.unknownReason)).toContain('cannot wrap test command'); + expect(viaConsoleScript.gates.tests.passed).toBe(true); + expect(String(viaConsoleScript.reason)).not.toContain('not exercised by any test'); + // Disclosure is not optional. An earlier revision of this test dropped + // the reason assertion when the degradation moved from a decline to the + // guard, which quietly accepted less explanation than the previous + // release gave. The floor must always say why and what to do about it. + expect(viaConsoleScript.coverage.unknownReason ?? '').not.toBe(''); + }, + 180_000, + ); + + it.skipIf(NO_COVERAGE)( + 'a console-script testCmd cannot read SAFE when the gate imports another copy', + async () => { + // Issue #98. The out-of-band twin of the case above: nothing is written + // into testCmd, so there is no prefix to inspect and decline. The + // environment supplies a competing copy of the package to BOTH spawns, + // and only the spawn SHAPE decides which one wins: + // + // gate sh -c "pytest -q" console script, sys.path[0] is + // the bin dir, so the env copy wins + // coverage coverage run -m pytest -q `-m` puts CWD first, so the + // shadow copy wins + // + // The gate then passes against unmodified code while coverage measures the + // changed code as covered, and the shadow-bypass guard cannot help: the + // changed file IS in measuredFiles, because coverage really did measure it. + // + // This is the shape of an ordinary `pip install -e .` project, where the + // editable install resolves imports to the ORIGINAL tree. PYTHONPATH is + // used here only because it reproduces the same resolution order without + // needing a venv and a real install in the test suite. + const root = await flatLayoutFixture(); + const edits = [ + { path: 'rfpkg/__init__.py', newContent: 'def add(a, b):\n return a - b\n' }, + ]; + + process.env.PYTHONPATH = root; + { + const report = await verifyDiff({ repoRoot: root, edits, testCmd: 'pytest -q' }); + const control = await verifyDiff({ + repoRoot: root, + edits, + testCmd: 'python3 -m pytest -q', + }); + + // The edit genuinely breaks the suite, so the whole case has teeth. + expect(control.verdict).toBe('UNSAFE'); + + // The gate RAN and was GREEN against the copy the environment supplied. + // Without this the case is satisfiable by a red baseline: deleting the + // PYTHONPATH line above makes the package unimportable, the baseline + // fails, and UNPROVEN arrives for a reason unrelated to the bug. + expect(report.gates.tests.passed).toBe(true); + // An exact verdict, not `not.toBe('SAFE')`, so a spurious UNSAFE cannot + // satisfy it either. + expect(report.verdict).toBe('UNPROVEN'); + // Degraded through the shadow-bypass guard, carrying a reason that + // names the remedy rather than leaving the user with "could not be + // determined" and nowhere to go. + expect(report.coverage.tool).toBe('none'); + // Assert DISCLOSURE, not a specific sentence. Which mechanism degraded + // is platform-dependent: on POSIX the entry point resolves and the + // shadow-bypass guard fires, on Windows it cannot resolve and the + // wrapper declines. Both must explain themselves; only one of them can + // name the PYTHONPATH remedy, and that wording is pinned by the + // src-layout test above, which uses module form and so behaves + // identically everywhere. + expect(report.coverage.unknownReason ?? '').not.toBe(''); + } }, 180_000, );