Skip to content
Merged
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
62 changes: 27 additions & 35 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def no_retry_delay(monkeypatch):
monkeypatch.setattr("loopzero.candidate._retry_sleep", lambda delay: clock.__setitem__(0, clock[0] + delay))


def event() -> dict:
def event(head: str = "c" * 40) -> dict:
repo = {"id": 7, "full_name": "owner/repo"}
bot = {
"id": 37929162,
Expand All @@ -49,7 +49,7 @@ def event() -> dict:
"state": "open",
"draft": True,
"user": bot,
"head": {"sha": "c" * 40, "ref": "mergify/merge-queue/batch", "repo": deepcopy(repo)},
"head": {"sha": head, "ref": "mergify/merge-queue/batch", "repo": deepcopy(repo)},
"base": {"sha": "b" * 40, "ref": "main", "repo": deepcopy(repo)},
},
}
Expand Down Expand Up @@ -80,6 +80,15 @@ def pull(number: int, sha: str) -> dict:
}


def expected_sources(*sources):
return [{"number": number, "head_sha": sha} for number, sha in sources]


def tree_commit(git, tree, *parents, subject):
parent_args = [arg for parent in parents for arg in ("-p", parent)]
return git("commit-tree", f"{tree}^{{tree}}", *parent_args, "-m", subject)


def source_payloads(values, head, *sources):
for number, sha in sources:
values[f"/repos/owner/repo/pulls/{number}"] = pull(number, sha)
Expand Down Expand Up @@ -129,10 +138,8 @@ def run_attestation(

def test_attests_nested_candidate_and_transitive_parent_sources() -> None:
seen: list[int] = []
assert run_attestation(source_policy=lambda number, _source: seen.append(number)) == [
{"number": 101, "head_sha": "1" * 40},
{"number": 102, "head_sha": "2" * 40},
]
sources = run_attestation(source_policy=lambda number, _: seen.append(number))
assert sources == expected_sources((101, "1" * 40), (102, "2" * 40))
assert seen == [101, 102]


Expand Down Expand Up @@ -259,8 +266,7 @@ def attest(
main_after=None, extra_source=None, lineage="vanished", run=attest_candidate,
held_source=None,
):
candidate_event = event()
candidate_event["pull_request"]["head"]["sha"] = head
candidate_event = event(head)
values = payloads(candidate_event)
source_payloads(values, head, (102, source))
queue = status()
Expand Down Expand Up @@ -296,7 +302,7 @@ def get(path):
def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate):
attest, _, _, _, _, source, _ = tree_candidate
seen = []
assert attest(policy=lambda n, _: seen.append(n)) == [{"number": 102, "head_sha": source}]
assert attest(policy=lambda n, _: seen.append(n)) == expected_sources((102, source))
assert seen == [102]


Expand All @@ -323,7 +329,7 @@ def check_environment(argv, **kwargs):
return popen(argv, **kwargs)

monkeypatch.setattr(subprocess, "Popen", check_environment)
assert attest() == [{"number": 102, "head_sha": source}]
assert attest() == expected_sources((102, source))
assert seen == {"fetch", "non-fetch"}


Expand All @@ -343,8 +349,7 @@ def test_vanished_parent_rejects_unauthorized_trees(tree_candidate, mutation):
if mutation == "tampered":
# A forged resolution retains the exact original merge parents.
parents = git("show", "-s", "--format=%P", candidate_sha).split()
changed = git("commit-tree", git("rev-parse", f"{changed}^{{tree}}"),
"-p", parents[0], "-p", parents[1], "-m", "forged merge")
changed = tree_commit(git, changed, *parents, subject="forged merge")
kwargs["head"] = changed
with pytest.raises(CandidateError, match=r"Missing Mergify parent batches parent:.*"
r"(tree mismatch|objects unavailable)"):
Expand All @@ -367,8 +372,7 @@ def test_vanished_parent_rejects_main_change(tree_candidate):

def test_vanished_parent_rejects_ambiguous_topology(tree_candidate):
attest, git, _, base, parent, source, candidate_sha = tree_candidate
head = git("commit-tree", git("rev-parse", f"{candidate_sha}^{{tree}}"),
"-p", base, "-p", parent, "-p", source, "-m", "octopus")
head = tree_commit(git, candidate_sha, base, parent, source, subject="octopus")
with pytest.raises(CandidateError, match="parent: ambiguous"):
attest(head=head)

