|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import shutil |
| 5 | +import subprocess |
| 6 | +import sys |
| 7 | +import tempfile |
| 8 | +from contextlib import contextmanager |
| 9 | +from pathlib import Path |
| 10 | + |
| 11 | +import pytest |
| 12 | + |
| 13 | +import scripts.safe_pr_gate as safe_pr_gate |
| 14 | +from scripts.safe_pr_gate import GateState, _parse_porcelain_paths, evaluate_gate |
| 15 | + |
| 16 | + |
| 17 | +REPO_ROOT = Path(__file__).resolve().parents[1] |
| 18 | + |
| 19 | + |
| 20 | +def _run_gate(*args: str, cwd: Path | None = None) -> subprocess.CompletedProcess[str]: |
| 21 | + return subprocess.run( |
| 22 | + [sys.executable, "scripts/safe_pr_gate.py", *args], |
| 23 | + check=False, |
| 24 | + capture_output=True, |
| 25 | + text=True, |
| 26 | + cwd=cwd, |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +@contextmanager |
| 31 | +def _temporary_git_repo(branch: str): |
| 32 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 33 | + repo_root = Path(temp_dir) |
| 34 | + scripts_dir = repo_root / "scripts" |
| 35 | + scripts_dir.mkdir() |
| 36 | + shutil.copy2(REPO_ROOT / "scripts" / "safe_pr_gate.py", scripts_dir / "safe_pr_gate.py") |
| 37 | + subprocess.run(["git", "init"], cwd=repo_root, check=True, capture_output=True, text=True) |
| 38 | + subprocess.run(["git", "checkout", "-b", branch], cwd=repo_root, check=True, capture_output=True, text=True) |
| 39 | + yield repo_root |
| 40 | + |
| 41 | + |
| 42 | +def test_evaluate_gate_passes_on_clean_feature_branch_state() -> None: |
| 43 | + result = evaluate_gate( |
| 44 | + GateState(branch="feat/safe-pr-gate", status_short=(), changed_paths=()), |
| 45 | + allowed_prefixes=("scripts/",), |
| 46 | + ) |
| 47 | + |
| 48 | + assert result.ok is True |
| 49 | + assert result.problems == () |
| 50 | + assert result.to_dict() == { |
| 51 | + "allowed_prefixes": ["scripts/"], |
| 52 | + "allow_dirty": False, |
| 53 | + "branch": "feat/safe-pr-gate", |
| 54 | + "changed_paths": [], |
| 55 | + "ok": True, |
| 56 | + "problems": [], |
| 57 | + "result": "PASS", |
| 58 | + "status_short": [], |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | +def test_evaluate_gate_fails_on_main_branch() -> None: |
| 63 | + result = evaluate_gate(GateState(branch="main", status_short=(), changed_paths=())) |
| 64 | + |
| 65 | + assert result.ok is False |
| 66 | + assert result.problems == ("on_main_branch",) |
| 67 | + |
| 68 | + |
| 69 | +def test_evaluate_gate_allows_detached_head_state() -> None: |
| 70 | + result = evaluate_gate(GateState(branch="", status_short=(), changed_paths=())) |
| 71 | + |
| 72 | + assert result.ok is True |
| 73 | + assert result.problems == () |
| 74 | + |
| 75 | + |
| 76 | +def test_evaluate_gate_fails_on_dirty_tree_without_allow_dirty() -> None: |
| 77 | + result = evaluate_gate( |
| 78 | + GateState(branch="feat/safe-pr-gate", status_short=(" M scripts/example.py",), changed_paths=("scripts/example.py",)) |
| 79 | + ) |
| 80 | + |
| 81 | + assert result.ok is False |
| 82 | + assert result.problems == ("dirty_working_tree",) |
| 83 | + |
| 84 | + |
| 85 | +def test_evaluate_gate_flags_paths_outside_allowed_prefixes() -> None: |
| 86 | + result = evaluate_gate( |
| 87 | + GateState(branch="feat/safe-pr-gate", status_short=(" M docs/example.md",), changed_paths=("docs/example.md",)), |
| 88 | + allow_dirty=True, |
| 89 | + allowed_prefixes=("scripts/",), |
| 90 | + ) |
| 91 | + |
| 92 | + assert result.ok is False |
| 93 | + assert result.problems == ("changed_files_outside_allowed_prefixes", "outside_prefix:docs/example.md") |
| 94 | + |
| 95 | + |
| 96 | +def test_parse_porcelain_paths_handles_rename_status_in_second_position() -> None: |
| 97 | + assert _parse_porcelain_paths(" R old-name.txt\0new-name.txt\0") == ("new-name.txt",) |
| 98 | + |
| 99 | + |
| 100 | +@pytest.mark.parametrize( |
| 101 | + ("raised", "expected_message"), |
| 102 | + [ |
| 103 | + (subprocess.CalledProcessError(1, ["git", "status", "--short"]), "git command failed with exit code 1: git status --short"), |
| 104 | + (FileNotFoundError(), "git executable not found while running: git status --short"), |
| 105 | + ], |
| 106 | +) |
| 107 | +def test_run_git_wraps_git_subprocess_failures(monkeypatch: pytest.MonkeyPatch, raised: BaseException, expected_message: str) -> None: |
| 108 | + def fake_run(*args: object, **kwargs: object) -> subprocess.CompletedProcess[str]: |
| 109 | + raise raised |
| 110 | + |
| 111 | + monkeypatch.setattr(safe_pr_gate.subprocess, "run", fake_run) |
| 112 | + |
| 113 | + with pytest.raises(RuntimeError, match=expected_message): |
| 114 | + safe_pr_gate._run_git(["status", "--short"]) |
| 115 | + |
| 116 | + |
| 117 | +def test_main_reports_deterministic_error_json_on_git_failure(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None: |
| 118 | + monkeypatch.setattr(safe_pr_gate, "collect_gate_state", lambda: (_ for _ in ()).throw(RuntimeError("git command failed with exit code 1: git status --short"))) |
| 119 | + |
| 120 | + exit_code = safe_pr_gate.main([]) |
| 121 | + output = json.loads(capsys.readouterr().out) |
| 122 | + |
| 123 | + assert exit_code == 1 |
| 124 | + assert output == { |
| 125 | + "error": { |
| 126 | + "message": "git command failed with exit code 1: git status --short", |
| 127 | + "type": "RuntimeError", |
| 128 | + }, |
| 129 | + "ok": False, |
| 130 | + "result": "ERROR", |
| 131 | + } |
| 132 | + |
| 133 | + |
| 134 | +def test_cli_pass_and_fail_outputs_are_deterministic() -> None: |
| 135 | + with _temporary_git_repo("feat/safe-pr-gate") as repo_root: |
| 136 | + passing = _run_gate( |
| 137 | + "--allow-dirty", |
| 138 | + "--allowed-prefix", |
| 139 | + "docs/", |
| 140 | + "--allowed-prefix", |
| 141 | + "scripts/", |
| 142 | + "--allowed-prefix", |
| 143 | + "tests/", |
| 144 | + cwd=repo_root, |
| 145 | + ) |
| 146 | + dirty_path = repo_root / "_safe_pr_gate_dirty_test.tmp" |
| 147 | + dirty_path.write_text("dirty\n", encoding="utf-8") |
| 148 | + try: |
| 149 | + failing = _run_gate( |
| 150 | + "--allow-dirty", |
| 151 | + "--allowed-prefix", |
| 152 | + "docs/", |
| 153 | + "--allowed-prefix", |
| 154 | + "scripts/", |
| 155 | + "--allowed-prefix", |
| 156 | + "tests/", |
| 157 | + cwd=repo_root, |
| 158 | + ) |
| 159 | + finally: |
| 160 | + dirty_path.unlink(missing_ok=True) |
| 161 | + |
| 162 | + assert passing.returncode == 0 |
| 163 | + assert failing.returncode == 1 |
| 164 | + |
| 165 | + passing_payload = json.loads(passing.stdout) |
| 166 | + failing_payload = json.loads(failing.stdout) |
| 167 | + |
| 168 | + assert passing_payload["result"] == "PASS" |
| 169 | + assert passing_payload["allow_dirty"] is True |
| 170 | + assert failing_payload["result"] == "FAIL" |
| 171 | + assert failing_payload["problems"] == [ |
| 172 | + "changed_files_outside_allowed_prefixes", |
| 173 | + "outside_prefix:_safe_pr_gate_dirty_test.tmp", |
| 174 | + ] |
0 commit comments