Repository navigation
Share more sandbox and Mergify candidate test assertions #1900
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ | |
| from itertools import cycle | ||
| from os import environ | ||
| from shutil import copytree | ||
| from unittest.mock import Mock | ||
|
|
||
| import pytest | ||
|
|
||
|
|
@@ -125,10 +126,8 @@ def run_attestation( | |
| run=attest_candidate, | ||
| ): | ||
| candidate_event = candidate_event or event() | ||
| reads, values = ( | ||
| cycle(status_reads or [status()]), | ||
| github_payloads or payloads(candidate_event), | ||
| ) | ||
| reads = cycle(status_reads or [status()]) | ||
| values = github_payloads or payloads(candidate_event) | ||
| return run( | ||
| candidate_event, | ||
| github_get=github_get or (lambda path: deepcopy(values[path])), | ||
|
|
@@ -158,10 +157,9 @@ def test_attests_nested_candidate_and_transitive_parent_sources() -> None: | |
| ) | ||
| def test_rejects_forged_bot_or_prefix(mutation, message: str) -> None: | ||
| candidate_event = event() | ||
| original_payloads = payloads(candidate_event) | ||
| mutation(candidate_event) | ||
| with pytest.raises(CandidateError, match=message): | ||
| run_attestation(candidate_event=candidate_event, github_payloads=original_payloads) | ||
| run_attestation(candidate_event=candidate_event, github_payloads=payloads(event())) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("case,diagnostic", [ | ||
|
|
@@ -243,8 +241,21 @@ def commit(name, content): | |
| return git("rev-parse", "HEAD") | ||
|
|
||
| popen = subprocess.Popen | ||
| observed_transport = set() | ||
|
|
||
| def isolated_fetch(argv, **kwargs): | ||
| if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080" and "git" in argv: | ||
| env = kwargs["env"] | ||
| transport = {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} | ||
| if "fetch" in argv: | ||
| observed_transport.add("fetch") | ||
| assert env["HTTPS_PROXY"] == environ["HTTPS_PROXY"] | ||
| assert (env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"]) == ("1", "http.extraHeader") | ||
| header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ") | ||
| assert base64.b64decode(header) == b"x-access-token:secret-token" | ||
| else: | ||
| observed_transport.add("plumbing") | ||
| assert not transport & env.keys() | ||
| assert not any(arg.startswith("--as") for arg in argv) # arm64 Git exceeds RLIMIT_AS | ||
| if "fetch" in argv: | ||
| assert "https://github.com/owner/repo.git" in argv | ||
|
|
@@ -294,47 +305,24 @@ def get(path): | |
|
|
||
| if base_branch != "main": | ||
| run = partial(run, base_branch=base_branch) | ||
| return run_attestation(candidate_event, github_get=get, status_reads=[queue], | ||
| source_policy=policy, run=run) | ||
| sources = run_attestation(candidate_event, github_get=get, status_reads=[queue], | ||
| source_policy=policy, run=run) | ||
| if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080": | ||
| assert observed_transport == {"fetch", "plumbing"} | ||
| return sources | ||
|
|
||
| return attest, git, commit, base, parent, source, candidate_sha | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("base_branch", ["main", "trunk"]) | ||
| def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch): | ||
| def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch, monkeypatch): | ||
| monkeypatch.setenv("HTTPS_PROXY", "http://proxy.invalid:8080") | ||
| attest, _, _, _, _, source, _ = tree_candidate | ||
| seen = [] | ||
| assert attest(base_branch=base_branch, policy=lambda n, _: seen.append(n)) == expected_sources((102, source)) | ||
| assert seen == [102] | ||
|
|
||
|
|
||
| def test_candidate_transport_configuration_is_scoped_to_fetch(tree_candidate, monkeypatch): | ||
| attest, _, _, _, _, source, _ = tree_candidate | ||
| popen = subprocess.Popen | ||
| seen = set() | ||
| proxy = "http://proxy.invalid:8080" | ||
| monkeypatch.setenv("HTTPS_PROXY", proxy) | ||
|
|
||
| def check_environment(argv, **kwargs): | ||
| if "git" in argv: | ||
| env = kwargs["env"] | ||
| if "fetch" in argv: | ||
| seen.add("fetch") | ||
| assert env["HTTPS_PROXY"] == proxy | ||
| assert env["GIT_CONFIG_COUNT"] == "1" | ||
| assert env["GIT_CONFIG_KEY_0"] == "http.extraHeader" | ||
| header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ") | ||
| assert base64.b64decode(header) == b"x-access-token:secret-token" | ||
| else: | ||
| seen.add("non-fetch") | ||
| assert not {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} & env.keys() | ||
| return popen(argv, **kwargs) | ||
|
|
||
| monkeypatch.setattr(subprocess, "Popen", check_environment) | ||
| assert attest() == expected_sources((102, source)) | ||
| assert seen == {"fetch", "non-fetch"} | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("mutation,diagnostic", [ | ||
| ("replaced", "tree mismatch"), ("withdrawn", "tree mismatch"), ("extra", "tree mismatch|objects unavailable"), | ||
| ("tampered", "tree mismatch"), ("missing", "objects unavailable"), | ||
|
|
@@ -403,10 +391,7 @@ def run(event, *, github_get, mergify_status, source_policy): | |
|
|
||
| @pytest.fixture(params=["loopzero", "intelflo"]) | ||
| def candidate_policy(request): | ||
|
|
||
| if request.param == "intelflo": | ||
| return request.getfixturevalue("intelflo_policy") | ||
| return candidate, attest_candidate | ||
| return request.getfixturevalue("intelflo_policy") if request.param == "intelflo" else (candidate, attest_candidate) | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("case", [ | ||
|
|
@@ -566,10 +551,7 @@ def test_nonrace_failure_does_not_retry(monkeypatch, failure, reread): | |
| live["batches"].pop(0) | ||
| values["/repos/owner/repo/git/ref/heads/main"] = {"object": {"sha": "b" * 40}} | ||
|
|
||
| def mismatch(*_): | ||
| raise CandidateError("candidate tree mismatch") | ||
|
|
||
| monkeypatch.setattr(candidate, "_verify_tree", mismatch) | ||
| monkeypatch.setattr(candidate, "_verify_tree", Mock(side_effect=CandidateError("candidate tree mismatch"))) | ||
|
|
||
| def get(path): | ||
| if path == "/apps/mergify": | ||
|
|
@@ -583,10 +565,7 @@ def get(path): | |
| return deepcopy(reread) | ||
| return result | ||
|
|
||
| def policy(*_): | ||
| if failure == "policy": | ||
| raise expected | ||
|
|
||
| policy = Mock(side_effect=expected if failure == "policy" else None) | ||
| monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append) | ||
| with pytest.raises(CandidateError) as caught: | ||
| run_attestation(github_get=get, status_reads=[live], source_policy=policy) | ||
|
|
@@ -651,9 +630,8 @@ def read_status(*_): | |
| or (stop == "changed" and len(reads) >= 6) | ||
| ) else ambiguous | ||
| monkeypatch.setattr(candidate, "_retry_sleep", sleep) | ||
| def run(): | ||
| return run_attestation(github_payloads=values, mergify_status=read_status, | ||
| source_policy=lambda n, _: seen.append(n)) | ||
| run = partial(run_attestation, github_payloads=values, mergify_status=read_status, | ||
| source_policy=lambda n, _: seen.append(n)) | ||
| if stop in {"settled", "changed"}: | ||
| assert run() == expected_sources((101, "1" * 40), (102, "2" * 40)) | ||
| assert seen == [101, 102] * (2 if stop == "changed" and second else 1) | ||
|
|
@@ -695,10 +673,8 @@ def wait(self, timeout=None): | |
|
|
||
| error = pytest.raises(github.GhUnavailable, match="temporarily unavailable") if outcome == "fetch" else nullcontext() | ||
| with error, candidate.fetched_git("owner/repo", []) as git: | ||
| if outcome == "bound": | ||
| with pytest.raises(CandidateError, match="Git object/size bound exceeded"): | ||
| git("test-command") | ||
| else: | ||
| bound = pytest.raises(CandidateError, match="Git object/size bound exceeded") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Build the
|
||
| with bound if outcome == "bound" else nullcontext(): | ||
| assert git("test-command") == "" | ||
|
|
||
| assert waits == {"bound": [0.02, None], "normal": [0.02], "fetch": []}[outcome] | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -148,11 +148,15 @@ def test_check_pipeline_verdict(git_repo, bwrap_log, monkeypatch, capsys, comman | |
| assert capsys.readouterr().out.splitlines()[-1] == ("FAIL" if stage_exit else "PASS") | ||
|
|
||
|
|
||
| def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): | ||
| @pytest.mark.parametrize("limited", [False, True], ids=["default", "constrained"]) | ||
| def test_bwrap_flags(git_repo, bwrap_log, monkeypatch, limited): | ||
| options = {"limits": ResourceLimits(memory_mb=64, file_mb=3)} if limited else {} | ||
| if limited: | ||
| monkeypatch.setattr(resource, "getrlimit", lambda _: (0, 32 * 1024 * 1024)) | ||
| monkeypatch.setenv("LZ_KEEP", "kept") | ||
| monkeypatch.setenv("LZ_DROP", "dropped") | ||
| values = 'printf "%s\\n" "$PATH" "$LZ_KEEP" "${LZ_DROP-unset}" "$UV_CACHE_DIR" "$PYTHONDONTWRITEBYTECODE"' | ||
| (result,) = sandbox.run_checks(make_config(checks=(values,)), git_repo).results | ||
| (result,) = sandbox.run_checks(make_config(checks=(values,), **options), git_repo).results | ||
| argv = argv_of(bwrap_log) | ||
| head, tail = argv[: argv.index("--")], argv[argv.index("--") + 1 :] | ||
| for flag in ("--die-with-parent", "--new-session", "--unshare-all", "--clearenv"): | ||
|
|
@@ -183,9 +187,11 @@ def test_bwrap_flags(git_repo, bwrap_log, monkeypatch): | |
| assert sandbox.run_checks(make_config(), git_repo).dirty is False | ||
| # /tmp tmpfs comes before the worktree bind so a worktree under /tmp stays visible. | ||
| assert head.index("--tmpfs") < head.index(str(git_repo)) | ||
| assert tail == ["prlimit", f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", | ||
| f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", | ||
| "--", *sandbox.CHECK_SHELL, values] | ||
| limits = ["--as=33554432", "--fsize=3145728"] if limited else [ | ||
| f"--as={sandbox._cap_limit(4096 << 20, resource.RLIMIT_AS)}", | ||
| f"--fsize={sandbox._cap_limit(2048 << 20, resource.RLIMIT_FSIZE)}", | ||
| ] | ||
| assert tail == ["prlimit", *limits, "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", values] | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("checks", [(), ("echo hello",)], ids=["probe", "stage"]) | ||
|
|
@@ -272,17 +278,6 @@ def test_timeout_is_recorded_with_drained_output(git_repo, bwrap_log): | |
| assert len(result.tail.encode()) == 16 * 1024 | ||
|
|
||
|
|
||
| def test_configured_resource_limits_are_converted_to_bytes(git_repo, bwrap_log, monkeypatch): | ||
| limits = ResourceLimits(memory_mb=64, file_mb=3) | ||
| monkeypatch.setattr(resource, "getrlimit", lambda _: (0, 32 * 1024 * 1024)) | ||
| sandbox.run_checks(make_config(limits=limits), git_repo) | ||
| argv = argv_of(bwrap_log) | ||
| assert argv[argv.index("--") + 1:] == [ | ||
| "prlimit", "--as=33554432", "--fsize=3145728", | ||
| "--", "/bin/bash", "--posix", "-o", "pipefail", "-c", "echo hello", | ||
| ] | ||
|
|
||
|
|
||
| def test_linked_worktree_binds_common_git_dir(git_repo, bwrap_log, tmp_path): | ||
| linked = tmp_path / "linked" | ||
| git(git_repo, "worktree", "add", "-q", str(linked), "-b", "feature") | ||
|
|
@@ -323,10 +318,7 @@ def test_bwrap_missing_or_probe_failure(git_repo, fake_bin, fake_tool, monkeypat | |
|
|
||
|
|
||
| def test_probe_timeout_reports_only_the_timeout(git_repo, monkeypatch): | ||
| def timed_out(*args, **kwargs): | ||
| raise sandbox._proc.ProcTimeout("private probe diagnostic") | ||
|
|
||
| monkeypatch.setattr(sandbox._proc, "run", timed_out) | ||
| monkeypatch.setattr(sandbox._proc, "run", Mock(side_effect=sandbox._proc.ProcTimeout("private probe diagnostic"))) | ||
| with pytest.raises(sandbox.SandboxUnavailable) as info: | ||
| sandbox.probe(make_config(), git_repo, ["bwrap", "--"]) | ||
|
|
||
|
|
@@ -428,10 +420,8 @@ def test_real_sandbox_denies_writes(self, git_repo): | |
| report = sandbox.run_checks(make_config(checks=(command,)), git_repo) | ||
| assert report.results[0].exit_code != 0, report | ||
| assert not escaped.exists() | ||
| checks = ( | ||
| "echo x > \"$HOME/ok\" && cat \"$HOME/ok\" && test ! -e /tmp/repo", | ||
| "test \"$(pwd)\" = \"$PWD\" && env | grep -c '^LZ_' ; true", | ||
| ) | ||
| checks = ('echo x > "$HOME/ok" && cat "$HOME/ok" && test ! -e /tmp/repo', | ||
| 'test "$(pwd)" = "$PWD" && env | grep -c "^LZ_" ; true') | ||
| report = sandbox.run_checks(make_config(checks=checks), git_repo) | ||
| assert [r.exit_code for r in report.results] == [0, 0], report | ||
|
|
||
|
|
@@ -814,10 +804,7 @@ def test_input_diagnostic_failure_does_not_block_dirty_check( | |
| git_repo, bwrap_log, fetched_base, monkeypatch, path, | ||
| ): | ||
| if path == "README.md": | ||
| def timed_out(*args): | ||
| raise sandbox._proc.ProcTimeout("input lookup timed out") | ||
|
|
||
| monkeypatch.setattr(sandbox, "_input_blobs", timed_out) | ||
| monkeypatch.setattr(sandbox, "_input_blobs", Mock(side_effect=sandbox._proc.ProcTimeout("input lookup timed out"))) | ||
| (git_repo / "README.md").write_text("dirty\n") | ||
| command = 'test "$(cat README.md)" = dirty' | ||
| config = make_config(checks=(command,), inputs={command: (path,)}) | ||
|
|
@@ -872,7 +859,6 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe | |
| command = f"echo '{marker}'" | ||
| config = make_config(checks=(command,), inputs={command: ("README.md",)}) | ||
| original = sandbox.run_checks(config, git_repo) | ||
| assert original.ok | ||
| legacy = replace(original.results[0], tail=f"{'x' * 20_000}\n{marker}") | ||
| _save_report(git_repo, replace(original, results=(legacy,))) | ||
|
|
||
|
|
@@ -882,7 +868,7 @@ def test_reused_check_preserves_integration_shard_output(git_repo, bwrap_log, fe | |
| receipt = json.loads(receipt_path.read_text()) | ||
| assert receipt["head"] == git(git_repo, "rev-parse", "HEAD").strip() | ||
| [result] = receipt["results"] | ||
| assert result["reused_from"] == original.head | ||
| assert original.ok and result["reused_from"] == original.head | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. suggestion: Moving |
||
| assert marker in result["tail"].splitlines() | ||
| assert len(result["tail"].encode("utf-8")) <= 16 * 1024 | ||
|
|
||
|
|
@@ -892,8 +878,7 @@ def test_cache_fingerprint_spawn_error(git_repo, bwrap_log, fetched_base, monkey | |
| command = "echo stage ran" | ||
| config = make_config(checks=(command,), inputs={command: ("README.md",)}) | ||
| original = cache_check(config, clean=True, verify_reuse=True) | ||
| assert original.results[0].input_key | ||
| assert original.head == fetched_base | ||
| assert original.results[0].input_key and original.head == fetched_base | ||
|
|
||
| run = sandbox._proc.run | ||
|
|
||
|
|
@@ -980,9 +965,8 @@ def write_runner(path, exit_code): | |
| write_runner(original, 0) | ||
| runner.symlink_to(original) | ||
| config = make_config(check_runner=(str(runner),), inputs={"echo hello": (".",)}) | ||
| report = cache_check(config) | ||
| report = cache_check(config, verify_reuse=True) | ||
| assert _current_check_report(git_repo, config, report.head) | ||
| assert sandbox.run_checks(config, git_repo).results[0].reused_from == report.head | ||
|
|
||
| if change == "target": | ||
| replacement = tmp_path / "runner-b" | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: Transport-scope check depends on a hard-coded proxy value that only one test sets
The
tree_candidatefixture checks fetch and plumbing environments only whenenviron["HTTPS_PROXY"]is exactlyhttp://proxy.invalid:8080. It checksobserved_transportat line 310 only under the same condition. The value is spelled out in three places, and onlytest_vanished_squash_parent_passes_real_tree_attestationsets it. If someone later changes or removes thatsetenvline, the auth-header and proxy-scope check is skipped without any failure. The removed standalone test failed loudly in that case. The logic is correct today for bothmainandtrunk. Smallest fix: define a module constant such asPROXY = "http://proxy.invalid:8080". Then either letattest(..., check_transport=True)set it with monkeypatch, or have the vanished test also assertobserved_transport == {"fetch", "plumbing"}, so the check can't vanish silently.