Files
seaweedfs/.github/block/scripts/block-ci-port-test.py
T

407 lines
29 KiB
Python

"""Local-only checks for the nested-module CI port; no Go suites or publishing."""
from pathlib import Path
import copy
import importlib.util
import os
import shutil
import re
import subprocess
import tempfile
import unittest
from unittest.mock import patch
HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
class PortTests(unittest.TestCase):
def test_relative_documentation_links_are_checked(self):
text = (ROOT / ".github/workflows/block-test.yml").read_text()
marker = " - name: Relative documentation links\n"
self.assertEqual(text.count(marker), 1)
step = text.split(marker, 1)[1].split("\n - name:", 1)[0]
self.assertIn("if: matrix.suite == 'unit'", step)
self.assertIn("python3 -B ../.github/block/scripts/doc-links-check-test.py", step)
self.assertIn("python3 -I ../.github/block/scripts/doc-links-check.py .", step)
self.assertNotIn("continue-on-error", step)
self.assertNotIn("|| true", step)
def test_root_workflows_use_module_run_and_action_paths(self):
for name in ("test", "spec-trace", "post-merge-review", "known-bugs"):
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
self.assertIn("working-directory: seaweed-block", text)
if name == "post-merge-review":
self.assertIn("runs-on: ubuntu-latest", text)
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
else:
self.assertIn("vars.BLOCK_RUNNER_LABEL", text)
self.assertIn("|| 'ubuntu-latest'", text)
if "go-version-file:" in text: self.assertIn("go-version-file: seaweed-block/go.mod", text)
if name != "known-bugs":
self.assertIn('"seaweed-block/**"', text)
self.assertIn('".github/workflows/block-*.yml"', text)
test = (ROOT / ".github/workflows/block-test.yml").read_text()
self.assertIn("- master", test)
self.assertIn("git diff --relative --name-only --no-renames HEAD^1 HEAD -- .", test)
self.assertIn("go test (linux)", test)
self.assertIn("process-level tests (real binaries)", test)
scope = test.split(" - name: Docs-only pull request\n", 1)[1].split("\n", 2)[1]
self.assertEqual(scope.strip(), "if: matrix.suite == 'process' && github.event_name == 'pull_request'")
self.assertEqual(test.count("if: matrix.suite == 'process' && steps.scope.outputs.docs_only != '1'"), 5)
self.assertNotRegex(test, r"if: matrix\.suite == 'process'\s*\n")
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
self.assertIn("working-directory: ${{ github.workspace }}", post)
def test_labelled_post_merge_review_refuses_host_files(self):
post = (ROOT / ".github/workflows/block-post-merge-review.yml").read_text()
step = post.split(" - name: Check changed paths\n", 1)[1].split(" run: |\n", 1)[1].split("\n\n - name:", 1)[0]
script = "\n".join(line[10:] for line in step.splitlines())
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); module = root / "seaweed-block"
def git(*args): return subprocess.check_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
for name in ("post-merge-review-check.sh", "post-merge-review-allow.txt"):
source = ROOT / "seaweed-block/.github" / ("scripts/" + name if name.endswith(".sh") else name)
target = module / ".github" / ("scripts/" + name if name.endswith(".sh") else name)
target.parent.mkdir(parents=True, exist_ok=True); target.write_bytes(source.read_bytes())
(module / ".github/scripts/post-merge-review-check-test.sh").write_text("exit 0\n")
(root / ".github/block/scripts").mkdir(parents=True)
(root / ".github/block/scripts/post-merge-review-changed.sh").write_bytes((HERE / "post-merge-review-changed.sh").read_bytes())
git("add", "."); git("commit", "-m", "base"); git("remote", "add", "origin", str(root))
base = git("rev-parse", "HEAD").decode().strip()
def check(*paths):
git("reset", "-q", "--hard", base)
for path in paths: (root / path).parent.mkdir(parents=True, exist_ok=True); (root / path).write_text("changed\n")
git("add", "--", *paths); git("commit", "-m", "change")
git("update-ref", "refs/pull/1/head", "HEAD")
env = dict(os.environ, BASE=base, HEAD=git("rev-parse", "HEAD").decode().strip(), PR="1")
return subprocess.run(["bash", "-eo", "pipefail", "-c", script], cwd=module, env=env, capture_output=True, timeout=30)
self.assertEqual(check("seaweed-block/docs/a.md").returncode, 0)
for host in ("weed/example_test.go", "README.md", "docs/a.md"):
out = check("seaweed-block/docs/a.md", host)
self.assertEqual(out.returncode, 1, out)
self.assertEqual([l for l in out.stdout.splitlines() if l.startswith(b"DENY")], [b"DENY host " + host.encode() + b" (outside seaweed-block)"])
def test_known_bugs_use_the_module_verdict_helper(self):
text = (ROOT / ".github/workflows/block-known-bugs.yml").read_text()
self.assertIn("bash .github/scripts/known-bugs-test.sh", text)
self.assertIn("bash .github/scripts/known-bugs.sh <<'LIST'", text)
rows = text.split("<<'LIST'\n", 1)[1].split("\n LIST", 1)[0].split("\n")
self.assertTrue(rows)
for row in rows:
issue, pkg, test = row.split()
sources = (ROOT / "seaweed-block" / pkg).glob("*_test.go")
self.assertTrue(any("func " + test + "(" in s.read_text() for s in sources), row)
def test_release_tag_namespace_and_artifact_identity(self):
text = (ROOT / ".github/workflows/block-release.yml").read_text()
self.assertIn('"seaweed-block/v*"', text)
self.assertNotIn('tags:\n - "v*"', text)
self.assertIn("git tag -l 'seaweed-block/v*'", text)
self.assertIn('docker pull "${BLOCK_IMAGE}@${BLOCK_DIGEST}"', text)
self.assertIn('gh release create "$GITHUB_REF_NAME"', text)
self.assertIn('--latest=false', text)
self.assertIn('gh release upload "$GITHUB_REF_NAME" "$out/$asset" "$out/SHA256SUMS" --repo "$GITHUB_REPOSITORY" --clobber', text)
self.assertIn("runs-on: ubuntu-latest", text)
self.assertNotIn("BLOCK_RUNNER_LABEL", text)
self.assertIn('sw-block-${version}-linux-amd64.tar.gz', text)
self.assertNotIn("go build", text)
self.assertLess(text.index("refusing to publish: release notes"), text.index("docker/build-push-action"))
for name in ("sw-block", "blockcsi"):
recipe = (ROOT / (".github/dockerfiles/block-" + name + ".Dockerfile")).read_text()
self.assertIn("WORKDIR /src/seaweed-block", recipe)
self.assertIn("COPY . /src", recipe)
self.assertGreater(recipe.index("RUN bash scripts/refuse-lab-binary.sh"), recipe.rindex("go build"))
built = re.findall(r"go build -o (\S+)", recipe)
refused = re.search(r"^RUN bash scripts/refuse-lab-binary\.sh (.+)$", recipe, re.M).group(1).split()
self.assertTrue(built)
self.assertEqual(sorted(built), sorted(refused))
def test_nested_git_paths_and_blobs_stay_module_relative(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp); module = root / "seaweed-block"; module.mkdir()
def git(*args):
return subprocess.check_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master")
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
(module / "core").mkdir(); (module / "docs").mkdir()
code = module / "core/a.go"; code.write_text("package a\nconst N=1\n")
(root / "host.go").write_text("package host\n")
git("add", "."); git("commit", "-m", "base")
base = git("rev-parse", "HEAD").decode().strip()
(module / "docs/a.md").write_text("documentation\n")
git("add", "."); git("commit", "-m", "docs")
docs = git("rev-parse", "HEAD").decode().strip()
def run(name, *args):
return subprocess.check_output(["bash", str(HERE / name), *args], cwd=module, timeout=20)
self.assertEqual(run("docs-only-scope.sh", base, docs), b"docs_only 1\n")
code.write_text("package a\nconst N=2\n")
(root / "host.go").write_text("package host\nconst Changed=true\n")
git("add", "."); git("commit", "-m", "code")
head = git("rev-parse", "HEAD").decode().strip()
self.assertEqual(run("post-merge-review-changed.sh", docs, head), b"M\0core/a.go\0")
self.assertTrue(run("chunkstore-scope.sh", docs, head).startswith(b"skip 1"))
for durable in ("core/frontend/chunkstore/c.go", "core/storage/s.go", "core/frontend/durable/d.go"):
(module / durable).parent.mkdir(parents=True, exist_ok=True); (module / durable).write_text("package x\n")
git("add", "."); git("commit", "-m", "durable")
self.assertEqual(run("chunkstore-scope.sh", head, "HEAD"), b"run 1 " + durable.encode() + b"\n")
git("reset", "-q", "--hard", head)
blobs = root / "blobs"
run("changed-go-blobs.sh", docs, head, str(blobs))
self.assertEqual((blobs / "old/core/a.go").read_text(), "package a\nconst N=1\n")
self.assertEqual((blobs / "new/core/a.go").read_text(), "package a\nconst N=2\n")
self.assertFalse((blobs / "new/host.go").exists())
control = root / ".github/workflows/block-test.yml"
control.parent.mkdir(parents=True)
control.write_text("name: Block Test\n")
git("add", ".github"); git("commit", "-m", "CI control")
control_head = git("rev-parse", "HEAD").decode().strip()
self.assertIn(b".github/workflows/block-test.yml\0", run("post-merge-review-changed.sh", docs, control_head))
self.assertTrue(run("docs-only-scope.sh", base, control_head).startswith(b"run "))
checker = root / ".github/block/scripts/public-text-check.sh"
checker.parent.mkdir(parents=True)
checker.write_text("pattern='disk" + "station'\n")
git("add", ".github"); git("commit", "-m", "checker pattern")
pattern_head = git("rev-parse", "HEAD").decode().strip()
title, body = root / "title.txt", root / "body.txt"
title.write_text("CI scope"); body.write_text("Checker patterns")
self.assertEqual(run("public-text-check.sh", control_head, pattern_head, str(title), str(body)), b"public-text: clean\n")
from_root = subprocess.check_output(["bash", str(HERE / "public-text-check.sh"), control_head, pattern_head, str(title), str(body)], cwd=root, timeout=20)
self.assertEqual(from_root, b"public-text: clean\n")
artifact_path = "docs/spec/" + "recorded-example.txt"
artifact = module / artifact_path
artifact.parent.mkdir(parents=True); artifact.write_text("")
git("add", "."); git("commit", "-m", "artifact")
artifact_head = git("rev-parse", "HEAD").decode().strip()
command = ["bash", str(HERE / "public-text-check.sh"), pattern_head, artifact_head, str(title), str(body)]
for cwd in (root, module):
leak = subprocess.run(command, cwd=cwd, capture_output=True, timeout=20)
self.assertEqual(leak.returncode, 1, (cwd, leak.stdout, leak.stderr))
self.assertIn(b"artifact path: " + artifact_path.encode(), leak.stdout)
git("rm", str(artifact.relative_to(root))); git("commit", "-m", "remove artifact")
deleted = git("rev-parse", "HEAD").decode().strip()
removal = ["bash", str(HERE / "public-text-check.sh"), artifact_head, deleted, str(title), str(body)]
for cwd in (root, module):
result = subprocess.run(removal, cwd=cwd, capture_output=True, timeout=20)
self.assertEqual((result.returncode, result.stdout), (0, b"public-text: clean\n"), result.stderr)
fakebin = root / "fakebin"; fakebin.mkdir()
fakegit = fakebin / "git"
fakegit.write_text("#!/bin/sh\nfor arg; do\n if [ \"$arg\" = --diff-filter=ACMT ]; then\n printf 'docs/spec/partial.txt\\0'\n exit 23\n fi\ndone\nexec \"$PUBLIC_TEXT_REAL_GIT\" \"$@\"\n")
fakegit.chmod(0o755)
env = dict(os.environ, PUBLIC_TEXT_REAL_GIT=shutil.which("git"), PATH=str(fakebin) + os.pathsep + os.environ["PATH"])
for cwd in (root, module):
result = subprocess.run(removal, cwd=cwd, env=env, capture_output=True, timeout=20)
self.assertEqual(result.returncode, 2, (cwd, result.stdout, result.stderr))
self.assertIn(b"cannot enumerate artifact paths", result.stderr)
self.assertNotIn(b"public-text: clean", result.stdout)
def test_public_text_adapter_passes_the_module_self_test(self):
module = ROOT / "seaweed-block/.github/scripts"
pattern = lambda path: [l for l in path.read_text().splitlines() if l.startswith("pat=")]
self.assertEqual(pattern(HERE / "public-text-check.sh"), pattern(module / "public-text-check.sh"))
with tempfile.TemporaryDirectory() as tmp:
for source in (module / "public-text-check-test.sh", HERE / "public-text-check.sh"):
(Path(tmp) / source.name).write_bytes(source.read_bytes())
subprocess.run(["bash", str(Path(tmp) / "public-text-check-test.sh")], check=True, capture_output=True, timeout=60)
def test_root_block_ci_files_pass_the_public_text_scan(self):
pat = next(l for l in (HERE / "public-text-check.sh").read_text().splitlines() if l.startswith("pat='"))[5:-1]
files = [p for p in (ROOT / ".github/block").rglob("*") if p.is_file() and "__pycache__" not in p.parts and p.name != "public-text-check.sh"]
files += sorted((ROOT / ".github/workflows").glob("block-*.yml")) + sorted((ROOT / ".github/dockerfiles").glob("block-*.Dockerfile"))
hits = subprocess.run(["grep", "-E", "-i", "-n", "-H", "--", pat, *map(str, files)], capture_output=True, timeout=20)
self.assertEqual(hits.returncode, 1, hits.stdout.decode() + hits.stderr.decode())
def test_safe_merge_refuses_wrong_head_base_and_incomplete_jobs(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
check.validate(pr, run, jobs, "base")
for key, value in (("head_sha", "other"), ("conclusion", "cancelled"), ("name", "Other Test")):
wrong = copy.deepcopy(run); wrong[key] = value
with self.assertRaises(ValueError): check.validate(pr, wrong, jobs, "base")
with self.assertRaises(ValueError): check.validate(pr, run, jobs, "moved")
with self.assertRaises(ValueError): check.validate(pr, run, jobs[:1], "base")
failed = copy.deepcopy(jobs); failed[0]["conclusion"] = "failure"
with self.assertRaises(ValueError): check.validate(pr, run, failed, "base")
def test_same_named_workflow_cannot_satisfy_the_gate(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
pr = {"number": 1, "state": "open", "draft": False, "mergeable": True, "base": {"ref": "master"}, "head": {"sha": "head"}}
run = {"id": 1, "created_at": "1", "path": ".github/workflows/block-test.yml", "name": "Block Test", "head_sha": "head", "status": "completed", "conclusion": "success", "pull_requests": [{"number": 1, "base": {"sha": "base"}}]}
jobs = [{"name": n, "conclusion": "success"} for n in check.JOBS]
duplicate = dict(run, id=2, created_at="2", path=".github/workflows/pretend.yml")
with self.assertRaises(ValueError): check.validate(pr, duplicate, jobs, "base")
missing = dict(run); del missing["path"]
with self.assertRaises(ValueError): check.validate(pr, missing, jobs, "base")
import json
with patch.object(check, "api", return_value={"workflow_runs": [run, duplicate]}), patch.object(check.subprocess, "check_output", return_value=json.dumps([{"jobs": jobs}]).encode()):
self.assertEqual(check.successful_run(pr, "base")["id"], 1)
with patch.object(check, "api", return_value={"workflow_runs": [duplicate]}):
with self.assertRaises(ValueError): check.successful_run(pr, "base")
def test_control_path_changes_need_independent_workflow_review(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
real_output = subprocess.check_output
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args): return real_output(["git", *args], cwd=root, timeout=15)
git("init", "-b", "master"); git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid"); git("config", "commit.gpgsign", "false")
(root / "code.go").write_text("package example")
git("add", "."); git("commit", "-m", "base")
base = git("rev-parse", "HEAD").decode().strip()
for name in (".github/workflows/pretend.yml", ".github/block/scripts/check.py", ".github/dockerfiles/block-image.Dockerfile", "seaweed-block/.github/scripts/record-go-test.sh"):
path = root / name; path.parent.mkdir(parents=True, exist_ok=True); path.write_text("control")
git("add", "."); git("commit", "-m", "control")
added = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(base, added)
git("rm", name); git("commit", "-m", "remove")
removed = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(added, removed)
(root / "code.go").write_text("package example\nconst N=2")
git("add", "."); git("commit", "-m", "code")
head = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
check.check_control_paths(base, head)
git("checkout", "-q", "-b", "master-later", base)
(root / ".github/workflows").mkdir(parents=True, exist_ok=True)
(root / ".github/workflows/block-test.yml").write_text("master control")
git("add", "."); git("commit", "-m", "master control")
master = git("rev-parse", "HEAD").decode().strip()
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
check.check_control_paths(master, head)
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.check_control_paths(head, master)
with patch.object(check, "check_control_paths", side_effect=ValueError("workflow_review_required")), patch.object(check.subprocess, "check_output", side_effect=["base", "head"]), patch.object(check.subprocess, "run") as run:
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.local_checks({"number": 1, "body": "body", "title": "title", "head": {"sha": "head"}}, "base")
self.assertEqual(run.call_count, 1) # fetch only; no checker certification
def test_control_path_diff_refuses_multiple_merge_bases(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
real_output = subprocess.check_output
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
def git(*args): return real_output(["git", *args], cwd=root, timeout=15).decode().strip()
git("init", "-b", "master")
git("config", "user.name", "Example"); git("config", "user.email", "example@example.invalid")
git("config", "commit.gpgsign", "false")
git("commit", "--allow-empty", "-m", "base"); base = git("rev-parse", "HEAD")
git("checkout", "-q", "-b", "left")
(root / "left.txt").write_text("left")
git("add", "."); git("commit", "-m", "left"); left = git("rev-parse", "HEAD")
git("checkout", "-q", "-b", "right", base)
(root / "right.txt").write_text("right")
git("add", "."); git("commit", "-m", "right"); right = git("rev-parse", "HEAD")
git("checkout", "-q", "left"); git("merge", "--no-ff", right, "-m", "left merge")
left_merge = git("rev-parse", "HEAD")
git("checkout", "-q", "right"); git("merge", "--no-ff", left, "-m", "right merge")
right_merge = git("rev-parse", "HEAD")
self.assertEqual(set(git("merge-base", "--all", left_merge, right_merge).splitlines()), {left, right})
with patch.object(check.subprocess, "check_output", side_effect=lambda args, **kw: real_output(args, cwd=root, **kw)):
with self.assertRaisesRegex(ValueError, "ambiguous_merge_base"):
check.check_control_paths(left_merge, right_merge)
check.check_control_paths(left, left_merge)
def test_fork_runner_guard_is_required_not_only_the_fallback(self):
expected = "${{ (github.event_name == 'push' || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository) && vars.BLOCK_RUNNER_LABEL || 'ubuntu-latest' }}"
for name in ("test", "spec-trace", "known-bugs"):
text = (ROOT / (".github/workflows/block-" + name + ".yml")).read_text()
lines = [line.strip() for line in text.splitlines() if line.strip().startswith("runs-on:")]
self.assertEqual(lines, ["runs-on: " + expected])
def test_rerun_during_local_checks_cannot_report_ready(self):
import contextlib
import io
import json
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
def pr(number):
return {"number": number, "state": "open", "draft": False, "mergeable": True,
"base": {"ref": "master"}, "head": {"sha": str(number)}}
with tempfile.TemporaryDirectory() as tmp:
evidence = Path(tmp) / "acceptance"; evidence.write_text("accepted")
members = [pr(1), pr(2)]
manifest = {"base": "base", "head": "3", "batch_pr": 3,
"prs": [{"number": n, "head": str(n), "evidence": str(evidence)} for n in (1, 2)]}
path = Path(tmp) / "batch.json"; path.write_text(json.dumps(manifest))
for batch in (False, True):
for outcome in ("in_progress", "failed_run", "failed_job", "new_run", "success"):
with self.subTest(batch=batch, outcome=outcome):
changed = False
observations = []
number = 3 if batch else 1
def api(endpoint):
if endpoint == "git/ref/heads/master": return {"object": {"sha": "base"}}
if endpoint.startswith("pulls/"): return pr(int(endpoint.split("/")[-1]))
if endpoint == "git/commits/3": return {"tree": {"sha": "tree"}}
observations.append(("run", changed))
run = {"id": 10, "run_attempt": 2 if changed else 1, "created_at": "1",
"path": check.WORKFLOW_PATH, "name": "Block Test", "head_sha": str(number),
"status": "completed", "conclusion": "success",
"pull_requests": [{"number": number, "base": {"sha": "base"}}]}
if changed and outcome in ("in_progress", "new_run"):
run.update(status="in_progress", conclusion=None)
if outcome == "new_run": run.update(id=11, created_at="2")
if changed and outcome == "failed_run": run["conclusion"] = "failure"
return {"workflow_runs": [run]}
def jobs(*args, **kwargs):
observations.append(("jobs", changed))
result = [{"name": name, "conclusion": "success"} for name in check.JOBS]
if changed and outcome == "failed_job": result[0]["conclusion"] = "failure"
return json.dumps([{"jobs": result}]).encode()
def local(*args):
nonlocal changed
changed = True
output = io.StringIO()
with patch.object(check, "api", side_effect=api), patch.object(check.subprocess, "check_output", side_effect=jobs), patch.object(check, "fetch_review_head"), patch.object(check, "local_checks", side_effect=local), contextlib.redirect_stdout(output):
if outcome == "success":
check.main(["--batch", str(path)] if batch else ["1"])
else:
with self.assertRaises(ValueError):
check.main(["--batch", str(path)] if batch else ["1"])
if outcome == "success":
self.assertTrue(json.loads(output.getvalue())["ready"])
else:
self.assertNotIn('"ready": true', output.getvalue())
self.assertIn(("run", True), observations)
self.assertIn(("jobs", True), observations)
def test_batch_preserves_pinned_base_heads_order_and_evidence(self):
spec = importlib.util.spec_from_file_location("safe_merge", HERE / "safe-merge-check.py")
check = importlib.util.module_from_spec(spec); spec.loader.exec_module(check)
with tempfile.TemporaryDirectory() as tmp:
evidence = Path(tmp) / "acceptance"; evidence.write_text("review accepted")
prs = [{"number": n, "state": "open", "draft": False, "base": {"ref": "master"}, "head": {"sha": str(n)}} for n in (1, 2)]
manifest = {"base": "base", "head": "batch", "prs": [{"number": p["number"], "head": p["head"]["sha"], "evidence": str(evidence)} for p in prs]}
check.validate_batch(manifest, prs, "base")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "moved")
with self.assertRaises(ValueError): check.validate_batch(manifest, list(reversed(prs)), "base")
wrong = copy.deepcopy(prs); wrong[0]["head"]["sha"] = "new"
with self.assertRaises(ValueError): check.validate_batch(manifest, wrong, "base")
batch_manifest = dict(manifest, batch_pr=3)
manifest_path = Path(tmp) / "batch.json"
import json
manifest_path.write_text(json.dumps(batch_manifest))
replies = {"git/ref/heads/master": {"object": {"sha": "base"}}, "pulls/1": prs[0], "pulls/2": prs[1], "pulls/3": {"number": 3, "head": {"sha": "batch"}}}
with patch.object(check, "api", side_effect=lambda path: replies[path]), patch.object(check, "fetch_review_head", side_effect=ValueError("workflow_review_required")) as fetch, patch.object(check, "successful_run") as run:
with self.assertRaisesRegex(ValueError, "workflow_review_required"):
check.main(["--batch", str(manifest_path)])
fetch.assert_called_once_with(replies["pulls/3"], "base")
run.assert_not_called()
evidence.write_text("")
with self.assertRaises(ValueError): check.validate_batch(manifest, prs, "base")
if __name__ == "__main__": unittest.main()