Coverage for aq_testtools.py: 100%
270 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"""Testing tools behind `aq test` and `aq bench`: the impacted tests, a watch loop, flaky-test repeats, the slowest tests,
2a new module's test file, which tests cover a module, a clean checkout, mutation, fuzzing, and hot-path benchmarks.
4`aq_cli.cmd_test` hands a run here when it is one of these modes. Every subprocess goes through `aq_devtools.RUN`.
5"""
7from __future__ import annotations
9import argparse
10import json
11import os
12import shutil
13import socket
14import sys
15import tempfile
16import time
17import xml.etree.ElementTree as ElementTree
18from collections.abc import Callable, Mapping, Sequence
19from pathlib import Path
21import aq_devtools as dev
23ROOT_DIR = dev.ROOT_DIR
24TEST_VERBS = ("new", "where", "slowest", "clean-checkout", "mutation", "fuzz")
25JUNIT_LAST = Path("coverage-report") / "junit-last.xml"
28# ---------------------------------------------------------------------------
29# impacted tests and the watch loop
30# ---------------------------------------------------------------------------
33def impacted_tests() -> list[str]:
34 """Registered test files that name a module changed since HEAD, plus changed registered test files."""
35 import aq_cli
37 changed = aq_cli._changed_python_files(dev.RUN)
38 registered = {name for names in aq_cli._SUBSYSTEM_TEST_FILES.values() for name in names}
39 chosen = set(aq_cli._tests_for_changed(changed, registered, lambda needle: aq_cli._git_grep_tests(needle, dev.RUN)))
40 return sorted(chosen | (set(aq_cli._changed_test_files(dev.RUN)) & registered))
43def source_mtimes(root: Path = ROOT_DIR) -> dict[str, float]:
44 """{path: mtime} of every tracked or new .py file (what a save changes)."""
45 code, out = dev.run_capture(["git", "ls-files", "--cached", "--others", "--exclude-standard", "--", "*.py"], cwd=root)
46 stamps = {}
47 for line in out.splitlines() if code == 0 else []:
48 path = root / line.strip()
49 if path.exists():
50 stamps[line.strip()] = path.stat().st_mtime
51 return stamps
54def watch(run_once: Callable[[], int], *, snapshot: Callable[[], Mapping[str, float]] = source_mtimes, sleep: Callable[[float], None] = time.sleep,
55 interval: float = 1.0, debounce: float = 0.5, iterations: int | None = None) -> int:
56 """Run `run_once`, then again after every change `snapshot` sees, until Ctrl-C (exit 130) or `iterations` reruns."""
57 last = dict(snapshot())
58 code = run_once()
59 reruns = 0
60 try:
61 while iterations is None or reruns < iterations:
62 sleep(interval)
63 current = dict(snapshot())
64 if current == last:
65 continue
66 sleep(debounce)
67 last = dict(snapshot())
68 changed = sorted(path for path in set(current) | set(last) if current.get(path) != last.get(path)) or sorted(set(current) ^ set(last))
69 print(f"\n== change detected ({len(changed) or 'some'} file(s)): rerunning", flush=True)
70 code = run_once()
71 reruns += 1
72 except KeyboardInterrupt:
73 print("\naq test --watch: stopped")
74 return dev.EXIT_INTERRUPTED
75 return code
78# ---------------------------------------------------------------------------
79# JUnit: repeats and the slowest tests
80# ---------------------------------------------------------------------------
83def parse_junit(path: Path) -> list[dict]:
84 """[{file, name, seconds, outcome}] for every testcase of a JUnit XML file."""
85 root = ElementTree.parse(path).getroot()
86 cases = []
87 for case in root.iter("testcase"):
88 outcome = "passed"
89 for child in case:
90 if child.tag in {"failure", "error"}:
91 outcome = "failed"
92 elif child.tag == "skipped":
93 outcome = "skipped"
94 parts = case.get("classname", "").split(".")
95 module = next((part for part in parts if part.startswith("test_")), parts[-1]) # tests.test_x (or tests.test_x.TestClass)
96 file = case.get("file") or (f"{module}.py" if len(parts) > 1 else module)
97 cases.append({"file": Path(file).name, "name": case.get("name", ""), "seconds": float(case.get("time") or 0.0), "outcome": outcome})
98 return cases
101def flaky_summary(runs: Sequence[Sequence[dict]]) -> dict:
102 """Per test across repeated runs: passes, failures, and the flaky ones (both)."""
103 table: dict[str, dict[str, int]] = {}
104 for cases in runs:
105 for case in cases:
106 row = table.setdefault(f"{case['file']}::{case['name']}", {"passed": 0, "failed": 0})
107 if case["outcome"] in row:
108 row[case["outcome"]] += 1
109 flaky = sorted(test for test, row in table.items() if row["passed"] and row["failed"])
110 always = sorted(test for test, row in table.items() if row["failed"] and not row["passed"])
111 return {"runs": len(runs), "tests": len(table), "flaky": flaky, "always_failing": always}
114def slowest(cases: Sequence[dict], groups: Mapping[str, Sequence[str]], top: int = 15) -> dict:
115 """The `top` slowest tests, and the total seconds per file and per test group."""
116 by_file: dict[str, float] = {}
117 for case in cases:
118 by_file[case["file"]] = by_file.get(case["file"], 0.0) + case["seconds"]
119 group_of = {name: group for group, names in groups.items() for name in names}
120 by_group: dict[str, float] = {}
121 for file, seconds in by_file.items():
122 by_group[group_of.get(file, "(no group)")] = by_group.get(group_of.get(file, "(no group)"), 0.0) + seconds
123 return {
124 "tests": [{**case} for case in sorted(cases, key=lambda case: -case["seconds"])[:top]],
125 "files": dict(sorted(by_file.items(), key=lambda item: -item[1])[:top]),
126 "groups": dict(sorted(by_group.items(), key=lambda item: -item[1])),
127 "total_seconds": round(sum(by_file.values()), 2),
128 }
131def _render_slowest(data: dict) -> str:
132 lines = [f"{case['seconds']:8.2f}s {case['file']}::{case['name']}" for case in data["tests"]]
133 lines.append("by group:")
134 lines += [f"{seconds:8.1f}s {group}" for group, seconds in data["groups"].items()]
135 lines.append(f"total {data['total_seconds']}s")
136 return "\n".join(lines)
139def repeat(paths: Sequence[str], times: int, *, extra: Sequence[str] = (), root: Path = ROOT_DIR) -> dict:
140 """Run pytest `times` times on `paths`, each writing JUnit, and summarise flakiness."""
141 runs = []
142 folder = root / "coverage-report"
143 folder.mkdir(parents=True, exist_ok=True)
144 for index in range(times):
145 junit = folder / f"repeat_{index}.xml"
146 junit.unlink(missing_ok=True)
147 print(f"== run {index + 1}/{times}", flush=True)
148 dev.run_live([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "-m", "not lean_backtest", f"--junitxml={junit}", *extra, *paths])
149 runs.append(parse_junit(junit) if junit.exists() else [])
150 return flaky_summary(runs)
153# ---------------------------------------------------------------------------
154# where a module is tested
155# ---------------------------------------------------------------------------
158def test_where(module: str, root: Path = ROOT_DIR) -> dict:
159 """The registered (and unregistered) test files that name `module`, their groups, and its line coverage if known."""
160 import aq_cli
162 posix = module.replace("\\", "/")
163 if not posix.endswith(".py") and not (root / posix).exists():
164 candidate = posix.replace(".", "/") + ".py"
165 posix = candidate if (root / candidate).exists() else posix
166 group_of = {name: group for group, names in aq_cli._SUBSYSTEM_TEST_FILES.items() for name in names}
167 files = sorted({name for needle in aq_cli._module_needles(posix) for name in aq_cli._git_grep_tests(needle, dev.RUN)})
168 report = root / "coverage-report" / "coverage.json"
169 coverage = None
170 if report.exists():
171 data = json.loads(report.read_text(encoding="utf-8")).get("files", {})
172 entry = next((value for name, value in data.items() if name.replace("\\", "/") == posix), None)
173 coverage = entry["summary"]["percent_covered"] if entry else None
174 own = f"test_{Path(posix).stem}.py"
175 return {"module": posix, "tests": [{"file": name, "group": group_of.get(name)} for name in files], "own_test_file": own if (root / "tests" / own).exists() else None,
176 "coverage_percent": coverage}
179def _render_where(data: dict) -> str:
180 lines = [f"{data['module']}: own test file {data['own_test_file'] or 'MISSING (aq test new ' + data['module'] + ')'}"]
181 lines += [f" {item['file']} ({item['group'] or 'NOT REGISTERED'})" for item in data["tests"]]
182 if data["coverage_percent"] is not None:
183 lines.append(f" coverage (last run): {data['coverage_percent']:.1f}%")
184 return "\n".join(lines)
187# ---------------------------------------------------------------------------
188# clean checkout, mutation, fuzz
189# ---------------------------------------------------------------------------
192def clean_checkout(pytest_args: Sequence[str], *, keep: bool = False, root: Path = ROOT_DIR) -> int:
193 """The suite in a detached worktree of HEAD plus the working-tree changes and new files, without any gitignored file."""
194 if sys.platform == "win32":
195 command = ["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(root / "scripts" / "clean_checkout_test.ps1"),
196 "-PytestArgs", " ".join(pytest_args) or "tests", *(["-Keep"] if keep else [])]
197 return dev.run_live(command)
198 work = Path(tempfile.gettempdir()) / "aq-clean-checkout"
199 if work.exists():
200 dev.run_capture(["git", "worktree", "remove", "--force", str(work)], cwd=root)
201 shutil.rmtree(work, ignore_errors=True)
202 if (code := dev.run_live(["git", "worktree", "add", "--detach", str(work), "HEAD"])) != 0:
203 return code
204 try:
205 patch = Path(tempfile.gettempdir()) / "aq-clean-checkout.patch"
206 dev.run_capture(["git", "diff", "HEAD", "--binary", f"--output={patch}"], cwd=root)
207 if patch.exists() and patch.stat().st_size and dev.run_live(["git", "-C", str(work), "apply", "--binary", "--whitespace=nowarn", str(patch)]) != 0:
208 print("aq test clean-checkout: the working-tree changes did not apply", file=sys.stderr)
209 return dev.EXIT_FAIL
210 _, others = dev.run_capture(["git", "ls-files", "--others", "--exclude-standard"], cwd=root)
211 for line in others.splitlines():
212 if line.strip():
213 target = work / line.strip()
214 target.parent.mkdir(parents=True, exist_ok=True)
215 shutil.copy2(root / line.strip(), target)
216 dev.run_capture(["git", "-C", str(work), "add", "-A"], cwd=root)
217 env = {**os.environ, "PYTHONPATH": str(work)}
218 code = dev.run_live([sys.executable, "-m", "pytest", *(pytest_args or ["tests"]), "-m", "not lean_backtest", "-ra", "-q", "-p", "no:cacheprovider"], cwd=work, env=env)
219 print(f"clean-checkout pytest exit code: {code}")
220 return code
221 finally:
222 if not keep:
223 dev.run_capture(["git", "worktree", "remove", "--force", str(work)], cwd=root)
226def fuzz(target: str | None, seconds: int, root: Path = ROOT_DIR) -> int:
227 """atheris on `fuzz/targets.py` where it is installed (Linux), else the hypothesis drivers under the `fuzz` profile."""
228 try:
229 import atheris # noqa: F401
230 except ImportError:
231 atheris_found = False
232 else:
233 atheris_found = True
234 if atheris_found and target:
235 return dev.run_live([sys.executable, "fuzz/run_fuzz.py", target, f"-max_total_time={seconds}"])
236 env = {**os.environ, "HYPOTHESIS_PROFILE": "fuzz"}
237 return dev.run_live([sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", "tests/test_fuzz_targets.py", *(["-k", target] if target else [])], env=env)
240# ---------------------------------------------------------------------------
241# the dispatcher aq_cli.cmd_test calls
242# ---------------------------------------------------------------------------
245def run_verb(args: argparse.Namespace) -> int:
246 """`aq test new|where|slowest|clean-checkout|mutation|fuzz` (the first positional word)."""
247 verb, rest = args.paths[0], list(args.paths[1:])
248 if (missing := dev.needs_checkout()) is not None:
249 return missing
250 if verb == "new":
251 if len(rest) != 1:
252 print("usage: aq test new MODULE [--group G] [--dry-run]", file=sys.stderr)
253 return dev.EXIT_USAGE
254 code, actions = dev.scaffold_test(rest[0], group=args.group, dry_run=args.dry_run)
255 print("\n".join(("would " if args.dry_run else "") + action for action in actions))
256 return code
257 if verb == "where":
258 if len(rest) != 1:
259 print("usage: aq test where MODULE [--json]", file=sys.stderr)
260 return dev.EXIT_USAGE
261 data = test_where(rest[0])
262 dev.emit(data, args.json, _render_where)
263 return dev.EXIT_OK if data["tests"] else dev.EXIT_FAIL
264 if verb == "slowest":
265 junit = ROOT_DIR / JUNIT_LAST
266 if not junit.exists():
267 print("aq test slowest: no coverage-report/junit-last.xml yet: run aq test first", file=sys.stderr)
268 return dev.EXIT_FAIL
269 import aq_cli
271 dev.emit(slowest(parse_junit(junit), aq_cli._SUBSYSTEM_TEST_FILES, args.top), args.json, _render_slowest)
272 return dev.EXIT_OK
273 if verb == "clean-checkout":
274 return clean_checkout(rest)
275 if verb == "mutation":
276 out = rest[0] if rest else str(ROOT_DIR / "coverage-report" / "mutation.json")
277 return dev.run_live([sys.executable, "scripts/mutation_check.py", "--out", out])
278 return fuzz(args.target, args.seconds)
281def run_repeat(args: argparse.Namespace, pytest_extra: Sequence[str]) -> int:
282 if not args.paths:
283 print("aq test --repeat: name the tests to repeat (aq test --repeat 5 tests/test_x.py)", file=sys.stderr)
284 return dev.EXIT_USAGE
285 summary = repeat(args.paths, args.repeat, extra=pytest_extra)
286 dev.emit(summary, args.json, lambda data: "\n".join(
287 [f"{data['runs']} runs of {data['tests']} tests: {len(data['flaky'])} flaky, {len(data['always_failing'])} always failing"]
288 + [f" flaky: {test}" for test in data["flaky"]] + [f" failing: {test}" for test in data["always_failing"]]))
289 return dev.EXIT_GATE if summary["flaky"] else dev.EXIT_FAIL if summary["always_failing"] else dev.EXIT_OK
292# ---------------------------------------------------------------------------
293# aq bench: hot-path latency against a per-machine baseline
294# ---------------------------------------------------------------------------
297def _load_profile_inference(root: Path = ROOT_DIR):
298 sys.path.insert(0, str(root / "scripts"))
299 try:
300 import profile_inference
301 finally:
302 sys.path.pop(0)
303 return profile_inference
306def bench_exports(root: Path = ROOT_DIR) -> dict:
307 """The installed models' exports (ml/); without them, an installed example model as the multitask export."""
308 profile = _load_profile_inference(root)
309 if (root / "ml" / "multitask_model.json").exists():
310 return profile.load_real_exports()
311 from retraining import model_catalog
313 for name in model_catalog.catalog():
314 try:
315 loaded = model_catalog.load(name)
316 except (FileNotFoundError, KeyError, ValueError, OSError):
317 continue
318 empty = dict.fromkeys(profile.EXPERT_NAMES)
319 key = "multitask" if loaded["kind"] == "multitask" else "sequence"
320 return {"baseline": None, "multitask": None, "sequence": None, "experts": dict(empty), "expert_multitask": dict(empty), key: loaded["export"]}
321 raise FileNotFoundError("no model to time: install one (aq models install example-crypto-mlp) or run in a checkout with ml/")
324def bench_run(iterations: int, *, root: Path = ROOT_DIR, exports: dict | None = None) -> dict:
325 """p50/p95/p99/max/mean ms per symbol-bar of the numpy forward pass (scripts/profile_inference.py's workload)."""
326 profile = _load_profile_inference(root)
327 exports = exports or bench_exports(root)
328 width = 0
329 for export in [exports.get("multitask"), exports.get("sequence"), exports.get("baseline")]:
330 if export:
331 width = len(export.get("input_names") or export.get("feature_names") or []) or int(export.get("input_dim") or 0)
332 break
333 inputs = profile.pregenerate_inputs(max(width, 1), 20, iterations)
334 durations = profile.run_workload(exports, inputs, use_batched=True)
335 return {"iterations": iterations, **{key: round(value, 4) for key, value in profile.summarize_durations(durations).items()}}
338def baseline_path(host: str | None = None) -> Path:
339 return Path.home() / ".aq" / "bench" / f"{host or socket.gethostname()}.json"
342def bench_compare(current: Mapping[str, float], baseline: Mapping[str, float], threshold: float) -> dict:
343 """Each percentile's change against the baseline; regressed when p95 is more than `threshold` slower."""
344 keys = ("p50_ms", "p95_ms", "p99_ms", "mean_ms")
345 change = {key: (current[key] / baseline[key] - 1.0) if baseline.get(key) else None for key in keys}
346 return {"current": dict(current), "baseline": dict(baseline), "change": change, "regressed": bool(change["p95_ms"] is not None and change["p95_ms"] > threshold)}
349def cmd_bench(args: argparse.Namespace) -> int:
350 try:
351 result = bench_run(args.iterations)
352 except FileNotFoundError as error:
353 print(f"aq bench: {error}", file=sys.stderr)
354 return dev.EXIT_FAIL
355 path = baseline_path()
356 if args.bench_command == "baseline":
357 path.parent.mkdir(parents=True, exist_ok=True)
358 path.write_text(json.dumps(result, indent=2), encoding="utf-8")
359 print(f"saved the baseline for this machine: {path}")
360 dev.emit(result, args.json, lambda data: f"p50 {data['p50_ms']} ms, p95 {data['p95_ms']} ms, p99 {data['p99_ms']} ms over {data['iterations']}")
361 return dev.EXIT_OK
362 if args.bench_command == "run":
363 dev.emit(result, args.json, lambda data: f"p50 {data['p50_ms']} ms, p95 {data['p95_ms']} ms, p99 {data['p99_ms']} ms, max {data['max_ms']} ms over {data['iterations']}")
364 return dev.EXIT_OK
365 if not path.exists():
366 print(f"aq bench compare: no baseline for this machine yet: aq bench baseline ({path})", file=sys.stderr)
367 return dev.EXIT_FAIL
368 report = bench_compare(result, json.loads(path.read_text(encoding="utf-8")), args.threshold)
369 dev.emit(report, args.json, lambda data: "\n".join(
370 [f"{key}: {data['baseline'][key]} -> {data['current'][key]} ms ({value:+.1%})" for key, value in data["change"].items() if value is not None]
371 + [("REGRESSED: p95 is more than " + f"{args.threshold:.0%} slower") if data["regressed"] else "within the threshold"]))
372 return dev.EXIT_GATE if report["regressed"] else dev.EXIT_OK
375def register(subparsers) -> None:
376 bench = dev._parser(subparsers, "bench", "Hot-path latency of the numpy forward pass, against a baseline saved for this machine",
377 "aq bench baseline", "aq bench compare --threshold 0.2", "aq bench run --iterations 500 --json")
378 bench_sub = bench.add_subparsers(dest="bench_command", required=True, parser_class=type(bench))
379 for name, help_text, example in (("run", "Time it and print p50/p95/p99", "aq bench run"), ("baseline", "Time it and save the result as this machine's baseline", "aq bench baseline"),
380 ("compare", "Time it against the baseline (exit 3 when p95 regressed)", "aq bench compare")):
381 sub = dev._parser(bench_sub, name, help_text, example)
382 sub.add_argument("--iterations", type=int, default=2000, help="Symbol-bars to time (default 2000)")
383 dev.add_json_flag(sub)
384 if name == "compare":
385 sub.add_argument("--threshold", type=float, default=0.2, help="Allowed p95 slowdown as a fraction (default 0.2)")
386 bench.set_defaults(func=cmd_bench)