Files
cli-autoreview/tests/test_diff.py
Roberto Guagliardo 27af18a734
Some checks failed
AI Reviewer / review (pull_request) Failing after 1m28s
fix
2026-02-02 20:29:38 +00:00

87 lines
3.1 KiB
Python

from __future__ import annotations
from typing import Any
from unittest.mock import patch
import subprocess
from ai_reviewer.diff import run_git_diff
def _completed(cmd: list[str], returncode: int, stdout: str = "", stderr: str = "") -> subprocess.CompletedProcess[Any]:
return subprocess.CompletedProcess(cmd, returncode, stdout, stderr)
def test_run_git_diff_prefers_direct_refs():
calls: list[list[str]] = []
def fake_run(cmd, check=False, capture_output=False, text=False): # type: ignore[override]
calls.append(cmd)
if cmd[3] == "diff":
if cmd[4] == "base...head":
return _completed(cmd, 0, stdout="ok")
return _completed(cmd, 128, stderr="fatal")
raise AssertionError("fetch should not run when refs exist locally")
with patch("ai_reviewer.diff.subprocess.run", side_effect=fake_run):
output = run_git_diff(".", "base", "head")
assert output == "ok"
# Only one diff attempt should be needed when local refs exist.
assert len(calls) == 1
def test_run_git_diff_falls_back_to_origin_refs_after_fetch():
fetched = False
diff_attempts: list[str] = []
def fake_run(cmd, check=False, capture_output=False, text=False): # type: ignore[override]
nonlocal fetched
if cmd[3] == "diff":
if len(cmd) == 7:
spec = cmd[4]
else:
spec = " ".join(cmd[4:6])
diff_attempts.append(spec)
if spec == "origin/base...origin/head" and fetched:
return _completed(cmd, 0, stdout="remote-ok")
return _completed(cmd, 128, stderr="missing ref")
if cmd[3] == "fetch":
fetched = True
return _completed(cmd, 0)
raise AssertionError("unexpected git invocation")
with patch("ai_reviewer.diff.subprocess.run", side_effect=fake_run):
output = run_git_diff(".", "base", "head")
assert output == "remote-ok"
assert "origin/base...origin/head" in diff_attempts
# Ensure the fallback only succeeds after fetch.
assert diff_attempts.index("origin/base...origin/head") > diff_attempts.index("base...head")
def test_run_git_diff_fallbacks_to_two_dot_when_merge_base_missing():
fetched = False
diff_attempts: list[str] = []
def fake_run(cmd, check=False, capture_output=False, text=False): # type: ignore[override]
nonlocal fetched
if cmd[3] == "diff":
if len(cmd) == 7:
spec = cmd[4]
diff_attempts.append(f"sym:{spec}")
return _completed(cmd, 128, stderr="fatal: origin/main...origin/head: no merge base")
spec = " ".join(cmd[4:6])
diff_attempts.append(f"two:{spec}")
return _completed(cmd, 0, stdout="linear-diff")
if cmd[3] == "fetch":
fetched = True
return _completed(cmd, 0)
raise AssertionError("unexpected git invocation")
with patch("ai_reviewer.diff.subprocess.run", side_effect=fake_run):
output = run_git_diff(".", "base", "head")
assert output == "linear-diff"
assert any(attempt.startswith("two:") for attempt in diff_attempts)