diff --git a/tests/test_candidate.py b/tests/test_candidate.py index 28dfdc6e..c2c107a7 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -102,21 +102,24 @@ 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 = candidate_event or event() reads, values = ( cycle(status_reads or [status(), status()]), github_payloads or payloads(candidate_event), ) - return attest_candidate( + return run( candidate_event, - github_get=lambda path: deepcopy(values[path]), - mergify_status=lambda *_: deepcopy(next(reads)), + github_get=github_get or (lambda path: deepcopy(values[path])), + mergify_status=mergify_status or (lambda *_: deepcopy(next(reads))), source_policy=source_policy, ) @@ -184,10 +187,8 @@ def github_get(path: str): reads = iter([status(), status()]) with pytest.raises(CandidateError, match=diagnostic): - attest_candidate( - candidate_event, github_get=github_get, - mergify_status=lambda *_: deepcopy(next(reads)), source_policy=lambda *_: None, - ) + run_attestation(candidate_event, github_get=github_get, + mergify_status=lambda *_: deepcopy(next(reads))) def test_same_head_still_obeys_source_policy() -> None: @@ -286,8 +287,8 @@ def get(path): return {"object": {"sha": sha}} if sha else {} return deepcopy(values[path]) - return run(candidate_event, github_get=get, mergify_status=lambda *_: deepcopy(queue), - source_policy=policy) + return run_attestation(candidate_event, github_get=get, status_reads=[queue], + source_policy=policy, run=run) return attest, git, commit, base, parent, source, candidate_sha @@ -520,7 +521,8 @@ def verify_tree(repo, main_sha, candidate_sha, sources): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) monkeypatch.setattr(candidate, "_verify_tree", verify_tree) - assert attest_candidate(candidate_event, github_get=get, mergify_status=lineage, source_policy=policy) == [{"number": 102, "head_sha": source}] + assert run_attestation(candidate_event, github_get=get, mergify_status=lineage, + source_policy=policy) == [{"number": 102, "head_sha": source}] assert seen == {"metadata": [101, 102, 102], "policy": [101, 102], "initial": [102]}[timing] assert candidate_reads == (4 if timing == "metadata" else 3) assert verified == [(main, head, [source])] and sleeps == [2] @@ -545,12 +547,7 @@ def policy(number, source): raise CandidateError("fresh policy rejects drift") with pytest.raises(CandidateError, match="fresh policy rejects drift"): - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: status(), - source_policy=policy, - ) + run_attestation(github_get=get, source_policy=policy) assert snapshots == [ ("source 101", False), (value if field == "body" else "source 101", field == "draft"), @@ -598,12 +595,7 @@ def policy(*_): monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) with pytest.raises((CandidateError, LoopZeroError)) as caught: - attest_candidate( - event(), - github_get=get, - mergify_status=lambda *_: deepcopy(live), - source_policy=policy, - ) + run_attestation(github_get=get, status_reads=[live], source_policy=policy) assert not isinstance(caught.value, CandidateRaceError) and len(attempts) == 1 and sleeps == [] if failure == "policy": assert caught.value is expected and len(source_reads) == 2 @@ -632,12 +624,7 @@ def sleep(seconds): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) with pytest.raises(CandidateRaceError, match="membership changed") as caught: - attest_candidate( - event(), - github_get=lambda _: None, - mergify_status=lambda *_: None, - source_policy=lambda *_: None, - ) + run_attestation(github_get=lambda _: None, status_reads=[None]) assert len(attempts) == attempt_count and caught.value is attempts[-1] assert sum(sleeps) <= 4 @@ -673,7 +660,8 @@ def read_status(*_): monkeypatch.setattr(candidate, "_retry_clock", lambda: clock[0]) monkeypatch.setattr(candidate, "_retry_sleep", sleep) def run(): - return attest_candidate(event(), github_get=lambda p: deepcopy(values[p]), mergify_status=read_status, source_policy=lambda n, _: seen.append(n)) + return run_attestation(github_payloads=values, mergify_status=read_status, + source_policy=lambda n, _: seen.append(n)) if stop in {"settled", "changed"}: assert run() == [{"number": 101, "head_sha": "1" * 40}, {"number": 102, "head_sha": "2" * 40}] assert seen == [101, 102] * (2 if stop == "changed" and second else 1) diff --git a/tests/test_config.py b/tests/test_config.py index a877a3db..2ed48a21 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -102,14 +102,10 @@ def test_missing_file(tmp_path): config.load(tmp_path / "nope.toml") -def test_invalid_toml(tmp_path): - with pytest.raises(config.ConfigError, match="invalid TOML"): - config.load(write(tmp_path, "[repo\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"), @@ -148,6 +144,13 @@ def test_invalid_toml(tmp_path): "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") + ], ], ) def test_invalid_content(tmp_path, text, message): @@ -160,17 +163,17 @@ def test_invalid_content(tmp_path, text, message): FORBIDDEN += ["/var/run/docker.sock", "/sys/fs", "/tmp/../run"] -@pytest.mark.parametrize("path", FORBIDDEN) -def test_ro_paths_reject_host_secrets(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - with pytest.raises(config.ConfigError, match="must not expose"): - config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("path", ["/home/me/.local/bin", "/opt/tool", "/tmp/x"]) -def test_ro_paths_accept_explicit_subpaths(tmp_path, path): - text = f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n' - assert config.load(write(tmp_path, text)).sandbox_ro == (path,) +@pytest.mark.parametrize("path,allowed", [ + *((path, False) for path in FORBIDDEN), + *((path, True) for path in ("/home/me/.local/bin", "/opt/tool", "/tmp/x")), +]) +def test_ro_path_boundary(tmp_path, path, allowed): + cfg = write(tmp_path, f'[repo]\nname = "o/n"\n[checks]\nro_paths = ["{path}"]\n') + if allowed: + assert config.load(cfg).sandbox_ro == (path,) + else: + with pytest.raises(config.ConfigError, match="must not expose"): + config.load(cfg) def test_check_inputs(tmp_path): @@ -180,24 +183,9 @@ def test_check_inputs(tmp_path): config.load(write(tmp_path, FULL + '\n[checks.inputs]\n"uv run pytest -q" = "src"\n')) -def test_check_inputs_reject_unmatched_command(tmp_path): - text = '[repo]\nname = "o/n"\n[checks]\ncommands = ["echo ok"]\n' - text += '[checks.inputs]\n"echo okay" = ["."]\n' - with pytest.raises(config.ConfigError, match=r'checks\.inputs\."echo okay".*exact'): - config.load(write(tmp_path, text)) - - @pytest.mark.parametrize("strategy", ["", 'merge = "squash"\n', 'merge = "queue"\n']) def test_mergify_queue_rejects_other_strategies(tmp_path, strategy): selected = "queue" if "queue" in strategy else "squash" text = '[repo]\nname = "o/n"\n[delivery]\n' + strategy + 'mergify_queue = "main"\n' with pytest.raises(config.ConfigError, match=rf"delivery\.mergify_queue.*delivery\.merge.*{selected}"): config.load(write(tmp_path, text)) - - -@pytest.mark.parametrize("limit", ["file_mb", "memory_mb"]) -def test_delegated_runner_rejects_local_limit_overrides(tmp_path, limit): - text = '[repo]\nname = "o/n"\n[checks]\nrunner = ["runner"]\ncommands = ["true"]\n' - text += f"[checks.limits]\n{limit} = 1\n" - with pytest.raises(config.ConfigError, match=rf"checks\.limits\.{limit}.*local"): - config.load(write(tmp_path, text)) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 518c6002..ff3b70e0 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -13,16 +13,8 @@ from loopzero import mergify -class Response(io.BytesIO): - def __enter__(self): - return self - - def __exit__(self, *_args): - self.close() - - -def response(payload: object) -> Response: - return Response(json.dumps(payload).encode()) +def response(payload: object) -> io.BytesIO: + return io.BytesIO(json.dumps(payload).encode()) def test_membership_uses_bearer_and_validates_queue(monkeypatch): @@ -86,7 +78,7 @@ def queue_api(monkeypatch): {"batches": [], "mode": "serial"} if suffix.startswith("/merge-queue/status") else {"configuration": [{"name": "main", "config": {"allow_inplace_checks": True}}]} )) - def github_config(text, *, default="main", changed=False): + def github_config(text, *, default="main", changed=False, file_overrides=None): reads = 0 def get(path): nonlocal reads @@ -95,7 +87,7 @@ def get(path): assert path == "repos/acme/widgets/contents/.mergify.yml?ref=refs%2Fheads%2Fmain" reads += 1 return {"type": "file", "encoding": "base64", "sha": str(reads if changed else 1)*40, - "content": base64.b64encode(text.encode()).decode()} + "content": base64.b64encode(text.encode()).decode(), **(file_overrides or {})} monkeypatch.setattr(mergify.github, "api_get", get) return github_config @@ -104,13 +96,7 @@ def get(path): ONE_CHECK = SAFE_CONFIG.replace("checks: 3", "checks: 1") # in place unless batches are explicit -@pytest.mark.parametrize("text", [SAFE_CONFIG, ONE_CHECK.replace("main}", "main, batch_size: 8}")]) -def test_configured_accepts_documented_speculation_despite_raw_inplace_default(queue_api, text): - queue_api(text) - assert mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("text", [ +UNSAFE_CONFIGS = [ SAFE_CONFIG.replace("checks: 3", f"checks: {value}") for value in ["1", "0", "-1", "true", '"3"', "null"] ] + [ @@ -120,16 +106,22 @@ def test_configured_accepts_documented_speculation_despite_raw_inplace_default(q SAFE_CONFIG + "merge_queue: {max_parallel_checks: 1}\n", "[]", "!!python/object:object {}", "merge_queue: [", ] + [ONE_CHECK.replace("main}", r) for r in ["main, batch_size: 1}", "main, batch_size: true}", - 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]]) -def test_configured_rejects_unsafe_or_ambiguous_canonical_config(queue_api, text): - queue_api(text) - assert not mergify.configured("acme/widgets", "main", "main") - - -@pytest.mark.parametrize("options", [{"default": "other"}, {"changed": True}]) -def test_configured_rejects_wrong_default_branch_or_config_change(queue_api, options): - queue_api(SAFE_CONFIG, **options) - assert not mergify.configured("acme/widgets", "main", "main") + 'main, batch_size: "8"}', "main, batch_size: null}", "main}, {name: o, batch_size: 8}"]] + + +@pytest.mark.parametrize("text,options,accepted", [ + (SAFE_CONFIG, {}, True), + (ONE_CHECK.replace("main}", "main, batch_size: 8}"), {}, True), + *((text, {}, False) for text in UNSAFE_CONFIGS), + (SAFE_CONFIG, {"default": "other"}, False), + (SAFE_CONFIG, {"changed": True}, False), + *((SAFE_CONFIG, {"file_overrides": {key: value}}, False) + for key, value in (("encoding", "none"), ("type", "symlink"), ("sha", None), + ("sha", "z" * 40), ("content", None), ("content", "!"))), +]) +def test_configured_validates_canonical_github_config(queue_api, text, options, accepted): + queue_api(text, **options) + assert mergify.configured("acme/widgets", "main", "main") == accepted def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch): @@ -138,20 +130,6 @@ def test_configured_still_requires_vendor_queue_identity(queue_api, monkeypatch) assert not mergify.configured("acme/widgets", "main", "main") -@pytest.mark.parametrize("field,value", [("encoding", "none"), ("type", "symlink"), - ("sha", None), ("sha", "z"*40), ("content", None), ("content", "!")]) -def test_configured_rejects_malformed_github_file(queue_api, monkeypatch, field, value): - queue_api(SAFE_CONFIG) - original = mergify.github.api_get - def malformed(path): - data = original(path) - if "/contents/" in path: - data[field] = value - return data - monkeypatch.setattr(mergify.github, "api_get", malformed) - assert not mergify.configured("acme/widgets", "main", "main") - - def test_legacy_false_does_not_license_single_check_source_updates(queue_api, monkeypatch): queue_api(SAFE_CONFIG.replace("checks: 3", "checks: 1")) monkeypatch.setattr(mergify, "api_get", lambda _repo, suffix: ( diff --git a/tests/test_sandbox.py b/tests/test_sandbox.py index a21e2783..355fc0fb 100644 --- a/tests/test_sandbox.py +++ b/tests/test_sandbox.py @@ -15,6 +15,7 @@ from dataclasses import replace from pathlib import Path from select import select +from threading import Event, current_thread from unittest.mock import Mock import pytest @@ -512,15 +513,32 @@ def _pairs(argv: list[str], flag: str) -> list[tuple[str, str]]: return [(argv[i + 1], argv[i + 2]) for i, a in enumerate(argv) if a == flag] +@pytest.fixture +def heartbeat_log(monkeypatch): + monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) + observed, events, reporters = Event(), [], set() + + def status(message): + events.append(message) + if ": running " in message: + reporters.add(current_thread()) + observed.set() + else: + assert reporters and all(not reporter.is_alive() for reporter in reporters) + + def wait(): + assert observed.wait(5), "no running heartbeat" + + return events, reporters, status, wait + + @pytest.mark.parametrize("exit_code", [0, 7]) def test_silent_stage_reports_live_metadata_then_completion( - git_repo, bwrap_log, monkeypatch, exit_code + git_repo, bwrap_log, monkeypatch, heartbeat_log, exit_code ): import re - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], set() + events, _, status, wait_for_heartbeat = heartbeat_log monkeypatch.setenv("LZ_KEEP", "credential-value") command = f'echo "$LZ_KEEP"; echo private-stderr >&2; exit {exit_code}' cfg = make_config(checks=(command, "echo next")) @@ -528,17 +546,9 @@ def test_silent_stage_reports_live_metadata_then_completion( def run_stage(config, worktree, prefix, stage_command, timeout): if stage_command == command: - assert observed.wait(5), "no running heartbeat for first stage" + wait_for_heartbeat() return run_one(config, worktree, prefix, stage_command, timeout) - def status(event): - events.append(event) - if "running" in event: - reporters.add(threading.current_thread()) - observed.set() - else: - assert all(not reporter.is_alive() for reporter in reporters) - monkeypatch.setattr(sandbox, "_run_one", run_stage) report = sandbox.run_checks(cfg, git_repo, progress=events.append, status=status) assert report.results[0].exit_code == exit_code @@ -574,23 +584,8 @@ def test_early_failure_reports_actual_exit_without_heartbeat(git_repo, bwrap_log assert not report.ok -def test_timeout_stops_heartbeat_and_retains_failure_tail(git_repo, bwrap_log, monkeypatch): - import threading - - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def status(message): - events.append(message) - if message.startswith("stage 1/2: running"): - reporters.append(threading.current_thread()) - observed.set() - else: - assert reporters and all(not reporter.is_alive() for reporter in reporters) - - def wait_for_heartbeat(): - assert observed.wait(5), "no running heartbeat before timeout" - +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, @@ -603,22 +598,14 @@ def wait_for_heartbeat(): assert report.results[0].tail == "private\n\n[loopzero] timed out after 0.2s" -def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch): - import threading - monkeypatch.setattr(sandbox, "HEARTBEAT_INTERVAL", 0.03) - observed, events, reporters = threading.Event(), [], [] - - def heartbeat(message): - events.append(message) - reporters.append(threading.current_thread()) - observed.set() - +def test_cancellation_stops_heartbeat_without_reporting_verdict(git_repo, bwrap_log, monkeypatch, heartbeat_log): + events, reporters, status, wait_for_heartbeat = heartbeat_log def cancel(*args): - assert observed.wait(5), "no running heartbeat before cancellation" + wait_for_heartbeat() raise KeyboardInterrupt monkeypatch.setattr(sandbox, "_run_one", cancel) with pytest.raises(KeyboardInterrupt): - sandbox.run_checks(make_config(), git_repo, status=heartbeat) + sandbox.run_checks(make_config(), git_repo, status=status) assert events and all("running" in event for event in events) assert all(not reporter.is_alive() for reporter in reporters) @@ -635,34 +622,28 @@ def test_sigterm_cleans_only_the_cancelled_checks_private_directories( from tests.test_sandbox import _save_report, make_config, sandbox mode = sys.argv[1] -if mode == "creation": - mkdtemp = tempfile.mkdtemp +def interrupt(): + print(mode, flush=True) + signal.raise_signal(signal.SIGTERM) - def create(*args, **kwargs): - path = mkdtemp(*args, **kwargs) - print("creation", flush=True) - signal.raise_signal(signal.SIGTERM) - return path +def interrupt_after(call): + def wrapped(*args, **kwargs): + result = call(*args, **kwargs) + interrupt() + return result + return wrapped - tempfile.mkdtemp = create - -if mode == "removal": +if mode == "creation": + tempfile.mkdtemp = interrupt_after(tempfile.mkdtemp) +elif mode == "removal": rmtree = shutil.rmtree - def remove(path, **kwargs): - print("removal", flush=True) - signal.raise_signal(signal.SIGTERM) + interrupt() rmtree(path, **kwargs) - shutil.rmtree = remove - -if mode == "dispatch": +elif mode == "dispatch": class Callbacks(deque): - def pop(self): - callback = super().pop() - print("dispatch", flush=True) - signal.raise_signal(signal.SIGTERM) - return callback + pop = interrupt_after(deque.pop) class Stack(ExitStack): def __init__(self): @@ -720,6 +701,25 @@ def fetched_base(git_repo): return head +@pytest.fixture +def cache_check(git_repo): + exclude = git_repo / ".git/info/exclude" + with exclude.open("a") as stream: + stream.write("\n.loopzero/\n") + + def cache(config, *, clean=False, verify_reuse=False): + report = sandbox.run_checks(config, git_repo) + assert report.ok + if clean: + assert not report.dirty + _save_report(git_repo, report) + if verify_reuse: + assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head + return report + + return cache + + @pytest.mark.parametrize('change', ['other', 'input', 'shared', 'command', 'network', 'environment', 'version', 'failed', 'boolean_exit_code', 'dirty_receipt', 'keyless', 'dirty_tree', 'legacy']) @@ -772,14 +772,11 @@ def test_declared_input_reuse(git_repo, bwrap_log, monkeypatch, fetched_base, ch @pytest.mark.parametrize("case", ["typo", "empty", "dirty", "no_base"]) -def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_unmatched_inputs_run_fresh(git_repo, bwrap_log, fetched_base, case, cache_check): command = 'test "$(cat README.md)" = hello' paths = () if case == "empty" else ("ipnut.txt",) config = make_config(checks=(command,), inputs={command: paths}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) (git_repo / "README.md").write_text("fail\n") if case != "dirty": git(git_repo, "commit", "-qam", "change actual input") @@ -808,16 +805,12 @@ def timed_out(*args): assert report.ok and report.dirty and report.results[0].command == command -def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_check_reuse_tracks_checkout_bytes(git_repo, bwrap_log, fetched_base, cache_check): path = git_repo / "README.md" command = "python3 -c 'from pathlib import Path; exit(13 in Path(\"README.md\").read_bytes())'" config = make_config(checks=(command,), inputs={command: ("README.md",)}) assert path.read_bytes() == b"hello\n" - report = sandbox.run_checks(config, git_repo) - assert report.ok and not report.dirty - _save_report(git_repo, report) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert cache_check(config, clean=True, verify_reuse=True).head == fetched_base git(git_repo, "config", "core.autocrlf", "true") path.unlink() @@ -877,15 +870,12 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe @pytest.mark.parametrize("error", [errno.E2BIG, errno.ENOENT]) -def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error): +def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkeypatch, error, cache_check): command = "echo stage ran" config = make_config(checks=(command,), inputs={command: ("README.md",)}) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") - original = sandbox.run_checks(config, git_repo) - assert original.ok and not original.dirty + original = cache_check(config, clean=True, verify_reuse=True) assert original.results[0].input_key - _save_report(git_repo, original) - assert sandbox.run_checks(config, git_repo).results[0].reused_from == fetched_base + assert original.head == fetched_base run = sandbox._proc.run @@ -912,12 +902,9 @@ def fail_fingerprint(argv, **kwargs): assert saved.get("input_key") is None and saved.get("reused_from") is None -def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log): - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") +def test_local_checks_run_fresh_without_a_base(git_repo, bwrap_log, cache_check): config = make_config(inputs={"*": (".",)}) - first = sandbox.run_checks(config, git_repo) - assert first.ok - _save_report(git_repo, first) + cache_check(config) second = sandbox.run_checks(config, git_repo) assert second.ok @@ -984,7 +971,7 @@ def test_receipt_settings_distinguish_runner_paths(git_repo, monkeypatch, tmp_pa @pytest.mark.parametrize("change", ["target", "content"]) -def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change): +def test_runner_upgrade_invalidates_pass(git_repo, fetched_base, tmp_path, change, cache_check): def write_runner(path, exit_code): path.write_text( f"#!{sys.executable}\n" @@ -996,15 +983,12 @@ def write_runner(path, exit_code): ) path.chmod(0o755) - (git_repo / ".git/info/exclude").write_text(".loopzero/\n") runner = tmp_path / "runner" original = tmp_path / "runner-a" write_runner(original, 0) runner.symlink_to(original) config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) - report = sandbox.run_checks(config, git_repo) - assert report.ok - _save_report(git_repo, report) + report = cache_check(config) assert _current_check_report(git_repo, config, report.head) assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head diff --git a/tests/test_stage_runner.py b/tests/test_stage_runner.py index 17491193..95fca594 100644 --- a/tests/test_stage_runner.py +++ b/tests/test_stage_runner.py @@ -9,7 +9,7 @@ from loopzero.config import ConfigError, load from .conftest import git -from .test_sandbox import bwrap_log, make_config # noqa: F401 +from .test_sandbox import bwrap_log, fetched_base, make_config # noqa: F401 @pytest.mark.parametrize('base_ref', ['stale', 'missing', 'recorded']) @@ -85,14 +85,18 @@ 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): +def test_runner_unavailable(git_repo, monkeypatch, dirty, fetched_base): # noqa: F811 if dirty: (git_repo / 'dirty').write_text('x') - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') monkeypatch.setattr(sandbox.shutil, 'which', lambda name: None) - prefix = (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))') - report = sandbox.run_checks(make_config(check_runner=prefix), git_repo) + report = sandbox.run_checks(make_config(check_runner=FALLBACK_RUNNER), git_repo) assert not report.ok and report.dirty is dirty assert ('bwrap binary missing' in report.results[0].tail) is not dirty @@ -147,8 +151,7 @@ def test_runner_preserves_executable_symlink(git_repo, tmp_path, monkeypatch, ba assert report.ok, report.results[0].tail -def test_runner_timeout(git_repo, monkeypatch): - git(git_repo, 'update-ref', 'refs/remotes/origin/main', 'HEAD') +def test_runner_timeout(git_repo, monkeypatch, fetched_base): # noqa: F811 original = sandbox._proc.run def run(argv, **kwargs): if argv[0] == sys.executable: @@ -163,21 +166,17 @@ def run(argv, **kwargs): @pytest.mark.parametrize('change', ['fallback', 'base']) -def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, change): # noqa: F811 +def test_runner_reuse_binds_execution_context(git_repo, bwrap_log, fetched_base, change): # noqa: F811 from dataclasses import replace (git_repo / '.git/info/exclude').write_text('.loopzero/\n') - base = git(git_repo, 'rev-parse', 'HEAD').strip() - git(git_repo, 'update-ref', 'refs/remotes/origin/main', base) command = 'echo stage-ran; exit 7' if change == 'fallback' else 'echo one' cfg = make_config(checks=(command,), inputs={command: ('README.md',)}) - body = ('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))') - runner = (sys.executable, '-c', body) + runner = FALLBACK_RUNNER if change == 'fallback': passing = sandbox.run_checks(replace(cfg, checks=('echo seed',)), git_repo) result = replace(passing.results[0], command=command, - input_key=sandbox._input_key(cfg, git_repo, command, base)) + input_key=sandbox._input_key(cfg, git_repo, command, fetched_base)) _save_report(git_repo, replace(passing, results=(result,))) else: cfg = replace(cfg, check_runner=runner)