Expand Down Expand Up @@ -410,17 +414,11 @@ def test_intelflo_candidate_policy_parity(tree_candidate, candidate_policy, monk
attest, git, commit, base, parent, source, candidate_sha = tree_candidate
implementation, run = candidate_policy
if case == "single":
head = git("commit-tree", f"{source}^{{tree}}", "-p", base, "-p", source,
"-m", "single source integration")
assert attest(run=run, lineage="single", head=head, main_head=base) == [
{"number": 102, "head_sha": source},
]
head = tree_commit(git, source, base, source, subject="single source integration")
assert attest(run=run, lineage="single", head=head, main_head=base) == expected_sources((102, source))
return
if case == "stacked":
assert attest(run=run, lineage="stacked", main_head=base) == [
{"number": 101, "head_sha": parent},
{"number": 102, "head_sha": source},
]
assert attest(run=run, lineage="stacked", main_head=base) == expected_sources((101, parent), (102, source))
return

# The earlier batch has landed by squash. Both live source heads still need
Expand All @@ -431,18 +429,14 @@ def test_intelflo_candidate_policy_parity(tree_candidate, candidate_policy, monk
git("merge", "--no-ff", second, "-m", "second integration")
head = git("rev-parse", "HEAD")
if case == "combined":
assert attest(run=run, head=head, extra_source=second) == [
{"number": 101, "head_sha": second},
{"number": 102, "head_sha": source},
]
assert attest(run=run, head=head, extra_source=second) == expected_sources((101, second), (102, source))
return

kwargs = {}
if case == "mismatch":
changed = commit("injected", "unreviewed\n")
parents = git("show", "-s", "--format=%P", head).split()
head = git("commit-tree", f"{changed}^{{tree}}", "-p", parents[0], "-p", parents[1],
"-m", "forged merge")
head = tree_commit(git, changed, *parents, subject="forged merge")
diagnostic = "tree mismatch"
elif case == "incomplete":
kwargs["main_head"] = ""
Expand All @@ -451,8 +445,7 @@ def test_intelflo_candidate_policy_parity(tree_candidate, candidate_policy, monk
kwargs["main_after"] = base
diagnostic = "main changed"
elif case == "ambiguous":
head = git("commit-tree", f"{head}^{{tree}}", "-p", candidate_sha, "-p", second,
"-p", parent, "-m", "octopus")
head = tree_commit(git, head, candidate_sha, second, parent, subject="octopus")
diagnostic = "ambiguous"
else:
monkeypatch.setattr(implementation, "_TREE_OBJECTS", 1)
Expand All @@ -478,8 +471,7 @@ def test_vanished_parent_rejects_conflicting_current_main(tree_candidate):
@pytest.mark.parametrize("timing", ["metadata", "policy", "initial", TypeError, AttributeError, KeyError])
def test_predecessor_landing_restarts_complete_attestation(tree_candidate, monkeypatch, timing):
_, git, _, _, parent, source, head = tree_candidate
candidate_event = event()
candidate_event["pull_request"]["head"]["sha"] = head
candidate_event = event(head)
values = payloads(candidate_event)
source_payloads(values, head, (101, parent), (102, source))
main, vanished = git("rev-parse", "main"), status()
Expand Down Expand Up @@ -529,7 +521,7 @@ def verify_tree(repo, main_sha, candidate_sha, sources):
assert seen == [101] and source_reads == 1 and not sleeps
return
assert run_attestation(candidate_event, github_get=get, mergify_status=lineage,
source_policy=policy) == [{"number": 102, "head_sha": source}]
source_policy=policy) == expected_sources((102, 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]
Expand Down Expand Up @@ -670,7 +662,7 @@ def run():
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 run() == expected_sources((101, "1" * 40), (102, "2" * 40))
assert seen == [101, 102] * (2 if stop == "changed" and second else 1)
else:
with pytest.raises(CandidateError, match="superseded" if stop == "closed" else "not exactly one live"):
Expand Down
71 changes: 26 additions & 45 deletions tests/test_gh_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@
from tests.conftest import isolate_github_auth
from tests.test_github import (
HEAD,
PR_FILES,
REPO,
FakeGh,
gh as gh,
merge_json,
pr_json,
rest_pr_json,
threads_json,
arm_review,
arm_workflow_check,
)

REAL_GH = shutil.which("gh")
Expand Down Expand Up @@ -56,16 +56,12 @@ def captured_argv(tmp_path_factory: pytest.TempPathFactory) -> list[dict]:
fake = FakeGh(tmp_path, tmp_path)
merged = merge_json(state='MERGED', head=HEAD, sha='c' * 40)
fake.respond_pr_list([pr_json()], branch="lz/x")
fake.respond_pr_view(pr_json(), pr_json(), branch="lz/x")
fake.respond_pr_create(pr_json(), branch="lz/x")
arm_review(fake, branch="lz/x")
fake.respond_pr_view(pr_json(), branch="lz/x")
arm_workflow_check(fake)
fake.respond(f"api repos/{REPO}/pulls/7 --method PATCH", {})
fake.append(f"api repos/{REPO}/pulls/7", merged)
fake.respond("api graphql viewer", {"data": {"viewer": {"login": "bot-user"}}})
fake.respond(f"api repos/{REPO}/pulls/7/files", PR_FILES)
fake.respond(f"api repos/{REPO}/pulls/7/reviews", {"id": 1})
fake.respond("api graphql", threads_json())
fake.respond(f"api repos/{REPO}/commits/{HEAD}/check-runs", {"check_runs": []})
fake.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [])
fake.respond("pr ready", "")
fake.respond("pr merge", "")
fake.fail(f"api repos/{REPO}/git/ref/heads/lz/x", "gh: Not Found (HTTP 404)")
Expand Down Expand Up @@ -134,40 +130,35 @@ def test_contract_capture_covers_operations_with_rest_metadata(captured_argv: li
assert any("?state=open&head=acme%3Alz%2Fx" in argv[1] for argv in calls)


def test_captured_api_methods_match_the_wire(
captured_argv: list[dict], tmp_path: Path
) -> None:
api_calls = [call for call in captured_argv if call["argv"][0] == "api"]
for index, call in enumerate(api_calls):
def test_captured_methods_match_the_wire(captured_argv: list[dict], tmp_path: Path) -> None:
for index, call in enumerate(captured_argv):
argv = call["argv"]
if any(flag in argv for flag in ("-F", "-f")) and argv[1] != "graphql":
assert argv[argv.index("--method") + 1] == "GET", argv

if argv[1] == "graphql":
expected = "POST" # GitHub's GraphQL read transport is intentionally POST.
elif argv[1] == "-X":
expected = argv[2]
elif "--method" in argv:
expected = argv[argv.index("--method") + 1]
elif "--input" in argv:
if argv[0] == "pr":
assert argv[1] in {"ready", "merge"}
expected = "POST"
elif argv[1] == "graphql":
expected = "POST"
else:
expected = "GET"
if any(flag in argv for flag in ("-F", "-f")):
assert argv[argv.index("--method") + 1] == "GET", argv
if argv[1] == "-X":
expected = argv[2]
elif "--method" in argv:
expected = argv[argv.index("--method") + 1]
else:
expected = "POST" if "--input" in argv else "GET"
output = offline_run(argv, tmp_path / str(index), call)
methods = re.findall(r"^> (GET|POST|PATCH|PUT|DELETE) ", output, re.MULTILINE)
assert methods and methods[0] == expected, (argv, expected, output)


@pytest.mark.parametrize("command", ["ready", "merge"])
def test_captured_pr_mutations_use_graphql_post(
captured_argv: list[dict], tmp_path: Path, command: str
) -> None:
call = next(item for item in captured_argv if item["argv"][:2] == ["pr", command])
output = offline_run(call["argv"], tmp_path, call)
assert re.search(r"^> POST ", output, re.MULTILINE), output


def test_strict_fake_rejects_exhausted_calls(gh: FakeGh) -> None:
def test_strict_fake_checks_input_and_rejects_exhausted_calls(gh: FakeGh) -> None:
gh.expect(
["api", f"repos/{REPO}/pulls/7", "--method", "PATCH", "--input", "<temp-file>", "--include"],
{},
input_files={"--input": json.dumps({"body": "new body"})},
)
github.update_body(REPO, 7, "new body")
gh.expect(
["api", f"repos/{REPO}/pulls/7", "--include"], rest_pr_json(pr_json()),
)
Expand All @@ -181,13 +172,3 @@ def test_strict_fake_rejects_unexpected_argv(gh: FakeGh) -> None:
gh.expect(["pr", "ready", "8", "--repo", REPO])
with pytest.raises(github.GhError, match="unexpected argv"):
github.mark_ready(REPO, 7)


def test_strict_fake_matches_input_contents(gh: FakeGh) -> None:
gh.expect(
["api", f"repos/{REPO}/pulls/7", "--method", "PATCH", "--input", "<temp-file>", "--include"],
{},
input_files={"--input": json.dumps({"body": "new body"})},
)
github.update_body(REPO, 7, "new body")
gh.assert_complete()
Loading
Loading