Each backend module in its own container of the deployed image, the repo mounted read-only at its own layout, run with pytest: the 15 pytest-style modules that ran 0 tests under unittest now count, and the old recipe (backend/ alone at /app, /tmp a noexec tmpfs) no longer makes ~40 tests look broken on main. Plus the sidecar and cli/ under uv + pytest, the runner's node --test, vitest (JSON report, failures named per test) and tsc. scripts/test-known-failures.txt: the 5 tests that fail on main today (4 backend, 1 frontend) and 3 that fail only under load (flaky). On this branch: backend 126 modules 1,589 passed, sidecar 545, cli 112, runner 4, vitest 1,030, tsc clean — OK. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
306 lines
14 KiB
Python
Executable File
306 lines
14 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Every test suite of the repo, one command, one verdict.
|
||
|
||
scripts/test.py # all suites
|
||
scripts/test.py backend sidecar # some of them
|
||
scripts/test.py backend -k parse # only the backend modules whose name has "parse"
|
||
scripts/test.py --list # what would run
|
||
|
||
Suites:
|
||
|
||
- backend each ``backend/test_*.py`` module in its **own** container of the
|
||
``homelab-ai-agent`` image (the repo mounted read-only at
|
||
``/repo``, ``/data`` a throwaway tmpfs), run with
|
||
pytest — so unittest classes *and* the pytest-style modules (plain
|
||
``def test_*`` with fixtures, which ``python -m unittest`` silently
|
||
runs 0 tests of) both count. One process per module because the
|
||
modules set their env at import and collide in one process (a
|
||
single ``unittest discover`` fails ~336 tests on a clean main).
|
||
pytest itself is not in the image: it is installed once into
|
||
``~/.cache/ai-agent-tests/pytest`` and mounted on ``PYTHONPATH``.
|
||
The image is the *deployed* one — a branch that changes
|
||
``backend/requirements.txt`` needs a rebuilt image first.
|
||
- sidecar ``sidecar/`` with pytest in a uv env of its requirements.
|
||
- cli ``cli/`` with pytest (stdlib only).
|
||
- runner ``node --test runner/test/*.test.mjs`` (pi's runner).
|
||
- frontend ``vitest run`` (JSON report, so failures are named per test).
|
||
- types ``tsc --noEmit -p .`` in ``frontend/``.
|
||
|
||
Tests that already fail on main are listed in ``scripts/test-known-failures.txt``
|
||
(one ``suite: name`` per line, ``#`` comments). They are reported as *known*
|
||
and don't fail the run; a known failure that passes again is reported so the
|
||
line can be removed. A ``flaky suite: name`` line is a test that fails only
|
||
under load: tolerated either way. Exit status: 0 when nothing but known or
|
||
flaky tests failed.
|
||
|
||
Logs of every module/suite land in ``--logs`` (default: a fresh dir under the
|
||
system temp dir), printed at the end."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import concurrent.futures as cf
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import shutil
|
||
import subprocess
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
|
||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||
IMAGE = os.environ.get("AI_AGENT_TEST_IMAGE", "homelab-ai-agent")
|
||
CACHE = pathlib.Path(os.environ.get("XDG_CACHE_HOME", pathlib.Path.home() / ".cache")) / "ai-agent-tests"
|
||
KNOWN = ROOT / "scripts" / "test-known-failures.txt"
|
||
SUITES = ("backend", "sidecar", "cli", "runner", "frontend", "types")
|
||
_SUMMARY = re.compile(r"(\d+) (passed|failed|error|errors|skipped)")
|
||
_PYTEST_FAIL = re.compile(r"^(?:FAILED|ERROR) (\S+?)(?: - .*)?$", re.M)
|
||
|
||
|
||
class Result:
|
||
def __init__(self, suite: str, name: str, ok: bool, log: pathlib.Path,
|
||
counts: dict | None = None, failed: list[str] | None = None,
|
||
secs: float = 0.0, note: str = ""):
|
||
self.suite, self.name, self.ok, self.log = suite, name, ok, log
|
||
self.counts, self.failed = counts or {}, failed or []
|
||
self.secs, self.note = secs, note
|
||
|
||
|
||
def _run(cmd: list[str], log: pathlib.Path, cwd: pathlib.Path, timeout: int,
|
||
env: dict | None = None) -> tuple[int, str]:
|
||
log.parent.mkdir(parents=True, exist_ok=True)
|
||
try:
|
||
p = subprocess.run(cmd, cwd=cwd, env={**os.environ, **(env or {})},
|
||
capture_output=True, text=True, timeout=timeout)
|
||
out, code = p.stdout + p.stderr, p.returncode
|
||
except subprocess.TimeoutExpired as e:
|
||
out = f"{e.stdout or ''}{e.stderr or ''}\nTIMEOUT after {timeout}s"
|
||
code = 124
|
||
log.write_text(out)
|
||
return code, out
|
||
|
||
|
||
def _pytest_counts(out: str) -> dict:
|
||
# pytest's last "N passed, M failed … in 1.2s" line (warnings printed at
|
||
# interpreter exit can follow it).
|
||
lines = [ln for ln in out.splitlines() if _SUMMARY.search(ln) and re.search(r" in [\d.]+s", ln)]
|
||
tail = lines[-1] if lines else ""
|
||
counts: dict[str, int] = {}
|
||
for n, kind in _SUMMARY.findall(tail):
|
||
kind = "error" if kind.startswith("error") else kind
|
||
counts[kind] = counts.get(kind, 0) + int(n)
|
||
return counts
|
||
|
||
|
||
def _pytest_result(suite: str, name: str, code: int, out: str, log, secs) -> Result:
|
||
counts = _pytest_counts(out)
|
||
failed = [f"{suite}: {t}" for t in _PYTEST_FAIL.findall(out)]
|
||
if code == 5: # pytest: no tests collected
|
||
return Result(suite, name, False, log, counts, [f"{suite}: {name} (no tests collected)"],
|
||
secs, "no tests")
|
||
if code != 0 and not failed:
|
||
failed = [f"{suite}: {name} (exit {code})"]
|
||
return Result(suite, name, code == 0, log, counts, failed, secs)
|
||
|
||
|
||
# ── backend ────────────────────────────────────────────────────────────────
|
||
def _pytest_dir() -> pathlib.Path:
|
||
"""pytest + its deps, pure Python, installed once for the image's Python."""
|
||
target = CACHE / "pytest"
|
||
if not (target / "pytest").is_dir():
|
||
target.mkdir(parents=True, exist_ok=True)
|
||
subprocess.run(["uv", "pip", "install", "--quiet", "--python-version", "3.12",
|
||
"--target", str(target), "pytest"], check=True)
|
||
return target
|
||
|
||
|
||
def backend_modules(pattern: str | None) -> list[str]:
|
||
mods = sorted(p.name for p in (ROOT / "backend").glob("test_*.py"))
|
||
return [m for m in mods if not pattern or pattern in m]
|
||
|
||
|
||
def run_backend_module(mod: str, logs: pathlib.Path, pt: pathlib.Path) -> Result:
|
||
log = logs / "backend" / f"{mod[:-3]}.log"
|
||
# The whole repo, read-only, at its own layout: tests find ../cli,
|
||
# ../frontend, ../sidecar as they do in a checkout. /tmp stays the
|
||
# container's own (a --tmpfs is noexec: labsync's mode checks then fail).
|
||
cmd = ["docker", "run", "--rm", "--entrypoint", "sh",
|
||
"-v", f"{ROOT}:/repo:ro", "-v", f"{pt}:/pt:ro", "--tmpfs", "/data:uid=1000",
|
||
"-e", "PYTHONPATH=/pt", "-e", "PYTHONDONTWRITEBYTECODE=1", "-w", "/repo/backend", IMAGE,
|
||
"-c", f"python -m pytest -q -p no:cacheprovider -o addopts= {mod}"]
|
||
t = time.monotonic()
|
||
code, out = _run(cmd, log, ROOT, timeout=900)
|
||
return _pytest_result("backend", mod, code, out, log, time.monotonic() - t)
|
||
|
||
|
||
# ── the others ─────────────────────────────────────────────────────────────
|
||
def run_sidecar(logs: pathlib.Path) -> Result:
|
||
log, t = logs / "sidecar.log", time.monotonic()
|
||
code, out = _run(["uv", "run", "--quiet", "--with", "pytest", "--with", "httpx",
|
||
"--with-requirements", "requirements.txt", "python", "-m", "pytest",
|
||
"-q", "-p", "no:cacheprovider"], log, ROOT / "sidecar", timeout=1800)
|
||
return _pytest_result("sidecar", "sidecar", code, out, log, time.monotonic() - t)
|
||
|
||
|
||
def run_cli(logs: pathlib.Path) -> Result:
|
||
log, t = logs / "cli.log", time.monotonic()
|
||
code, out = _run(["uv", "run", "--quiet", "--with", "pytest", "python", "-m", "pytest",
|
||
"-q", "-p", "no:cacheprovider"], log, ROOT / "cli", timeout=600)
|
||
return _pytest_result("cli", "cli", code, out, log, time.monotonic() - t)
|
||
|
||
|
||
def run_runner(logs: pathlib.Path) -> Result:
|
||
log, t = logs / "runner.log", time.monotonic()
|
||
files = sorted(str(p.relative_to(ROOT)) for p in (ROOT / "runner" / "test").glob("*.test.mjs"))
|
||
code, out = _run(["node", "--test", *files], log, ROOT, timeout=600)
|
||
counts = {k: int(v) for k, v in re.findall(r"^ℹ (pass|fail) (\d+)", out, re.M)}
|
||
counts = {"passed": counts.get("pass", 0), "failed": counts.get("fail", 0)}
|
||
failed = [f"runner: {n}" for n in re.findall(r"^✖ (.+?) \(\d", out, re.M)
|
||
if not n.startswith("runner/test")]
|
||
if code and not failed:
|
||
failed = [f"runner: (exit {code})"]
|
||
return Result("runner", "runner", code == 0, log, counts, failed, time.monotonic() - t)
|
||
|
||
|
||
def run_frontend(logs: pathlib.Path) -> Result:
|
||
log, t = logs / "frontend.log", time.monotonic()
|
||
report = logs / "vitest.json"
|
||
code, out = _run(["npx", "vitest", "run", "--reporter=default", "--reporter=json",
|
||
f"--outputFile.json={report}"], log, ROOT / "frontend", timeout=1800)
|
||
failed, counts = [], {}
|
||
try:
|
||
data = json.loads(report.read_text())
|
||
counts = {"passed": data.get("numPassedTests", 0), "failed": data.get("numFailedTests", 0)}
|
||
for f in data.get("testResults", []):
|
||
rel = os.path.relpath(f.get("name", ""), ROOT / "frontend")
|
||
for a in f.get("assertionResults", []):
|
||
if a.get("status") == "failed":
|
||
failed.append(f"frontend: {rel} > {a.get('fullName') or a.get('title')}")
|
||
if f.get("status") == "failed" and not any(
|
||
a.get("status") == "failed" for a in f.get("assertionResults", [])):
|
||
failed.append(f"frontend: {rel} (suite failed to run)")
|
||
except (OSError, ValueError):
|
||
pass
|
||
if code and not failed:
|
||
failed = [f"frontend: (exit {code}, no report)"]
|
||
return Result("frontend", "frontend", code == 0, log, counts, failed, time.monotonic() - t)
|
||
|
||
|
||
def run_types(logs: pathlib.Path) -> Result:
|
||
log, t = logs / "types.log", time.monotonic()
|
||
code, out = _run(["npx", "tsc", "--noEmit", "-p", "."], log, ROOT / "frontend", timeout=900)
|
||
errs = sorted({m for m in re.findall(r"^(src/\S+?)\(\d+,\d+\): error", out, re.M)})
|
||
failed = [f"types: {e}" for e in errs] or ([f"types: (exit {code})"] if code else [])
|
||
return Result("types", "types", code == 0, log, {"files with errors": len(errs)}, failed,
|
||
time.monotonic() - t)
|
||
|
||
|
||
# ── report ─────────────────────────────────────────────────────────────────
|
||
def known_failures() -> tuple[set[str], set[str]]:
|
||
"""(failing on main, flaky): a ``flaky `` line passes or fails with load."""
|
||
known, flaky = set(), set()
|
||
if KNOWN.exists():
|
||
for ln in KNOWN.read_text().splitlines():
|
||
ln = ln.split("#", 1)[0].strip()
|
||
if ln.startswith("flaky "):
|
||
flaky.add(ln[6:].strip())
|
||
elif ln:
|
||
known.add(ln)
|
||
return known, flaky
|
||
|
||
|
||
def _fmt_counts(c: dict) -> str:
|
||
return ", ".join(f"{v} {k}" for k, v in c.items() if v) or "no counts"
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
|
||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||
ap.add_argument("suites", nargs="*", metavar="SUITE", help=f"{', '.join(SUITES)} (default: all)")
|
||
ap.add_argument("-k", dest="pattern", help="backend: only modules whose file name contains this")
|
||
ap.add_argument("-j", "--jobs", type=int, default=int(os.environ.get("AI_AGENT_TEST_JOBS", 3)),
|
||
help="backend containers at a time (default 3 — the lab is small)")
|
||
ap.add_argument("--logs", type=pathlib.Path, help="log dir (default: a new temp dir)")
|
||
ap.add_argument("--list", action="store_true", help="print what would run and exit")
|
||
args = ap.parse_args()
|
||
unknown = [s for s in args.suites if s not in SUITES]
|
||
if unknown:
|
||
ap.error(f"unknown suite(s): {', '.join(unknown)} — pick from {', '.join(SUITES)}")
|
||
suites = args.suites or list(SUITES)
|
||
|
||
if args.list:
|
||
for s in suites:
|
||
if s == "backend":
|
||
mods = backend_modules(args.pattern)
|
||
print(f"backend: {len(mods)} modules — {' '.join(mods)}")
|
||
else:
|
||
print(s)
|
||
return 0
|
||
|
||
logs = args.logs or pathlib.Path(tempfile.mkdtemp(prefix="ai-agent-tests-"))
|
||
logs.mkdir(parents=True, exist_ok=True)
|
||
if "backend" in suites and not shutil.which("docker"):
|
||
sys.exit("backend: docker not found")
|
||
started = time.monotonic()
|
||
results: list[Result] = []
|
||
others = {"sidecar": run_sidecar, "cli": run_cli, "runner": run_runner,
|
||
"frontend": run_frontend, "types": run_types}
|
||
# The node suites and the Python ones don't share anything: run the
|
||
# non-backend suites one after another beside the backend pool.
|
||
with cf.ThreadPoolExecutor(max_workers=max(1, args.jobs) + 1) as pool:
|
||
futs = []
|
||
if "backend" in suites:
|
||
pt = _pytest_dir()
|
||
futs += [pool.submit(run_backend_module, m, logs, pt)
|
||
for m in backend_modules(args.pattern)]
|
||
|
||
def serial():
|
||
return [others[s](logs) for s in suites if s in others]
|
||
serial_fut = pool.submit(serial)
|
||
for f in cf.as_completed(futs):
|
||
r = f.result()
|
||
results.append(r)
|
||
if not r.ok:
|
||
print(f" ✗ backend {r.name} ({r.note or _fmt_counts(r.counts)})", flush=True)
|
||
results += serial_fut.result()
|
||
|
||
known, flaky = known_failures()
|
||
failed_all = [t for r in results for t in r.failed]
|
||
fixed = sorted(k for k in known if k.split(":", 1)[0] in suites and k not in failed_all
|
||
and (k.split(":", 1)[0] != "backend" or not args.pattern))
|
||
known |= flaky
|
||
new = [t for t in failed_all if t not in known]
|
||
print()
|
||
for s in suites:
|
||
rs = [r for r in results if r.suite == s]
|
||
if not rs:
|
||
continue
|
||
tot: dict[str, int] = {}
|
||
for r in rs:
|
||
for k, v in r.counts.items():
|
||
tot[k] = tot.get(k, 0) + v
|
||
secs = max(r.secs for r in rs) if s != "backend" else sum(r.secs for r in rs)
|
||
bad = [t for r in rs for t in r.failed if t not in known]
|
||
kn = [t for r in rs for t in r.failed if t in known]
|
||
mark = "✗" if bad else "✓"
|
||
what = f"{len(rs)} modules, " if s == "backend" else ""
|
||
extra = f" — {len(kn)} known" if kn else ""
|
||
print(f"{mark} {s:<9} {what}{_fmt_counts(tot)} ({secs:.0f}s){extra}")
|
||
if new:
|
||
print(f"\nNEW FAILURES ({len(new)}):")
|
||
for t in new:
|
||
print(f" {t}")
|
||
if fixed:
|
||
print(f"\nknown failures that passed — remove them from {KNOWN.relative_to(ROOT)}:")
|
||
for t in fixed:
|
||
print(f" {t}")
|
||
print(f"\nlogs: {logs} wall: {time.monotonic() - started:.0f}s")
|
||
print("FAILED" if new else "OK")
|
||
return 1 if new else 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|