Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 33 additions & 60 deletions tests/test_github.py
Original file line number Diff line number Diff line change
Expand Up @@ -808,17 +808,14 @@ def test_app_review_is_comment_with_inline_findings(gh: FakeGh, app_token_helper
assert payload["event"] == "COMMENT" and payload["comments"]


def test_marker_parser_accepts_only_the_emitted_v1_line() -> None:
def test_marker_parser_and_finding_ids() -> None:
assert github.MARKER_RE.fullmatch("<!-- loopzero:finding severity=critical -->") is None
finding = Finding("important", "src/b.py", 2, "Missing check", "validate")
new = github.MARKER_RE.fullmatch(github.finding_marker("important", HEAD, finding))
assert new and new.groupdict() == {
"severity": "important", "head": HEAD,
"id": github.finding_id(HEAD, "src/b.py", 2, "Missing check"),
}


def test_finding_id_is_deterministic_and_uses_location_and_title() -> None:
expected = "aa3b81ec"
assert github.finding_id(HEAD, "src/a.py", 10, "Null deref") == expected
assert github.finding_id(HEAD, "src/a.py", 10, "Null deref") == expected
Expand Down Expand Up @@ -854,18 +851,6 @@ def test_thread_reply_read_rejects_repeated_cursor(gh: FakeGh) -> None:
# --- checks --------------------------------------------------------------------------------


def test_gh_api_reads_with_fields_use_method_get(gh: FakeGh) -> None:
arm_review(gh)
github.post_review(REPO, 7, HEAD, review(findings=FINDINGS[:1]))
gh.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs", {"check_runs": []})
gh.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [])
github._check_signals(REPO, HEAD)
reads = [c["argv"] for c in gh.calls if c["argv"][0] == "api" and "-F" in c["argv"]]
assert len(reads) == 3, "files, check-runs and status all pass -F"
for argv in reads:
assert argv[argv.index("--method") + 1] == "GET", argv


def check_run(conclusion, *, name="checks", status="completed", **fields):
return {"name": name, "status": status, "conclusion": conclusion, **fields}

Expand Down Expand Up @@ -907,6 +892,9 @@ def test_check_runs_validates_check_page_shape(gh: FakeGh, page: dict) -> None:

if page.get("check_runs") == []:
assert github._check_signals(REPO, HEAD)[0] == {}
assert len(gh.calls) == 2
for argv in (gh.argv(0), gh.argv(1)):
assert "-F" in argv and argv[argv.index("--method") + 1] == "GET"
else:
with pytest.raises(github.GhError, match=endpoint):
github._check_signals(REPO, HEAD)
Expand Down Expand Up @@ -936,26 +924,23 @@ def test_status_pagination_rejects_a_repeated_full_page(gh: FakeGh) -> None:

def arm_readiness(gh: FakeGh, *, threads=(), runs=None) -> None:
runs = {"checks": "success"} if runs is None else runs
arm_workflow_check(gh, *(
{"name": name, "status": "completed", "conclusion": conclusion}
for name, conclusion in runs.items()
), threads=threads)
checks = (check_run(conclusion, name=name) for name, conclusion in runs.items())
arm_workflow_check(gh, *checks, threads=threads)


def arm_workflow_check(gh: FakeGh, *checks: dict, statuses=(), threads=()) -> None:
gh.respond("api graphql", threads_json(*threads))
arm_check_pages(gh, {"check_runs": list(checks)}, statuses=(list(statuses),))


def readiness(*, reviewed=HEAD, workflow_wait=False):
pr = github.pr_from_rest(rest_pr_json(pr_json()))
return github.readiness(REPO, pr, "main", ("checks",), reviewed, workflow_wait=workflow_wait,
def readiness(*, reviewed=HEAD, workflow_wait=False, required_ci=("checks",), **metadata):
pr = github.pr_from_rest(rest_pr_json(pr_json(**metadata)))
return github.readiness(REPO, pr, "main", required_ci, reviewed, workflow_wait=workflow_wait,
publishers=PUBLISHERS)


def failed_check(conclusion="failure", **fields):
return {"name": "checks", "status": "completed", "conclusion": conclusion,
"check_suite": {"id": 10}, **fields}
return check_run(conclusion, **({"check_suite": {"id": 10}} | fields))


def producing_run(**fields):
Expand Down Expand Up @@ -1136,27 +1121,18 @@ def test_readiness_rerun_attempt_requires_start_after_old_failure(
], ids=["behind-base", "merge-conflict", "merged-pr"])
def test_readiness_metadata_blocker(gh: FakeGh, metadata: dict, reason: str) -> None:
arm_readiness(gh)
pr = github.pr_from_rest(rest_pr_json(pr_json(**metadata)))
r = github.readiness(REPO, pr, "main", ("checks",), HEAD, publishers=PUBLISHERS)
assert r.reasons == (reason,)
assert readiness(**metadata).reasons == (reason,)


