diff --git a/tests/test_architecture_docs.py b/tests/test_architecture_docs.py index 4dcda4e4..bacdddfe 100644 --- a/tests/test_architecture_docs.py +++ b/tests/test_architecture_docs.py @@ -13,15 +13,16 @@ SCRIPT = Path(__file__).resolve().parents[1] / "scripts/check_architecture_docs.py" -def prepare(repo): +@pytest.fixture +def base(git_repo): for name in ("docs/ARCHITECTURE.md", "docs/README.md", "README.md", "AGENTS.md", "core/CONTRACT.md"): - path = repo / name + path = git_repo / name path.parent.mkdir(parents=True, exist_ok=True) path.write_text("# Current\n") - git(repo, "add", ".") - git(repo, "commit", "-m", "architecture base") - return git(repo, "rev-parse", "HEAD").strip() + git(git_repo, "add", ".") + git(git_repo, "commit", "-m", "architecture base") + return git(git_repo, "rev-parse", "HEAD").strip() def run(repo, base, *args): @@ -29,27 +30,18 @@ def run(repo, base, *args): text=True, capture_output=True, check=False) -@pytest.mark.skipif(sys.platform != "linux", reason="requires raw pathname bytes") -@pytest.mark.parametrize("staged", [False, True]) -def test_architecture_check_accepts_non_utf8_path(git_repo, staged): - base = prepare(git_repo) - path = os.fsdecode(b"caf\xe9.txt") - (git_repo / path).write_text("unrelated file\n") - if staged: - git(git_repo, "add", "--", path) - - done = run(git_repo, base) - assert done.returncode == 0, done.stderr - - (git_repo / "core/CONTRACT.md").write_text("# New authority\n") - done = run(git_repo, base) - assert done.returncode == 1 - assert "without guide update or reasoned Architecture-Review trailer" in done.stderr - - -@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash"]) -def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync): - base = prepare(git_repo) +@pytest.mark.parametrize("sync", ["missing", "guide", "trailer", "empty", "squash", + "untracked-non-utf8", "staged-non-utf8"]) +def test_architecture_change_requires_update_or_reasoned_review(git_repo, base, sync): + if sync.endswith("non-utf8"): + if sys.platform != "linux": + pytest.skip("requires raw pathname bytes") + path = os.fsdecode(b"caf\xe9.txt") + (git_repo / path).write_text("unrelated file\n") + if sync == "staged-non-utf8": + git(git_repo, "add", "--", path) + done = run(git_repo, base) + assert done.returncode == 0, done.stderr git(git_repo, "checkout", "-b", "authored") (git_repo / "core/CONTRACT.md").write_text("# New authority\n") if sync == "guide": @@ -73,16 +65,14 @@ def test_architecture_change_requires_update_or_reasoned_review(git_repo, sync): @pytest.mark.parametrize("target", ["absent.md", "../README.md#absent"]) -def test_broken_local_link_fails_even_with_guide_update(git_repo, target): - base = prepare(git_repo) +def test_broken_local_link_fails_even_with_guide_update(git_repo, base, target): (git_repo / "docs/ARCHITECTURE.md").write_text(f"# Current\n[reference]({target})\n") done = run(git_repo, base) assert done.returncode == 1 assert "invalid local" in done.stderr -def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo): - base = prepare(git_repo) +def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo, base): path = git_repo / "src/loopzero/_cli_args.py" path.parent.mkdir(parents=True) path.write_text("def build_parser():\n return 'public'\n\ndef _fix():\n return 1\n") @@ -96,8 +86,7 @@ def test_private_code_fix_needs_no_pointless_documentation_edit(git_repo): assert run(git_repo, base).returncode == 1 -def test_missing_base_fails_closed(git_repo): - prepare(git_repo) +def test_missing_base_fails_closed(git_repo, base): assert run(git_repo, "not-a-revision").returncode == 1 @@ -127,10 +116,6 @@ def test_tach_enforces_module_boundaries(tmp_path): repo_root = Path(__file__).resolve().parents[1] tach = Path(sys.executable).with_name("tach") assert tach.exists(), f"tach not installed next to {sys.executable}" - clean = subprocess.run([str(tach), "check"], cwd=repo_root, - text=True, capture_output=True, check=False) - assert clean.returncode == 0, clean.stdout + clean.stderr - shutil.copy2(repo_root / "tach.toml", tmp_path / "tach.toml") shutil.copytree(repo_root / "src", tmp_path / "src") types_py = tmp_path / "src/loopzero/types.py" diff --git a/tests/test_config.py b/tests/test_config.py index 4ab54b06..3aa91cea 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,41 +1,15 @@ from __future__ import annotations +import json + import pytest from loopzero import config from loopzero.types import Config, ResourceLimits, ReviewConfig -FULL = """ -[repo] -name = "owner/name" -base = "develop" - -[checks] -commands = ["uv run pytest -q", "uv run ruff check ."] -required_ci = ["checks"] -network = true -env_allowlist = ["PATH", "HOME"] -ro_paths = ["/nonexistent/cache", "/tmp/whatever/../cache"] -writable = ["/home/me/.cache/uv"] -scratch = [".venv"] -env = { UV_CACHE_DIR = "/home/me/.cache/uv", UV_PYTHON_DOWNLOADS = "never" } -limits = { memory_mb = 1024, file_mb = 512 } - -[checks.inputs] -"uv run pytest -q" = ["src/**"] -"*" = ["lock"] - -[delivery] -merge = "rebase" -reviewers = ["codex"] -reviewer_ro_paths = ["/opt/claude", "/opt/codex"] -review_chunk_bytes = 12345 - -[delivery.review.codex] -model = "gpt-5.6-luna" -effort = "medium" -allowed_efforts = ["low", "medium", "high"] -""" +MINIMAL = '[repo]\nname = "o/n"\n' +COMMANDS = ("uv run pytest -q", "uv run ruff check .") +CHECK_INPUTS = {COMMANDS[0]: ("src/**",), "*": ("lock",)} def write(tmp_path, text): @@ -44,50 +18,46 @@ def write(tmp_path, text): return path +def table(section, **settings): + # JSON strings, arrays, bools and integers are also valid TOML values. + rows = [f"{json.dumps(key)} = {json.dumps(value)}" for key, value in settings.items()] + return "\n".join([f"[{section}]", *rows, ""]) + + @pytest.mark.parametrize("strategy,queue", [("rebase", None), ("mergify", "main")]) def test_load_full_config(tmp_path, strategy, queue): - workflow = FULL if queue is None else FULL.replace('merge = "rebase"', 'merge = "mergify"\nmergify_queue = "main"') + review = ReviewConfig("gpt-5.6-luna", "medium", ("low", "medium", "high")) + env = {"UV_CACHE_DIR": "/home/me/.cache/uv", "UV_PYTHON_DOWNLOADS": "never"} + execution = dict(required_ci=("checks",), network=True, env_allowlist=("PATH", "HOME"), + writable=("/home/me/.cache/uv",), scratch=(".venv",)) + delivery = dict(reviewers=("codex",), reviewer_ro_paths=("/opt/claude", "/opt/codex"), + review_chunk_bytes=12345) + limits = dict(memory_mb=1024, file_mb=512) + workflow = "".join(( + table("repo", name="owner/name", base="develop"), + table("checks", commands=COMMANDS, ro_paths=["/nonexistent/cache", "/tmp/whatever/../cache"], **execution), + table("checks.env", **env), table("checks.limits", **limits), + table("checks.inputs", **CHECK_INPUTS), + table("delivery", merge=strategy, **({"mergify_queue": queue} if queue else {}), **delivery), + table("delivery.review.codex", model=review.model, effort=review.effort, allowed_efforts=review.allowed_efforts), + )) assert config.load(write(tmp_path, workflow)) == Config( - repo="owner/name", - base_branch="develop", - checks=("uv run pytest -q", "uv run ruff check ."), - required_ci=("checks",), - merge_strategy=strategy, - mergify_queue=queue, - reviewers=("codex",), - review={"codex": ReviewConfig("gpt-5.6-luna", "medium", ("low", "medium", "high"))}, - reviewer_ro_paths=("/opt/claude", "/opt/codex"), - review_chunk_bytes=12345, - network=True, - env_allowlist=("PATH", "HOME"), - sandbox_ro=("/nonexistent/cache", "/tmp/whatever/../cache"), - writable=("/home/me/.cache/uv",), - scratch=(".venv",), - env=(("UV_CACHE_DIR", "/home/me/.cache/uv"), ("UV_PYTHON_DOWNLOADS", "never")), - limits=ResourceLimits(memory_mb=1024, file_mb=512), - inputs={"uv run pytest -q": ("src/**",), "*": ("lock",)}, + repo="owner/name", base_branch="develop", checks=COMMANDS, merge_strategy=strategy, mergify_queue=queue, + review={"codex": review}, sandbox_ro=("/nonexistent/cache", "/tmp/whatever/../cache"), env=tuple(env.items()), + limits=ResourceLimits(**limits), inputs=CHECK_INPUTS, **execution, **delivery, ) - - padded = FULL.replace('"uv run pytest -q"', '" uv run pytest -q "') + padded = workflow.replace('"uv run pytest -q"', '" uv run pytest -q "') assert config.load(write(tmp_path, padded)).checks[0] == " uv run pytest -q " def test_load_applies_defaults(tmp_path): - loaded = config.load(write(tmp_path, '[repo]\nname = "o/n"\n')) - assert loaded == Config( - repo="o/n", - base_branch="main", - checks=(), - required_ci=(), - merge_strategy="squash", - reviewers=("claude", "codex"), + assert config.load(write(tmp_path, MINIMAL)) == Config( + repo="o/n", base_branch="main", checks=(), required_ci=(), merge_strategy="squash", + reviewers=("claude", "codex"), network=False, env_allowlist=("PATH", "HOME", "LANG", "LC_ALL", "TERM"), + sandbox_ro=(), writable=(), reviewer_ro_paths=(), + scratch=(".venv", ".ruff_cache", ".pytest_cache", "node_modules/.cache"), + limits=ResourceLimits(memory_mb=4096, file_mb=2048), ) - assert loaded.network is False - assert loaded.env_allowlist == ("PATH", "HOME", "LANG", "LC_ALL", "TERM") - assert loaded.sandbox_ro == () and loaded.writable == () - assert loaded.reviewer_ro_paths == () - assert loaded.scratch == (".venv", ".ruff_cache", ".pytest_cache", "node_modules/.cache") - assert loaded.limits == ResourceLimits(memory_mb=4096, file_mb=2048) def test_missing_file(tmp_path): @@ -95,62 +65,62 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -@pytest.mark.parametrize( - ("text", "message"), - [ - ("[repo\n", "invalid TOML"), - ("[checks]\ncommands = []\n", "missing required key repo.name"), - ('[repo]\nname = "noslash"\n', 'must look like "owner/name"'), - ('[repo]\nname = 3\n', "repo.name must be a str"), - ('[repo]\nname = "o/n"\n[checks]\ncommands = "pytest"\n', "checks.commands must be a list"), - ('[repo]\nname = "o/n"\n[checks]\ncommands = ["ok", 1]\n', "non-empty strings"), - ('[repo]\nname = "o/n"\n[checks]\ncommands = ["true", " "]\n', - r"workflow\.toml: checks\.commands.*nonblank command"), - ('[repo]\nname = "o/n"\n[checks]\nnetwork = "yes"\n', "checks.network must be a bool"), - ('[repo]\nname = "o/n"\n[delivery]\nmerge = "ff"\n', "delivery.merge must be one of"), - ('[repo]\nname = "o/n"\n[delivery]\nmerge = "mergify"\n', "mergify_queue is required"), - *((f'[repo]\nname = "o/n"\n[delivery]\n{strategy}mergify_queue = "main"\n', - rf"delivery\.mergify_queue.*delivery\.merge.*{selected}") - for strategy, selected in [("", "squash"), ('merge = "squash"\n', "squash"), ('merge = "queue"\n', "queue")]), - (FULL.replace('["src/**"]', '"src"'), r"checks\.inputs"), - ('[repo]\nname = "o/n"\n[delivery]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"), - ('[repo]\nname = "o/n"\n[repo2]\nx = 1\n', "unknown key\\(s\\) in top level: repo2"), - ('[repo]\nname = "o/n"\nnmae = "x"\n', "unknown key\\(s\\) in \\[repo\\]: nmae"), - ('repo = "o/n"\n', "\\[repo\\] must be a table"), - ('[repo]\nname = "o/n"\nbase = ""\n', "repo.base must not be empty"), - ('[repo]\nname = "o/n"\n[delivery]\nreviewers = []\n', "at least one reviewer"), - ('[repo]\nname = "o/n"\n[delivery]\nreviewer_ro_paths = ["relative"]\n', "must be absolute"), - *[(f'[repo]\nname = "o/n"\n[delivery]\nreview_chunk_bytes = {value}\n', "int >= 4096") - for value in (0, 1, 4095)], - ('[repo]\nname = "o/n"\n[delivery.review.codex]\nmode = "x"\n', - "unknown key\\(s\\) in \\[delivery.review.codex\\]: mode"), - ('[repo]\nname = "o/n"\n[delivery.review.codex]\nallowed_efforts = [1]\n', - "allowed_efforts must be a list of non-empty strings"), - ('[repo]\nname = "o/n"\n[delivery.review.codex]\nallowed_efforts = "medium"\n', - "allowed_efforts must be a list"), - ('[repo]\nname = "o/n"\n[checks]\nro_paths = ["rel/path"]\n', "must be absolute"), - ('[repo]\nname = "o/n"\n[checks]\nwritable = ["/run/x"]\n', "writable must not expose"), - ('[repo]\nname = "o/n"\n[checks]\nscratch = ["../x"]\n', "scratch entries must be relative"), - ('[repo]\nname = "o/n"\n[checks]\nscratch = ["/abs"]\n', "scratch entries must be relative"), - ('[repo]\nname = "o/n"\n[checks.env]\nlower = "x"\n', "invalid variable name 'lower'"), - ('[repo]\nname = "o/n"\n[checks.env]\nPATH = "/x"\n', "must not override PATH"), - ('[repo]\nname = "o/n"\n[checks.env]\nHOME = "/x"\n', "must not override HOME"), - ('[repo]\nname = "o/n"\n[checks.env]\nX = 1\n', "checks.env.X must be a str"), - ('[repo]\nname = "o/n"\n[checks]\nenv = ["X=1"]\n', "checks.env must be a dict"), - ('[repo]\nname = "o/n"\n[checks]\nlimits = 1\n', "checks.limits must be a dict"), - ('[repo]\nname = "o/n"\n[checks]\nlimits = { memory_mb = 0 }\n', - "checks.limits.memory_mb must be a positive int"), - ('[repo]\nname = "o/n"\n[checks]\nlimits = { cpu = 1 }\n', - "unknown key\\(s\\) in checks.limits: cpu"), - ('[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' - '[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'), - *[ - ('[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' - f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local") - for limit in ("file_mb", "memory_mb") - ], - ], -) +MINIMAL = '[repo]\nname = "o/n"\n' + + +@pytest.mark.parametrize("text,message", [ + ("[repo\n", "invalid TOML"), + ("[checks]\ncommands = []\n", "missing required key repo.name"), + ('[repo]\nname = "noslash"\n', 'must look like "owner/name"'), + ('[repo]\nname = 3\n', "repo.name must be a str"), + (MINIMAL + '[checks]\ncommands = "pytest"\n', "checks.commands must be a list"), + *((MINIMAL + f"[checks]\nrunner = {value}", "checks.runner") for value in + ('[]', '[""]', '[1]', '"runner"', '["./runner"]', '["tools/runner"]')), + (MINIMAL + '[checks]\ncommands = ["ok", 1]\n', "non-empty strings"), + (MINIMAL + '[checks]\ncommands = ["true", " "]\n', + r"workflow\.toml: checks\.commands.*nonblank command"), + (MINIMAL + '[checks]\nnetwork = "yes"\n', "checks.network must be a bool"), + (MINIMAL + '[delivery]\nmerge = "ff"\n', "delivery.merge must be one of"), + (MINIMAL + '[delivery]\nmerge = "mergify"\n', "mergify_queue is required"), + *((MINIMAL + f'[delivery]\n{strategy}mergify_queue = "main"\n', + rf"delivery\.mergify_queue.*delivery\.merge.*{selected}") + for strategy, selected in [("", "squash"), ('merge = "squash"\n', "squash"), ('merge = "queue"\n', "queue")]), + (MINIMAL + '[checks]\ncommands = ["uv run pytest -q"]\n[checks.inputs]\n"uv run pytest -q" = "src"\n', r"checks\.inputs"), + (MINIMAL + '[delivery]\nreviewers = ["gpt"]\n', "delivery.reviewers entries"), + (MINIMAL + '[repo2]\nx = 1\n', "unknown key\\(s\\) in top level: repo2"), + (MINIMAL + 'nmae = "x"\n', "unknown key\\(s\\) in \\[repo\\]: nmae"), + ('repo = "o/n"\n', "\\[repo\\] must be a table"), + (MINIMAL + 'base = ""\n', "repo.base must not be empty"), + (MINIMAL + '[delivery]\nreviewers = []\n', "at least one reviewer"), + (MINIMAL + '[delivery]\nreviewer_ro_paths = ["relative"]\n', "must be absolute"), + *[(MINIMAL + f'[delivery]\nreview_chunk_bytes = {value}\n', "int >= 4096") + for value in (0, 1, 4095)], + (MINIMAL + '[delivery.review.codex]\nmode = "x"\n', + "unknown key\\(s\\) in \\[delivery.review.codex\\]: mode"), + (MINIMAL + '[delivery.review.codex]\nallowed_efforts = [1]\n', + "allowed_efforts must be a list of non-empty strings"), + (MINIMAL + '[delivery.review.codex]\nallowed_efforts = "medium"\n', + "allowed_efforts must be a list"), + (MINIMAL + '[checks]\nro_paths = ["rel/path"]\n', "must be absolute"), + (MINIMAL + '[checks]\nwritable = ["/run/x"]\n', "writable must not expose"), + *((MINIMAL + f'[checks]\nscratch = ["{path}"]\n', "scratch entries must be relative") + for path in ("../x", "/abs")), + (MINIMAL + '[checks.env]\nlower = "x"\n', "invalid variable name 'lower'"), + *((MINIMAL + f'[checks.env]\n{key} = "/x"\n', f"must not override {key}") + for key in ("PATH", "HOME")), + (MINIMAL + '[checks.env]\nX = 1\n', "checks.env.X must be a str"), + (MINIMAL + '[checks]\nenv = ["X=1"]\n', "checks.env must be a dict"), + (MINIMAL + '[checks]\nlimits = 1\n', "checks.limits must be a dict"), + (MINIMAL + '[checks]\nlimits = { memory_mb = 0 }\n', + "checks.limits.memory_mb must be a positive int"), + (MINIMAL + '[checks]\nlimits = { cpu = 1 }\n', + "unknown key\\(s\\) in checks.limits: cpu"), + (MINIMAL + '[checks]\ncommands = ["echo ok"]\n' + '[checks.inputs]\n"echo okay" = ["."]\n', r'checks\.inputs\."echo okay".*exact'), + *((MINIMAL + '[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' + f"[checks.limits]\n{limit} = 1\n", rf"checks\.limits\.{limit}.*local") + for limit in ("file_mb", "memory_mb")), +]) def test_invalid_content(tmp_path, text, message): with pytest.raises(config.ConfigError, match=message) as info: config.load(write(tmp_path, text)) @@ -161,6 +131,12 @@ def test_invalid_content(tmp_path, text, message): FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] +@pytest.mark.parametrize("runner", [("dispatch", "--stage"), ("python3", "tools/run_stage.py"), + ("dispatch", "--opt=/operator/run.py")]) +def test_runner_prefix(tmp_path, runner): + assert config.load(write(tmp_path, MINIMAL + f"[checks]\nrunner = {list(runner)!r}")).check_runner == runner + + @pytest.mark.parametrize("path,allowed", [ *((path, False) for path in FORBIDDEN), *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), diff --git a/tests/test_hosted.py b/tests/test_hosted.py index bc8d116d..26e83553 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -2,12 +2,13 @@ import json import subprocess import sys +from contextlib import nullcontext from pathlib import Path from types import SimpleNamespace import pytest -from loopzero import eligibility, github, hosted +from loopzero import github, hosted from loopzero.candidate import CandidateError, CandidateRaceError from tests import test_github as fixtures from tests.test_candidate import event as candidate_event @@ -49,13 +50,17 @@ def test_event_selection(event, number): assert hosted.event_number(event) == number +def prepare_event(tmp_path, monkeypatch, repo, event): + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("GITHUB_REPOSITORY", repo) + Path("event.json").write_text(json.dumps(event)) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) + Path("workflow.toml").write_text(f'[repo]\nname="{repo}"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') + + @pytest.fixture def publisher(tmp_path, fake_bin, monkeypatch): - monkeypatch.chdir(tmp_path) - monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - (event := tmp_path / "event.json").write_text(json.dumps({"pull_request": {"number": 7}})) - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) - Path("workflow.toml").write_text(f'[repo]\nname="{REPO}"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') + prepare_event(tmp_path, monkeypatch, REPO, {"pull_request": {"number": 7}}) gh = FakeGh(fake_bin, tmp_path) gh.respond_pr_view(pr_json(), branch="lz/task") gh.respond("api graphql", threads_json()) @@ -64,56 +69,45 @@ def publisher(tmp_path, fake_bin, monkeypatch): return gh -def written_statuses(publisher): - return [json.loads(call["--input"]) for call in publisher.calls if "--input" in call] +def approval(head=HEAD): + return {"state": "APPROVED", "commit_id": head, "user": {"login": "trusted-publisher"}, + "body": f"\n**approve**"} -def written_states(publisher): - return [status["state"] for status in written_statuses(publisher)] +def check_source(publisher, states, *, exit_code=0, error=None, match=None): + with pytest.raises(error, match=match) if error else nullcontext(): + assert hosted.main() == exit_code + statuses = [json.loads(call["--input"]) for call in publisher.calls if "--input" in call] + assert [status["state"] for status in statuses] == states + return statuses @pytest.mark.parametrize("case,blocker,status", [ ("COMMENTED", "", "success"), ("APPROVED", "", "success"), - ("DISMISSED", "", "pending"), ("PENDING", "", "pending"), ("absent", "", "pending"), ("untrusted", "", "pending"), ("stale", "", "pending"), ("malformed", "", "pending"), ("revoked", "", "pending"), ("absent", "important", "failure"), ("absent", "conflict", "failure"), ("COMMENTED", "important", "failure"), ]) def test_source_publication_is_bound_to_live_review(publisher, case, blocker, status): - review = {"state": "COMMENTED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, - "body": f"\n**approve**"} - changed = {"state": case} if case in {"APPROVED", "DISMISSED", "PENDING"} else { - "untrusted": {"user": {"login": "attacker"}}, "stale": {"commit_id": "b" * 40}, - "malformed": {"body": "\n**approve**"}, "revoked": {"state": "DISMISSED"}, - }.get(case, {}) - reviews = [] if case == "absent" else [review | changed] - if case == "revoked": - reviews.insert(0, review | {"state": "APPROVED"}) + review = approval() | {"state": "COMMENTED"} + reviews = { + "absent": [], "APPROVED": [approval()], "revoked": [approval(), review | {"state": "DISMISSED"}], + "untrusted": [review | {"user": {"login": "attacker"}}], "stale": [approval("b" * 40)], + "malformed": [review | {"body": "\n**approve**"}], + }.get(case, [review]) publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", reviews) if blocker == "conflict": publisher.respond(f"api repos/{REPO}/pulls/7", fixtures.rest_pr_json(pr_json(mergeable="CONFLICTING"))) if blocker == "important": publisher.respond("api graphql", threads_json(fixtures.thread(fixtures.marker("important") + "\nFinding", author="trusted-publisher"))) - assert hosted.main() == (1 if status == "failure" else 0) - statuses = written_statuses(publisher) - assert ([s["state"] for s in statuses] == ["pending", status] - and all(s["context"] == "Loop-zero Eligibility" for s in statuses)) + statuses = check_source(publisher, ["pending", status], exit_code=int(status == "failure")) + assert all(s["context"] == "Loop-zero Eligibility" for s in statuses) assert status != "success" or sum(c["argv"][1] != "graphql" for c in publisher.calls) <= 5 assert status != "pending" or statuses[-1]["description"] == "Awaiting trusted review of current source head" -def test_hosted_reviews_reject_a_repeated_full_page(publisher): - publisher.respond(f"api repos/{REPO}/pulls/7", fixtures.rest_pr_json(pr_json())) - endpoint = f"api repos/{REPO}/pulls/7/reviews?per_page={github.PAGE}" - page = [{"id": i, "state": "COMMENTED"} for i in range(github.PAGE)] - for number in (1, 2): - publisher.respond(f"{endpoint}&page={number}", page) - with pytest.raises(github.GhError, match="GitHub repeated a full page"): - eligibility.evaluate(REPO, 7, HEAD, "main", ("trusted-publisher",)) - - def test_merged_source_refresh_publishes_nothing(publisher): body = json.dumps({"head": {"sha": HEAD, "ref": "lz/task"}, "user": {"login": "author"}, "merged": True, "title": "before\u2028after"}, ensure_ascii=False) @@ -152,46 +146,57 @@ def lose_reply(repo, head, context, value, description): raise github.ProcTimeout("lost status reply", "") monkeypatch.setattr(github, "commit_status", lose_reply) - if readback == "match": - assert hosted.main() == (0 if ready else 1) - else: - with pytest.raises(hosted.LoopZeroError, match="confirm eligibility status publication"): - hosted.main() - assert written_states(publisher) == ["pending", state] + check_source(publisher, ["pending", state], exit_code=int(not ready), + error=hosted.LoopZeroError if readback != "match" else None, + match="confirm eligibility status publication") -@pytest.mark.parametrize("error", ["api", "recover", "head", "metadata", "merged", "publication", "config", "before"]) -def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): +@pytest.mark.parametrize("error,states", [ + ("before", []), ("config", []), ("head", ["pending", "failure"]), + ("metadata", ["pending", "failure"]), ("merged", ["pending"]), + ("api", ["pending"]), ("recover", ["pending", "success"]), + ("publication", ["pending", "pending"]), ("pages", ["pending", "failure"]), +]) +def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error, states): sleeps = [] monkeypatch.setattr(github, "_retry_sleep", sleeps.append) - endpoint = f"api repos/{REPO}/pulls/7" + ("" if error == "before" else "/reviews?per_page=100&page=1") - approval = [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] + pr = f"api repos/{REPO}/pulls/7" + reviews = f"{pr}/reviews?per_page={github.PAGE}" if error in {"api", "recover", "before"}: - fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "exit": 1} - publisher.respond(endpoint, fault, approval if error == "recover" else fault) - elif error in {"head", "metadata", "merged"}: - changes = {"head": {"headRefOid": "b" * 40}, "metadata": {"labels": [{"name": "hold"}]}, "merged": {"state": "MERGED"}} + fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n" + '{"message":"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ"}', "exit": 1} + endpoint = pr if error == "before" else f"{reviews}&page=1" + publisher.respond(endpoint, fault, [approval()] if error == "recover" else fault) + check_source(publisher, states, exit_code=int(error == "before")) + assert sleeps == [5] + assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") + return + + exception, message = hosted.LoopZeroError, None + if error in {"head", "metadata", "merged"}: + changes = {"head": {"headRefOid": "b" * 40}, "metadata": {"labels": [{"name": "hold"}]}, + "merged": {"state": "MERGED"}} publisher.respond_pr_view(pr_json(**changes[error])) - publisher.respond(endpoint, approval) + publisher.respond(f"{reviews}&page=1", [approval()]) elif error == "publication": - publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) + message = "invalid description" + publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, {"stdout": "", "exit": 1, "stderr": f"{message} (HTTP 422)"}) publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) + elif error == "pages": + page = [{"id": i, "state": "COMMENTED"} for i in range(github.PAGE)] + for number in (1, 2): + publisher.respond(f"{reviews}&page={number}", page) + exception, message = github.GhError, "GitHub repeated a full page" else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - if error in {"api", "recover", "before", "merged"}: - assert hosted.main() == (1 if error == "before" else 0) and sleeps == ([] if error == "merged" else [5]) - assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error in {"api", "before"}) - else: - with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): - hosted.main() - states = {"before": [], "config": [], "head": ["pending", "failure"], "metadata": ["pending", "failure"], "merged": ["pending"], "api": ["pending"], "recover": ["pending", "success"]} - assert written_states(publisher) == states.get(error, ["pending", "pending"]) + check_source(publisher, states, error=None if error == "merged" else exception, match=message) + if error == "merged": + assert not sleeps and "status=503" not in capsys.readouterr().err @pytest.mark.parametrize("case,error,message", [ ("valid", None, ""), ("policy", hosted.LoopZeroError, "no review recorded"), ("hold", hosted.LoopZeroError, "source #101: PR #101 has a merge-authority hold"), - ("merged", CandidateError, "not open"), ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), ("head", hosted.LoopZeroError, "head changed"), ("publisher", CandidateError, "not open"), @@ -214,20 +219,14 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc number=number, headRefOid=sha, isDraft=False, labels=[{"name": "hold"}] if case == "hold" and number == 101 else [], )) | values[path] - values[f"{path}/reviews?per_page=100&page=1"] = [{ - "state": "APPROVED", "commit_id": sha, "user": {"login": "trusted-publisher"}, - "body": f"\nreview: **approve**", - }] + values[f"{path}/reviews?per_page=100&page=1"] = [approval(sha)] if case == "stale": values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": values["/repos/owner/repo/pulls/101"] = [] - (tmp_path / "event.json").write_text(json.dumps(event)) - (tmp_path / "workflow.toml").write_text('[repo]\nname="owner/repo"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') - monkeypatch.chdir(tmp_path) - monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) - sleeps, rest_calls = [], [] + prepare_event(tmp_path, monkeypatch, "owner/repo", {"inputs": {"pr": "900"}} if case == "manual" else event) + rest_calls, sleeps = [], [] + def api_get(path): rest_calls.append(path) if case == "race" and path == "repos/owner/repo/pulls/101": @@ -236,12 +235,9 @@ def api_get(path): monkeypatch.setattr(github, "api_get", api_get) monkeypatch.setattr("loopzero.candidate._retry_sleep", sleeps.append) published = [] - if case == "manual": - (tmp_path / "event.json").write_text(json.dumps({"inputs": {"pr": "900"}})) - def publish(*args): published.append(args) - if args[3] == "pending" and case in {"merged", "publisher"}: + if args[3] == "pending" and case == "publisher": values["/repos/owner/repo/pulls/101"]["state"] = "closed" if args[3] == "failure" and case == "publisher": raise RuntimeError("publication details must not replace attestation error") @@ -266,21 +262,20 @@ def evaluate(repo, number, head, base, publishers, *, snapshot): hosted.main() else: assert hosted.main() == 0 - terminal = [] if case in {"manual", "metadata", "stale", "interrupt", "api"} else ["failure"] - expected = [] if case in {"manual", "metadata", "stale"} else ["pending", *terminal] - assert case != "race" or (rest_calls.count("apps/mergify") == 3 and sleeps == [2, 2] and len(evaluated) == 6) + states = {"valid": ["pending", "success"], "interrupt": ["pending"], "api": ["pending"], + "manual": [], "metadata": [], "stale": []} + assert [call[3] for call in published] == states.get(case, ["pending", "failure"]) + assert all(call[:3] == ("owner/repo", "c" * 40, "Loop-zero Eligibility") for call in published) + if case == "race": + assert rest_calls.count("apps/mergify") == 3 and sleeps == [2, 2] and len(evaluated) == 6 if case == "valid": assert len(rest_calls) + len(published) <= 16 - assert evaluated == [("owner/repo", 101, "1" * 40, "main", ("trusted-publisher",)), - ("owner/repo", 102, "2" * 40, "main", ("trusted-publisher",))] - assert published == [("owner/repo", "c" * 40, "Loop-zero Eligibility", "pending", - "Refreshing live source review evidence"), - ("owner/repo", "c" * 40, "Loop-zero Eligibility", "success", - "All attested candidate sources are reviewed")] - else: - assert [call[3] for call in published] == expected - assert all(call[1] == "c" * 40 for call in published) - assert not terminal or published[-1][-1] == "Eligibility refresh failed; inspect workflow logs" + assert evaluated == [("owner/repo", n, str(n - 100) * 40, "main", ("trusted-publisher",)) + for n in (101, 102)] + assert [call[-1] for call in published] == [ + "Refreshing live source review evidence", "All attested candidate sources are reviewed"] + elif case not in states: + assert published[-1][-1] == "Eligibility refresh failed; inspect workflow logs" def test_privileged_workflow_runs_only_the_trusted_default_branch_package(): @@ -291,11 +286,11 @@ def test_privileged_workflow_runs_only_the_trusted_default_branch_package(): source, candidate = workflow.split("\n source-eligibility:\n", 1)[1].split( "\n candidate-eligibility:\n", 1 ) - assert " environment:" not in source - assert "${{ secrets.MERGIFY_API_KEY }}" not in source + secret = "${{ secrets.MERGIFY_API_KEY }}" + assert " environment:" not in source and secret not in source assert "github.event.label.name == 'hold'" in source assert "environment:\n name: mergify-metadata\n deployment: false" in candidate - assert "MERGIFY_API_KEY: ${{ secrets.MERGIFY_API_KEY }}" in candidate + assert f"MERGIFY_API_KEY: {secret}" in candidate for job in (source, candidate): assert "ref: ${{ github.event.repository.default_branch }}" in job assert "ref: ${{ github.event.pull_request.head" not in job @@ -303,13 +298,11 @@ def test_privileged_workflow_runs_only_the_trusted_default_branch_package(): assert "permissions:\n contents: read\n pull-requests: read\n statuses: write" in job assert "PYTHONPATH: src" in job assert "python -m loopzero.hosted" in job - ruleset = json.loads( - (Path(__file__).parents[1] / ".github/rulesets/main.json").read_text() - ) - status_rule = next(rule for rule in ruleset["rules"] - if rule["type"] == "required_status_checks") - assert [check["context"] for check in - status_rule["parameters"]["required_status_checks"]] == ["checks", "Loop-zero Eligibility"] + ruleset = json.loads((Path(__file__).parents[1] / ".github/rulesets/main.json").read_text()) + status_rule = next(rule for rule in ruleset["rules"] if rule["type"] == "required_status_checks") + assert [check["context"] for check in status_rule["parameters"]["required_status_checks"]] == [ + "checks", "Loop-zero Eligibility", + ] @pytest.mark.parametrize("prior", [998, 999, 1000]) @@ -336,18 +329,12 @@ def test_source_status_limit(publisher, monkeypatch, capsys, prior): )) if prior == 998: - assert hosted.main() == 0 - assert written_states(publisher) == ["pending", "success"] + check_source(publisher, ["pending", "success"]) assert not any("/commits/" in " ".join(call["argv"]) for call in publisher.calls) return message = rf"{HEAD}.*{context}.*1,000.*fresh head.*review" expected = ["pending", "success"] if prior == 999 else ["pending"] - with pytest.raises(github.GhError, match=message): - hosted.main() - assert written_states(publisher) == expected - - with pytest.raises(github.GhError, match=message): - hosted.main() - assert written_states(publisher) == [*expected, "pending"] + for states in (expected, [*expected, "pending"]): + check_source(publisher, states, error=github.GhError, match=message) assert capsys.readouterr().out == "" diff --git a/tests/test_proc.py b/tests/test_proc.py index 78a6d782..65b5a209 100644 --- a/tests/test_proc.py +++ b/tests/test_proc.py @@ -36,20 +36,14 @@ def deliver_before_restore(signum, disposition): @pytest.fixture def run_python(tmp_path): - def run(script, *, timeout=30, env_allowlist=("PATH",), unbuffered=False, **kwargs): + def run(script, *, timeout=30, env_allowlist=("PATH",), unbuffered=False, args=(), **kwargs): python = [sys.executable, "-u"] if unbuffered else [sys.executable] - return _proc.run([*python, "-c", script], cwd=tmp_path, env_allowlist=env_allowlist, + return _proc.run([*python, "-c", script, *args], cwd=tmp_path, env_allowlist=env_allowlist, timeout=timeout, **kwargs) return run -def test_run_captures_output_exit_code_and_duration(run_python): - done = run_python("import sys; print('out'); print('err', file=sys.stderr); sys.exit(3)") - assert (done.exit_code, done.stdout, done.stderr) == (3, "out\n", "err\n") - assert done.duration_s >= 0 - - def test_run_strips_environment_to_allowlist(run_python, monkeypatch): monkeypatch.delenv("LZ_ABSENT", raising=False) monkeypatch.setenv("LZ_SECRET", "nope") @@ -59,28 +53,11 @@ def test_run_strips_environment_to_allowlist(run_python, monkeypatch): assert done.stdout.strip() == "['LZ_EXTRA', 'LZ_KEEP']" -def test_run_uses_cwd(tmp_path, run_python): - done = run_python("import os; print(os.getcwd())", env_allowlist=()) - assert done.stdout.strip() == str(tmp_path.resolve()) - - -def test_run_never_uses_a_shell(tmp_path): - marker = tmp_path / "pwned" - done = _proc.run(["true", ";", "touch", str(marker)], cwd=tmp_path, env_allowlist=("PATH",), timeout=30) - assert done.exit_code == 0 - assert not marker.exists() - - def test_run_raises_tool_missing(tmp_path): with pytest.raises(_proc.ToolMissing, match="definitely-not-a-tool"): _proc.run(["definitely-not-a-tool"], cwd=tmp_path, env_allowlist=("PATH",), timeout=30) -def test_run_raises_on_timeout(run_python): - with pytest.raises(_proc.ProcTimeout, match="timed out"): - run_python("import time; time.sleep(5)", timeout=0.2) - - def test_run_reaps_child_before_propagating_keyboard_interrupt(run_python, monkeypatch): children = [] @@ -118,7 +95,7 @@ def communicate(self, input=None, timeout=None): with subprocess.Popen([sys.executable, "-c", wait]) as unrelated: monkeypatch.setattr(subprocess, "Popen", ReadyPopen) try: - with pytest.raises(_proc.ProcTimeout) as raised: + with pytest.raises(_proc.ProcTimeout, match="timed out") as raised: _proc.run( [sys.executable, "-c", parent], cwd=tmp_path, env_allowlist=(), timeout=0.75, ) @@ -144,11 +121,15 @@ def communicate(self, input=None, timeout=None): unrelated.kill() -def test_merge_output_interleaves_streams(run_python): - done = run_python("import sys; print('a'); print('b', file=sys.stderr); print('c')", - unbuffered=True, merge_output=True) - assert done.stdout.splitlines() == ["a", "b", "c"] - assert done.stderr == "" +@pytest.mark.parametrize("merge,stderr", [(True, ""), (False, "b\n")]) +def test_run_captures_exit_duration_cwd_and_streams(tmp_path, run_python, merge, stderr): + done = run_python( + "import os,sys; print(os.getcwd()); print('b', file=sys.stderr); print(sys.argv[1]); sys.exit(3)", + unbuffered=True, merge_output=merge, env_allowlist=(), args=("argument with spaces",), + ) + assert (done.exit_code, done.stderr) == (3, stderr) + assert done.duration_s >= 0 + assert done.stdout.splitlines() == [str(tmp_path.resolve()), *(["b"] if merge else []), "argument with spaces"] def test_tail_keeps_last_lines(): diff --git a/tests/test_retro_metrics.py b/tests/test_retro_metrics.py index dcdb314c..fc5473a5 100644 --- a/tests/test_retro_metrics.py +++ b/tests/test_retro_metrics.py @@ -17,31 +17,22 @@ def issue(number, created, closed=None, reason=None): @pytest.fixture def sources(tmp_path, monkeypatch, request): commit_rows, commit_total = getattr(request, "param", (1, 1)) - merged = issue(1, "2026-05-26T06:00:00Z", SINCE) - at_end = issue(2, SINCE, END) - p0 = issue(4, "2026-05-23T12:00:00Z") - active = issue(5, "2026-05-25T12:00:00Z") - pull_ref = { - "event": "cross-referenced", "created_at": "2026-05-26T01:00:00Z", - "source": {"issue": {"created_at": "2026-05-26T00:00:00Z", "pull_request": { - "url": f"https://api.github.com/repos/{REPO}/pulls/3", - }}}, - } + pulls = [(1, "2026-05-26T06:00:00Z", SINCE), (2, SINCE, END)] rows = { - "pulls": [dict(merged, merged_at=SINCE), dict(at_end, merged_at=END)], - "outcomes": [ - issue(6, "2026-05-24T00:00:00Z", SINCE, "completed"), - issue(7, "2026-05-24T00:00:00Z", SINCE, "not_planned"), - ], + "pulls": [dict(issue(n, created, closed), merged_at=closed) for n, created, closed in pulls], + "outcomes": [issue(n, "2026-05-24T00:00:00Z", SINCE, reason) + for n, reason in [(6, "completed"), (7, "not_planned")]], "orders": [issue(8, "2026-05-27T00:00:00Z", SINCE, "completed")], "orders_open": [issue(9, "2026-01-01T00:00:00Z")], - "p0": [p0, active], - "issues/4/timeline": [ - {"event": "labeled", "created_at": "2026-05-28T23:45:00Z"}, - {"event": "commented", "created_at": "2026-05-28T06:00:00Z"}, - {"event": "commented", "created_at": END}, - ], - "issues/5/timeline": [pull_ref], + "p0": [issue(4, "2026-05-23T12:00:00Z"), issue(5, "2026-05-25T12:00:00Z")], + "issues/4/timeline": [{"event": event, "created_at": time} for event, time in [ + ("labeled", "2026-05-28T23:45:00Z"), ("commented", "2026-05-28T06:00:00Z"), ("commented", END), + ]], + "issues/5/timeline": [{ + "event": "cross-referenced", "created_at": "2026-05-26T01:00:00Z", + "source": {"issue": {"created_at": "2026-05-26T00:00:00Z", + "pull_request": {"url": f"https://api.github.com/repos/{REPO}/pulls/3"}}}, + }], "pulls/3": {"commits": commit_total}, "pulls/3/commits": [{"commit": {"committer": {"date": "2026-05-28T21:00:00Z"}}}] * commit_rows, "issues/3/comments": [], @@ -78,11 +69,8 @@ def collect(argv, *, input, **kwargs): monkeypatch.setattr(retro_metrics.subprocess, "run", collect) ledger = tmp_path / "receipts.jsonl" base = {"event": "job", "command_class": "loopzero-check"} - outcomes = [ - ("ok", 0, "2026-04-30T00:00:00Z"), ("ok", 0, SINCE), ("ok", 0, SINCE), - ("fail", 1, "2026-05-28T01:00:00Z"), ("cancelled", 143, "2026-05-28T02:00:00Z"), - ("ok", 0, END), - ] + outcomes = [("ok", 0, when) for when in ("2026-04-30T00:00:00Z", SINCE, SINCE, END)] + outcomes += [("fail", 1, "2026-05-28T01:00:00Z"), ("cancelled", 143, "2026-05-28T02:00:00Z")] ledger.write_text("".join(json.dumps(dict(base, outcome=outcome, exit_code=code, end_utc=end)) + "\n" for outcome, code, end in outcomes)) return calls, [ @@ -92,16 +80,27 @@ def collect(argv, *, input, **kwargs): ] -def test_record_replay_and_weekly_window(sources, capsys): +@pytest.fixture +def record(sources, capsys): calls, args = sources - assert retro_metrics.main([*args, "--record", "--host-command", "host-adapter"]) == 0 - live = capsys.readouterr() - assert sum(call == ["host-adapter"] for call in calls) == 1 - assert retro_metrics.main(args) == 0 - assert capsys.readouterr() == live - assert len(calls) == 6 - - report = json.loads(live.out) + + def run(*options, host=False, replay=True): + command = [*args, *options] + adapter = ["--host-command", "host-adapter"] if host else [] + assert retro_metrics.main([*command, "--record", *adapter]) == 0 + live, count = capsys.readouterr(), len(calls) + if replay: + assert retro_metrics.main(command) == 0 + assert capsys.readouterr() == live and len(calls) == count + return json.loads(live.out), live.err + + return run + + +def test_record_replay_and_weekly_window(sources, record): + calls, _ = sources + report, stderr = record(host=True) + assert sum(call == ["host-adapter"] for call in calls) == 1 and len(calls) == 6 row = report["custom_window"] assert row["merges"] == 1 assert row["open_to_merge_median_hours"] == 42 @@ -122,7 +121,7 @@ def test_record_replay_and_weekly_window(sources, capsys): {"kind": "oldest_open_order", "number": 9}, ] assert report["weekly_sample"]["shortfall"] == 3 - assert "Previous 7d" in live.err + assert "Previous 7d" in stderr def test_weekly_sample_reserves_controls_and_deduplicates_stalled_order(): @@ -148,46 +147,27 @@ def test_weekly_sample_reserves_controls_and_deduplicates_stalled_order(): assert [item["number"] for item in sample["items"][2:]] == [8, 7, 1, 2, 3, 4] -def assert_replay(args, calls, capsys, live): - count = len(calls) - assert retro_metrics.main(args) == 0 - assert capsys.readouterr() == live - assert len(calls) == count - - -def test_weekly_report_uses_stall_threshold_without_running_other_alerts(sources, capsys): - calls, args = sources - args = [*args, "--stall-hours", "12", "--dead-owner", "coordinator"] - assert retro_metrics.main([*args, "--record"]) == 0 - live = capsys.readouterr() - report = json.loads(live.out) - assert {"kind": "stalled_p0", "number": 4} in report["weekly_sample"]["items"] - assert all(alert["kind"] == "unknown" for alert in report["alerts"]) - assert_replay(args, calls, capsys, live) - - -def test_alerts_find_stalled_order_and_dead_owner(sources, capsys): - calls, args = sources - options = ["--alerts", "--stall-hours", "12", "--owner", "coordinator", - "--band", "merges", "2", "3"] - assert retro_metrics.main([*args, *options, "--record", "--host-command", "host-adapter"]) == 0 - live = capsys.readouterr() - findings = json.loads(live.out)["alerts"] - assert live.err == "" - assert [finding for finding in findings if finding["kind"] != "unknown"] == [ - {"kind": "outside_band", "metric": "merges", "value": 1, "min": 2, "max": 3}, - {"kind": "stalled_p0", "issue": 4, "last_activity": "2026-05-28T06:00:00Z", "hours": 18}, - {"kind": "dead_owner", "owner": "coordinator"}, - ] - assert_replay([*args, *options], calls, capsys, live) +@pytest.mark.parametrize("alerts", [False, True]) +def test_stall_and_dead_owner_modes_record_and_replay(record, alerts): + options = (["--alerts", "--owner", "coordinator", "--band", "merges", "2", "3"] if alerts + else ["--dead-owner", "coordinator"]) + report, stderr = record("--stall-hours", "12", *options, host=alerts) + findings = [item for item in report["alerts"] if item["kind"] != "unknown"] + if alerts: + assert stderr == "" and findings == [ + {"kind": "outside_band", "metric": "merges", "value": 1, "min": 2, "max": 3}, + {"kind": "stalled_p0", "issue": 4, "last_activity": "2026-05-28T06:00:00Z", "hours": 18}, + {"kind": "dead_owner", "owner": "coordinator"}, + ] + else: + assert not findings and {"kind": "stalled_p0", "number": 4} in report["weekly_sample"]["items"] -def test_missing_and_failed_sources_do_not_report_zero(sources, capsys): +def test_missing_and_failed_sources_do_not_report_zero(sources, record): _, args = sources args[args.index("--label-order") + 1] = "missing" args[args.index("--check-receipts") + 1] = "/no-such-receipt-test-file" - assert retro_metrics.main([*args, "--record"]) == 0 - report = json.loads(capsys.readouterr().out) + report, _ = record(replay=False) for key in ("orders_accepted", "checks_passed", "checks_failed", *retro_metrics.HOST_KEYS): assert report["custom_window"][key] == "UNKNOWN" assert any(a["source"] == f"custom_window/{key}" for a in report["alerts"]) @@ -208,14 +188,10 @@ def test_invalid_band_is_usage_error(capsys): ((250, 251), 1, False), ((250, None), 1, False), ], indirect=["sources"]) -def test_stalled_issue_checks_linked_pr_commit_count_at_limit(sources, detail_reads, stalled, capsys): - calls, args = sources - options = ["--alerts", "--stall-hours", "1"] - assert retro_metrics.main([*args, *options, "--record"]) == 0 - live = capsys.readouterr() - alerts = json.loads(live.out)["alerts"] +def test_stalled_issue_checks_linked_pr_commit_count_at_limit(sources, detail_reads, stalled, record): + calls, _ = sources + report, _ = record("--alerts", "--stall-hours", "1") + alerts = report["alerts"] assert any(a["kind"] == "stalled_p0" and a["issue"] == 5 for a in alerts) == stalled assert any(a.get("source") == "p0/#5/activity" for a in alerts) == (not stalled) assert sum(call[-1] == f"repos/{REPO}/pulls/3" for call in calls) == detail_reads - - assert_replay([*args, *options], calls, capsys, live) diff --git a/tests/test_setup.py b/tests/test_setup.py index 4d2cb1c5..46e22374 100644 --- a/tests/test_setup.py +++ b/tests/test_setup.py @@ -6,21 +6,22 @@ SETUP = Path(__file__).resolve().parents[1] / "SETUP.md" +def setup_commands(shell, prefix, *, text=None): + return next(block for block in re.findall(rf"```{shell}\n(.*?)```", (SETUP.read_text() if text is None else text), re.S) + if block.startswith(prefix)) + + def test_agent_skill_links_install_and_upgrade_without_gnu_mv(tmp_path, fake_tool): home = tmp_path / "home" home.mkdir() fake_tool("mv", '[ "$1" != "-T" ] || exit 64\nexec /bin/mv "$@"\n') env = dict(os.environ, HOME=str(home)) - setup_block = next( - block for block in re.findall(r"```sh\n(.*?)```", SETUP.read_text(), re.S) - if block.startswith("CHECKOUT=") - ) + commands = setup_commands("sh", "CHECKOUT=").replace("/path/to/loop-zero-checkout", '"$CHECKOUT"') source = home / ".local/share/loopzero/source" first_checkout = tmp_path / "first checkout" for checkout in (first_checkout, tmp_path / "new checkout"): skill = checkout / "core/skills/example" skill.mkdir(parents=True) - commands = setup_block.replace("/path/to/loop-zero-checkout", '"$CHECKOUT"') subprocess.run(["sh", "-ec", commands], env=dict(env, CHECKOUT=str(checkout)), check=True) assert source.readlink() == checkout for agent in (".agents", ".claude"): @@ -30,3 +31,20 @@ def test_agent_skill_links_install_and_upgrade_without_gnu_mv(tmp_path, fake_too reference = SETUP.parent / "core/skills/work-issue/reference.md" reentry = reference.read_text().split("## Re-entry\n", 1)[1].split("\n## ", 1)[0] assert "(../../CONTRACT.md#the-six-steps)" in reentry + + +def test_api_key_permissions_without_gnu_stat(tmp_path, fake_tool): + fake_tool("stat", '[ "$1" != "-c" ] || exit 64\nexec /usr/bin/stat "$@"\n') + directory = tmp_path / ".config/typesafe" + directory.mkdir(parents=True) + directory.chmod(0o700) + key = directory / "api-key" + key.write_text("placeholder") + key.chmod(0o600) + commands = setup_commands("bash", 'test -r "$HOME/.config/typesafe/api-key"') + env = dict(os.environ, HOME=str(tmp_path)) + for contents, code in (("placeholder", 0), ("", 1)): + key.write_text(contents) + result = subprocess.run(["bash", "-c", commands], env=env, capture_output=True, text=True, check=False) + assert result.returncode == code + assert result.stdout.splitlines() == ([f"700 {directory}", f"600 {key}"] if contents else []) diff --git a/tests/test_setup_permissions.py b/tests/test_setup_permissions.py deleted file mode 100644 index 4972ab9f..00000000 --- a/tests/test_setup_permissions.py +++ /dev/null @@ -1,28 +0,0 @@ -import os -import re -import subprocess -from pathlib import Path - -SETUP = Path(__file__).resolve().parents[1] / "SETUP.md" - - -def test_api_key_permissions_without_gnu_stat(tmp_path, fake_tool): - fake_tool("stat", '[ "$1" != "-c" ] || exit 64\nexec /usr/bin/stat "$@"\n') - directory = tmp_path / ".config/typesafe" - directory.mkdir(parents=True) - directory.chmod(0o700) - key = directory / "api-key" - key.write_text("placeholder") - key.chmod(0o600) - commands = next( - block for block in re.findall(r"```bash\n(.*?)```", SETUP.read_text(), re.S) - if block.startswith('test -r "$HOME/.config/typesafe/api-key"') - ) - env = dict(os.environ, HOME=str(tmp_path)) - result = subprocess.run(["bash", "-c", commands], env=env, capture_output=True, text=True, check=True) - assert result.stdout.splitlines() == [f"700 {directory}", f"600 {key}"] - - key.write_text("") - result = subprocess.run(["bash", "-c", commands], env=env, capture_output=True, text=True) - assert result.returncode == 1 - assert result.stdout == "" diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index ddc88774..4e16c1ee 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -6,14 +6,19 @@ from loopzero import sandbox from loopzero.cli import _load_report, _save_report -from loopzero.config import ConfigError, load from .conftest import git from .test_sandbox import bwrap_log, fetched_base, make_config # noqa: F401 +READ_FRAME = 'import json,sys;r=json.load(sys.stdin);r.pop("env");' +STAGE_FIELDS = 'r.update(exit_code=0,duration_s=0,not_started={fallback},tail={tail!r});' +RETURN_FRAME = 'print(json.dumps(r))' +FALLBACK_RUNNER = (sys.executable, '-c', READ_FRAME + STAGE_FIELDS.format(fallback=True, tail='') + RETURN_FRAME) + + @pytest.mark.parametrize('base_ref,body,verdict,tails', [ - *[(base_ref, 'print(json.dumps(r))', True, ['ok', 'ok']) for base_ref in ('stale', 'missing', 'recorded')], + *[(base_ref, 'print(json.dumps(r))', True, ['ok', 'ok']) for base_ref in ('stale', 'missing', 'recorded', 'abs-link', 'path-link')], ('stale', 'r["exit_code"]=7;print(json.dumps(r))', False, ['ok']), ('stale', 'print("x" * 3000 + "worker socket unavailable", file=sys.stderr);sys.exit(42)', False, None), ('stale', 'r["exit_code"]=7;r["tail"]="Ω"*10000+" newest";print(json.dumps(r))', False, @@ -30,7 +35,7 @@ *[f'r["{field}"]="wrong";print(json.dumps(r))' for field in ('head', 'base', 'command', 'env_sha256', 'network', 'worktree')], ]], ]) -def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): # noqa: F811 +def test_runner(git_repo, tmp_path, bwrap_log, monkeypatch, body, verdict, tails, base_ref): # noqa: F811 git(git_repo, 'switch', '-c', 'task') git(git_repo, 'commit', '--allow-empty', '-m', 'advance') base = git(git_repo, 'rev-parse', 'HEAD').strip() @@ -42,19 +47,26 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): git(git_repo, 'update-ref', 'refs/remotes/origin/main', base) if base_ref == 'missing': git(git_repo, 'branch', '-D', 'main') + expected = dict(sandbox.SANDBOX_ENV, UV_CACHE_DIR="/operator/cache") body = (f'repo=r["worktree"]\nassert r["base"] == "{base}"\n' 'assert not Path.cwd().is_relative_to(Path(repo))\n' - f'assert r.pop("env") == {dict(sandbox.SANDBOX_ENV, UV_CACHE_DIR="/operator/cache")!r}\n' - 'assert r["network"] is True\n' - 'assert r["env_sha256"] == hashlib.sha256(json.dumps(' - f'{dict(sandbox.SANDBOX_ENV, UV_CACHE_DIR="/operator/cache")!r},' + f'assert r.pop("env") == {expected!r} and r["network"] is True\n' + f'assert r["env_sha256"] == hashlib.sha256(json.dumps({expected!r},' 'sort_keys=True,separators=(",", ":")).encode()).hexdigest()\n' + body) path = tmp_path / 'runner.py' - path.write_text('import hashlib,json,sys,subprocess\nfrom pathlib import Path\nr=json.load(sys.stdin)\nr.update(exit_code=0,duration_s=0.1,not_started=False,tail="ok")\n' + body) + preamble = 'import hashlib,json,sys,subprocess\nfrom pathlib import Path\nr=json.load(sys.stdin)\n' + launcher = (sys.executable, str(path)) + if base_ref in ('abs-link', 'path-link'): + link = tmp_path / 'runner-python' + link.symlink_to(sys.executable) + monkeypatch.setenv('PATH', f'{tmp_path}:' + os.environ['PATH']) + preamble += f'assert sys.executable == {str(link)!r}\n' + launcher = (link.name if base_ref == 'path-link' else str(link), str(path), 'relative/argument') + path.write_text(preamble + STAGE_FIELDS.format(fallback=False, tail='ok') + '\n' + body) calls = [] report = sandbox.run_checks(make_config(checks=('echo one', 'echo two'), env=(("UV_CACHE_DIR", "/operator/cache"),), network=True, - check_runner=(sys.executable, str(path))), git_repo, progress=calls.append) + check_runner=launcher), git_repo, progress=calls.append) assert report.ok is verdict if 'exit_code"]=7' in body: assert report.results[0].exit_code == 7 @@ -82,12 +94,6 @@ def test_runner(git_repo, tmp_path, bwrap_log, body, verdict, tails, base_ref): assert receipt.keys() == {'head', 'dirty', 'results', 'settings_sha256'} -FALLBACK_RUNNER = (sys.executable, '-c', ( - 'import json,sys;r=json.load(sys.stdin);r.pop("env");' - 'r.update(exit_code=0,duration_s=0,not_started=True,tail="");print(json.dumps(r))' -)) - - @pytest.mark.parametrize('dirty', [True, False]) def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa: F811 if dirty: @@ -98,17 +104,6 @@ def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa assert ('bwrap binary missing' in report.results[0].tail) is not dirty -@pytest.mark.parametrize('value', ['[]', '[""]', '[1]', '"runner"', '["./runner"]', '["tools/runner"]', '["python3","tools/run_stage.py"]', '["dispatch","--stage"]', '["dispatch","--opt=/operator/run.py"]']) -def test_runner_config(tmp_path, value): - path = tmp_path / 'workflow.toml' - path.write_text('[repo]\nname="o/n"\n[checks]\nrunner=' + value) - if 'dispatch' in value or 'tools/run_stage.py' in value: - assert load(path).check_runner == tuple(json.loads(value)) - else: - with pytest.raises(ConfigError): - load(path) - - @pytest.mark.parametrize('kind', ['executable', 'argument', 'symlink', 'path', 'executable_symlink', 'option', 'option_symlink', 'short', 'list', 'parent', 'colon_link', 'colon_tree']) def test_runner_rejects_task_paths(git_repo, tmp_path, monkeypatch, kind): runner = git_repo / 'runner' @@ -135,19 +130,6 @@ def test_runner_rejects_task_paths(git_repo, tmp_path, monkeypatch, kind): assert not report.ok and 'references task worktree' in report.results[0].tail -@pytest.mark.parametrize('bare', [False, True]) -def test_runner_preserves_executable_symlink(git_repo, tmp_path, monkeypatch, bare): - link = tmp_path / 'runner-python' - link.symlink_to(sys.executable) - monkeypatch.setenv('PATH', f'{tmp_path}:' + os.environ['PATH']) - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') - body = (f'import json,sys;assert sys.executable == {str(link)!r};' - 'r=json.load(sys.stdin);r.pop("env");' - 'r.update(exit_code=0,duration_s=0,not_started=False,tail="ok");print(json.dumps(r))') - report = sandbox.run_checks(make_config(check_runner=(link.name if bare else str(link), '-c', body, 'relative/argument')), git_repo) - assert report.ok, report.results[0].tail - - def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 original = sandbox._proc.run def run(argv, **kwargs): diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 14e0ca42..a6be946b 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -9,6 +9,7 @@ from loopzero import worktree from tests.conftest import commit_file, git, git_environment, init_git_repo +from tests.test_setup import SETUP, setup_commands @pytest.fixture @@ -31,7 +32,7 @@ def commit_on_origin(repo: Path, name: str) -> str: git(repo, "clone", "-q", str(repo.parent / "origin.git"), str(clone)) commit_file(clone, name, name, name) git(clone, "push", "-q", "origin", "main") - return git(clone, "rev-parse", "HEAD").strip() + return worktree.head(clone) def test_git_fixture_ignores_inherited_directory(tmp_path, monkeypatch): @@ -42,16 +43,10 @@ def test_git_fixture_ignores_inherited_directory(tmp_path, monkeypatch): @pytest.mark.parametrize("slug", ["zażółć\u00a0", "ok-1.2_x"]) -def test_branch_round_trips_valid_names(repo: Path, slug: str) -> None: - name = worktree.branch_name(repo, slug) - git(repo, "switch", "-c", name) - +def test_branch_reads_valid_names_and_rejects_detached_head(repo: Path, slug: str) -> None: + git(repo, "switch", "-c", worktree.branch_name(repo, slug)) assert worktree.branch(repo) == f"lz/{slug}" - - -def test_branch_refuses_detached_head(repo: Path) -> None: git(repo, "switch", "--detach") - with pytest.raises(worktree.WorktreeError): worktree.branch(repo) @@ -115,27 +110,21 @@ def interrupt_after_add(cwd, *args, **kwargs): task = worktree.task_file(wt) assert worktree.branch(wt) == "lz/my-task" and worktree.head(wt) == base assert not task.exists() - if state == "dirty": - (wt / "untracked").write_text("work in progress") - with pytest.raises(worktree.WorktreeError, match="worktree directory already exists"): - worktree.start(repo, "my-task", "main") - assert not task.exists() - return - if state == "moved-base": - current_base = commit_on_origin(repo, "next-base") + if state == "same-base": + assert worktree.start(repo, "my-task", "main") == wt + assert worktree.base_sha(wt) == base + assert task.read_text().startswith("# My task\n") + assert task.read_text().endswith("(filled by `loopzero review`)\n") + else: + details = ("worktree directory already exists",) + if state == "dirty": + (wt / "untracked").write_text("work in progress") + else: + details = (base, "origin/main", commit_on_origin(repo, "next-base"), "new slug") with pytest.raises(worktree.WorktreeError) as error: worktree.start(repo, "my-task", "main") - for detail in (base, "origin/main", current_base, "new slug"): - assert detail in str(error.value) - assert worktree.branch(wt) == "lz/my-task" - assert worktree.head(wt) == base - assert not task.exists() - return - - assert worktree.start(repo, "my-task", "main") == wt - assert worktree.base_sha(wt) == base - assert task.read_text().startswith("# My task\n") - assert task.read_text().endswith("(filled by `loopzero review`)\n") + assert all(detail in str(error.value) for detail in details) + assert worktree.branch(wt) == "lz/my-task" and worktree.head(wt) == base and not task.exists() @pytest.mark.parametrize("case", ["regular", "file", "directory", "append", "replace"]) @@ -202,8 +191,8 @@ def test_start_explains_missing_origin(repo: Path, change: tuple[str, ...]) -> N with pytest.raises(worktree.WorktreeError, match="no Git remote named 'origin'") as info: worktree.start(repo, "my-task", "main") - assert "git remote add origin " in str(info.value) - assert "git remote rename origin" in str(info.value) + for repair in ("add origin ", "rename origin"): + assert f"git remote {repair}" in str(info.value) assert git(repo, "branch", "--list", "lz/my-task") == "" assert not worktree.worktree_dir(repo, "my-task").exists() @@ -224,45 +213,29 @@ def _commit_files(repo: Path, files: dict[str, bytes | None]) -> str: def test_diff_since_shows_changes_the_reviewed_files_try_to_hide(git_repo: Path) -> None: - base = _commit_files(git_repo, {"attr.py": b"old\n", "nul.py": b"old\n"}) + from loopzero.runners import render_patch, split_diff + + base = _commit_files(git_repo, dict.fromkeys(("attr.py", "nul.py", "gone.py", "padded.py", "carriage.py"), b"old\n")) git(git_repo, "update-index", "--add", "--cacheinfo", f"160000,{base},a-sub") _commit_files(git_repo, { ".gitattributes": b"attr.py -diff\nnul.py binary\n", "attr.py": b"new = 'attr hunk'\n", "nul.py": b"new = 'nul hunk'\x00\n", "image.png": b"\x89PNG\r\n\x1a\n\x00\xff\xfe", + "gone.py": None, "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x\n" * 300, + "carriage.py": b"new \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" + b"y\n" * 300, ".gitmodules": b'[submodule "a-sub"]\n\tpath = a-sub\n\tignore = all\n'}) + assert not worktree.is_dirty(git_repo) and worktree.head(git_repo) != base + (git_repo / "attr.py").write_text("uncommitted edit") + assert worktree.is_dirty(git_repo) diff = worktree.diff_since(git_repo, base) + assert b"uncommitted edit" not in diff assert b"Binary files" not in diff and f"+Subproject commit {base}".encode() in diff assert b"+new = 'attr hunk'" in diff and b"+new = 'nul hunk'\x00" in diff and b"+\x89PNG\r" in diff - -def test_split_diff_summarizes_only_files_git_reports_deleted(git_repo: Path) -> None: - from loopzero.runners import render_patch, split_diff # keeps the shared import block untouched - base = _commit_files(git_repo, {"gone.py": b"old\n", "padded.py": b"old\n", "carriage.py": b"old\n"}) - _commit_files(git_repo, {"gone.py": None, "padded.py": b"new = 'padded hunk'\n++ /dev/null\n" + b"x\n" * 300, - "carriage.py": b"new \rdiff --git a/carriage.py b/carriage.py\rdeleted file mode 100644\r" - + b"y\n" * 300}) - joined = "".join(split_diff(render_patch(worktree.diff_since(git_repo, base)), 1_000)) + joined = "".join(split_diff(render_patch(diff), 1_000)) assert "+++ /dev/null" in joined and "+new = 'padded hunk'" in joined and "+new \r" in joined assert "gone.py: deleted, 1 lines" in joined and joined.count(": deleted, ") == 1 -def test_dirty_head_and_diff(repo: Path) -> None: - wt = worktree.start(repo, "work", "main") - base = worktree.base_sha(wt) - assert not worktree.is_dirty(wt) - (wt / "new.py").write_text("print(1)\n") - assert worktree.is_dirty(wt), "untracked files count as dirty" - git(wt, "add", "new.py") - git(wt, "commit", "-q", "-m", "add new") - assert not worktree.is_dirty(wt) - assert worktree.head(wt) != base - diff = worktree.diff_since(wt, base) - assert b"+print(1)" in diff and b"new.py" in diff - (wt / "new.py").write_text("print(2)\n") - assert b"print(2)" not in worktree.diff_since(wt, base), "diff covers commits only" - assert worktree.is_dirty(wt) - - def test_task_helpers_errors(repo: Path) -> None: wt = worktree.start(repo, "tk", "main") worktree.task_file(wt).write_text("# no base line\n") @@ -299,9 +272,8 @@ def test_cleanup_missing_worktree(repo: Path) -> None: @pytest.mark.parametrize("state", ["clean", "dirty", "divergent", "unpublished", "remote-moved", "stash"]) def test_abandoned_worktree_guide(repo: Path, tmp_path: Path, state: str) -> None: - original = worktree.start(repo, "abandoned", "main") wt = tmp_path / "linked task checkout" - git(repo, "worktree", "move", str(original), str(wt)) + git(repo, "worktree", "move", str(worktree.start(repo, "abandoned", "main")), str(wt)) caller = tmp_path / "caller" caller.mkdir() git(wt, "commit", "--allow-empty", "-m", "published task") @@ -310,19 +282,15 @@ def test_abandoned_worktree_guide(repo: Path, tmp_path: Path, state: str) -> Non git(wt, "push", "-u", "origin", "lz/abandoned") if state == "dirty": (wt / "untracked.txt").write_text("keep my work") - if state == "divergent": + elif state == "divergent": git(wt, "commit", "--allow-empty", "-m", "local follow-up") - if state == "remote-moved": + elif state == "remote-moved": git(repo, "push", "--force", "origin", "main:refs/heads/lz/abandoned") - - if state == "stash": + elif state == "stash": (repo / "README.md").write_text("keep my stashed work") git(repo, "stash", "push") - setup = (Path(__file__).resolve().parents[1] / "SETUP.md").read_text() - _, heading, section = setup.partition("## Removing an abandoned task worktree") - assert heading, "the guide must cover closed, unmerged tasks outside retention" - commands = section.split("```sh\n", 1)[1].split("```", 1)[0] + commands = setup_commands("sh", "", text=SETUP.read_text().split("## Removing an abandoned task worktree", 1)[1]) result = subprocess.run( ["sh", "-c", commands, "cleanup-guide", str(wt), "abandoned", head], cwd=caller, env=git_environment(), capture_output=True, text=True, check=False,