From 41e132ac6212c08a70c5cf78d511a250803d9a04 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 16:03:22 +0100 Subject: [PATCH] Consolidate candidate, GitHub, and sandbox test scenarios Architecture-Review: unchanged; only test scaffolding changes, with the existing behavioral assertions retained. Co-Authored-By: Codex --- tests/test_candidate.py | 116 ++++++++++++++-------------------------- tests/test_github.py | 105 +++++++++++++++--------------------- tests/test_sandbox.py | 75 ++++++++++++-------------- 3 files changed, 118 insertions(+), 178 deletions(-) diff --git a/tests/test_candidate.py b/tests/test_candidate.py index acd04349..cfc18b37 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -37,19 +37,13 @@ def no_retry_delay(monkeypatch): def event(head: str = "c" * 40) -> dict: repo = {"id": 7, "full_name": "owner/repo"} bot = { - "id": 37929162, - "login": "mergify[bot]", - "type": "Bot", + "id": 37929162, "login": "mergify[bot]", "type": "Bot", "html_url": "https://github.com/apps/mergify", } return { - "action": "synchronize", - "repository": repo, - "sender": deepcopy(bot), + "action": "synchronize", "repository": repo, "sender": deepcopy(bot), "pull_request": { - "number": 900, - "state": "open", - "draft": True, + "number": 900, "state": "open", "draft": True, "user": bot, "head": {"sha": head, "ref": "mergify/merge-queue/batch", "repo": deepcopy(repo)}, "base": {"sha": "b" * 40, "ref": "main", "repo": deepcopy(repo)}, @@ -73,11 +67,8 @@ def status() -> dict: def pull(number: int, sha: str) -> dict: return { - "number": number, - "state": "open", - "draft": False, - "body": f"source {number}", - "head": {"sha": sha}, + "number": number, "state": "open", "draft": False, + "body": f"source {number}", "head": {"sha": sha}, "base": {"ref": "main", "repo": {"id": 7, "full_name": "owner/repo"}}, } @@ -100,14 +91,9 @@ def source_payloads(values, head, *sources): def payloads(candidate_event: dict) -> dict[str, object]: - candidate = deepcopy(candidate_event["pull_request"]) - candidate["number"] = 900 + candidate = deepcopy(candidate_event["pull_request"]) | {"number": 900} values = { - "/apps/mergify": { - "id": 10562, - "slug": "mergify", - "owner": {"login": "Mergifyio"}, - }, + "/apps/mergify": {"id": 10562, "slug": "mergify", "owner": {"login": "Mergifyio"}}, "/users/mergify%5Bbot%5D": deepcopy(candidate["user"]), "/repos/owner/repo/pulls/900": candidate, } @@ -116,14 +102,9 @@ def payloads(candidate_event: dict) -> dict[str, object]: def run_attestation( - candidate_event: dict | None = None, - *, - status_reads: list[dict] | None = None, - github_payloads: dict[str, object] | None = None, - github_get=None, - mergify_status=None, - source_policy=lambda _number, _source: None, - run=attest_candidate, + candidate_event: dict | None = None, *, + status_reads: list[dict] | None = None, github_payloads: dict[str, object] | None = None, + github_get=None, mergify_status=None, source_policy=lambda _number, _source: None, run=attest_candidate, ): candidate_event = candidate_event or event() reads = cycle(status_reads or [status()]) @@ -143,41 +124,44 @@ def test_attests_nested_candidate_and_transitive_parent_sources() -> None: assert seen == [101, 102] -@pytest.mark.parametrize( - "mutation,message", - [ - (lambda value: value["pull_request"]["user"].update(id=1), "Mergify GitHub App"), - (lambda value: value["sender"].update(id=1), "head event was not sent"), - (lambda value: value.update(action="edited"), "creation or head-update event"), - ( - lambda value: value["pull_request"]["head"].update(ref="feature/forged"), - "unexpected head ref", - ), - ], -) -def test_rejects_forged_bot_or_prefix(mutation, message: str) -> None: - candidate_event = event() - mutation(candidate_event) - with pytest.raises(CandidateError, match=message): - run_attestation(candidate_event=candidate_event, github_payloads=payloads(event())) - - @pytest.mark.parametrize("case,diagnostic", [ + ("author", "Mergify GitHub App"), ("sender", "head event was not sent"), + ("action", "creation or head-update event"), ("ref", "unexpected head ref"), ("missing status", "status is not an object"), ("missing ancestor", "not an ancestor"), + ("same-head policy", "source policy blocked"), ]) def test_rejects_invalid_attestation_evidence(case, diagnostic): - values = payloads(event()) - if case == "missing ancestor": + incoming = event() + values = payloads(incoming) + status_reads = [None] if case == "missing status" else None + + def policy(number, _source): + if case == "same-head policy" and number == 102: + raise CandidateError("source policy blocked same-head source") + + if case == "author": + incoming["pull_request"]["user"]["id"] = 1 + elif case == "sender": + incoming["sender"]["id"] = 1 + elif case == "action": + incoming["action"] = "edited" + elif case == "ref": + incoming["pull_request"]["head"]["ref"] = "feature/forged" + elif case == "missing ancestor": values[f"/repos/owner/repo/compare/{'2' * 40}...{'c' * 40}"]["status"] = "diverged" + elif case == "same-head policy": + head = "c" * 40 + values["/repos/owner/repo/pulls/102"]["head"]["sha"] = head + values[f"/repos/owner/repo/compare/{head}...{head}"] = { + "status": "identical", "merge_base_commit": {"sha": head}, + } with pytest.raises(CandidateError, match=diagnostic): - run_attestation(github_payloads=values, status_reads=[None] if case == "missing status" else None) + run_attestation(incoming, github_payloads=values, status_reads=status_reads, source_policy=policy) -@pytest.mark.parametrize( - "pr_number,diagnostic", - [(101, "head changed"), (900, "Candidate head changed")], - ids=["source-head", "candidate-head"], -) +@pytest.mark.parametrize("pr_number,diagnostic", [ + (101, "head changed"), (900, "Candidate head changed"), +], ids=["source-head", "candidate-head"]) def test_rejects_head_change_during_attestation(pr_number: int, diagnostic: str) -> None: values = payloads(event()) calls = 0 @@ -195,21 +179,6 @@ def github_get(path: str): run_attestation(github_get=github_get) -def test_same_head_still_obeys_source_policy() -> None: - values = payloads(event()) - values["/repos/owner/repo/pulls/102"]["head"]["sha"] = "c" * 40 - values["/repos/owner/repo/compare/" + "c" * 40 + "..." + "c" * 40] = { - "status": "identical", - "merge_base_commit": {"sha": "c" * 40}, - } - - def block(number: int, _source: dict) -> None: - if number == 102: - raise CandidateError("source policy blocked same-head source") - with pytest.raises(CandidateError, match="source policy blocked"): - run_attestation(github_payloads=values, source_policy=block) - - @pytest.fixture(scope="session") def candidate_seed(tmp_path_factory): remote = tmp_path_factory.mktemp("candidate-seed") @@ -456,10 +425,7 @@ def test_predecessor_landing_restarts_complete_attestation(tree_candidate, monke source_payloads(values, head, (101, parent), (102, source)) main, vanished = git("rev-parse", "main"), status() vanished["batches"].pop(0) - reads = iter( - ([status(), status()] if timing == "metadata" else [status()]) - + [vanished, vanished] - ) + reads = iter([status()] * (2 if timing == "metadata" else 1) + [vanished, vanished]) source_reads = candidate_reads = status_reads = 0 seen, verified, sleeps, verify = [], [], [], candidate._verify_tree diff --git a/tests/test_github.py b/tests/test_github.py index a8cb8798..314bf4bb 100644 --- a/tests/test_github.py +++ b/tests/test_github.py @@ -107,18 +107,12 @@ def _response(response: object, *, exit: int = 0, stderr: str = "") -> dict[str, return dict(response) return { "stdout": response if isinstance(response, str) else json.dumps(response), - "stderr": stderr, - "exit_code": exit, + "stderr": stderr, "exit_code": exit, } def expect( - self, - argv: list[str], - response: object = "", - *, - exit: int = 0, - stderr: str = "", - input_files: dict[str, str] | None = None, + self, argv: list[str], response: object = "", *, + exit: int = 0, stderr: str = "", input_files: dict[str, str] | None = None, ) -> None: """Queue one exact interaction; temp path arguments are ````.""" plan = json.loads(self.scenario_file.read_text()) @@ -768,8 +762,8 @@ def test_app_helper_failure_falls_back_to_operator(gh: FakeGh, monkeypatch, app_ def test_app_review_is_comment_with_inline_findings(gh: FakeGh, app_token_helper) -> None: app_token_helper() - gh.respond(f"api repos/{REPO}/pulls/7/files", PR_FILES) - gh.respond(f"api repos/{REPO}/pulls/7/reviews", {"id": 3}) + gh.respond(FILES_KEY, PR_FILES) + gh.respond(REVIEWS_KEY, {"id": 3}) github.post_review(REPO, 7, HEAD, review(verdict="approve", findings=FINDINGS[:1]), pr=github.PR(7, "url", HEAD, "main", True, "OPEN", "UNKNOWN")) posted = gh.calls[-1] @@ -787,8 +781,7 @@ def test_marker_parser_and_finding_ids() -> None: "id": github.finding_id(HEAD, "src/b.py", 2, "Missing check"), } 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 + assert all(github.finding_id(HEAD, "src/a.py", 10, "Null deref") == expected for _ in range(2)) assert github.finding_id(HEAD, "src/a.py", 11, "Null deref") != expected @@ -912,10 +905,10 @@ def arm_workflow_check(gh: FakeGh, *checks: dict, statuses=(), threads=()) -> No arm_check_pages(gh, {"check_runs": list(checks)}, statuses=(list(statuses),)) -def readiness(*, reviewed=HEAD, workflow_wait=False, required_ci=("checks",), **metadata): +def readiness(*, reviewed=HEAD, workflow_wait=False, required_ci=("checks",), review_grace=False, **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) + review_grace=review_grace, publishers=PUBLISHERS) def failed_check(conclusion="failure", **fields): @@ -955,9 +948,7 @@ def test_readiness_requires_current_review_and_resolved_findings(gh: FakeGh, rev assert not any("actions/runs" in " ".join(c["argv"]) for c in gh.calls) -def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks( - gh: FakeGh, -) -> None: +def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks(gh: FakeGh) -> None: stale = "b" * 40 arm_readiness(gh, threads=( thread(f"{marker('important', stale)}\n**important: Still applies**"), @@ -976,10 +967,7 @@ def test_readiness_uses_head_or_non_outdated_rule_and_resolved_never_blocks( @pytest.mark.parametrize("wait,grace", [(False, True), (True, False), (True, True)]) def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) -> None: arm_readiness(gh, runs={"checks": failure}) - r = github.readiness( - REPO, github.pr_from_rest(rest_pr_json(pr_json())), "main", ("checks", "e2e"), HEAD, workflow_wait=wait, review_grace=grace, - publishers=PUBLISHERS, - ) + r = readiness(required_ci=("checks", "e2e"), workflow_wait=wait, review_grace=grace) assert r.reasons == ( f"required check 'checks' is {failure}", f"required check 'e2e' missing on {HEAD[:12]}", @@ -988,10 +976,10 @@ def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) - assert r.waitable_failures == ((f"required check 'checks' is {failure}",) if wait and grace else ()) -@pytest.mark.parametrize("check,producer,replacement,statuses,waitable", [ +@pytest.mark.parametrize("check,runs,statuses,waitable", [ *(pytest.param( failed_check(failure, id=100, started_at="2026-09-23T21:53:00Z", completed_at="2026-09-23T21:54:41Z"), - producing_run(), replacement_run() | changes, [], waitable, id=case, + (producing_run(), replacement_run() | changes), [], waitable, id=case, ) for case, failure, changes, waitable in ( ("failed", "failure", {}, True), ("cancelled", "cancelled", {}, True), ("different-workflow", "failure", {"workflow_id": 8}, False), @@ -1002,14 +990,22 @@ def test_readiness_missing_and_failed_checks(gh: FakeGh, failure, wait, grace) - ("newer-fraction", "failure", {"created_at": "2026-09-23T21:53:00.250Z"}, True), ("invalid-creation", "failure", {"created_at": "invalid"}, False), )), - pytest.param(failed_check(id=100), producing_run(created_at=replacement_run()["created_at"]), - replacement_run(), [], True, id="same-second-newer-run"), - pytest.param(failed_check(id=100), producing_run(), replacement_run(), + pytest.param(failed_check(id=100), (producing_run(created_at=replacement_run()["created_at"]), replacement_run()), + [], True, id="same-second-newer-run"), + pytest.param(failed_check(id=100), (producing_run(), replacement_run()), [{"context": "checks", "state": "failure"}], False, id="failing-commit-status"), + *(pytest.param( + failed_check(id=100, completed_at="2026-09-23T21:54:41Z"), + (producing_run(status="in_progress", run_attempt=2, run_started_at=started and f"2026-09-23T{started}"),), + [], waitable, id=f"rerun-{started}", + ) for started, waitable in ( + ("21:55:00Z", True), ("21:54:00Z", False), ("21:54:41.250Z", True), + ("22:54:41+01:00", False), ("23:54:40.999+02:00", False), ("invalid", False), (None, False), + )), ]) -def test_readiness_defers_only_replaceable_failure(gh, check, producer, replacement, statuses, waitable): +def test_readiness_defers_only_replaceable_failure(gh, check, runs, statuses, waitable): arm_workflow_check(gh, check, statuses=statuses) - arm_workflow_runs(gh, producer, replacement) + arm_workflow_runs(gh, *runs) result = readiness(workflow_wait=True) assert not result.ready and result.reasons == (f"required check 'checks' is {check['conclusion']}",) assert result.waitable_failures == (result.reasons if waitable else ()) @@ -1073,19 +1069,6 @@ def test_readiness_actions_api_error_does_not_defer_failure(gh: FakeGh) -> None: readiness(workflow_wait=True) -@pytest.mark.parametrize("started,waitable", [ - ("21:55:00Z", True), ("21:54:00Z", False), ("21:54:41.250Z", True), - ("22:54:41+01:00", False), ("23:54:40.999+02:00", False), ("invalid", False), (None, False), -]) -def test_readiness_rerun_attempt_requires_start_after_old_failure( - gh: FakeGh, started: str | None, waitable: bool -) -> None: - arm_workflow_check(gh, failed_check(id=100, completed_at="2026-09-23T21:54:41Z")) - arm_workflow_runs(gh, producing_run(status="in_progress", run_attempt=2, run_started_at=started and f"2026-09-23T{started}")) - result = readiness(workflow_wait=True) - assert result.waitable_failures == (result.reasons if waitable else ()) - - @pytest.mark.parametrize(("metadata", "reason"), [ ({"mergeStateStatus": "BEHIND"}, "PR #7 is behind main. Finish any pending delta review, then run `git fetch origin main`, `git merge origin/main`, `loopzero check` and `loopzero pr` before retrying readiness."), ({"mergeable": "CONFLICTING"}, "PR #7 has merge conflicts with main"), @@ -1191,13 +1174,6 @@ def test_merge_reports_queue_admission_or_landing(gh, strategy, queue_state): assert "--queue" not in writes[0] -def test_merged_sha_only_for_merged_state(gh: FakeGh) -> None: - gh.respond(f"api repos/{REPO}/pulls/7", merge_json(state='MERGED', sha='c' * 40), - merge_json(state='OPEN', sha="d" * 40)) - assert github.merged_sha(REPO, 7) == "c" * 40 - assert github.merged_sha(REPO, 7) is None - - def test_merge_rejects_unknown_strategy(gh: FakeGh) -> None: with pytest.raises(github.MergeFailed): github.merge(REPO, 7, "fast-forward", HEAD) @@ -1312,23 +1288,29 @@ def test_graphql_limit_reports_only_verified_reset(gh, diagnostic): assert "quota resets at" not in str(info.value) -@pytest.mark.parametrize("view", [None, {}, merge_json("CLOSED"), - merge_json("MERGED"), merge_json("MERGED", sha="invalid"), - merge_json("MERGED", sha="c" * 40) | {"merged": "true"}, - merge_json(head="f" * 40), merge_json(head=None), merge_json() | {"head": []}]) -def test_invalid_merge_evidence_fails_closed(gh, view): - gh.respond(f"api repos/{REPO}/pulls/7", view) - with pytest.raises(github.GhError, match=r"merge evidence|without a verified merge|head changed"): - github.merged_sha(REPO, 7, expected_head=HEAD) +@pytest.mark.parametrize("views,expected", [ + ((merge_json("MERGED", sha="c" * 40), merge_json(sha="d" * 40)), ("c" * 40, None)), + *(((view,), "reject") for view in ( + None, {}, merge_json("CLOSED"), merge_json("MERGED"), merge_json("MERGED", sha="invalid"), + merge_json("MERGED", sha="c" * 40) | {"merged": "true"}, merge_json(head="f" * 40), + merge_json(head=None), merge_json() | {"head": []}, + )), +]) +def test_merged_sha_requires_verified_merge_evidence(gh, views, expected): + gh.respond(f"api repos/{REPO}/pulls/7", *views) + if expected == "reject": + with pytest.raises(github.GhError, match=r"merge evidence|without a verified merge|head changed"): + github.merged_sha(REPO, 7, expected_head=HEAD) + else: + assert tuple(github.merged_sha(REPO, 7) for _ in views) == expected @pytest.mark.parametrize("merged", [None, pr_json(number=101, state="MERGED")]) def test_merged_branch_history_reads_terminal_page(gh: FakeGh, merged: dict | None) -> None: gh.respond(branch_head_key(), {"commit": {"sha": HEAD}}) gh.respond(f"api repos/{REPO}/commits/{HEAD}/pulls?per_page=100&page=1", []) - gh.respond(branch_history_key(), [ - closed_history_row(pr_json(number=n, state="CLOSED")) for n in range(1, 101) - ]) + closed_page = [closed_history_row(pr_json(number=n, state="CLOSED")) for n in range(1, 101)] + gh.respond(branch_history_key(), closed_page) gh.respond(branch_history_key(2), [closed_history_row(merged)] if merged else []) if merged: gh.respond_pr_view(merged) @@ -1411,8 +1393,7 @@ def test_readiness_at_check_suite_limit(gh: FakeGh, unrelated, legacy_success, c runs.append({"name": "required-ci", "conclusion": "failure", "check_suite": {"id": 1}}) gh.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs", *({"check_runs": runs[i:i + 100]} for i in range(0, len(runs) + 1, 100))) - result = github.readiness(REPO, github.pr_from_rest(rest_pr_json(pr_json())), - "main", ("required-ci",), HEAD, publishers=PUBLISHERS) + result = readiness(required_ci=("required-ci",)) reasons = { "suite limit": f"cannot determine required check 'required-ci' on {HEAD[:12]}: GitHub's 1,000-suite limit", diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index 7a98ecaa..a667f384 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -68,9 +68,9 @@ def make_config(**overrides) -> Config: - values = {"repo": "o/n", "base_branch": "main", "checks": ("echo hello",), "required_ci": ()} - values |= {"merge_strategy": "squash", "reviewers": ("claude",)} - return Config(**{**values, "env_allowlist": ("PATH", "HOME", "LZ_KEEP"), **overrides}) + defaults = {"repo": "o/n", "base_branch": "main", "checks": ("echo hello",), "required_ci": (), + "merge_strategy": "squash", "reviewers": ("claude",), "env_allowlist": ("PATH", "HOME", "LZ_KEEP")} + return Config(**(defaults | overrides)) @pytest.fixture @@ -86,9 +86,8 @@ def argv_of(log: Path) -> list[str]: def test_report_head_and_results(git_repo, bwrap_log): - report = sandbox.run_checks( - make_config(checks=("echo one", "echo two; exit 4", "echo never")), git_repo - ) + checks = ("echo one", "echo two; exit 4", "echo never") + report = sandbox.run_checks(make_config(checks=checks), git_repo) assert report.head == git(git_repo, "rev-parse", "HEAD").strip() assert report.dirty is False assert [(r.command, r.exit_code, r.tail) for r in report.results] == [ @@ -269,9 +268,7 @@ def test_verbose_stage_bounds_parent_memory(git_repo, bwrap_log): def test_timeout_is_recorded_with_drained_output(git_repo, bwrap_log): command = "printf '%20000s\\n' ''; echo last diagnostic >&2; exec sleep 30" - report = sandbox.run_checks( - make_config(checks=(command, "echo after")), git_repo, timeout=1 - ) + report = sandbox.run_checks(make_config(checks=(command, "echo after")), git_repo, timeout=1) (result,) = report.results assert result.exit_code == sandbox.TIMEOUT_EXIT and not report.ok assert result.tail.endswith("\nlast diagnostic\n\n[loopzero] timed out after 1s") @@ -434,22 +431,21 @@ def test_real_sandbox_memory_limit_fails_check_and_preserves_report(self, git_re assert result.command == command and result.exit_code != 0 assert not report.ok - def test_real_network_sandbox_resolves_localhost(self, git_repo): - config = make_config(checks=("test -r /etc/resolv.conf && getent hosts localhost",), network=True) - assert sandbox.run_checks(config, git_repo).ok - - def test_real_sandbox_hides_host_sockets_and_homes(self, git_repo): - uid = os.getuid() - checks = ( - f"test ! -e /run/user/{uid}", + @pytest.mark.parametrize("network", [False, True], ids=["isolated", "localhost"]) + def test_real_sandbox_system_visibility(self, git_repo, network): + checks = ("test -r /etc/resolv.conf && getent hosts localhost",) if network else ( + f"test ! -e /run/user/{os.getuid()}", "test ! -e /var/run/docker.sock && test ! -e /run/docker.sock", "test ! -e /home && test ! -e /root", "test -z \"$(ls -A /run 2>/dev/null)\"", "test -d /usr && test -d /etc && test -w /tmp", 'test "$(cat /proc/1/comm)" = bwrap', # private pid namespace: pid 1 is not host init ) - report = sandbox.run_checks(make_config(checks=checks), git_repo) - assert [r.exit_code for r in report.results] == [0] * len(checks), report + report = sandbox.run_checks(make_config(checks=checks, network=network), git_repo) + if network: + assert report.ok + else: + assert [r.exit_code for r in report.results] == [0] * len(checks), report def test_real_sandbox_scratch_cannot_rebind_git_between_checks(self, git_repo): sentinel = git_repo / ".git" / "external-sentinel" @@ -569,29 +565,26 @@ def run_stage(config, worktree, prefix, stage_command, timeout): assert statuses[-1].startswith("stage 2/2: exit 0") -def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log, monkeypatch): - events = [] - report = sandbox.run_checks( - make_config(checks=("echo secret; exit 17", "echo never")), git_repo, - status=events.append, - ) - assert len(events) == 1 and events[0].startswith("stage 1/2: exit 17 (") - assert report.results[0].tail == "secret" and len(report.results) == 1 - assert not report.ok - - -def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch, heartbeat_log): - events, _, status, wait_for_heartbeat = heartbeat_log - inject_check_timeout(monkeypatch, b"private\n", wait_for_heartbeat) - report = sandbox.run_checks( - make_config(checks=("echo private", "echo never")), git_repo, - timeout=0.2, status=status, - ) - assert any("running" in event for event in events) - assert events[-1].startswith("stage 1/2: exit 124 (") - assert all("private" not in event for event in events) +@pytest.mark.parametrize("timed_out", [False, True], ids=["early-failure", "timeout"]) +def test_failed_stage_status_and_tail(git_repo, bwrap_log, monkeypatch, request, timed_out): + if timed_out: + events, _, status, wait = request.getfixturevalue("heartbeat_log") + inject_check_timeout(monkeypatch, b"private\n", wait) + command, exit_code, tail = "echo private", 124, "private\n\n[loopzero] timed out after 0.2s" + else: + events = [] + status = events.append + command, exit_code, tail = "echo secret; exit 17", 17, "secret" + report = sandbox.run_checks(make_config(checks=(command, "echo never")), git_repo, + status=status, **({"timeout": 0.2} if timed_out else {})) assert len(report.results) == 1 and not report.ok - assert report.results[0].tail == "private\n\n[loopzero] timed out after 0.2s" + assert report.results[0].tail == tail + assert events[-1].startswith(f"stage 1/2: exit {exit_code} (") + if timed_out: + assert any("running" in event for event in events) + assert all("private" not in event for event in events) + else: + assert len(events) == 1 def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch, heartbeat_log):