def test_readiness_without_required_ci_skips_check_lookup(gh: FakeGh) -> None:
gh.respond("api graphql", threads_json())
assert github.readiness(REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", (), HEAD,
publishers=PUBLISHERS).ready
assert readiness(required_ci=()).ready
assert [c["argv"][:2] for c in gh.calls] == [["api", "graphql"]]


# --- ready / merge ---------------------------------------------------------------------


def test_mark_ready(gh: FakeGh) -> None:
gh.respond("pr ready", "")
github.mark_ready(REPO, 7)
assert gh.argv(0) == ["pr", "ready", "7", "--repo", REPO]


def test_merge_success_verifies_rest_landing(gh: FakeGh) -> None:
gh.expect(["pr", "merge", "7", "--repo", REPO, "--squash", "--match-head-commit", HEAD])
gh.expect(["api", f"repos/{REPO}/pulls/7", "--include"], merge_json("MERGED", sha="c" * 40))
Expand Down Expand Up @@ -1382,31 +1358,28 @@ def test_merged_branch_history_reads_terminal_page(gh: FakeGh, merged: dict | No
assert gh.argv(3) == [*branch_history_key(2).split(), "--include"]


@pytest.mark.parametrize("change", [
{"number": True}, {"state": "open"}, {"merged_at": False},
{"merged_at": "bad-date"}, {"merged_at": "2026-10-07T05:04:29"},
{"head": None}, {"head": {"ref": "lz/other", "repo": {"full_name": REPO}}},
{"head": {"ref": "lz/t1", "repo": {"full_name": "other/widgets"}}},
])
def test_merged_branch_history_rejects_invalid_rows(gh: FakeGh, change: dict) -> None:
row = closed_history_row(pr_json(state="CLOSED"))
gh.respond(branch_history_key(), [{**row, **change}])

with pytest.raises(github.GhError, match="invalid or repeated closed PR history"):
github.merged_pr_for_branch(REPO, "lz/t1")


@pytest.mark.parametrize("detail", [
rest_pr_json(pr_json(state="CLOSED")),
rest_pr_json(pr_json(state="MERGED"), branch="lz/other"),
{**rest_pr_json(pr_json(state="MERGED")),
"head": {"sha": HEAD, "ref": "lz/t1", "repo": {"full_name": "other/widgets"}}},
@pytest.mark.parametrize("change,detail", [
*((change, None) for change in (
{"number": True}, {"state": "open"}, {"merged_at": False},
{"merged_at": "bad-date"}, {"merged_at": "2026-10-07T05:04:29"},
{"head": None}, {"head": {"ref": "lz/other", "repo": {"full_name": REPO}}},
{"head": {"ref": "lz/t1", "repo": {"full_name": "other/widgets"}}},
)),
*(({}, detail) for detail in (
rest_pr_json(pr_json(state="CLOSED")),
rest_pr_json(pr_json(state="MERGED"), branch="lz/other"),
rest_pr_json(pr_json(state="MERGED")) |
{"head": {"sha": HEAD, "ref": "lz/t1", "repo": {"full_name": "other/widgets"}}},
)),
])
def test_merged_branch_history_rejects_changed_detail(gh: FakeGh, detail: dict) -> None:
gh.respond(branch_history_key(), [closed_history_row(pr_json(state="MERGED"))])
gh.respond(f"api repos/{REPO}/pulls/7", detail)

with pytest.raises(github.GhError, match="PR changed during completion lookup"):
def test_merged_branch_history_requires_consistent_evidence(gh: FakeGh, change: dict, detail: dict | None) -> None:
row = closed_history_row(pr_json(state="CLOSED" if detail is None else "MERGED"))
gh.respond(branch_history_key(), [row | change])
reason = "invalid or repeated closed PR history"
if detail is not None:
gh.respond(f"api repos/{REPO}/pulls/7", detail)
reason = "PR changed during completion lookup"
with pytest.raises(github.GhError, match=reason):
github.merged_pr_for_branch(REPO, "lz/t1")


Expand Down
65 changes: 26 additions & 39 deletions tests/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,10 +261,11 @@ def replace_codex_events(script: Path, events, *, prepend=False) -> None:
script.write_text(text[:start] + f"printf '%s\\n' {shlex.quote(lines)}\n" + suffix)


def _fake_review(bin_dir, family):
def _fake_review(bin_dir, family, payload=APPROVE, *, exit_code=0, diagnostic=None):
if family == "claude":
return _fake_claude(bin_dir, _claude_envelope(APPROVE))
return _fake_codex(bin_dir, json.dumps(APPROVE))
envelope = _claude_envelope(payload, **({"result": diagnostic} if diagnostic is not None else {}))
return _fake_claude(bin_dir, envelope, exit_code=exit_code)
return _fake_codex(bin_dir, json.dumps(payload), stderr=diagnostic or "", exit_code=exit_code)


def _review(family: str, cwd: Path, diff: str = "--- a\n+++ b\n+x\n", **options):
Expand Down Expand Up @@ -382,21 +383,20 @@ def test_codex_uses_supplied_diff_without_requiring_git_reads(fake_bin, tmp_path
assert [call["inspection"] for call in proof["calls"]] == ["unknown"] * len(diffs)


@pytest.mark.parametrize("version", ["codex-cli 0.168.0", "codex-cli 1.0.0-beta.1", "custom build", ""])
def test_codex_observes_version_without_pinning(fake_bin, tmp_path, version):
_fake_codex(fake_bin, json.dumps(APPROVE), version=version)
result = _review("codex", tmp_path)
assert result.verdict == "approve"
assert result.provenance["cli_version"] == version
assert json.loads(result.raw)["cli_version"] == version
assert (fake_bin / "codex.stdin").exists()


@pytest.mark.parametrize("failure", ["nonzero", "missing", "timeout"])
def test_codex_version_probe_errors_use_known_failure_path(fake_bin, tmp_path, monkeypatch, failure):
@pytest.mark.parametrize("version,failure", [
*((version, None) for version in ("codex-cli 0.168.0", "codex-cli 1.0.0-beta.1", "custom build", "")),
*(("codex-cli 0.161.0", failure) for failure in ("nonzero", "missing", "timeout")),
])
def test_codex_version_probe(fake_bin, tmp_path, monkeypatch, version, failure):
from loopzero import _proc

_fake_codex(fake_bin, json.dumps(APPROVE), version_exit=int(failure == "nonzero"))
_fake_codex(fake_bin, json.dumps(APPROVE), version=version, version_exit=int(failure == "nonzero"))
if failure is None:
result = _review("codex", tmp_path)
assert result.verdict == "approve"
assert result.provenance["cli_version"] == json.loads(result.raw)["cli_version"] == version
assert (fake_bin / "codex.stdin").exists()
return
original = _proc.run

def probe(argv, **kwargs):
Expand Down Expand Up @@ -512,13 +512,11 @@ def test_real_claude_environment_auth_hides_host_state(repo,
config = tmp_path / "custom-config" if custom else host / ".claude"
config.mkdir(parents=True)
host.mkdir(exist_ok=True)
history = config / "history.jsonl"
history.write_text("synthetic sibling history marker")
(config / "history.jsonl").write_text("synthetic sibling history marker")
(config / ".credentials.json").write_text('{"token":"synthetic-disk-auth"}')
global_state = host / ".claude.json"
global_state.write_text('{"oauth":"synthetic-disk-auth","history":"mixed marker"}')
alternate_state = config / ".config.json"
alternate_state.write_text('{"history":"custom mixed marker"}')
(config / ".config.json").write_text('{"history":"custom mixed marker"}')
before = {path: path.read_bytes() for path in (*config.iterdir(), global_state)}
monkeypatch.setenv("HOME", str(host))
if custom:
Expand All @@ -527,11 +525,9 @@ def test_real_claude_environment_auth_hides_host_state(repo,
monkeypatch.delenv("CLAUDE_CONFIG_DIR", raising=False)
monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", oauth)
monkeypatch.setenv("ANTHROPIC_API_KEY", api)
hidden = [history, global_state, alternate_state, config / ".credentials.json",
Path(SANDBOX_HOME) / ".claude/history.jsonl",
Path(SANDBOX_HOME) / ".claude.json",
Path(SANDBOX_HOME) / ".claude/.config.json",
Path(SANDBOX_HOME) / ".claude/.credentials.json"]
state_names = ("history.jsonl", ".config.json", ".credentials.json")
hidden = [global_state, Path(SANDBOX_HOME) / ".claude.json"]
hidden.extend(root / name for root in (config, Path(SANDBOX_HOME) / ".claude") for name in state_names)
checks = "\n".join(
f"test ! -e {shlex.quote(str(path))} || "
"{ echo 'host state exposed' >&2; exit 70; }" for path in hidden
Expand Down Expand Up @@ -638,10 +634,7 @@ def record(config, cwd, home, common_dir, git_dir, **kwargs):

@pytest.mark.parametrize("family", ["claude", "codex"])
def test_review_escalates_verdict_with_blocking_finding(fake_bin, tmp_path, family):
if family == "claude":
_fake_claude(fake_bin, _claude_envelope(CHANGES))
else:
_fake_codex(fake_bin, json.dumps(CHANGES), stderr="model: fallback")
_fake_review(fake_bin, family, CHANGES, diagnostic="model: fallback" if family == "codex" else None)

result = _review(family, tmp_path)

Expand Down Expand Up @@ -712,10 +705,7 @@ def test_claude_classifies_error_envelopes(fake_bin, tmp_path, exit_code, output
])
@pytest.mark.parametrize("exit_code", [0, 1])
def test_auth_phrases_only_fail_on_nonzero_exit(fake_bin: Path, tmp_path: Path, family, message, exit_code) -> None:
if family == "claude":
_fake_claude(fake_bin, _claude_envelope(APPROVE, result=message), exit_code=exit_code)
else:
_fake_codex(fake_bin, json.dumps(APPROVE), stderr=message, exit_code=exit_code)
_fake_review(fake_bin, family, exit_code=exit_code, diagnostic=message)
if exit_code:
with pytest.raises(RunnerAuthFailed):
_review(family, tmp_path)
Expand All @@ -733,10 +723,8 @@ def test_auth_phrases_only_fail_on_nonzero_exit(fake_bin: Path, tmp_path: Path,
@pytest.mark.parametrize("family", ["claude", "codex"])
def test_success_with_auth_words_is_not_auth_failure(fake_bin: Path, tmp_path: Path,
family: str) -> None:
if family == "claude":
_fake_claude(fake_bin, _claude_envelope(AUTH_WORDS))
else:
_fake_codex(fake_bin, json.dumps(AUTH_WORDS), stderr="warning: not authenticated to telemetry")
diagnostic = "warning: not authenticated to telemetry" if family == "codex" else None
_fake_review(fake_bin, family, AUTH_WORDS, diagnostic=diagnostic)
result = _review(family, tmp_path)
assert result.verdict == "approve" and result.findings[0].title == "Handle 401 Unauthorized"

Expand Down Expand Up @@ -780,8 +768,7 @@ def test_reviewer_binary_selection(fake_bin: Path, git_repo: Path, monkeypatch,
real_dir.mkdir()
(fake_bin / "git").symlink_to("/usr/bin/git")
if mode in {"shim-first", "ordinary"}:
real = (_fake_claude(real_dir, _claude_envelope(APPROVE)) if family == "claude"
else _fake_codex(real_dir, json.dumps(APPROVE)))
real = _fake_review(real_dir, family)
real.rename(real_dir / "2.1.286")
real.symlink_to(real_dir / "2.1.286")
if mode == "ordinary":
Expand Down
Loading