Coverage for scripts/coverage_misses.py: 100%
75 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""The coverage worklist (V6.6.7, #367): which lines a run left uncovered, grouped by function, with their context.
3Reads the `coverage-report/coverage.json` that `aq test --coverage` (or `coverage json`) writes. The gate is 100% of every tracked module
4(AGENTS.md "Coverage: 100% after every commit"), so a run's misses are the next tests to write.
6 python scripts/coverage_misses.py # every file with a miss, by count
7 python scripts/coverage_misses.py --include "risk/*" --by-function # per function
8 python scripts/coverage_misses.py --include risk/kelly.py --context 2
9"""
11from __future__ import annotations
13import argparse
14import ast
15import fnmatch
16import json
17import sys
18from collections.abc import Sequence
19from pathlib import Path
21ROOT = Path(__file__).resolve().parents[1]
24def load(path: Path) -> dict:
25 return json.loads(Path(path).read_text(encoding="utf-8"))
28def misses(data: dict, include: Sequence[str] | None = None) -> dict[str, list[int]]:
29 """{posix path: missing line numbers} for files with at least one miss, optionally only those matching `include`."""
30 out: dict[str, list[int]] = {}
31 for name, report in (data.get("files") or {}).items():
32 path = name.replace("\\", "/")
33 if include and not any(fnmatch.fnmatch(path, pattern) for pattern in include):
34 continue
35 lines = sorted(report.get("missing_lines") or [])
36 if lines:
37 out[path] = lines
38 return out
41def by_function(source: str, lines: Sequence[int]) -> dict[str, list[int]]:
42 """Missing lines keyed by their innermost enclosing `def`/`class` (dotted), or `<module>`."""
43 spans: list[tuple[int, int, str]] = []
45 def walk(node: ast.AST, prefix: str) -> None:
46 for child in ast.iter_child_nodes(node):
47 if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
48 name = f"{prefix}{child.name}"
49 spans.append((child.lineno, child.end_lineno or child.lineno, name))
50 walk(child, name + ".")
51 else:
52 walk(child, prefix)
54 walk(ast.parse(source), "")
55 out: dict[str, list[int]] = {}
56 for line in lines:
57 inside = [span for span in spans if span[0] <= line <= span[1]]
58 owner = min(inside, key=lambda span: span[1] - span[0])[2] if inside else "<module>"
59 out.setdefault(owner, []).append(line)
60 return out
63def context(source: str, lines: Sequence[int], radius: int = 2) -> str:
64 """The missing lines with `radius` lines around each, `>>` marking a miss, gaps shown as `...`."""
65 text = source.splitlines()
66 wanted = sorted({n for line in lines for n in range(max(1, line - radius), min(len(text), line + radius) + 1)})
67 out: list[str] = []
68 previous = None
69 for number in wanted:
70 if previous is not None and number != previous + 1:
71 out.append(" ...")
72 out.append(f"{'>>' if number in lines else ' '} {number:5d} {text[number - 1]}")
73 previous = number
74 return "\n".join(out)
77def main(argv: Sequence[str] | None = None, *, root: Path = ROOT) -> int:
78 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
79 parser.add_argument("--json", default=str(root / "coverage-report" / "coverage.json"), help="coverage.json to read (default: the repo's)")
80 parser.add_argument("--include", action="append", help="glob of files to show (repeatable)")
81 parser.add_argument("--by-function", action="store_true", help="group each file's misses by function")
82 parser.add_argument("--context", type=int, default=None, metavar="N", help="print each miss with N lines around it")
83 args = parser.parse_args(argv)
84 path = Path(args.json)
85 if not path.exists():
86 print(f"{path} not found: run `aq test --coverage` first", file=sys.stderr)
87 return 2
88 found = misses(load(path), args.include)
89 for name, lines in sorted(found.items(), key=lambda item: (-len(item[1]), item[0])):
90 print(f"{name}: {len(lines)} missing")
91 source_path = root / name
92 if not source_path.exists() or not (args.by_function or args.context is not None):
93 continue
94 source = source_path.read_text(encoding="utf-8")
95 if args.by_function:
96 for owner, owned in by_function(source, lines).items():
97 print(f" {owner}: {owned}")
98 if args.context is not None:
99 print(context(source, lines, args.context))
100 print(f"{sum(len(lines) for lines in found.values())} missing line(s) in {len(found)} file(s)")
101 return 1 if found else 0
104if __name__ == "__main__":
105 raise SystemExit(main())