stocks / scripts /coverage_floors.py
user
python version
ee446e8
Raw History Blame Contribute Delete
7.57 kB
#!/usr/bin/env python3
"""Per-module coverage floors and delta tracking (plan TEST-T1).
`make test-cov` keeps the hard 100% gate on core/dsl only. This script adds
explicit, ratcheting floors for other high-value modules plus route
registration coverage, so coverage can only move up.
Floors start at the measured 2026-09-25 baseline and
are meant to be raised, never lowered. Regenerate coverage.json with:
.venv/bin/python -m pytest tests/ -q -m "not e2e" -n auto \
--cov=core --cov=lt --cov-report=json:coverage.json -p no:cacheprovider
Usage:
.venv/bin/python scripts/coverage_floors.py # check floors
.venv/bin/python scripts/coverage_floors.py --report # print report
.venv/bin/python scripts/coverage_floors.py --update-baseline
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
os.chdir(ROOT)
COVERAGE_JSON = ROOT / "coverage.json"
BASELINE = ROOT / "tests" / "coverage_baseline.json"
# Floor values are measured 2026-09-25 baselines (percentage points).
# Raise them as coverage improves; never lower a floor.
FLOORS: dict[str, float] = {
"core/shared/db.py": 54.0,
"core/domain/schemas.py": 95.0,
"core/domain/llm_contracts.py": 71.0,
"modules/scan/calendar_export.py": 14.0,
"core/dsl/security.py": 100.0,
"core/dsl/compiler.py": 100.0,
# `lt/` is the front door. 100% because it is by
# construction a set of thin delegations with no branches, and every capability already
# requires a direct-call test per capability — the floor is the mechanical
# form of "no logic in the facade", which is the rule most likely to erode
# without anyone noticing. A facade that grows a branch fails here first.
"lt/__init__.py": 100.0,
"lt/errors.py": 100.0,
"lt/scan.py": 100.0,
"lt/sync.py": 100.0,
# The CLI is the one exception §15.3 anticipates: argparse dispatch has
# error paths that are awkward to cover. Its `__main__` guard carries
# `# pragma: no cover`; the rest is covered by tests/lt/test_cli.py.
"lt/cli.py": 100.0,
}
# Route registration: every router module included by app/main.py must
# actually contribute registered routes to the app. A handler that loses its
# @router decorator or whose router stops being included shows up here.
ROUTER_MODULES: tuple[str, ...] = (
"modules.analysis.routes",
"modules.at_risk.routes",
"modules.backtest.routes",
"modules.bankruptcy.routes",
"modules.chart.routes",
"modules.dashboard.routes",
"modules.dilution.routes",
"modules.discover.routes",
"modules.dsl.routes",
"modules.level2.routes",
"modules.lists.routes",
"modules.market_pulse.routes",
"modules.monitor.routes",
"modules.notifications.routes",
"modules.playbook.routes",
"modules.scan.routes",
"modules.schwab.compat",
"modules.screener.routes",
"modules.settings.routes",
"modules.signals.routes",
"modules.symbol_flags.routes",
"modules.trades.routes",
"modules.watchlist.routes",
)
def load_coverage() -> dict:
if not COVERAGE_JSON.is_file():
sys.exit(
"coverage.json not found. Generate it with:\n"
' .venv/bin/python -m pytest tests/ -q -m "not e2e" -n auto '
"--cov=core --cov=lt --cov-report=json:coverage.json -p no:cacheprovider"
)
return json.loads(COVERAGE_JSON.read_text())
def module_pct(data: dict, module: str) -> float | None:
entry = data["files"].get(module)
if entry is None:
return None
return float(entry["summary"]["percent_covered"])
def _app_paths(app) -> set[str]:
"""Fully-resolved route paths, recursing through included routers.
Newer FastAPI wraps each include_router() in an _IncludedRouter whose
effective_candidates() yields _EffectiveRouteContext objects carrying the
prefix-resolved path.
"""
def walk(routes: list) -> set[str]:
paths: set[str] = set()
for route in routes:
path = getattr(route, "path", "")
if path:
paths.add(path)
inner = getattr(route, "original_route", None)
if inner is not None and getattr(inner, "path", ""):
paths.add(inner.path) # websocket routes can carry an empty path on the wrapper
if hasattr(route, "effective_candidates"):
for candidate in route.effective_candidates():
paths |= walk([candidate])
return paths
return walk(list(app.routes))
def route_modules_missing() -> list[str]:
"""Router modules whose paths are absent from the mounted app."""
from app.main import app
app_paths = _app_paths(app)
missing: list[str] = []
for module_name in ROUTER_MODULES:
module = __import__(module_name, fromlist=["router", "page_router"])
router = getattr(module, "router", None) or getattr(module, "page_router", None)
if router is None:
missing.append(f"{module_name} (no router attribute)")
continue
paths = {getattr(route, "path", "") for route in router.routes}
if not paths:
missing.append(f"{module_name} (empty router)")
continue
if not paths <= app_paths:
missing.append(f"{module_name} (unmounted paths: {sorted(paths - app_paths)})")
return missing
def report(data: dict) -> tuple[list[str], bool]:
failures: list[str] = []
ok = True
lines: list[str] = []
for module, floor in sorted(FLOORS.items()):
pct = module_pct(data, module)
if pct is None:
failures.append(f"{module}: missing from coverage.json")
ok = False
continue
status = "ok" if pct >= floor else "FAIL"
if pct < floor:
ok = False
lines.append(f" [{status:>4}] {module}: {pct:6.2f}% (floor {floor:.1f}%)")
if pct < floor:
failures.append(f"{module}: {pct:.2f}% < floor {floor:.1f}%")
lines.append(" Route registration:")
missing = route_modules_missing()
if missing:
ok = False
for entry in missing:
failures.append(f"route registration: {entry}")
lines.append(f" [FAIL] {entry}")
else:
lines.append(f" [ ok] all {len(ROUTER_MODULES)} router modules fully mounted")
return lines, ok
def update_baseline(data: dict) -> None:
payload = {module: round(module_pct(data, module) or 0.0, 2) for module in sorted(FLOORS)}
payload["_total"] = round(float(data["totals"]["percent_covered"]), 2)
BASELINE.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
print(f"baseline written to {BASELINE.relative_to(ROOT)}")
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--report", action="store_true", help="print the per-module report")
parser.add_argument("--update-baseline", action="store_true", help="rewrite tests/coverage_baseline.json")
args = parser.parse_args()
data = load_coverage()
if args.update_baseline:
update_baseline(data)
return 0
lines, ok = report(data)
if args.report or not ok:
print("Coverage floors:")
print("\n".join(lines))
if not ok:
print("coverage-floors: FAIL")
return 1
if args.report:
print("coverage-floors: ok")
return 0
if __name__ == "__main__":
sys.exit(main())