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
48 changes: 18 additions & 30 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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]
Expand All @@ -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"),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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)
Expand Down
50 changes: 19 additions & 31 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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):
Expand All @@ -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):
Expand All @@ -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))
64 changes: 21 additions & 43 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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"]
] + [
Expand All @@ -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):
Expand All @@ -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: (
Expand Down
Loading
Loading