From ad41a3ad568005a2315c72d7e1ff01a1efd3783c Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:09:31 -0700 Subject: [PATCH 01/10] Drop the PTY tests that never call diffui, drive _spawn_agent for real instead --- tests/test_agent_terminal.py | 192 ++++------------------------------- 1 file changed, 21 insertions(+), 171 deletions(-) diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index 9f1eff4..e82d8c9 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -1,13 +1,7 @@ from __future__ import annotations -import os -import pty -import select -import struct -import subprocess -import termios +import sys import time -import tty from pathlib import Path from unittest.mock import MagicMock, patch @@ -237,28 +231,27 @@ def test_start_stores_pending(self, _server_app): assert rat._pending_start["prompt"] == "prompt text" assert rat._pending_start["repo_root"] == "/repo" - def test_spawn_agent_creates_process(self): - proc = MagicMock() - proc.pid = 4242 - rat._pending_start = {"prompt": "test", "repo_root": "/repo", "agent": "claude", "cmd": ["claude"]} - with ( - patch.object(rat.pty, "openpty", return_value=(10, 11)), - patch.object(rat.os, "ttyname", return_value="/dev/pts/99"), - patch.object(rat.tty, "setraw"), - patch.object(rat.subprocess, "Popen", return_value=proc) as mock_popen, - patch.object(rat.os, "close") as mock_close, - ): - result = rat._spawn_agent(30, 100) + def test_spawned_agent_runs_in_its_own_session_on_a_sized_terminal(self, temp_repo): + script = ( + "import os, sys; " + "print(os.getsid(0) == os.getpid(), *os.get_terminal_size(0), os.environ['COLUMNS'], os.environ['LINES'], " + "sys.argv[1])" + ) + rat._pending_start = { + "prompt": "the-prompt", + "repo_root": str(temp_repo), + "agent": "claude", + "cmd": [sys.executable, "-c", script], + } + result = rat._spawn_agent(30, 100) + output = b"" + deadline = time.monotonic() + 10 + while time.monotonic() < deadline and not output.endswith(b"\n"): + output += rat._read_pty(rat._agent_pty_fd) or b"" + rat._kill_agent() - assert result == {"ok": True, "pid": 4242, "agent": "claude"} - mock_close.assert_called_once_with(11) - called_cmd = mock_popen.call_args[0][0] - assert called_cmd[0] == "claude" - kwargs = mock_popen.call_args[1] - assert kwargs["stdin"] == 11 - assert kwargs["env"]["COLUMNS"] == "100" - assert kwargs["env"]["LINES"] == "30" - assert kwargs["preexec_fn"] is not None + assert result["ok"] is True + assert output.decode().split() == ["True", "100", "30", "100", "30", "the-prompt"] def test_spawn_closes_child_fd_on_popen_failure(self): rat._pending_start = {"prompt": "test", "repo_root": "/repo", "agent": "claude", "cmd": ["claude"]} @@ -275,149 +268,6 @@ def test_spawn_closes_child_fd_on_popen_failure(self): mock_close.assert_called_once_with(11) -def _read_until_exit(pty_fd: int, proc: subprocess.Popen) -> bytes: - output = b"" - for _ in range(50): - ready, _, _ = select.select([pty_fd], [], [], 0.1) - if ready: - try: - output += os.read(pty_fd, 4096) - except OSError: # Linux raises EIO once the child closes its end; macOS returns b"". - break - if proc.poll() is not None: - break - return output - - -class TestPtyIntegration: - def test_child_has_controlling_terminal(self): - pty_fd, child_fd = pty.openpty() - child_tty = os.ttyname(child_fd) - tty.setraw(child_fd) - - def child_setup(): - os.setsid() - fd = os.open(child_tty, os.O_RDWR) - os.close(fd) - - proc = subprocess.Popen( - ["python3", "-c", "import os; print(os.ctermid())"], - stdin=child_fd, - stdout=child_fd, - stderr=child_fd, - preexec_fn=child_setup, - close_fds=True, - ) - os.close(child_fd) - - output = _read_until_exit(pty_fd, proc) - - proc.wait(timeout=5) - os.close(pty_fd) - assert b"/dev/" in output - - def test_arrow_key_sequences_pass_through_raw_pty(self): - pty_fd, child_fd = pty.openpty() - child_tty = os.ttyname(child_fd) - tty.setraw(child_fd) - - def child_setup(): - os.setsid() - fd = os.open(child_tty, os.O_RDWR) - os.close(fd) - - proc = subprocess.Popen( - ["cat"], - stdin=child_fd, - stdout=child_fd, - stderr=child_fd, - preexec_fn=child_setup, - close_fds=True, - ) - os.close(child_fd) - - os.write(pty_fd, b"\x1b[A") - - output = b"" - for _ in range(20): - ready, _, _ = select.select([pty_fd], [], [], 0.1) - if ready: - output += os.read(pty_fd, 4096) - if b"\x1b[A" in output: - break - - proc.terminate() - proc.wait(timeout=5) - os.close(pty_fd) - assert b"\x1b[A" in output - - def test_sigwinch_delivered_after_resize(self): - pty_fd, child_fd = pty.openpty() - child_tty = os.ttyname(child_fd) - tty.setraw(child_fd) - import fcntl - - fcntl.ioctl(pty_fd, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0)) - - def child_setup(): - os.setsid() - fd = os.open(child_tty, os.O_RDWR) - os.close(fd) - - script = ( - "import signal, sys, struct, fcntl, termios\n" - "got = []\n" - "def handler(sig, frame):\n" - " ws = fcntl.ioctl(0, termios.TIOCGWINSZ, b'\\x00' * 8)\n" - " rows, cols = struct.unpack('HHHH', ws)[:2]\n" - " got.append(f'{rows}x{cols}')\n" - "signal.signal(signal.SIGWINCH, handler)\n" - "import time; time.sleep(0.5)\n" - "print(','.join(got) if got else 'NO_SIGWINCH')\n" - ) - - proc = subprocess.Popen( - ["python3", "-c", script], - stdin=child_fd, - stdout=child_fd, - stderr=child_fd, - preexec_fn=child_setup, - close_fds=True, - ) - os.close(child_fd) - - import time - - time.sleep(0.1) - fcntl.ioctl(pty_fd, termios.TIOCSWINSZ, struct.pack("HHHH", 40, 100, 0, 0)) - - output = _read_until_exit(pty_fd, proc) - - proc.wait(timeout=5) - os.close(pty_fd) - text = output.decode("utf-8", errors="replace") - assert "40x100" in text, f"Expected SIGWINCH with 40x100, got: {text!r}" - - def test_without_setsid_no_controlling_terminal(self): - pty_fd, child_fd = pty.openpty() - tty.setraw(child_fd) - - proc = subprocess.Popen( - ["python3", "-c", "import os; print(os.ttyname(0))"], - stdin=child_fd, - stdout=child_fd, - stderr=child_fd, - close_fds=True, - ) - os.close(child_fd) - - output = _read_until_exit(pty_fd, proc) - - proc.wait(timeout=5) - os.close(pty_fd) - assert b"/dev/" in output - - class TestAgentWebSocket: def test_no_process_sends_error(self, _server_app): with ( From 528d2995745cb005520f1b06166cf9e1a66cfc81 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:11:11 -0700 Subject: [PATCH 02/10] Delete tests that cannot fail, repeat another test, or exercise pydantic and pygments --- tests/test_agent_terminal.py | 26 ------- tests/test_diff.py | 13 ---- tests/test_events.py | 59 ---------------- tests/test_git_utils.py | 57 --------------- tests/test_highlight.py | 8 --- tests/test_server.py | 131 +---------------------------------- tests/test_themes.py | 17 ----- 7 files changed, 1 insertion(+), 310 deletions(-) diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index e82d8c9..7bf6345 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -10,7 +10,6 @@ import diffui.server.routes_agent_terminal as rat from diffui.server.routes_agent_terminal import ( _BUFFER_MAX_BYTES, - _is_running, _kill_agent, _read_pty, _resize_pty, @@ -49,24 +48,6 @@ def test_buffer_stays_under_max_as_output_arrives(self): assert result.endswith(chunk) -class TestIsRunning: - def test_none_process(self): - rat._agent_proc = None - assert _is_running() is False - - def test_exited_process(self): - proc = MagicMock() - proc.poll.return_value = 0 - rat._agent_proc = proc - assert _is_running() is False - - def test_running_process(self): - proc = MagicMock() - proc.poll.return_value = None - rat._agent_proc = proc - assert _is_running() is True - - class TestReadPty: def test_data_available(self): with ( @@ -97,13 +78,6 @@ def test_oserror_swallowed(self): class TestResizePty: - def test_calls_ioctl(self): - with patch("fcntl.ioctl") as mock_ioctl: - _resize_pty(9, 40, 120) - assert mock_ioctl.called - args = mock_ioctl.call_args[0] - assert args[0] == 9 - def test_oserror_swallowed(self): with patch("fcntl.ioctl", side_effect=OSError("bad fd")): _resize_pty(9, 40, 120) # must not raise diff --git a/tests/test_diff.py b/tests/test_diff.py index 40d8565..d47281b 100644 --- a/tests/test_diff.py +++ b/tests/test_diff.py @@ -162,18 +162,10 @@ def test_only_header(self): class TestGetLexer: - def test_python_file(self): - lexer = get_lexer("test.py") - assert "python" in lexer.name.lower() - def test_unknown_extension_falls_back_to_text(self): lexer = get_lexer("file.xyz_unknown") assert "text" in lexer.name.lower() - def test_terraform(self): - lexer = get_lexer("main.tf") - assert "terraform" in lexer.name.lower() or "hcl" in lexer.name.lower() - class TestTokenColor: def test_direct_match(self): @@ -215,11 +207,6 @@ def test_deletion(self): assert len(old_ranges) == 1 assert new_ranges == [] - def test_empty_lines(self): - old_ranges, new_ranges = word_diff_ranges("", "") - assert old_ranges == [] - assert new_ranges == [] - class TestPairDiffLines: def test_paired_add_remove(self): diff --git a/tests/test_events.py b/tests/test_events.py index 2f78e77..ce83137 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -144,12 +144,6 @@ def test_broadcast_empty_events_is_noop(self): finally: _clients.discard(q) - def test_broadcast_no_clients_is_noop(self): - from diffui.server.events import _sse_clients as _clients - - _clients.clear() - _broadcast(["files_changed"]) - def test_broadcast_full_queue_skipped(self): from diffui.server.events import _sse_clients as _clients @@ -183,36 +177,8 @@ def test_broadcast_delivers_to_ws_clients(self): finally: _ws_clients.discard(ws) - def test_broadcast_sends_to_both_sse_and_ws(self): - - from diffui.server.events import _sse_clients as _clients - - q = asyncio.Queue(maxsize=8) - _clients.add(q) - ws = AsyncMock() - _ws_clients.add(ws) - try: - asyncio.run(_broadcast_on_loop(["git_changed"])) - assert not q.empty() - ws.send_text.assert_called_once() - finally: - _clients.discard(q) - _ws_clients.discard(ws) - class TestApplyStateUpdates: - def test_git_changed_reloads_and_clears_cache(self): - - with ( - patch("diffui.server.state.app_state.reload_repo_state") as reload, - patch("diffui.server.events.clear_diff_cache") as clear_cache, - ): - result = _apply_state_updates(["git_changed"]) - - reload.assert_called_once() - clear_cache.assert_called_once() - assert "files_changed" in result - def test_git_changed_does_not_duplicate_files_changed(self): with ( @@ -385,25 +351,6 @@ def test_git_changed_also_unreviews_modified_files(self): finally: app_state.reviewed = prev_reviewed - def test_files_changed_keeps_reviewed_when_mtime_matches(self): - prev_reviewed = app_state.reviewed.copy() - prev_numstat = app_state.numstat - prev_working = app_state.working_files - try: - app_state.reviewed = {"stable.py": 3000.0} - with ( - patch("diffui.server.events.get_diff_numstat", return_value={}), - patch("diffui.server.events.get_working_changed_files", return_value=[]), - patch("diffui.server.events.get_file_mtime", return_value=3000.0), - ): - _apply_state_updates(["files_changed"]) - - assert "stable.py" in app_state.reviewed - finally: - app_state.reviewed = prev_reviewed - app_state.numstat = prev_numstat - app_state.working_files = prev_working - class TestWatcherLifecycle: def test_do_restart_sets_cancel_event(self): @@ -495,9 +442,3 @@ def test_github_workflow_is_a_file_change(self): events = _classify_changes({(1, "/repo/.github/workflows/ci.yml")}, "/repo/.git", "/cfg/comments.json") assert events == ["files_changed"] - - def test_git_head_is_a_git_change(self): - from diffui.server.events import _classify_changes - - events = _classify_changes({(1, "/repo/.git/HEAD")}, "/repo/.git", "/cfg/comments.json") - assert events == ["git_changed"] diff --git a/tests/test_git_utils.py b/tests/test_git_utils.py index f1676b2..9c9bcba 100644 --- a/tests/test_git_utils.py +++ b/tests/test_git_utils.py @@ -1,6 +1,5 @@ from __future__ import annotations -import json from pathlib import Path import pytest @@ -62,45 +61,6 @@ def test_save_and_load(self, tmp_path: Path): loaded = _load_json(p, {}) assert loaded == data - def test_save_creates_file(self, tmp_path: Path): - p = tmp_path / "new.json" - assert not p.exists() - _save_json(p, {"a": 1}) - assert p.exists() - - def test_save_format(self, tmp_path: Path): - p = tmp_path / "fmt.json" - _save_json(p, {"x": 1}) - content = p.read_text() - assert content.endswith("\n") - parsed = json.loads(content) - assert parsed == {"x": 1} - - def test_roundtrip_reviewed(self, tmp_path: Path): - p = tmp_path / "reviewed.json" - data: dict[str, float] = {"file.py": 1234567890.123} - _save_json(p, data) - loaded = _load_json(p, {}) - assert loaded["file.py"] == pytest.approx(1234567890.123) - - def test_roundtrip_comments(self, tmp_path: Path): - p = tmp_path / "comments.json" - data = { - "file.py": [ - { - "file_path": "file.py", - "file_line_num": 10, - "line_text": "+new code", - "comment": "looks good", - "timestamp": "2024-01-01T00:00:00Z", - } - ] - } - _save_json(p, data) - loaded = _load_json(p, {}) - assert loaded["file.py"][0]["comment"] == "looks good" - assert loaded["file.py"][0]["file_line_num"] == 10 - class TestDiffStat: def test_simple_diff(self): @@ -136,13 +96,6 @@ def test_ignores_meta_lines(self): class TestResolveRepos: - def test_from_current_dir(self): - from diffui.git_utils import resolve_repos - - repos, idx = resolve_repos() - assert len(repos) >= 1 - assert 0 <= idx < len(repos) - def test_explicit_paths(self): from diffui.git_utils import resolve_repos @@ -190,16 +143,6 @@ def test_unknown_file_returns_empty(self): assert get_blame("does_not_exist.py") == [] -class TestSessionPersistence: - def test_save_overwrites_not_merges(self, tmp_path: Path): - from diffui.git_utils import _load_json, _save_json - - p = tmp_path / "session.json" - _save_json(p, {"a": 1}) - _save_json(p, {"b": 2}) - assert _load_json(p, {}) == {"b": 2} - - class TestDiscoverSiblingRepos: def test_no_git_dirs_returns_empty(self, tmp_path: Path): from diffui.git_utils import discover_sibling_repos diff --git a/tests/test_highlight.py b/tests/test_highlight.py index f44d9c2..709e184 100644 --- a/tests/test_highlight.py +++ b/tests/test_highlight.py @@ -88,14 +88,6 @@ def test_line_numbers_present(self): assert remove_line["old_num"] is not None assert add_line["new_num"] is not None - def test_each_line_has_index(self): - diff = "diff --git a/f.py b/f.py\n--- a/f.py\n+++ b/f.py\n@@ -1 +1 @@\n-old\n+new\n" - result = parse_diff_to_json(diff, "f.py", CATPPUCCIN_MOCHA) - for hunk in result["hunks"]: - for line in hunk["lines"]: - assert "index" in line - assert isinstance(line["index"], int) - def test_header_and_hunk_lines_are_not_emitted(self): diff = "diff --git a/f.py b/f.py\nnew file mode 100644\n--- /dev/null\n+++ b/f.py\n@@ -0,0 +1 @@\n+x\n" result = parse_diff_to_json(diff, "f.py", CATPPUCCIN_MOCHA) diff --git a/tests/test_server.py b/tests/test_server.py index c2b5058..da0808e 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -8,7 +8,7 @@ from diffui.server.routes_diff import _order_files from diffui.server.theme_css import generate_css_vars -from diffui.themes.definitions import ALL_THEMES, CATPPUCCIN_MOCHA, GITHUB_DARK +from diffui.themes.definitions import ALL_THEMES, CATPPUCCIN_MOCHA class TestGenerateCssVars: @@ -34,11 +34,6 @@ def test_underscores_become_hyphens(self): assert "--bg-dark:" in result assert "--bg_dark:" not in result - def test_different_themes_produce_different_css(self): - mocha = generate_css_vars(CATPPUCCIN_MOCHA) - github = generate_css_vars(GITHUB_DARK) - assert mocha != github - @pytest.fixture(scope="class") def _server_app(temp_repo): @@ -110,11 +105,6 @@ def test_themes(self, _server_app): assert len(data) == len(ALL_THEMES) assert all("name" in t for t in data) - def test_theme_css(self, _server_app): - r = _server_app.get("/api/theme/css") - assert r.status_code == 200 - assert ":root {" in r.json()["css"] - @pytest.mark.parametrize("requested, expected", [(1, 1), (len(ALL_THEMES), 0)]) def test_settings_switches_theme(self, _server_app, requested, expected): _server_app.put("/api/settings", json={"theme_index": 0}) @@ -422,16 +412,6 @@ def test_review_summary_returns_markdown(self, _server_app): total = len(_server_app.get("/api/files").json()) assert f"/{total} reviewed" in md - def test_session_get_returns_dict(self, _server_app): - r = _server_app.get("/api/session") - assert r.status_code == 200 - assert isinstance(r.json(), dict) - - def test_session_put_and_get_roundtrip(self, _server_app): - _server_app.put("/api/session", json={"activeFile": "test.py"}) - r = _server_app.get("/api/session") - assert r.json().get("activeFile") == "test.py" - def test_session_put_is_additive(self, _server_app): _server_app.put("/api/session", json={"activeFile": "a.py"}) _server_app.put("/api/session", json={"diffMode": "split"}) @@ -590,10 +570,6 @@ def test_files_include_ignored_field(self, _server_app): if data: assert "ignored" in data[0] - def test_pydantic_validation_rejects_bad_comment(self, _server_app): - r = _server_app.post("/api/comments", json={"bad_field": "nope"}) - assert r.status_code == 422 - def test_repo_switch_invalid_index(self, _server_app): r = _server_app.post("/api/repo/switch", json={"index": 999}) assert r.status_code == 400 @@ -617,10 +593,6 @@ def test_bulk_resolve_reopen(self, _server_app): for c in _server_app.get("/api/comments").json().get("_test_reopen_.py", []): _server_app.delete(f"/api/comments/_test_reopen_.py/{c['id']}") - def test_bulk_resolve_invalid_action(self, _server_app): - r = _server_app.post("/api/comments/bulk-resolve", json={"action": "delete"}) - assert r.status_code == 422 - def test_apply_suggestion_success(self, _server_app): from diffui.git_utils import get_repo_root @@ -652,14 +624,6 @@ def test_apply_suggestion_success(self, _server_app): for c in _server_app.get("/api/comments").json().get("_test_apply_ok_.py", []): _server_app.delete(f"/api/comments/_test_apply_ok_.py/{c['id']}") - def test_settings_include_agent_cli(self, _server_app): - r = _server_app.get("/api/settings") - assert r.status_code == 200 - data = r.json() - assert "agent_cli" in data - assert isinstance(data["agent_cli"], str) - assert len(data["agent_cli"]) > 0 - def test_review_summary_with_comments(self, _server_app): _server_app.post( "/api/comments", @@ -774,15 +738,6 @@ def test_diff_expanded_context(self, _server_app): assert r.status_code == 200 assert "file_path" in r.json() - def test_diff_cache_hit_returns_same(self, _server_app): - files = _server_app.get("/api/files?view=all").json() - if not files: - pytest.skip("No changed files") - path = files[0]["path"] - first = _server_app.get(f"/api/diff/{path}?view=all").json() - second = _server_app.get(f"/api/diff/{path}?view=all").json() - assert first == second - @pytest.mark.parametrize("route", ["diff", "file"]) def test_html_off_drops_only_the_html(self, _server_app, route): def lines(data): @@ -794,18 +749,6 @@ def lines(data): assert not any("html" in ln for ln in without) assert [{k: v for k, v in ln.items() if k != "html"} for ln in with_html] == without - def test_clear_diff_cache_empties_cache(self, _server_app): - from diffui.server.routes_diff import _diff_cache, clear_diff_cache - - files = _server_app.get("/api/files?view=all").json() - if not files: - pytest.skip("No changed files") - path = files[0]["path"] - _server_app.get(f"/api/diff/{path}?view=all") - assert len(_diff_cache) >= 1 - clear_diff_cache() - assert len(_diff_cache) == 0 - def test_repo_switch_valid_index(self, _server_app): original = _server_app.get("/api/repos").json() active = next((r["index"] for r in original if r["active"]), 0) @@ -818,13 +761,6 @@ def test_repo_switch_valid_index(self, _server_app): finally: _server_app.post("/api/repo/switch", json={"index": active}) - def test_repos_caching_repeated_calls(self, _server_app): - first = _server_app.get("/api/repos") - second = _server_app.get("/api/repos") - assert first.status_code == 200 - assert second.status_code == 200 - assert first.json() == second.json() - def test_branch_includes_head_sha_and_remote(self, _server_app): r = _server_app.get("/api/branch") assert r.status_code == 200 @@ -1051,45 +987,6 @@ def test_no_extension_path(self): class TestExportJson: - def test_output_structure(self): - import json - from io import StringIO - from pathlib import Path - from unittest.mock import patch - - from diffui.git_utils import resolve_repo_root, set_active_repo - - root = resolve_repo_root(Path(__file__).parent.parent) - set_active_repo(root) - - buf = StringIO() - with patch("builtins.print", side_effect=lambda *a, **kw: buf.write(a[0] if a else "")): - from diffui.cli import export_json - - export_json() - - data = json.loads(buf.getvalue()) - assert "branch" in data - assert "main_branch" in data - assert "merge_base" in data - assert "summary" in data - assert "files" in data - - summary = data["summary"] - assert "total_files" in summary - assert "reviewed_files" in summary - assert "total_comments" in summary - assert "open_comments" in summary - assert "resolved_comments" in summary - assert summary["resolved_comments"] == summary["total_comments"] - summary["open_comments"] - - assert isinstance(data["files"], list) - for f in data["files"]: - assert "path" in f - assert "reviewed" in f - assert "comments" in f - assert "open_comment_count" in f - def test_export_lists_the_files_the_ui_lists(self, _server_app, temp_repo, capsys): from diffui.cli import export_json from diffui.git_utils import set_active_repo @@ -1099,19 +996,6 @@ def test_export_lists_the_files_the_ui_lists(self, _server_app, temp_repo, capsy exported = [f["path"] for f in json.loads(capsys.readouterr().out)["files"]] assert exported == [f["path"] for f in _server_app.get("/api/files").json()] - def test_agent_start_no_comments(self, _server_app): - r = _server_app.post("/api/agent/start") - assert r.status_code == 200 - data = r.json() - assert data["ok"] is False - assert "No open comments" in data["error"] - - def test_agent_ws_no_process(self, _server_app): - with _server_app.websocket_connect("ws://localhost/api/agent/ws") as ws: - msg = ws.receive_json() - assert msg["type"] == "error" - assert "No agent running" in msg["message"] - class TestPathContainment: def test_preview_rejects_absolute_path(self, _server_app, tmp_path): @@ -1270,19 +1154,6 @@ def test_unknown_agent_cli_is_rejected(self, _server_app): r = _server_app.put("/api/settings", json={"agent_cli": "curl"}) assert r.status_code == 422 - def test_font_size_out_of_range_is_rejected(self, _server_app): - assert _server_app.put("/api/settings", json={"font_size": 0}).status_code == 422 - assert _server_app.put("/api/settings", json={"font_size": 400}).status_code == 422 - - def test_documented_editor_is_accepted(self, _server_app): - original = _server_app.get("/api/settings").json() - try: - r = _server_app.put("/api/settings", json={"editor": "nvim"}) - assert r.status_code == 200 - assert _server_app.get("/api/settings").json()["editor"] == "nvim" - finally: - _server_app.put("/api/settings", json={"editor": original["editor"]}) - _FAKE_HERDR = """#!/usr/bin/env python3 import json, os, sys diff --git a/tests/test_themes.py b/tests/test_themes.py index 1348f61..254050b 100644 --- a/tests/test_themes.py +++ b/tests/test_themes.py @@ -1,30 +1,13 @@ from __future__ import annotations from diffui.themes import ALL_THEMES, DEFAULT_THEME -from diffui.themes.definitions import GRAPHITE class TestThemeDefinitions: - def test_all_themes_count(self): - assert len(ALL_THEMES) == 16 - - def test_all_themes_have_names(self): - for theme in ALL_THEMES: - assert theme.name - assert isinstance(theme.name, str) - - def test_all_themes_have_syntax(self): - for theme in ALL_THEMES: - assert theme.syntax - assert isinstance(theme.syntax, dict) - def test_unique_names(self): names = [t.name for t in ALL_THEMES] assert len(names) == len(set(names)) - def test_graphite_is_first(self): - assert ALL_THEMES[0] is GRAPHITE - def test_all_color_fields_are_hex(self): color_fields = [ "bg", From e960fdc94c0a30e42d2fe577900ef7b126570d51 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:13:20 -0700 Subject: [PATCH 03/10] Request files the fixture repo has, drop skip guards on state temp_repo always provides, assert what diff context and ignore_whitespace do --- tests/test_server.py | 140 ++++++++++++++++--------------------------- 1 file changed, 53 insertions(+), 87 deletions(-) diff --git a/tests/test_server.py b/tests/test_server.py index da0808e..c05d53a 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -76,27 +76,21 @@ def test_commits(self, _server_app): assert isinstance(r.json(), list) def test_files(self, _server_app): - r = _server_app.get("/api/files?view=all") - assert r.status_code == 200 - data = r.json() - assert isinstance(data, list) - if data: - assert "path" in data[0] - assert "short_name" in data[0] - assert "reviewed" in data[0] + files = _server_app.get("/api/files?view=all").json() + assert [f["path"] for f in files] == ["app.py", "extra.py", "untracked.txt"] + assert {k: files[0][k] for k in ("short_name", "reviewed", "adds", "dels", "risk_level", "ignored")} == { + "short_name": "app.py", + "reviewed": False, + "adds": 3, + "dels": 2, + "risk_level": "low", + "ignored": False, + } def test_diff(self, _server_app): - files = _server_app.get("/api/files?view=all").json() - if not files: - pytest.skip("No changed files") - path = files[0]["path"] - r = _server_app.get(f"/api/diff/{path}?view=all") - assert r.status_code == 200 - data = r.json() - assert "file_path" in data - assert "hunks" in data - assert "adds" in data - assert "dels" in data + data = _server_app.get("/api/diff/app.py?view=all").json() + assert (data["file_path"], data["adds"], data["dels"]) == ("app.py", 3, 2) + assert data["hunks"] def test_themes(self, _server_app): r = _server_app.get("/api/themes") @@ -202,18 +196,8 @@ def test_comment_resolve_toggle(self, _server_app): _server_app.delete(f"/api/comments/_test_resolve_.py/{c['id']}") def test_review_toggle(self, _server_app): - files = _server_app.get("/api/files?view=all").json() - if not files: - pytest.skip("No changed files") - path = files[0]["path"] - - r = _server_app.post(f"/api/reviewed/{path}") - assert r.status_code == 200 - assert r.json()["reviewed"] is True - - r = _server_app.post(f"/api/reviewed/{path}") - assert r.status_code == 200 - assert r.json()["reviewed"] is False + assert _server_app.post("/api/reviewed/app.py").json()["reviewed"] is True + assert _server_app.post("/api/reviewed/app.py").json()["reviewed"] is False def test_static_files(self, _server_app): r = _server_app.get("/static/app.js") @@ -380,10 +364,13 @@ def test_apply_suggestion_missing_comment(self, _server_app): r = _server_app.post("/api/comments/_test_apply3_.py/nonexistent-id/apply") assert r.status_code == 400 - def test_blame_returns_list(self, _server_app): - r = _server_app.get("/api/blame/diffui/__init__.py") - assert r.status_code == 200 - assert isinstance(r.json(), list) + def test_blame_attributes_each_line_to_its_commit(self, _server_app): + blame = _server_app.get("/api/blame/app.py").json() + assert len(blame) == 21 + assert all(len(entry["sha"]) == 8 for entry in blame) + assert blame[0]["author"] == "diffui test" + assert blame[4]["sha"] != blame[0]["sha"] + assert blame[20]["author"] == "Not Committed Yet" def test_blame_unknown_file(self, _server_app): r = _server_app.get("/api/blame/_nonexistent_path_.py") @@ -391,11 +378,9 @@ def test_blame_unknown_file(self, _server_app): assert r.json() == [] def test_preview_text_file(self, _server_app): - r = _server_app.get("/api/preview/diffui/__init__.py") - assert r.status_code == 200 - data = r.json() + data = _server_app.get("/api/preview/app.py").json() assert data["type"] == "text" - assert "content" in data + assert data["content"].startswith("line 1\nline 2\n") def test_preview_image_not_found(self, _server_app): r = _server_app.get("/api/preview/_fake_.png") @@ -435,18 +420,6 @@ def test_websocket_ping_pong(self, _server_app): data = json.loads(ws.receive_text()) assert data == {"type": "pong"} - def test_files_include_risk_scoring(self, _server_app): - r = _server_app.get("/api/files?view=all") - assert r.status_code == 200 - data = r.json() - if data: - f = data[0] - assert "risk_score" in f - assert "risk_level" in f - assert f["risk_level"] in ("low", "medium", "high") - assert "risk_reasons" in f - assert isinstance(f["risk_reasons"], list) - def test_agent_status_not_running(self, _server_app): r = _server_app.get("/api/agent/status") assert r.status_code == 200 @@ -554,21 +527,27 @@ def test_bulk_resolve_all_comments(self, _server_app): for c in _server_app.get("/api/comments").json().get(fp, []): _server_app.delete(f"/api/comments/{fp}/{c['id']}") - def test_diff_ignore_whitespace(self, _server_app): - files = _server_app.get("/api/files?view=all").json() - if not files: - pytest.skip("No changed files") - path = files[0]["path"] - r = _server_app.get(f"/api/diff/{path}?view=all&ignore_whitespace=true") - assert r.status_code == 200 - assert "file_path" in r.json() + def test_diff_context_widens_the_hunks(self, _server_app): + def context_lines(**params): + hunks = _server_app.get("/api/diff/app.py", params={"view": "all", **params}).json()["hunks"] + return [ln for h in hunks for ln in h["lines"] if ln["type"] == "context"] - def test_files_include_ignored_field(self, _server_app): - r = _server_app.get("/api/files?view=all") - assert r.status_code == 200 - data = r.json() - if data: - assert "ignored" in data[0] + assert len(context_lines(context=10)) > len(context_lines()) + + def test_diff_ignore_whitespace_drops_whitespace_only_changes(self, _server_app, temp_repo): + app_py = temp_repo / "app.py" + original = app_py.read_text() + app_py.write_text(original.replace("line 1\n", "line 1 \n", 1)) + try: + + def stats(**params): + data = _server_app.get("/api/diff/app.py", params={"view": "all", **params}).json() + return data["adds"], data["dels"] + + assert stats() == (4, 3) + assert stats(ignore_whitespace="true") == (3, 2) + finally: + app_py.write_text(original) def test_repo_switch_invalid_index(self, _server_app): r = _server_app.post("/api/repo/switch", json={"index": 999}) @@ -711,33 +690,21 @@ def test_editor_open(self, _server_app): assert mock_popen.called def test_files_view_working(self, _server_app): - r = _server_app.get("/api/files?view=working") - assert r.status_code == 200 - assert isinstance(r.json(), list) + files = _server_app.get("/api/files?view=working").json() + assert [f["path"] for f in files] == ["app.py", "untracked.txt"] def test_files_view_commit_sha(self, _server_app): commits = _server_app.get("/api/commits").json() - if not commits: - pytest.skip("No commits") - sha = commits[0]["sha"] - r = _server_app.get(f"/api/files?view={sha}") - assert r.status_code == 200 - assert isinstance(r.json(), list) + assert len(commits) == 2 + for commit in commits: + files = _server_app.get(f"/api/files?view={commit['sha']}").json() + assert [f["path"] for f in files] == commit["files"] def test_files_view_unknown_commit(self, _server_app): r = _server_app.get("/api/files?view=deadbeefdeadbeef") assert r.status_code == 200 assert r.json() == [] - def test_diff_expanded_context(self, _server_app): - files = _server_app.get("/api/files?view=all").json() - if not files: - pytest.skip("No changed files") - path = files[0]["path"] - r = _server_app.get(f"/api/diff/{path}?view=all&context=10") - assert r.status_code == 200 - assert "file_path" in r.json() - @pytest.mark.parametrize("route", ["diff", "file"]) def test_html_off_drops_only_the_html(self, _server_app, route): def lines(data): @@ -1070,10 +1037,9 @@ def test_option_shaped_view_does_not_reach_git(self, _server_app, tmp_path): assert not target.exists() def test_known_commit_sha_still_works(self, _server_app): - commits = _server_app.get("/api/commits").json() - sha = commits[0]["sha"] - r = _server_app.get(f"/api/diff/app.py?view={sha}") - assert r.status_code == 200 + sha = _server_app.get("/api/commits").json()[0]["sha"] + data = _server_app.get(f"/api/diff/app.py?view={sha}").json() + assert (data["adds"], data["dels"]) == (2, 2) class TestExplainViewGuard: From 3ef4bb138089ee24c8ccfc9220bd649cc61d2f9c Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:28:04 -0700 Subject: [PATCH 04/10] Reset comments and the active repo in one fixture, fold test_server cases into parametrized tables --- tests/conftest.py | 15 + tests/test_server.py | 967 +++++++++++-------------------------------- tests/test_themes.py | 49 +-- 3 files changed, 281 insertions(+), 750 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index edd5309..c8e4ce5 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -34,6 +34,21 @@ def diffui_config_root(tmp_path_factory): mp.undo() +@pytest.fixture(autouse=True) +def _isolate_repo_state(): + """Comments, reviewed marks and the active repo are process-wide, so one test's leftovers would reach the next.""" + from diffui.server.state import app_state + + active = diffui.git_utils._active_repo_root + yield + if active is not None: + diffui.git_utils.set_active_repo(active) + app_state.comments = {} + app_state.reviewed = {} + diffui.git_utils.save_comments({}) + diffui.git_utils.save_reviewed({}) + + @pytest.fixture(scope="session") def temp_repo(tmp_path_factory) -> Path: repo = tmp_path_factory.mktemp("diffui-repo") diff --git a/tests/test_server.py b/tests/test_server.py index c05d53a..b3362ae 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -2,50 +2,38 @@ import json import os -import pathlib +import subprocess +import tempfile +from pathlib import Path +from unittest.mock import MagicMock, patch import pytest - -from diffui.server.routes_diff import _order_files +from fastapi.testclient import TestClient +from starlette.websockets import WebSocketDisconnect + +from diffui.cli import export_json +from diffui.git_utils import set_active_repo +from diffui.server import routes_review +from diffui.server.app import create_app +from diffui.server.events import _apply_state_updates +from diffui.server.routes_diff import _order_files, _score_risk +from diffui.server.routes_review import _process_status from diffui.server.theme_css import generate_css_vars -from diffui.themes.definitions import ALL_THEMES, CATPPUCCIN_MOCHA - - -class TestGenerateCssVars: - def test_contains_root(self): - result = generate_css_vars(CATPPUCCIN_MOCHA) - assert result.startswith(":root {") - assert result.endswith("}") - - def test_contains_bg(self): - result = generate_css_vars(CATPPUCCIN_MOCHA) - assert f"--bg: {CATPPUCCIN_MOCHA.bg};" in result - - def test_skips_name(self): - result = generate_css_vars(CATPPUCCIN_MOCHA) - assert "--name:" not in result - - def test_skips_syntax(self): - result = generate_css_vars(CATPPUCCIN_MOCHA) - assert "--syntax:" not in result - - def test_underscores_become_hyphens(self): - result = generate_css_vars(CATPPUCCIN_MOCHA) - assert "--bg-dark:" in result - assert "--bg_dark:" not in result +from diffui.server.turns import TurnTracker, poll_once +from diffui.themes.definitions import ALL_THEMES +from tests.conftest import _git @pytest.fixture(scope="class") def _server_app(temp_repo): - from diffui.git_utils import set_active_repo - from diffui.server.app import create_app - set_active_repo(temp_repo) - app = create_app([temp_repo]) + return TestClient(create_app([temp_repo]), base_url="http://localhost") - from fastapi.testclient import TestClient - return TestClient(app, base_url="http://localhost") +def _post_comment(client, **fields) -> str: + payload = {"file_path": "app.py", "line_index": 1, "comment": "check", **fields} + client.post("/api/comments", json=payload) + return client.get("/api/comments").json()[payload["file_path"]][-1]["id"] class TestServerRoutes: @@ -54,26 +42,16 @@ def test_index_returns_html(self, _server_app): assert r.status_code == 200 assert "diffui" in r.text - def test_repos(self, _server_app): - r = _server_app.get("/api/repos") - assert r.status_code == 200 - data = r.json() - assert isinstance(data, list) - assert len(data) >= 1 - assert "name" in data[0] - assert "has_changes" in data[0] - - def test_branch(self, _server_app): - r = _server_app.get("/api/branch") - assert r.status_code == 200 - data = r.json() - assert "name" in data - assert "main_branch" in data + def test_repos(self, _server_app, temp_repo): + repos = _server_app.get("/api/repos").json() + assert [(r["name"], r["has_changes"], r["active"]) for r in repos] == [(temp_repo.name, True, True)] def test_commits(self, _server_app): - r = _server_app.get("/api/commits") - assert r.status_code == 200 - assert isinstance(r.json(), list) + commits = _server_app.get("/api/commits").json() + assert [(c["message"], c["files"]) for c in commits] == [ + ("reword two lines", ["app.py"]), + ("add extra module", ["extra.py"]), + ] def test_files(self, _server_app): files = _server_app.get("/api/files?view=all").json() @@ -111,89 +89,51 @@ def test_settings_switches_theme(self, _server_app, requested, expected): finally: _server_app.put("/api/settings", json={"theme_index": 0}) - def test_settings_roundtrip(self, _server_app): - r = _server_app.get("/api/settings") - assert r.status_code == 200 - original = r.json() - assert "editor" in original - + @pytest.mark.parametrize( + ("key", "value"), + [ + ("editor", "nvim"), + ("agent_cli", "codex"), + ("font_size", 16), + ("word_wrap", True), + ("keybindings", {"toggle-review": "R", "sort-risk": "x"}), + ], + ) + def test_settings_roundtrip(self, _server_app, key, value): + original = _server_app.get("/api/settings").json()[key] try: - r = _server_app.put("/api/settings", json={"editor": "nvim"}) - assert r.status_code == 200 - - r = _server_app.get("/api/settings") - assert r.json()["editor"] == "nvim" + assert _server_app.put("/api/settings", json={key: value}).status_code == 200 + assert _server_app.get("/api/settings").json()[key] == value finally: - _server_app.put("/api/settings", json={"editor": original["editor"]}) + _server_app.put("/api/settings", json={key: original}) def test_comment_crud(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_.py", - "line_index": 1, - "comment": "test comment", - }, - ) - assert r.status_code == 200 + cid = _post_comment(_server_app, comment="test comment") + comment = _server_app.get("/api/comments").json()["app.py"][0] + assert (comment["id"], comment["comment"], comment["status"]) == (cid, "test comment", "open") + assert comment["timestamp"] - try: - comments = _server_app.get("/api/comments").json() - assert "_test_.py" in comments - comment = comments["_test_.py"][0] - assert comment["comment"] == "test comment" - assert comment["status"] == "open" - assert "id" in comment - assert "timestamp" in comment - cid = comment["id"] - - r = _server_app.put(f"/api/comments/_test_.py/{cid}", json={"comment": "edited"}) - assert r.status_code == 200 - assert _server_app.get("/api/comments").json()["_test_.py"][0]["comment"] == "edited" + assert _server_app.put(f"/api/comments/app.py/{cid}", json={"comment": "edited"}).status_code == 200 + assert _server_app.get("/api/comments").json()["app.py"][0]["comment"] == "edited" - r = _server_app.post(f"/api/comments/_test_.py/{cid}/reply", json={"text": "reply"}) - assert r.status_code == 200 - replies = _server_app.get("/api/comments").json()["_test_.py"][0]["replies"] - assert len(replies) == 1 - assert replies[0]["text"] == "reply" + assert _server_app.post(f"/api/comments/app.py/{cid}/reply", json={"text": "reply"}).status_code == 200 + replies = _server_app.get("/api/comments").json()["app.py"][0]["replies"] + assert [r["text"] for r in replies] == ["reply"] - r = _server_app.delete(f"/api/comments/_test_.py/{cid}") - assert r.status_code == 200 - comments = _server_app.get("/api/comments").json() - assert "_test_.py" not in comments or len(comments["_test_.py"]) == 0 - finally: - comments = _server_app.get("/api/comments").json() - for c in comments.get("_test_.py", []): - _server_app.delete(f"/api/comments/_test_.py/{c['id']}") + assert _server_app.delete(f"/api/comments/app.py/{cid}").status_code == 200 + assert _server_app.get("/api/comments").json() == {} def test_comment_resolve_toggle(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_resolve_.py", - "line_index": 1, - "comment": "needs fix", - }, - ) - assert r.status_code == 200 - try: - comments = _server_app.get("/api/comments").json() - c = comments["_test_resolve_.py"][0] - assert c.get("status") == "open" + cid = _post_comment(_server_app) - r = _server_app.post(f"/api/comments/_test_resolve_.py/{c['id']}/resolve") - assert r.status_code == 200 - comments = _server_app.get("/api/comments").json() - assert comments["_test_resolve_.py"][0]["status"] == "resolved" + def status(): + return _server_app.get("/api/comments").json()["app.py"][0]["status"] - r = _server_app.post(f"/api/comments/_test_resolve_.py/{c['id']}/resolve") - assert r.status_code == 200 - comments = _server_app.get("/api/comments").json() - assert comments["_test_resolve_.py"][0]["status"] == "open" - finally: - comments = _server_app.get("/api/comments").json() - for c in comments.get("_test_resolve_.py", []): - _server_app.delete(f"/api/comments/_test_resolve_.py/{c['id']}") + assert status() == "open" + _server_app.post(f"/api/comments/app.py/{cid}/resolve") + assert status() == "resolved" + _server_app.post(f"/api/comments/app.py/{cid}/resolve") + assert status() == "open" def test_review_toggle(self, _server_app): assert _server_app.post("/api/reviewed/app.py").json()["reviewed"] is True @@ -205,164 +145,38 @@ def test_static_files(self, _server_app): r = _server_app.get("/static/style.css") assert r.status_code == 200 - def test_comment_category_stored(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_cat_.py", - "line_index": 1, - "comment": "bug here", - "category": "bug", - }, - ) - assert r.status_code == 200 - try: - c = _server_app.get("/api/comments").json()["_test_cat_.py"][0] - assert c["category"] == "bug" - finally: - for c in _server_app.get("/api/comments").json().get("_test_cat_.py", []): - _server_app.delete(f"/api/comments/_test_cat_.py/{c['id']}") - - def test_comment_category_defaults_empty(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_cat2_.py", - "line_index": 1, - "comment": "no cat", - }, - ) - assert r.status_code == 200 - try: - c = _server_app.get("/api/comments").json()["_test_cat2_.py"][0] - assert c["category"] == "" - finally: - for c in _server_app.get("/api/comments").json().get("_test_cat2_.py", []): - _server_app.delete(f"/api/comments/_test_cat2_.py/{c['id']}") - - def test_comment_suggestion_stored(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_sug_.py", - "line_index": 1, - "comment": "fix this", - "suggestion": "x = 1\n", - }, - ) - assert r.status_code == 200 - try: - c = _server_app.get("/api/comments").json()["_test_sug_.py"][0] - assert c["suggestion"] == "x = 1\n" - finally: - for c in _server_app.get("/api/comments").json().get("_test_sug_.py", []): - _server_app.delete(f"/api/comments/_test_sug_.py/{c['id']}") - - def test_comment_selection_stored(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_sel_.py", - "line_index": 1, - "comment": "this call is redundant", - "selected_text": "bar.baz", - "sel_start": 12, - "sel_end": 19, - }, - ) - assert r.status_code == 200 - try: - c = _server_app.get("/api/comments").json()["_test_sel_.py"][0] - assert c["selected_text"] == "bar.baz" - assert c["sel_start"] == 12 - assert c["sel_end"] == 19 - assert c["sel_end_index"] is None - finally: - for c in _server_app.get("/api/comments").json().get("_test_sel_.py", []): - _server_app.delete(f"/api/comments/_test_sel_.py/{c['id']}") - - def test_comment_multiline_selection_stored(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_sel3_.py", - "line_index": 4, - "comment": "this block should be extracted", - "selected_text": "if x:\n return y", - "sel_start": 4, - "sel_end": 12, - "sel_end_index": 6, - }, - ) - assert r.status_code == 200 - try: - c = _server_app.get("/api/comments").json()["_test_sel3_.py"][0] - assert c["line_index"] == 4 - assert c["sel_start"] == 4 - assert c["sel_end"] == 12 - assert c["sel_end_index"] == 6 - finally: - for c in _server_app.get("/api/comments").json().get("_test_sel3_.py", []): - _server_app.delete(f"/api/comments/_test_sel3_.py/{c['id']}") - - def test_comment_selection_defaults_empty(self, _server_app): - r = _server_app.post( - "/api/comments", - json={ - "file_path": "_test_sel2_.py", - "line_index": 1, - "comment": "whole line", - }, - ) - assert r.status_code == 200 - try: - c = _server_app.get("/api/comments").json()["_test_sel2_.py"][0] - assert c["selected_text"] == "" - assert c["sel_start"] is None - assert c["sel_end"] is None - finally: - for c in _server_app.get("/api/comments").json().get("_test_sel2_.py", []): - _server_app.delete(f"/api/comments/_test_sel2_.py/{c['id']}") - - def test_apply_suggestion_no_suggestion(self, _server_app): - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_apply1_.py", - "line_index": 1, - "comment": "no suggestion", - }, - ) - try: - cid = _server_app.get("/api/comments").json()["_test_apply1_.py"][0]["id"] - r = _server_app.post(f"/api/comments/_test_apply1_.py/{cid}/apply") - assert r.status_code == 400 - finally: - for c in _server_app.get("/api/comments").json().get("_test_apply1_.py", []): - _server_app.delete(f"/api/comments/_test_apply1_.py/{c['id']}") - - def test_apply_suggestion_no_line_num(self, _server_app): - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_apply2_.py", - "line_index": 1, - "comment": "fix", - "suggestion": "x = 1\n", - }, - ) - try: - cid = _server_app.get("/api/comments").json()["_test_apply2_.py"][0]["id"] - r = _server_app.post(f"/api/comments/_test_apply2_.py/{cid}/apply") - assert r.status_code == 400 - assert "line number" in r.json()["detail"].lower() - finally: - for c in _server_app.get("/api/comments").json().get("_test_apply2_.py", []): - _server_app.delete(f"/api/comments/_test_apply2_.py/{c['id']}") - - def test_apply_suggestion_missing_comment(self, _server_app): - r = _server_app.post("/api/comments/_test_apply3_.py/nonexistent-id/apply") - assert r.status_code == 400 + @pytest.mark.parametrize( + ("fields", "stored"), + [ + pytest.param( + {}, + {"category": "", "suggestion": "", "selected_text": "", "sel_start": None, "sel_end": None}, + id="defaults", + ), + pytest.param({"category": "bug"}, {"category": "bug"}, id="category"), + pytest.param({"suggestion": "x = 1\n"}, {"suggestion": "x = 1\n"}, id="suggestion"), + pytest.param( + {"selected_text": "bar.baz", "sel_start": 12, "sel_end": 19}, + {"selected_text": "bar.baz", "sel_start": 12, "sel_end": 19, "sel_end_index": None}, + id="selection", + ), + pytest.param( + { + "line_index": 4, + "selected_text": "if x:\n return y", + "sel_start": 4, + "sel_end": 12, + "sel_end_index": 6, + }, + {"line_index": 4, "sel_start": 4, "sel_end": 12, "sel_end_index": 6}, + id="multiline-selection", + ), + ], + ) + def test_comment_fields_are_stored(self, _server_app, fields, stored): + _post_comment(_server_app, **fields) + comment = _server_app.get("/api/comments").json()["app.py"][0] + assert {k: comment[k] for k in stored} == stored def test_blame_attributes_each_line_to_its_commit(self, _server_app): blame = _server_app.get("/api/blame/app.py").json() @@ -405,127 +219,53 @@ def test_session_put_is_additive(self, _server_app): assert session.get("diffMode") == "split" def test_websocket_connected_event(self, _server_app): - import json - with _server_app.websocket_connect("ws://localhost/api/ws") as ws: data = json.loads(ws.receive_text()) assert data == {"events": ["connected"]} def test_websocket_ping_pong(self, _server_app): - import json - with _server_app.websocket_connect("ws://localhost/api/ws") as ws: ws.receive_text() # consume connected ws.send_text(json.dumps({"type": "ping"})) data = json.loads(ws.receive_text()) assert data == {"type": "pong"} - def test_agent_status_not_running(self, _server_app): - r = _server_app.get("/api/agent/status") - assert r.status_code == 200 - assert r.json()["running"] is False + @pytest.mark.parametrize("route", ["agent", "explain"]) + def test_status_reports_nothing_running(self, _server_app, route): + assert _server_app.get(f"/api/{route}/status").json()["running"] is False - def test_agent_run_no_comments(self, _server_app): - r = _server_app.post("/api/agent/run") - assert r.status_code == 200 - data = r.json() + @pytest.mark.parametrize("route", ["run", "prompt"]) + def test_agent_routes_refuse_without_open_comments(self, _server_app, route): + data = _server_app.post(f"/api/agent/{route}").json() assert data["ok"] is False assert "No open comments" in data["error"] - def test_explain_status_not_running(self, _server_app): - r = _server_app.get("/api/explain/status") - assert r.status_code == 200 - assert r.json()["running"] is False - def test_explain_view_placeholder(self, _server_app): r = _server_app.get("/api/explain/view") assert r.status_code == 200 assert "No explanation generated yet" in r.text - def test_agent_prompt_no_comments(self, _server_app): - r = _server_app.post("/api/agent/prompt") - assert r.status_code == 200 - data = r.json() - assert data["ok"] is False - assert "No open comments" in data["error"] - - def test_settings_agent_cli_roundtrip(self, _server_app): - original = _server_app.get("/api/settings").json() - try: - r = _server_app.put("/api/settings", json={"agent_cli": "codex"}) - assert r.status_code == 200 - assert _server_app.get("/api/settings").json()["agent_cli"] == "codex" - finally: - _server_app.put("/api/settings", json={"agent_cli": original["agent_cli"]}) - - def test_settings_font_size(self, _server_app): - original = _server_app.get("/api/settings").json() - try: - r = _server_app.put("/api/settings", json={"font_size": 16}) - assert r.status_code == 200 - assert _server_app.get("/api/settings").json()["font_size"] == 16 - finally: - _server_app.put("/api/settings", json={"font_size": original.get("font_size", 13)}) + def test_bulk_resolve_and_reopen_one_file(self, _server_app): + _post_comment(_server_app, line_index=1) + _post_comment(_server_app, line_index=2) + _post_comment(_server_app, file_path="extra.py") - def test_settings_word_wrap(self, _server_app): - original = _server_app.get("/api/settings").json() - try: - r = _server_app.put("/api/settings", json={"word_wrap": True}) - assert r.status_code == 200 - assert _server_app.get("/api/settings").json()["word_wrap"] is True - finally: - _server_app.put("/api/settings", json={"word_wrap": original.get("word_wrap", False)}) + def statuses(path): + return [c["status"] for c in _server_app.get("/api/comments").json()[path]] - def test_settings_keybindings(self, _server_app): - original = _server_app.get("/api/settings").json() - try: - bindings = {"toggle-review": "R", "sort-risk": "x"} - r = _server_app.put("/api/settings", json={"keybindings": bindings}) - assert r.status_code == 200 - assert _server_app.get("/api/settings").json()["keybindings"] == bindings - finally: - _server_app.put("/api/settings", json={"keybindings": original.get("keybindings", {})}) + r = _server_app.post("/api/comments/bulk-resolve", json={"file_path": "app.py", "action": "resolve"}) + assert r.json() == {"ok": True, "count": 2} + assert statuses("app.py") == ["resolved", "resolved"] + assert statuses("extra.py") == ["open"] - def test_bulk_resolve_comments(self, _server_app): - _server_app.post( - "/api/comments", - json={"file_path": "_test_bulk_.py", "line_index": 1, "comment": "bulk1"}, - ) - _server_app.post( - "/api/comments", - json={"file_path": "_test_bulk_.py", "line_index": 2, "comment": "bulk2"}, - ) - try: - r = _server_app.post( - "/api/comments/bulk-resolve", json={"file_path": "_test_bulk_.py", "action": "resolve"} - ) - assert r.status_code == 200 - data = r.json() - assert data["ok"] is True - assert data["count"] == 2 - comments = _server_app.get("/api/comments").json().get("_test_bulk_.py", []) - assert all(c["status"] == "resolved" for c in comments) - finally: - for c in _server_app.get("/api/comments").json().get("_test_bulk_.py", []): - _server_app.delete(f"/api/comments/_test_bulk_.py/{c['id']}") + r = _server_app.post("/api/comments/bulk-resolve", json={"file_path": "app.py", "action": "reopen"}) + assert r.json() == {"ok": True, "count": 2} + assert statuses("app.py") == ["open", "open"] - def test_bulk_resolve_all_comments(self, _server_app): - _server_app.post( - "/api/comments", - json={"file_path": "_test_bulkall1_.py", "line_index": 1, "comment": "ba1"}, - ) - _server_app.post( - "/api/comments", - json={"file_path": "_test_bulkall2_.py", "line_index": 1, "comment": "ba2"}, - ) - try: - r = _server_app.post("/api/comments/bulk-resolve", json={"action": "resolve"}) - assert r.status_code == 200 - assert r.json()["count"] >= 2 - finally: - for fp in ("_test_bulkall1_.py", "_test_bulkall2_.py"): - for c in _server_app.get("/api/comments").json().get(fp, []): - _server_app.delete(f"/api/comments/{fp}/{c['id']}") + def test_bulk_resolve_without_a_file_covers_every_file(self, _server_app): + _post_comment(_server_app) + _post_comment(_server_app, file_path="extra.py") + assert _server_app.post("/api/comments/bulk-resolve", json={"action": "resolve"}).json()["count"] == 2 def test_diff_context_widens_the_hunks(self, _server_app): def context_lines(**params): @@ -553,141 +293,40 @@ def test_repo_switch_invalid_index(self, _server_app): r = _server_app.post("/api/repo/switch", json={"index": 999}) assert r.status_code == 400 - def test_bulk_resolve_reopen(self, _server_app): - _server_app.post( - "/api/comments", - json={"file_path": "_test_reopen_.py", "line_index": 1, "comment": "reopen test"}, - ) - try: - cid = _server_app.get("/api/comments").json()["_test_reopen_.py"][0]["id"] - _server_app.post(f"/api/comments/_test_reopen_.py/{cid}/resolve") - assert _server_app.get("/api/comments").json()["_test_reopen_.py"][0]["status"] == "resolved" - r = _server_app.post( - "/api/comments/bulk-resolve", json={"file_path": "_test_reopen_.py", "action": "reopen"} - ) - assert r.status_code == 200 - assert r.json()["count"] == 1 - assert _server_app.get("/api/comments").json()["_test_reopen_.py"][0]["status"] == "open" - finally: - for c in _server_app.get("/api/comments").json().get("_test_reopen_.py", []): - _server_app.delete(f"/api/comments/_test_reopen_.py/{c['id']}") - - def test_apply_suggestion_success(self, _server_app): - - from diffui.git_utils import get_repo_root - - test_file = get_repo_root() / "_test_apply_ok_.py" - test_file.write_text("old_line\nsecond\n") - try: - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_apply_ok_.py", - "line_index": 0, - "file_line_num": 1, - "comment": "fix it", - "suggestion": "new_line", - }, - ) - cid = _server_app.get("/api/comments").json()["_test_apply_ok_.py"][0]["id"] - r = _server_app.post(f"/api/comments/_test_apply_ok_.py/{cid}/apply") - assert r.status_code == 200 - assert r.json()["ok"] is True - content = test_file.read_text() - assert content.startswith("new_line\n") - assert "second" in content - comment = _server_app.get("/api/comments").json()["_test_apply_ok_.py"][0] - assert comment["status"] == "resolved" - finally: - test_file.unlink(missing_ok=True) - for c in _server_app.get("/api/comments").json().get("_test_apply_ok_.py", []): - _server_app.delete(f"/api/comments/_test_apply_ok_.py/{c['id']}") - - def test_review_summary_with_comments(self, _server_app): - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_summary_.py", - "line_index": 1, - "file_line_num": 10, - "comment": "fix this bug", - "category": "bug", - }, - ) - try: - r = _server_app.get("/api/review-summary") - assert r.status_code == 200 - md = r.json()["markdown"] - assert "## Open Comments" in md - assert "fix this bug" in md - assert "_test_summary_.py:10" in md - assert "1 total, 1 open, 0 resolved" in md - finally: - for c in _server_app.get("/api/comments").json().get("_test_summary_.py", []): - _server_app.delete(f"/api/comments/_test_summary_.py/{c['id']}") - - def test_review_summary_categorizes_open_comments(self, _server_app): - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_summary_cat_.py", - "line_index": 1, - "comment": "a bug", - "category": "bug", - }, - ) - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_summary_cat_.py", - "line_index": 2, - "comment": "a nit", - "category": "nit", - }, - ) - try: - md = _server_app.get("/api/review-summary").json()["markdown"] - assert "### Bug" in md - assert "### Nit" in md - finally: - for c in _server_app.get("/api/comments").json().get("_test_summary_cat_.py", []): - _server_app.delete(f"/api/comments/_test_summary_cat_.py/{c['id']}") + def test_review_summary_lists_open_comments_by_category(self, _server_app): + _post_comment(_server_app, comment="fix this bug", file_line_num=10, category="bug") + _post_comment(_server_app, comment="a nit", file_line_num=2, category="nit") + _post_comment(_server_app, comment="already handled", status="resolved") + md = _server_app.get("/api/review-summary").json()["markdown"] + assert "3 total, 2 open, 1 resolved" in md + assert "### Bug\n\n- **app.py:10** — fix this bug" in md + assert "### Nit\n\n- **app.py:2** — a nit" in md + assert "already handled" not in md def test_agent_prompt_with_comments(self, _server_app): - _server_app.post( - "/api/comments", - json={ - "file_path": "_test_prompt_.py", - "line_index": 1, - "file_line_num": 5, - "comment": "rename this variable", - "category": "suggestion", - }, - ) + _post_comment(_server_app, comment="rename this variable", file_line_num=5, category="suggestion") + data = _server_app.post("/api/agent/prompt").json() + assert data["ok"] is True + assert "rename this variable" in data["prompt"] + assert data["comment_count"] == 1 + assert "context_path" in data + assert "agent_cli" in data + + @pytest.mark.parametrize( + ("editor", "args"), + [("code", ["--goto", "{path}:3"]), ("nvim", ["+3", "{path}"])], + ) + def test_editor_open_launches_the_editor_at_the_line(self, _server_app, temp_repo, editor, args): + original = _server_app.get("/api/settings").json()["editor"] + _server_app.put("/api/settings", json={"editor": editor}) try: - r = _server_app.post("/api/agent/prompt") - assert r.status_code == 200 - data = r.json() - assert data["ok"] is True - assert "rename this variable" in data["prompt"] - assert data["comment_count"] == 1 - assert "context_path" in data - assert "agent_cli" in data + with patch("diffui.server.routes_settings.subprocess.Popen") as popen: + r = _server_app.post("/api/editor/open", json={"file_path": "app.py", "line_num": 3}) finally: - for c in _server_app.get("/api/comments").json().get("_test_prompt_.py", []): - _server_app.delete(f"/api/comments/_test_prompt_.py/{c['id']}") - - def test_editor_open(self, _server_app): - from unittest.mock import patch - - with patch("diffui.server.routes_settings.subprocess.Popen") as mock_popen: - r = _server_app.post( - "/api/editor/open", - json={"file_path": "diffui/__init__.py", "line_num": 3}, - ) - assert r.status_code == 200 - assert r.json()["ok"] is True - assert mock_popen.called + _server_app.put("/api/settings", json={"editor": original}) + assert r.json() == {"ok": True} + path = str((temp_repo / "app.py").resolve()) + assert popen.call_args.args[0] == [editor, *(a.format(path=path) for a in args)] def test_files_view_working(self, _server_app): files = _server_app.get("/api/files?view=working").json() @@ -728,21 +367,16 @@ def test_repo_switch_valid_index(self, _server_app): finally: _server_app.post("/api/repo/switch", json={"index": active}) - def test_branch_includes_head_sha_and_remote(self, _server_app): - r = _server_app.get("/api/branch") - assert r.status_code == 200 - data = r.json() - assert "head_sha" in data - assert "remote_url" in data - assert "merge_base" in data - assert "repo_name" in data + def test_branch(self, _server_app, temp_repo): + data = _server_app.get("/api/branch").json() + assert (data["name"], data["main_branch"], data["repo_name"]) == ("feature", "main", temp_repo.name) + assert len(data["head_sha"]) == 40 + assert data["merge_base"] != data["head_sha"] + assert data["remote_url"] == "" class TestReviewModule: def test_build_agent_context_no_comments(self): - from unittest.mock import patch - - from diffui.server import routes_review with patch.object(routes_review.app_state, "comments", {}): result = routes_review._build_agent_context() @@ -750,9 +384,6 @@ def test_build_agent_context_no_comments(self): assert result[1] == "No open comments" def test_build_agent_context_with_comments(self): - from unittest.mock import patch - - from diffui.server import routes_review comments = { "src/auth.py": [ @@ -778,8 +409,6 @@ def test_build_agent_context_with_comments(self): assert repo_root assert context_path - from pathlib import Path - ctx = Path(context_path).read_text() assert "### src/auth.py" in ctx assert "this is wrong" in ctx @@ -788,14 +417,10 @@ def test_build_agent_context_with_comments(self): assert "src/resolved.py" not in ctx def test_process_status_none(self): - from diffui.server.routes_review import _process_status assert _process_status(None) == {"running": False} def test_process_status_running(self): - from unittest.mock import MagicMock - - from diffui.server.routes_review import _process_status proc = MagicMock() proc.poll.return_value = None @@ -803,18 +428,12 @@ def test_process_status_running(self): assert _process_status(proc) == {"running": True, "pid": 4242} def test_process_status_finished(self): - from unittest.mock import MagicMock - - from diffui.server.routes_review import _process_status proc = MagicMock() proc.poll.return_value = 0 assert _process_status(proc) == {"running": False, "exit_code": 0} def test_explain_already_running(self, _server_app): - from unittest.mock import MagicMock, patch - - from diffui.server import routes_review running = MagicMock() running.poll.return_value = None @@ -826,9 +445,6 @@ def test_explain_already_running(self, _server_app): assert "already generating" in data["error"] def test_explain_unknown_agent(self, _server_app): - from unittest.mock import patch - - from diffui.server import routes_review with ( patch.object(routes_review, "_explain_process", None), @@ -841,11 +457,6 @@ def test_explain_unknown_agent(self, _server_app): assert "Unknown agent CLI" in data["error"] def test_view_explanation_with_temp_file(self, _server_app): - import tempfile - from pathlib import Path - from unittest.mock import patch - - from diffui.server import routes_review # Resolve gettempdir so the module's startswith() guard matches the # symlink-resolved path (macOS /var -> /private/var). @@ -864,9 +475,6 @@ def test_view_explanation_with_temp_file(self, _server_app): tmp.unlink(missing_ok=True) def test_view_explanation_path_traversal_guard(self, _server_app): - from unittest.mock import patch - - from diffui.server import routes_review with patch.object(routes_review, "_explain_output_path", "/etc/passwd"): r = _server_app.get("/api/explain/view") @@ -874,11 +482,6 @@ def test_view_explanation_path_traversal_guard(self, _server_app): assert "No explanation generated yet" in r.text def test_view_explanation_missing_file(self, _server_app): - import tempfile - from pathlib import Path - from unittest.mock import patch - - from diffui.server import routes_review tmp_dir = Path(tempfile.gettempdir()).resolve() missing = str(tmp_dir / "diffui-explain-does-not-exist.html") @@ -891,72 +494,28 @@ def test_view_explanation_missing_file(self, _server_app): assert "No explanation generated yet" in r.text -class TestRiskScoring: - def test_migration_file_high_risk(self): - from diffui.server.routes_diff import _score_risk - - _score, level, reasons = _score_risk("alembic/versions/001_init.py", 50, 0) - assert level in ("medium", "high") - assert "infra/migration" in reasons - - def test_config_file_scored(self): - from diffui.server.routes_diff import _score_risk - - score, _level, reasons = _score_risk("config/settings.yaml", 10, 5) - assert score >= 2 - assert "config" in reasons - - def test_large_deletion_scored(self): - from diffui.server.routes_diff import _score_risk - - _score, _level, reasons = _score_risk("src/module.py", 0, 100) - assert "large deletion" in reasons - - def test_test_removal_scored(self): - from diffui.server.routes_diff import _score_risk - - _score, _level, reasons = _score_risk("tests/test_auth.py", 5, 30) - assert "test removal" in reasons - - def test_low_risk_source_file(self): - from diffui.server.routes_diff import _score_risk - - _score, level, reasons = _score_risk("src/utils.py", 10, 5) - assert level == "low" - assert reasons == [] - - def test_high_churn_scored(self): - from diffui.server.routes_diff import _score_risk - - _score, _level, reasons = _score_risk("src/big_refactor.py", 150, 100) - assert "high churn" in reasons - - def test_moderate_deletion_adds_score_without_reason(self): - from diffui.server.routes_diff import _score_risk - - score, _level, reasons = _score_risk("src/module.py", 0, 30) - assert score == 1 - assert "large deletion" not in reasons - - def test_moderate_churn_adds_score_without_reason(self): - from diffui.server.routes_diff import _score_risk - - score, _level, reasons = _score_risk("src/module.py", 40, 20) - assert score >= 1 - assert "high churn" not in reasons - - def test_no_extension_path(self): - from diffui.server.routes_diff import _score_risk - - _score, level, reasons = _score_risk("Makefile", 5, 5) - assert level == "low" - assert reasons == [] +@pytest.mark.parametrize( + ("path", "adds", "dels", "expected"), + [ + pytest.param("alembic/versions/001_init.py", 50, 0, (3, "medium", ["infra/migration"]), id="migration"), + pytest.param("config/settings.yaml", 10, 5, (2, "low", ["config"]), id="config"), + pytest.param("infra/values.yaml", 1, 1, (5, "high", ["infra/migration", "config"]), id="infra-config"), + pytest.param("src/module.py", 0, 100, (3, "medium", ["large deletion"]), id="large-deletion"), + pytest.param("tests/test_auth.py", 5, 30, (3, "medium", ["test removal"]), id="test-removal"), + pytest.param("tests/test_auth.py", 30, 5, (0, "low", []), id="test-additions-are-not-removals"), + pytest.param("src/big_refactor.py", 150, 100, (4, "medium", ["large deletion", "high churn"]), id="churn"), + pytest.param("src/module.py", 0, 30, (1, "low", []), id="moderate-deletion-scores-without-a-reason"), + pytest.param("src/module.py", 40, 20, (1, "low", []), id="moderate-churn-scores-without-a-reason"), + pytest.param("src/utils.py", 10, 5, (0, "low", []), id="plain-source"), + pytest.param("Makefile", 5, 5, (0, "low", []), id="no-extension"), + ], +) +def test_score_risk(path, adds, dels, expected): + assert _score_risk(path, adds, dels) == expected class TestExportJson: def test_export_lists_the_files_the_ui_lists(self, _server_app, temp_repo, capsys): - from diffui.cli import export_json - from diffui.git_utils import set_active_repo set_active_repo(temp_repo) export_json() @@ -1044,71 +603,65 @@ def test_known_commit_sha_still_works(self, _server_app): class TestExplainViewGuard: def test_sibling_of_tempdir_is_rejected(self, _server_app, tmp_path): - import tempfile - from unittest.mock import patch - evil = pathlib.Path(f"{tempfile.gettempdir()}-evil") / "payload.html" + evil = Path(f"{tempfile.gettempdir()}-evil") / "payload.html" with patch("diffui.server.routes_review._explain_output_path", str(evil)): r = _server_app.get("/api/explain/view") assert r.status_code == 400 -class TestApplySuggestionGuards: - def _add(self, client, **fields): - payload = {"file_path": "app.py", "line_index": 0, "comment": "fix it", **fields} - client.post("/api/comments", json=payload) - return client.get("/api/comments").json()["app.py"][-1]["id"] +@pytest.fixture +def app_py(temp_repo): + path = temp_repo / "app.py" + original = path.read_text() + yield path + path.write_text(original) - def _cleanup(self, client): - _delete_app_py_comments(client) - def test_stale_line_text_is_rejected(self, _server_app, temp_repo): - before = (temp_repo / "app.py").read_text() - cid = self._add( - _server_app, - file_line_num=1, - line_text="-this line is long gone", - suggestion="replacement", - ) - try: - r = _server_app.post(f"/api/comments/app.py/{cid}/apply") - assert r.status_code == 409 - assert (temp_repo / "app.py").read_text() == before - finally: - self._cleanup(_server_app) - - def test_multi_line_range_is_rejected(self, _server_app, temp_repo): - before = (temp_repo / "app.py").read_text() - cid = self._add( - _server_app, - file_line_num=1, - line_text=" line 1", - suggestion="replacement", - sel_end_index=4, - ) - try: - r = _server_app.post(f"/api/comments/app.py/{cid}/apply") - assert r.status_code == 400 - assert "more than one line" in r.json()["detail"] - assert (temp_repo / "app.py").read_text() == before - finally: - self._cleanup(_server_app) - - def test_matching_line_text_still_applies(self, _server_app, temp_repo): - original = (temp_repo / "app.py").read_text() - cid = self._add( - _server_app, - file_line_num=1, - line_text=" line 1", - suggestion="line one", - ) - try: - r = _server_app.post(f"/api/comments/app.py/{cid}/apply") - assert r.status_code == 200 - assert (temp_repo / "app.py").read_text().splitlines()[0] == "line one" - finally: - (temp_repo / "app.py").write_text(original) - self._cleanup(_server_app) +class TestApplySuggestion: + @pytest.mark.parametrize( + ("fields", "status", "detail"), + [ + pytest.param({"file_line_num": 1}, 400, "No suggestion", id="no-suggestion"), + pytest.param({"suggestion": "x = 1\n"}, 400, "No line number", id="no-line-number"), + pytest.param( + {"file_line_num": 1, "line_text": "-this line is long gone", "suggestion": "replacement"}, + 409, + "changed since", + id="stale-line-text", + ), + pytest.param( + {"file_line_num": 1, "line_text": " line 1", "suggestion": "replacement", "sel_end_index": 4}, + 400, + "more than one line", + id="multi-line-range", + ), + ], + ) + def test_refusals_leave_the_file_and_comment_alone(self, _server_app, app_py, fields, status, detail): + before = app_py.read_text() + cid = _post_comment(_server_app, **fields) + r = _server_app.post(f"/api/comments/app.py/{cid}/apply") + assert (r.status_code, detail in r.json()["detail"]) == (status, True) + assert app_py.read_text() == before + assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "open" + + @pytest.mark.parametrize( + "fields", + [ + pytest.param({"line_text": " line 1"}, id="matching-line-text"), + pytest.param({}, id="no-line-text"), + ], + ) + def test_replaces_the_line_and_resolves_the_comment(self, _server_app, app_py, fields): + before = app_py.read_text() + cid = _post_comment(_server_app, file_line_num=1, suggestion="line one", **fields) + assert _server_app.post(f"/api/comments/app.py/{cid}/apply").json() == {"ok": True} + assert app_py.read_text() == before.replace("line 1\n", "line one\n", 1) + assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "resolved" + + def test_unknown_comment_is_refused(self, _server_app): + assert _server_app.post("/api/comments/app.py/no-such-id/apply").status_code == 400 class TestSettingsValidation: @@ -1145,11 +698,6 @@ def calls(): return calls -def _delete_app_py_comments(client): - for c in client.get("/api/comments").json().get("app.py", []): - client.delete(f"/api/comments/app.py/{c['id']}") - - def _agent(pane_id, cwd, status="idle"): return { "pane_id": pane_id, @@ -1163,14 +711,8 @@ def _agent(pane_id, cwd, status="idle"): class TestHerdr: def _paste(self, client, monkeypatch, agents): monkeypatch.setenv("HERDR_AGENTS", json.dumps(agents)) - client.post( - "/api/comments", - json={"file_path": "app.py", "line_index": 1, "file_line_num": 5, "comment": "end\x1b[201~\rrm -rf ~"}, - ) - try: - return client.post("/api/agent/paste").json() - finally: - _delete_app_py_comments(client) + _post_comment(client, file_line_num=5, comment="end\x1b[201~\rrm -rf ~") + return client.post("/api/agent/paste").json() @pytest.mark.parametrize( ("agents", "target"), @@ -1200,13 +742,10 @@ def test_paste_sends_one_bracketed_paste_to_the_right_agent( def test_prompt_names_the_pane_agent_only_inside_a_workspace(self, _server_app, temp_repo, fake_herdr, monkeypatch): monkeypatch.setenv("HERDR_AGENTS", json.dumps([_agent("w1:p1", temp_repo)])) - _server_app.post("/api/comments", json={"file_path": "app.py", "line_index": 1, "comment": "check"}) - try: - assert _server_app.post("/api/agent/prompt").json()["pane_agent"] == "claude" - monkeypatch.delenv("HERDR_WORKSPACE_ID") - assert _server_app.post("/api/agent/prompt").json()["pane_agent"] is None - finally: - _delete_app_py_comments(_server_app) + _post_comment(_server_app) + assert _server_app.post("/api/agent/prompt").json()["pane_agent"] == "claude" + monkeypatch.delenv("HERDR_WORKSPACE_ID") + assert _server_app.post("/api/agent/prompt").json()["pane_agent"] is None def test_paste_refuses_blocked_agent(self, _server_app, temp_repo, fake_herdr, monkeypatch): r = self._paste(_server_app, monkeypatch, [_agent("w1:p1", temp_repo, "blocked")]) @@ -1214,27 +753,22 @@ def test_paste_refuses_blocked_agent(self, _server_app, temp_repo, fake_herdr, m assert not [c for c in fake_herdr() if c[:2] == ["pane", "send-text"]] def test_reviewing_a_file_reports_sidebar_counts(self, _server_app, fake_herdr): - from diffui.server.events import _apply_state_updates - _server_app.post("/api/comments", json={"file_path": "app.py", "line_index": 1, "comment": "check"}) - try: - _server_app.post("/api/reviewed/app.py") - # The watcher sees reviewed.json change and runs this; TestClient never starts the watcher. - _apply_state_updates(["files_changed"]) - total = len(_server_app.get("/api/files").json()) - [*_, report] = [c for c in fake_herdr() if c[:2] == ["workspace", "report-metadata"]] - assert report[2:] == [ - "w1", - "--source", - "diffui", - "--token", - "comments=1 open", - "--token", - f"reviewed=☑ 1/{total}", - ] - finally: - _server_app.post("/api/reviewed/app.py") - _delete_app_py_comments(_server_app) + _post_comment(_server_app) + _server_app.post("/api/reviewed/app.py") + # The watcher sees reviewed.json change and runs this; TestClient never starts the watcher. + _apply_state_updates(["files_changed"]) + total = len(_server_app.get("/api/files").json()) + [*_, report] = [c for c in fake_herdr() if c[:2] == ["workspace", "report-metadata"]] + assert report[2:] == [ + "w1", + "--source", + "diffui", + "--token", + "comments=1 open", + "--token", + f"reviewed=☑ 1/{total}", + ] def _entry(path: str, risk: int = 0) -> dict: @@ -1293,11 +827,6 @@ def search(q, scope="all"): @pytest.fixture def own_repo(self, tmp_path, temp_repo): - from fastapi.testclient import TestClient - - from diffui.git_utils import set_active_repo - from diffui.server.app import create_app - from tests.conftest import _git (tmp_path / ".gitignore").write_text("generated/\n") (tmp_path / "generated").mkdir() @@ -1312,7 +841,6 @@ def own_repo(self, tmp_path, temp_repo): create_app([temp_repo]) def test_files_written_after_the_first_search_are_found(self, own_repo): - from diffui.server.events import _apply_state_updates client, repo = own_repo @@ -1342,7 +870,6 @@ def search(q): ], ) def test_turn_tracker_starts_on_the_rest_to_work_edge(samples, starts): - from diffui.server.turns import TurnTracker tracker = TurnTracker() assert [i for i, statuses in enumerate(samples) if tracker.observe(statuses)] == starts @@ -1350,13 +877,10 @@ def test_turn_tracker_starts_on_the_rest_to_work_edge(samples, starts): class TestLastTurn: def _git(self, repo, *args): - import subprocess return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout def test_lists_only_files_changed_since_the_turn_started(self, _server_app, temp_repo, fake_herdr, monkeypatch): - from diffui.server.events import _apply_state_updates - from diffui.server.turns import TurnTracker, poll_once reason = _server_app.get("/api/last-turn").json()["reason"] assert reason.startswith("No agent turn seen yet") @@ -1405,7 +929,6 @@ def test_requests_from_other_sites_are_rejected(self, _server_app, headers, stat assert _server_app.get("/api/files", headers=headers).status_code == status def test_foreign_websocket_is_rejected(self, _server_app): - from starlette.websockets import WebSocketDisconnect with ( pytest.raises(WebSocketDisconnect), diff --git a/tests/test_themes.py b/tests/test_themes.py index 254050b..f2c4499 100644 --- a/tests/test_themes.py +++ b/tests/test_themes.py @@ -1,6 +1,11 @@ from __future__ import annotations -from diffui.themes import ALL_THEMES, DEFAULT_THEME +import re +from dataclasses import MISSING, fields + +from diffui.server.theme_css import generate_css_vars +from diffui.themes import ALL_THEMES, DEFAULT_THEME, Theme +from diffui.themes.definitions import CATPPUCCIN_MOCHA class TestThemeDefinitions: @@ -8,36 +13,24 @@ def test_unique_names(self): names = [t.name for t in ALL_THEMES] assert len(names) == len(set(names)) - def test_all_color_fields_are_hex(self): - color_fields = [ - "bg", - "bg_dark", - "fg", - "fg_muted", - "border", - "accent", - "add_bg", - "add_hover", - "remove_bg", - "remove_hover", - "hunk_bg", - "hunk_fg", - "gutter_fg", - "gutter_sep", - "hover_bg", - "comment_bg", - "comment_header_bg", - "comment_accent", - "delete_fg", - "warn_bg", - "warn_hover", - "warn_fg", + def test_required_color_fields_are_hex(self): + required = [ + f.name for f in fields(Theme) if f.name != "name" and f.default is MISSING and f.default_factory is MISSING ] for theme in ALL_THEMES: - for field_name in color_fields: + for field_name in required: value = getattr(theme, field_name) - assert value.startswith("#"), f"{theme.name}.{field_name} = {value!r}" - assert len(value) == 7, f"{theme.name}.{field_name} = {value!r}" + assert re.fullmatch(r"#[0-9a-fA-F]{6}", value), f"{theme.name}.{field_name} = {value!r}" + + +def test_css_vars_hyphenate_each_color_field_and_skip_name_and_syntax(): + css = generate_css_vars(CATPPUCCIN_MOCHA) + assert css.startswith(":root {") and css.endswith("}") + assert f"--bg: {CATPPUCCIN_MOCHA.bg};" in css + assert f"--bg-dark: {CATPPUCCIN_MOCHA.bg_dark};" in css + assert "--bg_dark" not in css + assert "--name:" not in css + assert "--syntax:" not in css class TestDefaultTheme: From 303a794402060ea5b7e173de8d6b0832fca4ddb2 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:28:04 -0700 Subject: [PATCH 05/10] Fold git_utils and events cases into tables, run git_utils on temp_repo, drop mock-count watcher tests --- tests/test_events.py | 534 ++++++++++++---------------------------- tests/test_git_utils.py | 200 ++++----------- 2 files changed, 198 insertions(+), 536 deletions(-) diff --git a/tests/test_events.py b/tests/test_events.py index ce83137..d732709 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -1,444 +1,212 @@ from __future__ import annotations import asyncio -from pathlib import Path -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import patch import pytest from watchfiles import Change -from diffui.server.events import _apply_state_updates, _broadcast, _ws_clients +from diffui.server.events import ( + _apply_state_updates, + _broadcast, + _classify_changes, + _sse_clients, + _ws_clients, + make_watch_filter, +) from diffui.server.state import app_state - -@pytest.fixture() -def _setup_repo(): - from diffui.git_utils import resolve_repo_root, set_active_repo - - root = resolve_repo_root(Path(__file__).parent.parent) - set_active_repo(root) +GIT_DIR = "/repo/.git" +COMMENTS = "/cfg/comments.json" class TestClassifyChanges: - @pytest.fixture(autouse=True) - def setup(self, _setup_repo): - from diffui.git_utils import _comments_path, get_git_dir - from diffui.server.events import _classify_changes - - self._classify_fn = _classify_changes - self.git_dir = str(get_git_dir()) - self.comments_path = str(_comments_path()) - - def classify(self, changes): - return self._classify_fn(changes, self.git_dir, self.comments_path) - - def test_source_file_change(self): - changes = {(Change.modified, "/some/repo/src/main.py")} - events = self.classify(changes) - assert "files_changed" in events - - def test_git_head_change(self): - changes = {(Change.modified, f"{self.git_dir}/HEAD")} - events = self.classify(changes) - assert "git_changed" in events - - def test_git_index_change(self): - changes = {(Change.modified, f"{self.git_dir}/index")} - events = self.classify(changes) - assert "git_changed" in events - - def test_git_ref_change(self): - changes = {(Change.modified, f"{self.git_dir}/refs/heads/main")} - events = self.classify(changes) - assert "git_changed" in events - - def test_comments_change(self): - changes = {(Change.modified, self.comments_path)} - events = self.classify(changes) - assert "comments_changed" in events - - def test_mixed_changes(self): - changes = { - (Change.modified, "/some/repo/file.py"), - (Change.modified, f"{self.git_dir}/index"), - (Change.modified, self.comments_path), - } - events = self.classify(changes) - assert set(events) == {"files_changed", "git_changed", "comments_changed"} - - def test_empty_changes(self): - assert self.classify(set()) == [] - - def test_multiple_source_files_deduplicated(self): - changes = { - (Change.modified, "/some/repo/a.py"), - (Change.added, "/some/repo/b.py"), - } - events = self.classify(changes) - assert events.count("files_changed") == 1 + @pytest.mark.parametrize( + ("changes", "expected"), + [ + pytest.param({(Change.modified, "/repo/src/main.py")}, {"files_changed"}, id="source-file"), + pytest.param({(Change.modified, f"{GIT_DIR}/HEAD")}, {"git_changed"}, id="git-head"), + pytest.param({(Change.modified, f"{GIT_DIR}/index")}, {"git_changed"}, id="git-index"), + pytest.param({(Change.modified, f"{GIT_DIR}/refs/heads/main")}, {"git_changed"}, id="git-ref"), + pytest.param({(Change.modified, COMMENTS)}, {"comments_changed"}, id="comments"), + pytest.param({(Change.modified, "/repo/.gitignore")}, {"files_changed"}, id="gitignore-is-a-file-change"), + pytest.param( + {(Change.modified, "/repo/.github/workflows/ci.yml")}, + {"files_changed"}, + id="github-dir-is-a-file-change", + ), + pytest.param( + { + (Change.modified, "/repo/file.py"), + (Change.modified, f"{GIT_DIR}/index"), + (Change.modified, COMMENTS), + }, + {"files_changed", "git_changed", "comments_changed"}, + id="mixed", + ), + pytest.param( + {(Change.modified, "/repo/a.py"), (Change.added, "/repo/b.py")}, {"files_changed"}, id="dedup" + ), + pytest.param(set(), set(), id="empty"), + ], + ) + def test_classify(self, changes, expected): + events = _classify_changes(changes, GIT_DIR, COMMENTS) + assert (len(events), set(events)) == (len(expected), expected) class TestMakeWatchFilter: - @pytest.fixture(autouse=True) - def setup(self, _setup_repo): - from diffui.git_utils import get_git_dir - from diffui.server.events import make_watch_filter - - self.git_dir = str(get_git_dir()) - self.filt = make_watch_filter(self.git_dir) - - def test_accepts_source_file(self): - assert self.filt(Change.modified, "/some/repo/src/main.py") is True - - def test_rejects_pyc(self): - assert self.filt(Change.modified, "/some/repo/module.pyc") is False - - def test_rejects_pycache(self): - assert self.filt(Change.modified, "/some/repo/__pycache__/module.cpython-311.pyc") is False - - def test_accepts_git_head(self): - assert self.filt(Change.modified, f"{self.git_dir}/HEAD") is True - - def test_accepts_git_index(self): - assert self.filt(Change.modified, f"{self.git_dir}/index") is True - - def test_accepts_git_refs(self): - assert self.filt(Change.modified, f"{self.git_dir}/refs/heads/main") is True - - def test_rejects_git_objects(self): - assert self.filt(Change.modified, f"{self.git_dir}/objects/ab/cdef1234") is False - - def test_rejects_git_logs(self): - assert self.filt(Change.modified, f"{self.git_dir}/logs/HEAD") is False - - def test_rejects_unrelated_git_dir(self): - assert self.filt(Change.modified, "/other/repo/.git/HEAD") is False - - def test_rejects_bare_git_dir(self): - assert self.filt(Change.modified, "/some/repo/.git") is False + @pytest.mark.parametrize( + ("path", "accepted"), + [ + pytest.param("/repo/src/main.py", True, id="source-file"), + pytest.param("/repo/module.pyc", False, id="pyc"), + pytest.param("/repo/__pycache__/notes.txt", False, id="pycache"), + pytest.param(f"{GIT_DIR}/HEAD", True, id="git-head"), + pytest.param(f"{GIT_DIR}/index", True, id="git-index"), + pytest.param(f"{GIT_DIR}/refs/heads/main", True, id="git-refs"), + pytest.param(f"{GIT_DIR}/objects/ab/cdef1234", False, id="git-objects"), + pytest.param(f"{GIT_DIR}/logs/HEAD", False, id="git-logs"), + pytest.param("/other/repo/.git/HEAD", False, id="unrelated-git-dir"), + pytest.param("/repo/.git", False, id="bare-git-dir"), + ], + ) + def test_filter(self, path, accepted): + assert make_watch_filter(GIT_DIR)(Change.modified, path) is accepted + + +class _FakeWebSocket: + def __init__(self): + self.sent: list[str] = [] + + async def send_text(self, text: str) -> None: + self.sent.append(text) class TestBroadcast: - def test_broadcast_to_clients(self): - from diffui.server.events import _sse_clients as _clients - + def test_sse_clients_receive_the_events_as_data(self): q = asyncio.Queue(maxsize=8) - _clients.add(q) + _sse_clients.add(q) try: _broadcast(["files_changed"]) - msg = q.get_nowait() - assert '"files_changed"' in msg - assert msg.startswith("data: ") - assert msg.endswith("\n\n") + assert q.get_nowait() == 'data: {"events": ["files_changed"]}\n\n' finally: - _clients.discard(q) - - def test_broadcast_empty_events_is_noop(self): - from diffui.server.events import _sse_clients as _clients + _sse_clients.discard(q) + def test_no_events_sends_nothing(self): q = asyncio.Queue(maxsize=8) - _clients.add(q) + _sse_clients.add(q) try: _broadcast([]) assert q.empty() finally: - _clients.discard(q) - - def test_broadcast_full_queue_skipped(self): - from diffui.server.events import _sse_clients as _clients + _sse_clients.discard(q) + def test_full_queue_is_skipped(self): q = asyncio.Queue(maxsize=1) q.put_nowait("filler") - _clients.add(q) + _sse_clients.add(q) try: _broadcast(["files_changed"]) - assert q.qsize() == 1 + assert q.get_nowait() == "filler" + assert q.empty() finally: - _clients.discard(q) + _sse_clients.discard(q) + def test_ws_clients_receive_the_events(self): + async def broadcast_on_a_loop(): + _broadcast(["files_changed"]) + await asyncio.sleep(0) -async def _broadcast_on_loop(events): - _broadcast(events) - await asyncio.sleep(0) - - -class TestWsBroadcast: - def test_broadcast_delivers_to_ws_clients(self): - - ws = AsyncMock() + ws = _FakeWebSocket() _ws_clients.add(ws) try: - asyncio.run(_broadcast_on_loop(["files_changed"])) - ws.send_text.assert_called_once() - import json - - payload = json.loads(ws.send_text.call_args[0][0]) - assert "files_changed" in payload["events"] + asyncio.run(broadcast_on_a_loop()) + assert ws.sent == ['{"events": ["files_changed"]}'] finally: _ws_clients.discard(ws) -class TestApplyStateUpdates: - def test_git_changed_does_not_duplicate_files_changed(self): - - with ( - patch("diffui.server.state.app_state.reload_repo_state"), - patch("diffui.server.events.clear_diff_cache"), - ): - result = _apply_state_updates(["git_changed", "files_changed"]) +@pytest.fixture +def git_reload(): + """The git-changed path with the repo reload and its side effects stubbed; the reload mock sets what it changes.""" + with ( + patch("diffui.server.state.app_state.reload_repo_state") as reload, + patch("diffui.server.events.clear_diff_cache"), + patch("diffui.server.events._invalidate_stale_reviews"), + ): + yield reload - assert result.count("files_changed") == 1 - def test_files_changed_refreshes_numstat_and_working_files(self): - - prev_numstat = app_state.numstat - prev_working = app_state.working_files - try: - with ( - patch("diffui.server.events.get_diff_numstat", return_value={"a.py": (1, 2)}) as numstat, - patch("diffui.server.events.get_working_changed_files", return_value=["a.py"]) as working, - ): - result = _apply_state_updates(["files_changed"]) - - numstat.assert_called_once_with(app_state.merge_base) - working.assert_called_once() - assert app_state.numstat == {"a.py": (1, 2)} - assert app_state.working_files == ["a.py"] - assert result == ["files_changed"] - finally: - app_state.numstat = prev_numstat - app_state.working_files = prev_working - - def test_files_changed_skipped_when_git_changed_present(self): +class TestApplyStateUpdates: + @pytest.mark.parametrize("events", [["git_changed"], ["git_changed", "files_changed"]]) + def test_git_changed_announces_files_changed_once(self, git_reload, events): + assert _apply_state_updates(events).count("files_changed") == 1 + def test_files_changed_refreshes_numstat_and_working_files(self, monkeypatch): + monkeypatch.setattr(app_state, "numstat", {}) + monkeypatch.setattr(app_state, "working_files", []) with ( - patch("diffui.server.state.app_state.reload_repo_state"), - patch("diffui.server.events.clear_diff_cache"), - patch("diffui.server.events.get_diff_numstat") as numstat, - patch("diffui.server.events.get_working_changed_files") as working, + patch("diffui.server.events.get_diff_numstat", return_value={"a.py": (1, 2)}), + patch("diffui.server.events.get_working_changed_files", return_value=["a.py"]), ): + result = _apply_state_updates(["files_changed"]) + + assert app_state.numstat == {"a.py": (1, 2)} + assert app_state.working_files == ["a.py"] + assert result == ["files_changed"] + + def test_comments_changed_reloads_comments(self, monkeypatch): + monkeypatch.setattr(app_state, "comments", {}) + with patch("diffui.server.events.load_comments", return_value={"a.py": [{"id": "1"}]}): + result = _apply_state_updates(["comments_changed"]) + + assert app_state.comments == {"a.py": [{"id": "1"}]} + assert result == ["comments_changed"] + + @pytest.mark.parametrize( + ("reloaded", "announced"), + [ + pytest.param({"a.py": [{"id": "1", "comment": "from the new branch"}]}, True, id="new-branch-has-comments"), + pytest.param({}, False, id="comments-unchanged"), + ], + ) + def test_git_changed_announces_comments_only_when_they_differ(self, git_reload, monkeypatch, reloaded, announced): + monkeypatch.setattr(app_state, "comments", {}) + git_reload.side_effect = lambda: setattr(app_state, "comments", reloaded) + assert ("comments_changed" in _apply_state_updates(["git_changed"])) is announced + + @pytest.mark.parametrize(("new_branch", "restarted"), [("new-branch", True), ("old-branch", False)]) + def test_watcher_restarts_only_on_a_branch_switch(self, git_reload, monkeypatch, new_branch, restarted): + monkeypatch.setattr(app_state, "branch_name", "old-branch") + git_reload.side_effect = lambda: setattr(app_state, "branch_name", new_branch) + with patch("diffui.server.events.restart_watcher") as restart: _apply_state_updates(["git_changed"]) - numstat.assert_not_called() - working.assert_not_called() - - def test_comments_changed_reloads_comments(self): + assert restart.called is restarted - prev_comments = app_state.comments - try: - with patch("diffui.server.events.load_comments", return_value={"a.py": [{"id": "1"}]}) as load: - result = _apply_state_updates(["comments_changed"]) - - load.assert_called_once() - assert app_state.comments == {"a.py": [{"id": "1"}]} - assert result == ["comments_changed"] - finally: - app_state.comments = prev_comments - - def test_git_and_comments_changed_reload_comments_once(self): - - with ( - patch("diffui.server.state.app_state.reload_repo_state") as reload, - patch("diffui.server.events.clear_diff_cache") as clear_cache, - patch("diffui.server.events.load_comments") as load, - ): - result = _apply_state_updates(["git_changed", "comments_changed"]) - - reload.assert_called_once() - clear_cache.assert_called_once() - # reload_repo_state() already re-read them, so there's no second trip to disk. - load.assert_not_called() - assert "files_changed" in result - assert "comments_changed" in result - - def test_git_changed_announces_reloaded_comments(self): - prev_comments = app_state.comments - reloaded = {"a.py": [{"id": "1", "comment": "from the new branch"}]} - try: - app_state.comments = {} - with ( - patch( - "diffui.server.state.app_state.reload_repo_state", - side_effect=lambda: setattr(app_state, "comments", reloaded), - ), - patch("diffui.server.events.clear_diff_cache"), - patch("diffui.server.events._invalidate_stale_reviews"), - patch("diffui.server.events.load_comments", return_value=reloaded), - ): - result = _apply_state_updates(["git_changed"]) - - assert "comments_changed" in result - finally: - app_state.comments = prev_comments - def test_git_changed_stays_quiet_when_comments_unchanged(self): +class TestAutoUnreview: + def test_files_changed_unreviews_modified_files(self, monkeypatch): + monkeypatch.setattr(app_state, "reviewed", {"changed.py": 1000.0, "untouched.py": 2000.0}) + monkeypatch.setattr(app_state, "numstat", {}) + monkeypatch.setattr(app_state, "working_files", []) with ( - patch("diffui.server.state.app_state.reload_repo_state"), - patch("diffui.server.events.clear_diff_cache"), - patch("diffui.server.events._invalidate_stale_reviews"), + patch("diffui.server.events.get_diff_numstat", return_value={}), + patch("diffui.server.events.get_working_changed_files", return_value=[]), + patch("diffui.server.events.get_file_mtime", side_effect=lambda p: 1500.0 if p == "changed.py" else 2000.0), ): - result = _apply_state_updates(["git_changed"]) + _apply_state_updates(["files_changed"]) - assert "comments_changed" not in result + assert app_state.reviewed == {"untouched.py": 2000.0} - def test_branch_switch_restarts_watcher(self): - prev_branch = app_state.branch_name - try: - app_state.branch_name = "old-branch" - with ( - patch( - "diffui.server.state.app_state.reload_repo_state", - side_effect=lambda: setattr(app_state, "branch_name", "new-branch"), - ), - patch("diffui.server.events.clear_diff_cache"), - patch("diffui.server.events._invalidate_stale_reviews"), - patch("diffui.server.events.restart_watcher") as restart, - ): - _apply_state_updates(["git_changed"]) - - restart.assert_called_once() - finally: - app_state.branch_name = prev_branch - - def test_same_branch_leaves_watcher_alone(self): + def test_git_changed_also_unreviews_modified_files(self, monkeypatch): + monkeypatch.setattr(app_state, "reviewed", {"changed.py": 1000.0}) with ( patch("diffui.server.state.app_state.reload_repo_state"), patch("diffui.server.events.clear_diff_cache"), - patch("diffui.server.events._invalidate_stale_reviews"), - patch("diffui.server.events.restart_watcher") as restart, + patch("diffui.server.events.get_file_mtime", return_value=2000.0), ): _apply_state_updates(["git_changed"]) - restart.assert_not_called() - - -class TestAutoUnreview: - def test_files_changed_unreviews_modified_files(self): - prev_reviewed = app_state.reviewed.copy() - prev_numstat = app_state.numstat - prev_working = app_state.working_files - try: - app_state.reviewed = {"changed.py": 1000.0, "untouched.py": 2000.0} - with ( - patch("diffui.server.events.get_diff_numstat", return_value={}), - patch("diffui.server.events.get_working_changed_files", return_value=[]), - patch( - "diffui.server.events.get_file_mtime", side_effect=lambda p: 1500.0 if p == "changed.py" else 2000.0 - ), - ): - _apply_state_updates(["files_changed"]) - - assert "changed.py" not in app_state.reviewed - assert "untouched.py" in app_state.reviewed - finally: - app_state.reviewed = prev_reviewed - app_state.numstat = prev_numstat - app_state.working_files = prev_working - - def test_git_changed_also_unreviews_modified_files(self): - prev_reviewed = app_state.reviewed.copy() - try: - app_state.reviewed = {"changed.py": 1000.0} - with ( - patch("diffui.server.state.app_state.reload_repo_state"), - patch("diffui.server.events.clear_diff_cache"), - patch("diffui.server.events.get_file_mtime", return_value=2000.0), - patch("diffui.server.events.save_reviewed"), - ): - _apply_state_updates(["git_changed"]) - - assert "changed.py" not in app_state.reviewed - finally: - app_state.reviewed = prev_reviewed - - -class TestWatcherLifecycle: - def test_do_restart_sets_cancel_event(self): - - import diffui.server.events as events - - prev_cancel = events._watch_cancel - old_event = MagicMock() - events._watch_cancel = old_event - try: - with ( - patch.object(events.asyncio, "get_running_loop") as get_loop, - patch.object(events, "_watch_loop", return_value=MagicMock()), - ): - events._do_restart() - - old_event.set.assert_called_once() - assert events._watch_cancel is not old_event - assert isinstance(events._watch_cancel, asyncio.Event) - get_loop.return_value.create_task.assert_called_once() - finally: - events._watch_cancel = prev_cancel - - def test_do_restart_handles_no_prior_cancel(self): - - import diffui.server.events as events - - prev_cancel = events._watch_cancel - events._watch_cancel = None - try: - with ( - patch.object(events.asyncio, "get_running_loop") as get_loop, - patch.object(events, "_watch_loop", return_value=MagicMock()), - ): - events._do_restart() - - assert isinstance(events._watch_cancel, asyncio.Event) - get_loop.return_value.create_task.assert_called_once() - finally: - events._watch_cancel = prev_cancel - - def test_restart_watcher_noop_without_loop(self): - - import diffui.server.events as events - - with patch.object(events, "_loop", None), patch.object(events, "_do_restart") as do_restart: - events.restart_watcher() - - do_restart.assert_not_called() - - def test_restart_watcher_schedules_threadsafe(self): - - import diffui.server.events as events - - loop = MagicMock() - with patch.object(events, "_loop", loop): - events.restart_watcher() - - loop.call_soon_threadsafe.assert_called_once_with(events._do_restart) - - def test_start_poller_sets_loop_and_restarts(self): - - import diffui.server.events as events - - prev_loop = events._loop - loop = MagicMock() - try: - with ( - patch.object(events.asyncio, "get_running_loop", return_value=loop), - patch.object(events, "_do_restart") as do_restart, - ): - events.start_poller() - - assert events._loop is loop - do_restart.assert_called_once() - finally: - events._loop = prev_loop - - -class TestGitDirBoundary: - def test_gitignore_is_a_file_change(self): - from diffui.server.events import _classify_changes - - events = _classify_changes({(1, "/repo/.gitignore")}, "/repo/.git", "/cfg/comments.json") - assert events == ["files_changed"] - - def test_github_workflow_is_a_file_change(self): - from diffui.server.events import _classify_changes - - events = _classify_changes({(1, "/repo/.github/workflows/ci.yml")}, "/repo/.git", "/cfg/comments.json") - assert events == ["files_changed"] + assert app_state.reviewed == {} diff --git a/tests/test_git_utils.py b/tests/test_git_utils.py index 9c9bcba..1cc1afb 100644 --- a/tests/test_git_utils.py +++ b/tests/test_git_utils.py @@ -5,12 +5,24 @@ import pytest from diffui.git_utils import ( + PathOutsideRepo, _load_json, _safe_name, _save_json, diff_stat, + discover_sibling_repos, + get_changed_files, + get_diff_numstat, + get_file_content, + get_file_mtime, + get_merge_base, + repo_has_changes, + repo_relative, + resolve_repos, + set_active_repo, short_name, ) +from tests.conftest import _git class TestShortName: @@ -42,17 +54,9 @@ def test_no_special_chars(self): class TestLoadSaveJson: - def test_load_missing_file(self, tmp_path: Path): - result = _load_json(tmp_path / "missing.json", {}) - assert result == {} - - def test_load_missing_with_default(self, tmp_path: Path): - result = _load_json(tmp_path / "missing.json", []) - assert result == [] - - def test_load_missing_no_default(self, tmp_path: Path): - result = _load_json(tmp_path / "missing.json") - assert result == {} + @pytest.mark.parametrize(("args", "expected"), [((), {}), (({},), {}), (([],), [])]) + def test_load_missing_file_returns_the_default(self, tmp_path: Path, args, expected): + assert _load_json(tmp_path / "missing.json", *args) == expected def test_save_and_load(self, tmp_path: Path): p = tmp_path / "data.json" @@ -62,90 +66,35 @@ def test_save_and_load(self, tmp_path: Path): assert loaded == data -class TestDiffStat: - def test_simple_diff(self): - diff = ( - "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1,3 +1,4 @@\n line1\n-line2\n+line2_new\n+line2_extra\n line3\n" - ) - adds, dels = diff_stat(diff) - assert adds == 2 - assert dels == 1 - - def test_no_changes(self): - adds, dels = diff_stat("") - assert adds == 0 - assert dels == 0 - - def test_only_adds(self): - diff = "@@ -1 +1,3 @@\n+a\n+b\n+c\n" - adds, dels = diff_stat(diff) - assert adds == 3 - assert dels == 0 - - def test_only_deletes(self): - diff = "@@ -1,3 +1 @@\n-a\n-b\n-c\n" - adds, dels = diff_stat(diff) - assert adds == 0 - assert dels == 3 - - def test_ignores_meta_lines(self): - diff = "--- a/file\n+++ b/file\n@@ -1 +1 @@\n-old\n+new\n" - adds, dels = diff_stat(diff) - assert adds == 1 - assert dels == 1 +@pytest.mark.parametrize( + ("diff", "expected"), + [ + pytest.param( + "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1,3 +1,4 @@\n line1\n-line2\n+line2_new\n+line2_extra\n line3\n", + (2, 1), + id="mixed", + ), + pytest.param("", (0, 0), id="empty"), + pytest.param("--- a/file\n+++ b/file\n@@ -1 +1 @@\n-old\n+new\n", (1, 1), id="file-headers-are-not-counted"), + pytest.param( + "diff --git a/k8s.yaml b/k8s.yaml\n--- a/k8s.yaml\n+++ b/k8s.yaml\n@@ -1,3 +1,2 @@\n----\n-kind: Service\n+kind: Deployment\n", + (1, 2), + id="removed-yaml-separator-is-a-deletion", + ), + ], +) +def test_diff_stat(diff, expected): + assert diff_stat(diff) == expected class TestResolveRepos: - def test_explicit_paths(self): - from diffui.git_utils import resolve_repos - - repo_path = str(Path(__file__).parent.parent) - repos, idx = resolve_repos([repo_path]) - assert len(repos) == 1 - assert idx == 0 - assert repos[0].resolve() == Path(repo_path).resolve() - - def test_deduplicates(self): - from diffui.git_utils import resolve_repos - - repo_path = str(Path(__file__).parent.parent) - repos, _idx = resolve_repos([repo_path, repo_path]) - assert len(repos) == 1 - - -class TestGetBlame: - def test_returns_list_of_dicts(self): - from diffui.git_utils import get_blame, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) - result = get_blame("diffui/__init__.py") - assert isinstance(result, list) - if result: - assert "sha" in result[0] - assert "author" in result[0] - assert "timestamp" in result[0] - - def test_sha_is_8_chars(self): - from diffui.git_utils import get_blame, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) - result = get_blame("diffui/__init__.py") - for entry in result: - assert len(entry["sha"]) == 8 - - def test_unknown_file_returns_empty(self): - from diffui.git_utils import get_blame, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) - assert get_blame("does_not_exist.py") == [] + @pytest.mark.parametrize("copies", [1, 2]) + def test_explicit_paths_resolve_once(self, temp_repo, copies): + assert resolve_repos([str(temp_repo)] * copies) == ([temp_repo.resolve()], 0) class TestDiscoverSiblingRepos: def test_no_git_dirs_returns_empty(self, tmp_path: Path): - from diffui.git_utils import discover_sibling_repos (tmp_path / "parent").mkdir() child = tmp_path / "parent" / "child" @@ -153,7 +102,6 @@ def test_no_git_dirs_returns_empty(self, tmp_path: Path): assert discover_sibling_repos(child) == [] def test_finds_sibling_git_repos(self, tmp_path: Path): - from diffui.git_utils import discover_sibling_repos parent = tmp_path / "workspace" parent.mkdir() @@ -171,13 +119,10 @@ def test_finds_sibling_git_repos(self, tmp_path: Path): class TestRepoHasChanges: def test_branch_with_commits_has_changes(self, temp_repo): - from diffui.git_utils import repo_has_changes assert repo_has_changes(temp_repo) is True def test_untracked_file_alone_counts(self, tmp_path): - from diffui.git_utils import repo_has_changes - from tests.conftest import _git repo = tmp_path / "untracked-only" repo.mkdir() @@ -190,8 +135,6 @@ def test_untracked_file_alone_counts(self, tmp_path): class TestMergeBase: def test_stale_local_main_does_not_count_merged_commits(self, tmp_path): - from diffui.git_utils import get_changed_files, get_merge_base, set_active_repo - from tests.conftest import _git repo = tmp_path / "stale-main" repo.mkdir() @@ -212,31 +155,21 @@ def test_stale_local_main_does_not_count_merged_commits(self, tmp_path): class TestGetFileMtime: - def test_missing_file_returns_zero(self): - from diffui.git_utils import get_file_mtime, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) + def test_missing_file_returns_zero(self, temp_repo): + set_active_repo(temp_repo) assert get_file_mtime("_definitely_missing_file_.xyz") == 0.0 - def test_existing_file_returns_positive(self): - from diffui.git_utils import get_file_mtime, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) - assert get_file_mtime("diffui/__init__.py") > 0.0 + def test_existing_file_returns_its_mtime(self, temp_repo): + set_active_repo(temp_repo) + assert get_file_mtime("app.py") == (temp_repo / "app.py").stat().st_mtime class TestGetFileContent: - def test_missing_file_returns_empty(self): - from diffui.git_utils import get_file_content, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) + def test_missing_file_returns_empty(self, temp_repo): + set_active_repo(temp_repo) assert get_file_content("_definitely_missing_file_.xyz") == "" def test_binary_file_returns_empty(self, tmp_path: Path): - from diffui.git_utils import get_file_content, set_active_repo set_active_repo(tmp_path) binary = tmp_path / "data.bin" @@ -244,7 +177,6 @@ def test_binary_file_returns_empty(self, tmp_path: Path): assert get_file_content("data.bin") == "" def test_text_file_returns_content(self, tmp_path: Path): - from diffui.git_utils import get_file_content, set_active_repo set_active_repo(tmp_path) (tmp_path / "hello.txt").write_text("hi there\n") @@ -252,35 +184,18 @@ def test_text_file_returns_content(self, tmp_path: Path): class TestGetDiffNumstat: - def test_returns_dict(self): - from diffui.git_utils import get_diff_numstat, get_merge_base, set_active_repo - - root = Path(__file__).parent.parent - set_active_repo(root) - try: - from diffui.git_utils import get_main_branch - - main = get_main_branch() - base = get_merge_base(main) - stats = get_diff_numstat(base) - assert isinstance(stats, dict) - for path, (adds, dels) in stats.items(): - assert isinstance(path, str) - assert isinstance(adds, int) - assert isinstance(dels, int) - except RuntimeError: - pytest.skip("No merge base available") + def test_counts_committed_and_working_changes_but_not_untracked_files(self, temp_repo): + set_active_repo(temp_repo) + assert get_diff_numstat(get_merge_base("main")) == {"app.py": (3, 2), "extra.py": (1, 0)} class TestRepoRelative: def test_in_repo_path_returned_unchanged(self, temp_repo): - from diffui.git_utils import repo_relative, set_active_repo set_active_repo(temp_repo) assert repo_relative("app.py") == "app.py" def test_absolute_path_outside_repo_raises(self, temp_repo, tmp_path): - from diffui.git_utils import PathOutsideRepo, repo_relative, set_active_repo set_active_repo(temp_repo) outside = tmp_path / "secret.txt" @@ -289,14 +204,12 @@ def test_absolute_path_outside_repo_raises(self, temp_repo, tmp_path): repo_relative(str(outside)) def test_dotdot_escape_raises(self, temp_repo): - from diffui.git_utils import PathOutsideRepo, repo_relative, set_active_repo set_active_repo(temp_repo) with pytest.raises(PathOutsideRepo): repo_relative("../../etc/hostname") def test_symlink_pointing_outside_raises(self, temp_repo, tmp_path): - from diffui.git_utils import PathOutsideRepo, repo_relative, set_active_repo set_active_repo(temp_repo) outside = tmp_path / "target.txt" @@ -310,7 +223,6 @@ def test_symlink_pointing_outside_raises(self, temp_repo, tmp_path): link.unlink() def test_symlink_inside_repo_allowed(self, temp_repo): - from diffui.git_utils import repo_relative, set_active_repo set_active_repo(temp_repo) link = temp_repo / "alias.py" @@ -321,25 +233,8 @@ def test_symlink_inside_repo_allowed(self, temp_repo): link.unlink() -class TestDiffStatSeparatorLines: - def test_removed_separator_counts_as_a_deletion(self): - from diffui.git_utils import diff_stat - - diff = ( - "diff --git a/k8s.yaml b/k8s.yaml\n" - "--- a/k8s.yaml\n" - "+++ b/k8s.yaml\n" - "@@ -1,3 +1,2 @@\n" - "----\n" - "-kind: Service\n" - "+kind: Deployment\n" - ) - assert diff_stat(diff) == (1, 2) - - class TestJsonPersistence: def test_corrupt_file_is_moved_aside_and_default_returned(self, tmp_path): - from diffui.git_utils import _load_json path = tmp_path / "comments.json" path.write_text('{"a": [{"id"') @@ -348,7 +243,6 @@ def test_corrupt_file_is_moved_aside_and_default_returned(self, tmp_path): assert (tmp_path / "comments.json.corrupt").read_text() == '{"a": [{"id"' def test_save_leaves_no_temp_file(self, tmp_path): - from diffui.git_utils import _load_json, _save_json path = tmp_path / "comments.json" _save_json(path, {"a.py": [{"id": "1"}]}) From 11bb30b45bfd5fef4a045d81ea986fe1674285d9 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:28:04 -0700 Subject: [PATCH 06/10] Test pty helpers on real descriptors, pin exact ranges and marks in diff and highlight tests --- tests/test_agent_terminal.py | 127 ++++++++------------ tests/test_diff.py | 226 ++++++++++++----------------------- tests/test_highlight.py | 74 ++++++------ 3 files changed, 161 insertions(+), 266 deletions(-) diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index 7bf6345..864e049 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -1,5 +1,8 @@ from __future__ import annotations +import os +import signal +import subprocess import sys import time from pathlib import Path @@ -48,89 +51,56 @@ def test_buffer_stays_under_max_as_output_arrives(self): assert result.endswith(chunk) -class TestReadPty: - def test_data_available(self): - with ( - patch.object(rat.select, "select", return_value=([5], [], [])), - patch.object(rat.os, "read", return_value=b"data") as mock_read, - ): - assert _read_pty(5, timeout=0.1) == b"data" - mock_read.assert_called_once_with(5, 16384) - - def test_no_data_timeout(self): - with patch.object(rat.select, "select", return_value=([], [], [])): - assert _read_pty(5, timeout=0.1) is None - - def test_oserror_returns_none(self): - with patch.object(rat.select, "select", side_effect=OSError("boom")): - assert _read_pty(5) is None - - -class TestWritePty: - def test_normal_write_encodes(self): - with patch.object(rat.os, "write") as mock_write: - _write_pty(7, "hi") - mock_write.assert_called_once_with(7, b"hi") - - def test_oserror_swallowed(self): - with patch.object(rat.os, "write", side_effect=OSError("closed")): - _write_pty(7, "hi") # must not raise - - -class TestResizePty: - def test_oserror_swallowed(self): - with patch("fcntl.ioctl", side_effect=OSError("bad fd")): - _resize_pty(9, 40, 120) # must not raise +class TestPtyHelpers: + def test_read_returns_available_bytes_or_none(self): + r, w = os.pipe() + try: + assert _read_pty(r, timeout=0.01) is None + os.write(w, b"data") + assert _read_pty(r, timeout=1) == b"data" + finally: + os.close(r) + os.close(w) + + def test_closed_descriptors_are_swallowed(self): + r, w = os.pipe() + os.close(r) + try: + assert _read_pty(r) is None + _write_pty(w, "hi") + _resize_pty(r, 40, 120) + finally: + os.close(w) class TestKillAgent: def test_no_process_returns_none(self): - rat._agent_proc = None assert _kill_agent() is None - def test_terminates_cleanly(self): - proc = MagicMock() - proc.wait.return_value = 0 - proc.returncode = 0 - rat._agent_proc = proc - rat._agent_pty_fd = 12 + @pytest.mark.parametrize("fd_already_closed", [False, True]) + def test_terminates_the_process_and_releases_the_pty(self, fd_already_closed): + proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + r, w = os.pipe() + os.close(w) + if fd_already_closed: + os.close(r) + rat._agent_proc, rat._agent_pty_fd = proc, r - with patch.object(rat.os, "close") as mock_close: - code = _kill_agent() + assert _kill_agent() == -signal.SIGTERM - assert code == 0 - proc.terminate.assert_called_once() - proc.kill.assert_not_called() - mock_close.assert_called_once_with(12) - assert rat._agent_proc is None - assert rat._agent_pty_fd is None + assert proc.poll() is not None + assert (rat._agent_proc, rat._agent_pty_fd) == (None, None) + with pytest.raises(OSError): + os.fstat(r) - def test_needs_kill_after_timeout(self): + def test_kills_a_process_that_ignores_terminate(self): proc = MagicMock() - proc.wait.side_effect = [rat.subprocess.TimeoutExpired("cmd", 5), None] + proc.wait.side_effect = [subprocess.TimeoutExpired("cmd", 5), None] proc.returncode = -9 rat._agent_proc = proc - rat._agent_pty_fd = None - - code = _kill_agent() - assert code == -9 - proc.terminate.assert_called_once() + assert _kill_agent() == -9 proc.kill.assert_called_once() - assert proc.wait.call_count == 2 - - def test_close_oserror_swallowed(self): - proc = MagicMock() - proc.wait.return_value = 0 - proc.returncode = 0 - rat._agent_proc = proc - rat._agent_pty_fd = 3 - - with patch.object(rat.os, "close", side_effect=OSError("already closed")): - code = _kill_agent() - - assert code == 0 - assert rat._agent_pty_fd is None @pytest.fixture(scope="class") @@ -327,14 +297,11 @@ def test_kill_message_terminates(self, _server_app): class TestPendingStart: - def test_missing_pending_is_stale(self): - rat._pending_start = None - assert rat._pending_is_stale() is True - - def test_fresh_pending_is_not_stale(self): - rat._pending_start = {"created": time.monotonic()} - assert rat._pending_is_stale() is False - - def test_abandoned_pending_goes_stale(self): - rat._pending_start = {"created": time.monotonic() - rat._PENDING_TTL - 1} - assert rat._pending_is_stale() is True + @pytest.mark.parametrize( + ("age", "stale"), + [(None, True), (0, False), (rat._PENDING_TTL + 1, True)], + ids=["missing", "fresh", "abandoned"], + ) + def test_pending_start_goes_stale_after_its_ttl(self, age, stale): + rat._pending_start = None if age is None else {"created": time.monotonic() - age} + assert rat._pending_is_stale() is stale diff --git a/tests/test_diff.py b/tests/test_diff.py index d47281b..8d41557 100644 --- a/tests/test_diff.py +++ b/tests/test_diff.py @@ -18,84 +18,56 @@ ) -class TestClassifyLine: - def test_add(self): - assert classify_line("+new line") == "add" - - def test_remove(self): - assert classify_line("-old line") == "remove" - - def test_context(self): - assert classify_line(" unchanged") == "context" - - def test_hunk(self): - assert classify_line("@@ -1,3 +1,5 @@") == "hunk" - - def test_meta_diff(self): - assert classify_line("diff --git a/file b/file") == "meta" - - def test_meta_index(self): - assert classify_line("index abc123..def456 100644") == "meta" - - def test_meta_plus(self): - assert classify_line("+++ b/file.py") == "meta" - - def test_meta_minus(self): - assert classify_line("--- a/file.py") == "meta" - - def test_empty_line(self): - assert classify_line("") == "context" - - -class TestIsMetaLine: - def test_diff_header(self): - assert is_meta_line("diff --git a/f b/f") - - def test_index_line(self): - assert is_meta_line("index abc..def") - - def test_plus_header(self): - assert is_meta_line("+++ b/file") - - def test_minus_header(self): - assert is_meta_line("--- a/file") - - def test_regular_add(self): - assert not is_meta_line("+some code") - - def test_context(self): - assert not is_meta_line(" context line") - - -class TestStripDiffPrefix: - def test_add(self): - assert strip_diff_prefix("+new line") == "new line" - - def test_remove(self): - assert strip_diff_prefix("-old line") == "old line" - - def test_context(self): - assert strip_diff_prefix(" unchanged") == "unchanged" - - def test_no_prefix(self): - assert strip_diff_prefix("no prefix") == "no prefix" - - def test_empty(self): - assert strip_diff_prefix("") == "" - - -class TestResolveLineNum: - def test_prefers_new(self): - assert resolve_line_num("10", "20") == 20 - - def test_falls_back_to_old(self): - assert resolve_line_num("10", "") == 10 +@pytest.mark.parametrize( + ("line", "kind"), + [ + ("+new line", "add"), + ("-old line", "remove"), + (" unchanged", "context"), + ("@@ -1,3 +1,5 @@", "hunk"), + ("diff --git a/file b/file", "meta"), + ("index abc123..def456 100644", "meta"), + ("+++ b/file.py", "meta"), + ("--- a/file.py", "meta"), + ("", "context"), + ], +) +def test_classify_line(line, kind): + assert classify_line(line) == kind + + +@pytest.mark.parametrize( + ("line", "meta"), + [ + ("diff --git a/f b/f", True), + ("index abc..def", True), + ("+++ b/file", True), + ("--- a/file", True), + ("+some code", False), + (" context line", False), + ], +) +def test_is_meta_line(line, meta): + assert is_meta_line(line) is meta + + +@pytest.mark.parametrize( + ("line", "text"), + [ + ("+new line", "new line"), + ("-old line", "old line"), + (" unchanged", "unchanged"), + ("no prefix", "no prefix"), + ("", ""), + ], +) +def test_strip_diff_prefix(line, text): + assert strip_diff_prefix(line) == text - def test_returns_none_when_both_empty(self): - assert resolve_line_num("", "") is None - def test_new_only(self): - assert resolve_line_num("", "5") == 5 +@pytest.mark.parametrize(("old", "new", "expected"), [("10", "20", 20), ("10", "", 10), ("", "5", 5), ("", "", None)]) +def test_resolve_line_num_prefers_the_new_side(old, new, expected): + assert resolve_line_num(old, new) == expected class TestParseLineNumbers: @@ -181,77 +153,37 @@ def test_no_match(self): assert token_color(Token.Name, style_map) is None -class TestWordDiffRanges: - def test_single_word_change(self): - old_ranges, new_ranges = word_diff_ranges("hello world", "hello earth") - assert len(old_ranges) == 1 - assert len(new_ranges) == 1 - - def test_identical_lines(self): - old_ranges, new_ranges = word_diff_ranges("same text", "same text") - assert old_ranges == [] - assert new_ranges == [] - - def test_complete_replacement(self): - old_ranges, new_ranges = word_diff_ranges("old", "new") - assert len(old_ranges) == 1 - assert len(new_ranges) == 1 - - def test_insertion(self): - old_ranges, new_ranges = word_diff_ranges("a c", "a b c") - assert old_ranges == [] - assert len(new_ranges) == 1 - - def test_deletion(self): - old_ranges, new_ranges = word_diff_ranges("a b c", "a c") - assert len(old_ranges) == 1 - assert new_ranges == [] - - -class TestPairDiffLines: - def test_paired_add_remove(self): - lines = [ - "@@ -1,2 +1,2 @@", - "-old line", - "+new line", - ] - result = pair_diff_lines(lines) - assert 1 in result # remove line index - assert 2 in result # add line index - - def test_no_pairs(self): - lines = [ - "@@ -1 +1,2 @@", - " context", - "+added", - ] - result = pair_diff_lines(lines) - assert result == {} - - def test_multiple_pairs(self): - lines = [ - "-old1", - "-old2", - "+new1", - "+new2", - ] - result = pair_diff_lines(lines) - assert len(result) == 4 - for idx in (0, 1, 2, 3): - assert idx in result - assert isinstance(result[idx], list) - assert all(isinstance(r, tuple) and len(r) == 2 for r in result[idx]) - - def test_unmatched_removes(self): - lines = [ - "-removed1", - "-removed2", - "+added1", - ] - result = pair_diff_lines(lines) - assert 0 in result - assert 2 in result - assert 1 not in result +@pytest.mark.parametrize( + ("old", "new", "ranges"), + [ + ("hello world", "hello earth", ([(6, 11)], [(6, 11)])), + ("same text", "same text", ([], [])), + ("old", "new", ([(0, 3)], [(0, 3)])), + ("a c", "a b c", ([], [(2, 3)])), + ("a b c", "a c", ([(2, 3)], [])), + ], +) +def test_word_diff_ranges(old, new, ranges): + assert word_diff_ranges(old, new) == ranges + + +@pytest.mark.parametrize( + ("lines", "paired"), + [ + pytest.param(["@@ -1,2 +1,2 @@", "-old line", "+new line"], {1: [(0, 3)], 2: [(0, 3)]}, id="remove-and-add"), + pytest.param(["@@ -1 +1,2 @@", " context", "+added"], {}, id="no-removal-to-pair-with"), + pytest.param( + ["-old1", "-old2", "+new1", "+new2"], + {0: [(0, 4)], 1: [(0, 4)], 2: [(0, 4)], 3: [(0, 4)]}, + id="pairs-in-order", + ), + pytest.param( + ["-removed1", "-removed2", "+added1"], {0: [(0, 8)], 2: [(0, 6)]}, id="surplus-removal-stays-plain" + ), + ], +) +def test_pair_diff_lines(lines, paired): + assert pair_diff_lines(lines) == paired class TestYamlSeparatorLines: diff --git a/tests/test_highlight.py b/tests/test_highlight.py index 709e184..b992343 100644 --- a/tests/test_highlight.py +++ b/tests/test_highlight.py @@ -1,8 +1,11 @@ from __future__ import annotations +import pytest + from diffui.diff import get_lexer from diffui.server.highlight import ( _apply_word_highlights, + highlight_file_to_json, highlight_line_html, parse_diff_to_json, ) @@ -38,26 +41,28 @@ def test_empty_line(self): assert result == "" -class TestApplyWordHighlights: - def test_no_ranges_returns_unchanged(self): - html = 'hello' - assert _apply_word_highlights(html, [], "hello") == html - - def test_marks_plain_text(self): - result = _apply_word_highlights("hello world", [(0, 5)], "hello world") - assert "" in result - assert "" in result - assert "hello" in result - - def test_marks_inside_span(self): - html = 'abc' - result = _apply_word_highlights(html, [(0, 3)], "abc") - assert "" in result - - def test_handles_html_entities(self): - html = "<div>" - result = _apply_word_highlights(html, [(0, 5)], "
") - assert "" in result +@pytest.mark.parametrize( + ("code_html", "ranges", "plain", "marked"), + [ + pytest.param( + 'hello', [], "hello", 'hello', id="no-ranges" + ), + pytest.param("hello world", [(0, 5)], "hello world", "hello world", id="plain-text"), + pytest.param( + 'abc', + [(0, 3)], + "abc", + 'abc', + id="inside-span", + ), + pytest.param( + "<div>", [(0, 5)], "
", "<div>", id="entities-count-as-one-character" + ), + pytest.param("<div>", [(0, 1)], "
", "<div>", id="range-ends-inside-entities"), + ], +) +def test_apply_word_highlights(code_html, ranges, plain, marked): + assert _apply_word_highlights(code_html, ranges, plain) == marked class TestParseDiffToJson: @@ -71,22 +76,19 @@ def test_empty_diff(self): def test_simple_add(self): diff = "diff --git a/f.py b/f.py\n--- /dev/null\n+++ b/f.py\n@@ -0,0 +1,2 @@\n+line one\n+line two\n" result = parse_diff_to_json(diff, "f.py", CATPPUCCIN_MOCHA) - assert result["adds"] == 2 - assert result["dels"] == 0 - assert len(result["hunks"]) > 0 + assert (result["adds"], result["dels"]) == (2, 0) lines = result["hunks"][-1]["lines"] - add_lines = [line for line in lines if line["type"] == "add"] - assert len(add_lines) == 2 - assert all("html" in line for line in add_lines) + assert [(line["type"], line["new_num"]) for line in lines] == [("add", "1"), ("add", "2")] + assert all("html" in line for line in lines) - def test_line_numbers_present(self): + def test_line_numbers_track_both_sides(self): diff = "diff --git a/f.py b/f.py\n--- a/f.py\n+++ b/f.py\n@@ -1,2 +1,2 @@\n-old\n+new\n ctx\n" - result = parse_diff_to_json(diff, "f.py", CATPPUCCIN_MOCHA) - lines = result["hunks"][-1]["lines"] - remove_line = next(line for line in lines if line["type"] == "remove") - add_line = next(line for line in lines if line["type"] == "add") - assert remove_line["old_num"] is not None - assert add_line["new_num"] is not None + lines = parse_diff_to_json(diff, "f.py", CATPPUCCIN_MOCHA)["hunks"][-1]["lines"] + assert [(ln["type"], ln["old_num"], ln["new_num"]) for ln in lines] == [ + ("remove", "1", None), + ("add", None, "1"), + ("context", "2", "2"), + ] def test_header_and_hunk_lines_are_not_emitted(self): diff = "diff --git a/f.py b/f.py\nnew file mode 100644\n--- /dev/null\n+++ b/f.py\n@@ -0,0 +1 @@\n+x\n" @@ -104,14 +106,10 @@ def test_line_index_counts_skipped_header_and_hunk_lines(self): class TestHighlightFileToJson: def test_empty_content(self): - from diffui.server.highlight import highlight_file_to_json - result = highlight_file_to_json("", "", "f.py", CATPPUCCIN_MOCHA) assert result["lines"] == [] def test_basic_file(self): - from diffui.server.highlight import highlight_file_to_json - content = "line one\nline two\nline three\n" result = highlight_file_to_json(content, "", "f.txt", CATPPUCCIN_MOCHA) assert len(result["lines"]) == 3 @@ -120,8 +118,6 @@ def test_basic_file(self): assert all(line["type"] == "context" for line in result["lines"]) def test_with_diff_marks_added_lines(self): - from diffui.server.highlight import highlight_file_to_json - content = "old line\nnew line\n" diff = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1,2 @@\n old line\n+new line\n" result = highlight_file_to_json(content, diff, "f.txt", CATPPUCCIN_MOCHA) From e748ae7c092d81d29a29834d55ac00cd9a53c339 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:32:56 -0700 Subject: [PATCH 07/10] Run the agent terminal and export tests on temp_repo, share _server_app and post_comment through conftest --- tests/conftest.py | 15 ++++++++ tests/test_agent_terminal.py | 74 ++++++++---------------------------- tests/test_server.py | 67 ++++++++++++++++---------------- 3 files changed, 63 insertions(+), 93 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index c8e4ce5..58f6491 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -4,8 +4,10 @@ from pathlib import Path import pytest +from fastapi.testclient import TestClient import diffui.git_utils +from diffui.server.app import create_app _APP_V1 = "\n".join(f"line {i}" for i in range(1, 21)) + "\n" _APP_V2 = _APP_V1.replace("line 5", "line five").replace("line 12", "line twelve") @@ -70,3 +72,16 @@ def temp_repo(tmp_path_factory) -> Path: (repo / "app.py").write_text(_APP_DIRTY) (repo / "untracked.txt").write_text("never committed\n") return repo + + +@pytest.fixture(scope="class") +def _server_app(temp_repo) -> TestClient: + diffui.git_utils.set_active_repo(temp_repo) + return TestClient(create_app([temp_repo]), base_url="http://localhost") + + +def post_comment(client: TestClient, **fields) -> str: + """Add a comment on app.py line 1 unless `fields` say otherwise, and return its id.""" + payload = {"file_path": "app.py", "line_index": 1, "comment": "check", **fields} + client.post("/api/comments", json=payload) + return client.get("/api/comments").json()[payload["file_path"]][-1]["id"] diff --git a/tests/test_agent_terminal.py b/tests/test_agent_terminal.py index 864e049..ec74f42 100644 --- a/tests/test_agent_terminal.py +++ b/tests/test_agent_terminal.py @@ -5,7 +5,6 @@ import subprocess import sys import time -from pathlib import Path from unittest.mock import MagicMock, patch import pytest @@ -18,6 +17,7 @@ _resize_pty, _write_pty, ) +from tests.conftest import post_comment @pytest.fixture(autouse=True) @@ -103,78 +103,34 @@ def test_kills_a_process_that_ignores_terminate(self): proc.kill.assert_called_once() -@pytest.fixture(scope="class") -def _server_app(): - from diffui.git_utils import resolve_repo_root, set_active_repo - from diffui.server.app import create_app - - root = resolve_repo_root(Path(__file__).parent.parent) - set_active_repo(root) - app = create_app([root]) - - from fastapi.testclient import TestClient - - return TestClient(app, base_url="http://localhost") - - class TestStartAgentEndpoint: def test_already_running(self, _server_app): proc = MagicMock() proc.poll.return_value = None with patch.object(rat, "_agent_proc", proc): - r = _server_app.post("/api/agent/start") - assert r.status_code == 200 - body = r.json() + body = _server_app.post("/api/agent/start").json() assert body["ok"] is False assert "already running" in body["error"].lower() def test_no_open_comments(self, _server_app): - with ( - patch.object(rat, "_agent_proc", None), - patch.object(rat, "_build_agent_context", return_value=(None, "No open comments", "", 0)), - ): - r = _server_app.post("/api/agent/start") - assert r.status_code == 200 - body = r.json() - assert body["ok"] is False - assert body["error"] == "No open comments" + assert _server_app.post("/api/agent/start").json() == {"ok": False, "error": "No open comments"} - def test_unknown_agent_cli(self, _server_app): - with ( - patch.object(rat, "_agent_proc", None), - patch.object( - rat, - "_build_agent_context", - return_value=("prompt text", "/repo", "branch", 1), - ), - patch.object(rat.app_state, "agent_cli", "bogus-agent"), - ): - r = _server_app.post("/api/agent/start") - assert r.status_code == 200 - body = r.json() + def test_unknown_agent_cli(self, _server_app, monkeypatch): + monkeypatch.setattr(rat.app_state, "agent_cli", "bogus-agent") + post_comment(_server_app) + body = _server_app.post("/api/agent/start").json() assert body["ok"] is False - assert "Unknown agent CLI" in body["error"] - assert "bogus-agent" in body["error"] + assert "Unknown agent CLI: bogus-agent" in body["error"] - def test_start_stores_pending(self, _server_app): - with ( - patch.object(rat, "_agent_proc", None), - patch.object( - rat, - "_build_agent_context", - return_value=("prompt text", "/repo", "branch", 1), - ), - patch.object(rat.app_state, "agent_cli", "claude"), - ): - r = _server_app.post("/api/agent/start") + def test_start_stores_the_prompt_for_the_websocket_to_spawn(self, _server_app, temp_repo, monkeypatch): + monkeypatch.setattr(rat.app_state, "agent_cli", "claude") + post_comment(_server_app, comment="needs a rename") + assert _server_app.post("/api/agent/start").json() == {"ok": True, "agent": "claude"} + assert "needs a rename" in rat._pending_start["prompt"] + assert rat._pending_start["repo_root"] == str(temp_repo) - assert r.status_code == 200 - body = r.json() - assert body == {"ok": True, "agent": "claude"} - assert rat._pending_start is not None - assert rat._pending_start["prompt"] == "prompt text" - assert rat._pending_start["repo_root"] == "/repo" +class TestSpawnAgent: def test_spawned_agent_runs_in_its_own_session_on_a_sized_terminal(self, temp_repo): script = ( "import os, sys; " diff --git a/tests/test_server.py b/tests/test_server.py index b3362ae..66c47fa 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -21,19 +21,7 @@ from diffui.server.theme_css import generate_css_vars from diffui.server.turns import TurnTracker, poll_once from diffui.themes.definitions import ALL_THEMES -from tests.conftest import _git - - -@pytest.fixture(scope="class") -def _server_app(temp_repo): - set_active_repo(temp_repo) - return TestClient(create_app([temp_repo]), base_url="http://localhost") - - -def _post_comment(client, **fields) -> str: - payload = {"file_path": "app.py", "line_index": 1, "comment": "check", **fields} - client.post("/api/comments", json=payload) - return client.get("/api/comments").json()[payload["file_path"]][-1]["id"] +from tests.conftest import _git, post_comment class TestServerRoutes: @@ -108,7 +96,7 @@ def test_settings_roundtrip(self, _server_app, key, value): _server_app.put("/api/settings", json={key: original}) def test_comment_crud(self, _server_app): - cid = _post_comment(_server_app, comment="test comment") + cid = post_comment(_server_app, comment="test comment") comment = _server_app.get("/api/comments").json()["app.py"][0] assert (comment["id"], comment["comment"], comment["status"]) == (cid, "test comment", "open") assert comment["timestamp"] @@ -124,7 +112,7 @@ def test_comment_crud(self, _server_app): assert _server_app.get("/api/comments").json() == {} def test_comment_resolve_toggle(self, _server_app): - cid = _post_comment(_server_app) + cid = post_comment(_server_app) def status(): return _server_app.get("/api/comments").json()["app.py"][0]["status"] @@ -174,7 +162,7 @@ def test_static_files(self, _server_app): ], ) def test_comment_fields_are_stored(self, _server_app, fields, stored): - _post_comment(_server_app, **fields) + post_comment(_server_app, **fields) comment = _server_app.get("/api/comments").json()["app.py"][0] assert {k: comment[k] for k in stored} == stored @@ -246,9 +234,9 @@ def test_explain_view_placeholder(self, _server_app): assert "No explanation generated yet" in r.text def test_bulk_resolve_and_reopen_one_file(self, _server_app): - _post_comment(_server_app, line_index=1) - _post_comment(_server_app, line_index=2) - _post_comment(_server_app, file_path="extra.py") + post_comment(_server_app, line_index=1) + post_comment(_server_app, line_index=2) + post_comment(_server_app, file_path="extra.py") def statuses(path): return [c["status"] for c in _server_app.get("/api/comments").json()[path]] @@ -263,8 +251,8 @@ def statuses(path): assert statuses("app.py") == ["open", "open"] def test_bulk_resolve_without_a_file_covers_every_file(self, _server_app): - _post_comment(_server_app) - _post_comment(_server_app, file_path="extra.py") + post_comment(_server_app) + post_comment(_server_app, file_path="extra.py") assert _server_app.post("/api/comments/bulk-resolve", json={"action": "resolve"}).json()["count"] == 2 def test_diff_context_widens_the_hunks(self, _server_app): @@ -294,9 +282,9 @@ def test_repo_switch_invalid_index(self, _server_app): assert r.status_code == 400 def test_review_summary_lists_open_comments_by_category(self, _server_app): - _post_comment(_server_app, comment="fix this bug", file_line_num=10, category="bug") - _post_comment(_server_app, comment="a nit", file_line_num=2, category="nit") - _post_comment(_server_app, comment="already handled", status="resolved") + post_comment(_server_app, comment="fix this bug", file_line_num=10, category="bug") + post_comment(_server_app, comment="a nit", file_line_num=2, category="nit") + post_comment(_server_app, comment="already handled", status="resolved") md = _server_app.get("/api/review-summary").json()["markdown"] assert "3 total, 2 open, 1 resolved" in md assert "### Bug\n\n- **app.py:10** — fix this bug" in md @@ -304,7 +292,7 @@ def test_review_summary_lists_open_comments_by_category(self, _server_app): assert "already handled" not in md def test_agent_prompt_with_comments(self, _server_app): - _post_comment(_server_app, comment="rename this variable", file_line_num=5, category="suggestion") + post_comment(_server_app, comment="rename this variable", file_line_num=5, category="suggestion") data = _server_app.post("/api/agent/prompt").json() assert data["ok"] is True assert "rename this variable" in data["prompt"] @@ -515,12 +503,23 @@ def test_score_risk(path, adds, dels, expected): class TestExportJson: - def test_export_lists_the_files_the_ui_lists(self, _server_app, temp_repo, capsys): + def test_export_matches_the_files_comments_and_reviews_the_ui_shows(self, _server_app, capsys): + post_comment(_server_app) + post_comment(_server_app, file_path="extra.py", status="resolved") + _server_app.post("/api/reviewed/extra.py") - set_active_repo(temp_repo) export_json() - exported = [f["path"] for f in json.loads(capsys.readouterr().out)["files"]] - assert exported == [f["path"] for f in _server_app.get("/api/files").json()] + + exported = json.loads(capsys.readouterr().out) + assert (exported["branch"], exported["main_branch"]) == ("feature", "main") + assert exported["summary"] == { + "total_files": 3, + "reviewed_files": 1, + "total_comments": 2, + "open_comments": 1, + "resolved_comments": 1, + } + assert [f["path"] for f in exported["files"]] == [f["path"] for f in _server_app.get("/api/files").json()] class TestPathContainment: @@ -640,7 +639,7 @@ class TestApplySuggestion: ) def test_refusals_leave_the_file_and_comment_alone(self, _server_app, app_py, fields, status, detail): before = app_py.read_text() - cid = _post_comment(_server_app, **fields) + cid = post_comment(_server_app, **fields) r = _server_app.post(f"/api/comments/app.py/{cid}/apply") assert (r.status_code, detail in r.json()["detail"]) == (status, True) assert app_py.read_text() == before @@ -655,7 +654,7 @@ def test_refusals_leave_the_file_and_comment_alone(self, _server_app, app_py, fi ) def test_replaces_the_line_and_resolves_the_comment(self, _server_app, app_py, fields): before = app_py.read_text() - cid = _post_comment(_server_app, file_line_num=1, suggestion="line one", **fields) + cid = post_comment(_server_app, file_line_num=1, suggestion="line one", **fields) assert _server_app.post(f"/api/comments/app.py/{cid}/apply").json() == {"ok": True} assert app_py.read_text() == before.replace("line 1\n", "line one\n", 1) assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "resolved" @@ -711,7 +710,7 @@ def _agent(pane_id, cwd, status="idle"): class TestHerdr: def _paste(self, client, monkeypatch, agents): monkeypatch.setenv("HERDR_AGENTS", json.dumps(agents)) - _post_comment(client, file_line_num=5, comment="end\x1b[201~\rrm -rf ~") + post_comment(client, file_line_num=5, comment="end\x1b[201~\rrm -rf ~") return client.post("/api/agent/paste").json() @pytest.mark.parametrize( @@ -742,7 +741,7 @@ def test_paste_sends_one_bracketed_paste_to_the_right_agent( def test_prompt_names_the_pane_agent_only_inside_a_workspace(self, _server_app, temp_repo, fake_herdr, monkeypatch): monkeypatch.setenv("HERDR_AGENTS", json.dumps([_agent("w1:p1", temp_repo)])) - _post_comment(_server_app) + post_comment(_server_app) assert _server_app.post("/api/agent/prompt").json()["pane_agent"] == "claude" monkeypatch.delenv("HERDR_WORKSPACE_ID") assert _server_app.post("/api/agent/prompt").json()["pane_agent"] is None @@ -754,7 +753,7 @@ def test_paste_refuses_blocked_agent(self, _server_app, temp_repo, fake_herdr, m def test_reviewing_a_file_reports_sidebar_counts(self, _server_app, fake_herdr): - _post_comment(_server_app) + post_comment(_server_app) _server_app.post("/api/reviewed/app.py") # The watcher sees reviewed.json change and runs this; TestClient never starts the watcher. _apply_state_updates(["files_changed"]) From bcc6e9edef262c79987d7ac2fb85df3a644ef42b Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:37:23 -0700 Subject: [PATCH 08/10] Wait for the search row Enter would open, and report the rows when the TUI wait times out --- tests/test_tui.py | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/tests/test_tui.py b/tests/test_tui.py index 72435ed..ecfa2b5 100644 --- a/tests/test_tui.py +++ b/tests/test_tui.py @@ -31,10 +31,10 @@ def server(temp_repo): save_reviewed({}) -async def until(pilot, condition, timeout: float = 10): +async def until(pilot, condition, timeout: float = 10, state=lambda: ""): deadline = time.monotonic() + timeout while not condition(): - assert time.monotonic() < deadline, "timed out waiting for the TUI" + assert time.monotonic() < deadline, f"timed out waiting for the TUI: {state()}" await pilot.pause(0.05) @@ -124,6 +124,23 @@ def hints(app) -> str: return " · ".join(f"{k.key_display} {k.description}" for k in app.query_one(Footer).query("FooterKey")) +async def until_search_picks(pilot, text: str) -> None: + """Wait until Enter would open the result containing `text`. + + Typing searches on every pause longer than the debounce, so a row count or a matching row can come from + a half-typed query whose first result is another file. + """ + results = pilot.app.screen.query_one(OptionList) + + def rows() -> list[str]: + return [str(results.get_option_at_index(i).prompt) for i in range(results.option_count)] + + def picked() -> str: + return rows()[results.highlighted] if results.highlighted is not None else "" + + await until(pilot, lambda: text in picked(), state=lambda: f"highlighted {picked()!r} of {rows()}") + + async def type_text(pilot, text: str) -> None: await pilot.press(*("space" if ch == " " else ch for ch in text)) @@ -295,8 +312,7 @@ async def scenario(app, view, pilot): await pilot.press("slash") assert isinstance(app.screen, SearchScreen) await type_text(pilot, "value") - results = app.screen.query_one(OptionList) - await until(pilot, lambda: results.option_count > 1) + await until_search_picks(pilot, "VALUE = 1") await pilot.press("enter") await until(pilot, lambda: app.active == "extra.py" and view.path == "extra.py") assert view.current.line["text"] == "+VALUE = 1" @@ -311,8 +327,8 @@ async def scenario(app, view, pilot): await pilot.press("tab") assert "All files" in heading(app) await type_text(pilot, "render_25") + await until_search_picks(pilot, "render_25") results = app.screen.query_one(OptionList) - await until(pilot, lambda: results.option_count > 1) assert "not in diff" in str(results.get_option_at_index(0).prompt) await pilot.press("enter") await until(pilot, lambda: app.active == "renderer.py" and view.path == "renderer.py") From 4f83e376f67d70af4d4f2db516e25d16b84c33c9 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:37:23 -0700 Subject: [PATCH 09/10] Split test_server.py into comments, search and risk modules (pure move) --- tests/test_comments.py | 144 +++++++++++++++++++++++ tests/test_risk.py | 35 ++++++ tests/test_search.py | 87 ++++++++++++++ tests/test_server.py | 251 +---------------------------------------- 4 files changed, 267 insertions(+), 250 deletions(-) create mode 100644 tests/test_comments.py create mode 100644 tests/test_risk.py create mode 100644 tests/test_search.py diff --git a/tests/test_comments.py b/tests/test_comments.py new file mode 100644 index 0000000..4e4cb61 --- /dev/null +++ b/tests/test_comments.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import pytest + +from tests.conftest import post_comment + + +class TestComments: + def test_comment_crud(self, _server_app): + cid = post_comment(_server_app, comment="test comment") + comment = _server_app.get("/api/comments").json()["app.py"][0] + assert (comment["id"], comment["comment"], comment["status"]) == (cid, "test comment", "open") + assert comment["timestamp"] + + assert _server_app.put(f"/api/comments/app.py/{cid}", json={"comment": "edited"}).status_code == 200 + assert _server_app.get("/api/comments").json()["app.py"][0]["comment"] == "edited" + + assert _server_app.post(f"/api/comments/app.py/{cid}/reply", json={"text": "reply"}).status_code == 200 + replies = _server_app.get("/api/comments").json()["app.py"][0]["replies"] + assert [r["text"] for r in replies] == ["reply"] + + assert _server_app.delete(f"/api/comments/app.py/{cid}").status_code == 200 + assert _server_app.get("/api/comments").json() == {} + + def test_comment_resolve_toggle(self, _server_app): + cid = post_comment(_server_app) + + def status(): + return _server_app.get("/api/comments").json()["app.py"][0]["status"] + + assert status() == "open" + _server_app.post(f"/api/comments/app.py/{cid}/resolve") + assert status() == "resolved" + _server_app.post(f"/api/comments/app.py/{cid}/resolve") + assert status() == "open" + + @pytest.mark.parametrize( + ("fields", "stored"), + [ + pytest.param( + {}, + {"category": "", "suggestion": "", "selected_text": "", "sel_start": None, "sel_end": None}, + id="defaults", + ), + pytest.param({"category": "bug"}, {"category": "bug"}, id="category"), + pytest.param({"suggestion": "x = 1\n"}, {"suggestion": "x = 1\n"}, id="suggestion"), + pytest.param( + {"selected_text": "bar.baz", "sel_start": 12, "sel_end": 19}, + {"selected_text": "bar.baz", "sel_start": 12, "sel_end": 19, "sel_end_index": None}, + id="selection", + ), + pytest.param( + { + "line_index": 4, + "selected_text": "if x:\n return y", + "sel_start": 4, + "sel_end": 12, + "sel_end_index": 6, + }, + {"line_index": 4, "sel_start": 4, "sel_end": 12, "sel_end_index": 6}, + id="multiline-selection", + ), + ], + ) + def test_comment_fields_are_stored(self, _server_app, fields, stored): + post_comment(_server_app, **fields) + comment = _server_app.get("/api/comments").json()["app.py"][0] + assert {k: comment[k] for k in stored} == stored + + def test_bulk_resolve_and_reopen_one_file(self, _server_app): + post_comment(_server_app, line_index=1) + post_comment(_server_app, line_index=2) + post_comment(_server_app, file_path="extra.py") + + def statuses(path): + return [c["status"] for c in _server_app.get("/api/comments").json()[path]] + + r = _server_app.post("/api/comments/bulk-resolve", json={"file_path": "app.py", "action": "resolve"}) + assert r.json() == {"ok": True, "count": 2} + assert statuses("app.py") == ["resolved", "resolved"] + assert statuses("extra.py") == ["open"] + + r = _server_app.post("/api/comments/bulk-resolve", json={"file_path": "app.py", "action": "reopen"}) + assert r.json() == {"ok": True, "count": 2} + assert statuses("app.py") == ["open", "open"] + + def test_bulk_resolve_without_a_file_covers_every_file(self, _server_app): + post_comment(_server_app) + post_comment(_server_app, file_path="extra.py") + assert _server_app.post("/api/comments/bulk-resolve", json={"action": "resolve"}).json()["count"] == 2 + + +@pytest.fixture +def app_py(temp_repo): + path = temp_repo / "app.py" + original = path.read_text() + yield path + path.write_text(original) + + +class TestApplySuggestion: + @pytest.mark.parametrize( + ("fields", "status", "detail"), + [ + pytest.param({"file_line_num": 1}, 400, "No suggestion", id="no-suggestion"), + pytest.param({"suggestion": "x = 1\n"}, 400, "No line number", id="no-line-number"), + pytest.param( + {"file_line_num": 1, "line_text": "-this line is long gone", "suggestion": "replacement"}, + 409, + "changed since", + id="stale-line-text", + ), + pytest.param( + {"file_line_num": 1, "line_text": " line 1", "suggestion": "replacement", "sel_end_index": 4}, + 400, + "more than one line", + id="multi-line-range", + ), + ], + ) + def test_refusals_leave_the_file_and_comment_alone(self, _server_app, app_py, fields, status, detail): + before = app_py.read_text() + cid = post_comment(_server_app, **fields) + r = _server_app.post(f"/api/comments/app.py/{cid}/apply") + assert (r.status_code, detail in r.json()["detail"]) == (status, True) + assert app_py.read_text() == before + assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "open" + + @pytest.mark.parametrize( + "fields", + [ + pytest.param({"line_text": " line 1"}, id="matching-line-text"), + pytest.param({}, id="no-line-text"), + ], + ) + def test_replaces_the_line_and_resolves_the_comment(self, _server_app, app_py, fields): + before = app_py.read_text() + cid = post_comment(_server_app, file_line_num=1, suggestion="line one", **fields) + assert _server_app.post(f"/api/comments/app.py/{cid}/apply").json() == {"ok": True} + assert app_py.read_text() == before.replace("line 1\n", "line one\n", 1) + assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "resolved" + + def test_unknown_comment_is_refused(self, _server_app): + assert _server_app.post("/api/comments/app.py/no-such-id/apply").status_code == 400 diff --git a/tests/test_risk.py b/tests/test_risk.py new file mode 100644 index 0000000..5f5dc9a --- /dev/null +++ b/tests/test_risk.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import pytest + +from diffui.server.routes_diff import _order_files, _score_risk + + +@pytest.mark.parametrize( + ("path", "adds", "dels", "expected"), + [ + pytest.param("alembic/versions/001_init.py", 50, 0, (3, "medium", ["infra/migration"]), id="migration"), + pytest.param("config/settings.yaml", 10, 5, (2, "low", ["config"]), id="config"), + pytest.param("infra/values.yaml", 1, 1, (5, "high", ["infra/migration", "config"]), id="infra-config"), + pytest.param("src/module.py", 0, 100, (3, "medium", ["large deletion"]), id="large-deletion"), + pytest.param("tests/test_auth.py", 5, 30, (3, "medium", ["test removal"]), id="test-removal"), + pytest.param("tests/test_auth.py", 30, 5, (0, "low", []), id="test-additions-are-not-removals"), + pytest.param("src/big_refactor.py", 150, 100, (4, "medium", ["large deletion", "high churn"]), id="churn"), + pytest.param("src/module.py", 0, 30, (1, "low", []), id="moderate-deletion-scores-without-a-reason"), + pytest.param("src/module.py", 40, 20, (1, "low", []), id="moderate-churn-scores-without-a-reason"), + pytest.param("src/utils.py", 10, 5, (0, "low", []), id="plain-source"), + pytest.param("Makefile", 5, 5, (0, "low", []), id="no-extension"), + ], +) +def test_score_risk(path, adds, dels, expected): + assert _score_risk(path, adds, dels) == expected + + +def _entry(path: str, risk: int = 0) -> dict: + return {"path": path, "dir": path.rpartition("/")[0] or ".", "risk_score": risk} + + +def test_order_files_mirrors_the_web_tree(): + files = [_entry("a/z.py"), _entry("b/y.py", 5), _entry("top.py", 3), _entry("a/b/x.py")] + assert [f["path"] for f in _order_files(files, "tree")] == ["top.py", "a/z.py", "a/b/x.py", "b/y.py"] + assert [f["path"] for f in _order_files(files, "risk")] == ["b/y.py", "top.py", "a/z.py", "a/b/x.py"] diff --git a/tests/test_search.py b/tests/test_search.py new file mode 100644 index 0000000..d3ab6b4 --- /dev/null +++ b/tests/test_search.py @@ -0,0 +1,87 @@ +from __future__ import annotations + +import pytest +from fastapi.testclient import TestClient + +from diffui.git_utils import set_active_repo +from diffui.server.app import create_app +from diffui.server.events import _apply_state_updates +from tests.conftest import _git + + +class TestSearch: + def test_matches_file_names_and_content_of_the_view(self, _server_app): + r = _server_app.get("/api/search", params={"q": "EXTRA"}).json() + assert r["files"] == [{"path": "extra.py", "changed": True}] + assert r["hits"] == [] + + r = _server_app.get("/api/search", params={"q": "line five"}).json() + assert r["hits"] == [{"path": "app.py", "line": 5, "text": "line five", "changed": True}] + + # Content comes from the working tree, so an untracked file is searched too. + r = _server_app.get("/api/search", params={"q": "never committed"}).json() + assert [(h["path"], h["line"]) for h in r["hits"]] == [("untracked.txt", 1)] + + def test_search_is_scoped_to_the_view(self, _server_app): + r = _server_app.get("/api/search", params={"q": "value", "view": "working"}).json() + assert r["hits"] == [] + assert _server_app.get("/api/search", params={"q": "value"}).json()["hits"][0]["path"] == "extra.py" + + @pytest.mark.parametrize(("scope", "query"), [("changed", "line"), ("all", "render")]) + def test_hits_are_capped(self, _server_app, monkeypatch, scope, query): + monkeypatch.setattr("diffui.server.routes_search.MAX_HITS", 3) + r = _server_app.get("/api/search", params={"q": query, "scope": scope}).json() + assert len(r["hits"]) == 3 + assert r["truncated"] is True + + def test_empty_query_finds_nothing(self, _server_app): + assert _server_app.get("/api/search", params={"q": ""}).json() == {"files": [], "hits": [], "truncated": False} + + +class TestWholeRepoSearch: + def test_all_scope_finds_files_outside_the_diff_and_marks_the_changed_ones(self, _server_app): + def search(q, scope="all"): + return _server_app.get("/api/search", params={"q": q, "scope": scope}).json() + + assert search("rendrer")["files"] == [{"path": "renderer.py", "changed": False}] + assert search("RENDER_25")["hits"] == [ + {"path": "renderer.py", "line": 25, "text": "def render_25(): ...", "changed": False} + ] + assert search("extrra")["files"] == [{"path": "extra.py", "changed": True}] + assert [(h["path"], h["changed"]) for h in search("line five")["hits"]] == [("app.py", True)] + + assert search("rendrer", scope="changed")["files"] == [] + assert search("extrra", scope="changed")["files"] == [{"path": "extra.py", "changed": True}] + + @pytest.fixture + def own_repo(self, tmp_path, temp_repo): + + (tmp_path / ".gitignore").write_text("generated/\n") + (tmp_path / "generated").mkdir() + (tmp_path / "generated" / "out.py").write_text("needle\n") + (tmp_path / "blob.bin").write_bytes(b"\0needle") + (tmp_path / "keep.py").write_text("needle\n") + for args in (("init", "-q", "-b", "main"), ("add", "-A"), ("commit", "-qm", "init")): + _git(tmp_path, *args) + set_active_repo(tmp_path) + yield TestClient(create_app([tmp_path]), base_url="http://localhost"), tmp_path + set_active_repo(temp_repo) + create_app([temp_repo]) + + def test_files_written_after_the_first_search_are_found(self, own_repo): + + client, repo = own_repo + + def search(q): + return client.get("/api/search", params={"q": q, "scope": "all"}).json() + + assert [h["path"] for h in search("needle")["hits"]] == ["keep.py"] + + (repo / "later.py").write_text("needle again\n") + _apply_state_updates(["files_changed"]) + assert [h["path"] for h in search("needle")["hits"]] == ["keep.py", "later.py"] + assert [f["path"] for f in search("laterr")["files"]] == ["later.py"] + + (repo / "later.py").unlink() + _apply_state_updates(["files_changed"]) + assert [h["path"] for h in search("needle")["hits"]] == ["keep.py"] diff --git a/tests/test_server.py b/tests/test_server.py index 66c47fa..3027e86 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -8,20 +8,16 @@ from unittest.mock import MagicMock, patch import pytest -from fastapi.testclient import TestClient from starlette.websockets import WebSocketDisconnect from diffui.cli import export_json -from diffui.git_utils import set_active_repo from diffui.server import routes_review -from diffui.server.app import create_app from diffui.server.events import _apply_state_updates -from diffui.server.routes_diff import _order_files, _score_risk from diffui.server.routes_review import _process_status from diffui.server.theme_css import generate_css_vars from diffui.server.turns import TurnTracker, poll_once from diffui.themes.definitions import ALL_THEMES -from tests.conftest import _git, post_comment +from tests.conftest import post_comment class TestServerRoutes: @@ -95,34 +91,6 @@ def test_settings_roundtrip(self, _server_app, key, value): finally: _server_app.put("/api/settings", json={key: original}) - def test_comment_crud(self, _server_app): - cid = post_comment(_server_app, comment="test comment") - comment = _server_app.get("/api/comments").json()["app.py"][0] - assert (comment["id"], comment["comment"], comment["status"]) == (cid, "test comment", "open") - assert comment["timestamp"] - - assert _server_app.put(f"/api/comments/app.py/{cid}", json={"comment": "edited"}).status_code == 200 - assert _server_app.get("/api/comments").json()["app.py"][0]["comment"] == "edited" - - assert _server_app.post(f"/api/comments/app.py/{cid}/reply", json={"text": "reply"}).status_code == 200 - replies = _server_app.get("/api/comments").json()["app.py"][0]["replies"] - assert [r["text"] for r in replies] == ["reply"] - - assert _server_app.delete(f"/api/comments/app.py/{cid}").status_code == 200 - assert _server_app.get("/api/comments").json() == {} - - def test_comment_resolve_toggle(self, _server_app): - cid = post_comment(_server_app) - - def status(): - return _server_app.get("/api/comments").json()["app.py"][0]["status"] - - assert status() == "open" - _server_app.post(f"/api/comments/app.py/{cid}/resolve") - assert status() == "resolved" - _server_app.post(f"/api/comments/app.py/{cid}/resolve") - assert status() == "open" - def test_review_toggle(self, _server_app): assert _server_app.post("/api/reviewed/app.py").json()["reviewed"] is True assert _server_app.post("/api/reviewed/app.py").json()["reviewed"] is False @@ -133,39 +101,6 @@ def test_static_files(self, _server_app): r = _server_app.get("/static/style.css") assert r.status_code == 200 - @pytest.mark.parametrize( - ("fields", "stored"), - [ - pytest.param( - {}, - {"category": "", "suggestion": "", "selected_text": "", "sel_start": None, "sel_end": None}, - id="defaults", - ), - pytest.param({"category": "bug"}, {"category": "bug"}, id="category"), - pytest.param({"suggestion": "x = 1\n"}, {"suggestion": "x = 1\n"}, id="suggestion"), - pytest.param( - {"selected_text": "bar.baz", "sel_start": 12, "sel_end": 19}, - {"selected_text": "bar.baz", "sel_start": 12, "sel_end": 19, "sel_end_index": None}, - id="selection", - ), - pytest.param( - { - "line_index": 4, - "selected_text": "if x:\n return y", - "sel_start": 4, - "sel_end": 12, - "sel_end_index": 6, - }, - {"line_index": 4, "sel_start": 4, "sel_end": 12, "sel_end_index": 6}, - id="multiline-selection", - ), - ], - ) - def test_comment_fields_are_stored(self, _server_app, fields, stored): - post_comment(_server_app, **fields) - comment = _server_app.get("/api/comments").json()["app.py"][0] - assert {k: comment[k] for k in stored} == stored - def test_blame_attributes_each_line_to_its_commit(self, _server_app): blame = _server_app.get("/api/blame/app.py").json() assert len(blame) == 21 @@ -233,28 +168,6 @@ def test_explain_view_placeholder(self, _server_app): assert r.status_code == 200 assert "No explanation generated yet" in r.text - def test_bulk_resolve_and_reopen_one_file(self, _server_app): - post_comment(_server_app, line_index=1) - post_comment(_server_app, line_index=2) - post_comment(_server_app, file_path="extra.py") - - def statuses(path): - return [c["status"] for c in _server_app.get("/api/comments").json()[path]] - - r = _server_app.post("/api/comments/bulk-resolve", json={"file_path": "app.py", "action": "resolve"}) - assert r.json() == {"ok": True, "count": 2} - assert statuses("app.py") == ["resolved", "resolved"] - assert statuses("extra.py") == ["open"] - - r = _server_app.post("/api/comments/bulk-resolve", json={"file_path": "app.py", "action": "reopen"}) - assert r.json() == {"ok": True, "count": 2} - assert statuses("app.py") == ["open", "open"] - - def test_bulk_resolve_without_a_file_covers_every_file(self, _server_app): - post_comment(_server_app) - post_comment(_server_app, file_path="extra.py") - assert _server_app.post("/api/comments/bulk-resolve", json={"action": "resolve"}).json()["count"] == 2 - def test_diff_context_widens_the_hunks(self, _server_app): def context_lines(**params): hunks = _server_app.get("/api/diff/app.py", params={"view": "all", **params}).json()["hunks"] @@ -482,26 +395,6 @@ def test_view_explanation_missing_file(self, _server_app): assert "No explanation generated yet" in r.text -@pytest.mark.parametrize( - ("path", "adds", "dels", "expected"), - [ - pytest.param("alembic/versions/001_init.py", 50, 0, (3, "medium", ["infra/migration"]), id="migration"), - pytest.param("config/settings.yaml", 10, 5, (2, "low", ["config"]), id="config"), - pytest.param("infra/values.yaml", 1, 1, (5, "high", ["infra/migration", "config"]), id="infra-config"), - pytest.param("src/module.py", 0, 100, (3, "medium", ["large deletion"]), id="large-deletion"), - pytest.param("tests/test_auth.py", 5, 30, (3, "medium", ["test removal"]), id="test-removal"), - pytest.param("tests/test_auth.py", 30, 5, (0, "low", []), id="test-additions-are-not-removals"), - pytest.param("src/big_refactor.py", 150, 100, (4, "medium", ["large deletion", "high churn"]), id="churn"), - pytest.param("src/module.py", 0, 30, (1, "low", []), id="moderate-deletion-scores-without-a-reason"), - pytest.param("src/module.py", 40, 20, (1, "low", []), id="moderate-churn-scores-without-a-reason"), - pytest.param("src/utils.py", 10, 5, (0, "low", []), id="plain-source"), - pytest.param("Makefile", 5, 5, (0, "low", []), id="no-extension"), - ], -) -def test_score_risk(path, adds, dels, expected): - assert _score_risk(path, adds, dels) == expected - - class TestExportJson: def test_export_matches_the_files_comments_and_reviews_the_ui_shows(self, _server_app, capsys): post_comment(_server_app) @@ -609,60 +502,6 @@ def test_sibling_of_tempdir_is_rejected(self, _server_app, tmp_path): assert r.status_code == 400 -@pytest.fixture -def app_py(temp_repo): - path = temp_repo / "app.py" - original = path.read_text() - yield path - path.write_text(original) - - -class TestApplySuggestion: - @pytest.mark.parametrize( - ("fields", "status", "detail"), - [ - pytest.param({"file_line_num": 1}, 400, "No suggestion", id="no-suggestion"), - pytest.param({"suggestion": "x = 1\n"}, 400, "No line number", id="no-line-number"), - pytest.param( - {"file_line_num": 1, "line_text": "-this line is long gone", "suggestion": "replacement"}, - 409, - "changed since", - id="stale-line-text", - ), - pytest.param( - {"file_line_num": 1, "line_text": " line 1", "suggestion": "replacement", "sel_end_index": 4}, - 400, - "more than one line", - id="multi-line-range", - ), - ], - ) - def test_refusals_leave_the_file_and_comment_alone(self, _server_app, app_py, fields, status, detail): - before = app_py.read_text() - cid = post_comment(_server_app, **fields) - r = _server_app.post(f"/api/comments/app.py/{cid}/apply") - assert (r.status_code, detail in r.json()["detail"]) == (status, True) - assert app_py.read_text() == before - assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "open" - - @pytest.mark.parametrize( - "fields", - [ - pytest.param({"line_text": " line 1"}, id="matching-line-text"), - pytest.param({}, id="no-line-text"), - ], - ) - def test_replaces_the_line_and_resolves_the_comment(self, _server_app, app_py, fields): - before = app_py.read_text() - cid = post_comment(_server_app, file_line_num=1, suggestion="line one", **fields) - assert _server_app.post(f"/api/comments/app.py/{cid}/apply").json() == {"ok": True} - assert app_py.read_text() == before.replace("line 1\n", "line one\n", 1) - assert _server_app.get("/api/comments").json()["app.py"][0]["status"] == "resolved" - - def test_unknown_comment_is_refused(self, _server_app): - assert _server_app.post("/api/comments/app.py/no-such-id/apply").status_code == 400 - - class TestSettingsValidation: def test_unknown_editor_is_rejected(self, _server_app): r = _server_app.put("/api/settings", json={"editor": "rm -rf /"}) @@ -770,94 +609,6 @@ def test_reviewing_a_file_reports_sidebar_counts(self, _server_app, fake_herdr): ] -def _entry(path: str, risk: int = 0) -> dict: - return {"path": path, "dir": path.rpartition("/")[0] or ".", "risk_score": risk} - - -def test_order_files_mirrors_the_web_tree(): - files = [_entry("a/z.py"), _entry("b/y.py", 5), _entry("top.py", 3), _entry("a/b/x.py")] - assert [f["path"] for f in _order_files(files, "tree")] == ["top.py", "a/z.py", "a/b/x.py", "b/y.py"] - assert [f["path"] for f in _order_files(files, "risk")] == ["b/y.py", "top.py", "a/z.py", "a/b/x.py"] - - -class TestSearch: - def test_matches_file_names_and_content_of_the_view(self, _server_app): - r = _server_app.get("/api/search", params={"q": "EXTRA"}).json() - assert r["files"] == [{"path": "extra.py", "changed": True}] - assert r["hits"] == [] - - r = _server_app.get("/api/search", params={"q": "line five"}).json() - assert r["hits"] == [{"path": "app.py", "line": 5, "text": "line five", "changed": True}] - - # Content comes from the working tree, so an untracked file is searched too. - r = _server_app.get("/api/search", params={"q": "never committed"}).json() - assert [(h["path"], h["line"]) for h in r["hits"]] == [("untracked.txt", 1)] - - def test_search_is_scoped_to_the_view(self, _server_app): - r = _server_app.get("/api/search", params={"q": "value", "view": "working"}).json() - assert r["hits"] == [] - assert _server_app.get("/api/search", params={"q": "value"}).json()["hits"][0]["path"] == "extra.py" - - @pytest.mark.parametrize(("scope", "query"), [("changed", "line"), ("all", "render")]) - def test_hits_are_capped(self, _server_app, monkeypatch, scope, query): - monkeypatch.setattr("diffui.server.routes_search.MAX_HITS", 3) - r = _server_app.get("/api/search", params={"q": query, "scope": scope}).json() - assert len(r["hits"]) == 3 - assert r["truncated"] is True - - def test_empty_query_finds_nothing(self, _server_app): - assert _server_app.get("/api/search", params={"q": ""}).json() == {"files": [], "hits": [], "truncated": False} - - -class TestWholeRepoSearch: - def test_all_scope_finds_files_outside_the_diff_and_marks_the_changed_ones(self, _server_app): - def search(q, scope="all"): - return _server_app.get("/api/search", params={"q": q, "scope": scope}).json() - - assert search("rendrer")["files"] == [{"path": "renderer.py", "changed": False}] - assert search("RENDER_25")["hits"] == [ - {"path": "renderer.py", "line": 25, "text": "def render_25(): ...", "changed": False} - ] - assert search("extrra")["files"] == [{"path": "extra.py", "changed": True}] - assert [(h["path"], h["changed"]) for h in search("line five")["hits"]] == [("app.py", True)] - - assert search("rendrer", scope="changed")["files"] == [] - assert search("extrra", scope="changed")["files"] == [{"path": "extra.py", "changed": True}] - - @pytest.fixture - def own_repo(self, tmp_path, temp_repo): - - (tmp_path / ".gitignore").write_text("generated/\n") - (tmp_path / "generated").mkdir() - (tmp_path / "generated" / "out.py").write_text("needle\n") - (tmp_path / "blob.bin").write_bytes(b"\0needle") - (tmp_path / "keep.py").write_text("needle\n") - for args in (("init", "-q", "-b", "main"), ("add", "-A"), ("commit", "-qm", "init")): - _git(tmp_path, *args) - set_active_repo(tmp_path) - yield TestClient(create_app([tmp_path]), base_url="http://localhost"), tmp_path - set_active_repo(temp_repo) - create_app([temp_repo]) - - def test_files_written_after_the_first_search_are_found(self, own_repo): - - client, repo = own_repo - - def search(q): - return client.get("/api/search", params={"q": q, "scope": "all"}).json() - - assert [h["path"] for h in search("needle")["hits"]] == ["keep.py"] - - (repo / "later.py").write_text("needle again\n") - _apply_state_updates(["files_changed"]) - assert [h["path"] for h in search("needle")["hits"]] == ["keep.py", "later.py"] - assert [f["path"] for f in search("laterr")["files"]] == ["later.py"] - - (repo / "later.py").unlink() - _apply_state_updates(["files_changed"]) - assert [h["path"] for h in search("needle")["hits"]] == ["keep.py"] - - @pytest.mark.parametrize( ("samples", "starts"), [ From bc97b4a5264128a5021c42e87fdba9d506c01af7 Mon Sep 17 00:00:00 2001 From: Dillon Sienko Date: Fri, 23 Oct 2026 11:44:28 -0700 Subject: [PATCH 10/10] Update the testing docs for the split, drop the shallow-clone CI workaround, remove blank lines left by import hoisting --- .claude/skills/check-tests/SKILL.md | 2 +- .github/workflows/ci.yml | 3 --- AGENTS.md | 6 +++--- tests/test_events.py | 2 +- tests/test_git_utils.py | 14 -------------- tests/test_search.py | 2 -- tests/test_server.py | 22 ---------------------- 7 files changed, 5 insertions(+), 46 deletions(-) diff --git a/.claude/skills/check-tests/SKILL.md b/.claude/skills/check-tests/SKILL.md index 0e3f2ad..bc860e3 100644 --- a/.claude/skills/check-tests/SKILL.md +++ b/.claude/skills/check-tests/SKILL.md @@ -5,7 +5,7 @@ description: Check that a branch covers the behavior it changes, and that every Review the behavior the non-test code changes and every test the diff adds or edits. Read each changed test next to the code it calls. Open an unchanged test only to confirm a redundant finding. Don't run the tests. -A test earns its place by catching a named bug that no existing test catches. If you can't name the bug, it is a finding. Tests live in `tests/`: `test_server.py` drives the routes through a `TestClient`, `test_tui.py` drives the real `DiffuiApp` under `run_test()`, and the rest cover one module each. +A test earns its place by catching a named bug that no existing test catches. If you can't name the bug, it is a finding. Tests live in `tests/`: `test_server.py`, `test_comments.py` and `test_search.py` drive the routes through a `TestClient`, `test_tui.py` drives the real `DiffuiApp` under `run_test()`, and the rest cover one module each. ## What to check diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6b8905..45c7b0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -15,10 +15,7 @@ jobs: python: ["3.10", "3.13"] runs-on: ${{ matrix.os }} steps: - # Some tests diff this checkout against origin/main, which a shallow clone lacks. - uses: actions/checkout@v7 - with: - fetch-depth: 0 - uses: actions/setup-python@v7 with: python-version: ${{ matrix.python }} diff --git a/AGENTS.md b/AGENTS.md index 52b9f1c..3be8fe4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -154,14 +154,14 @@ ruff format --check . # Format check git config core.hooksPath .githooks # Once per clone: enables the pre-push hook ``` -CI (`.github/workflows/ci.yml`) runs `ruff check`, `ruff format --check` and `pytest` on Ubuntu and macOS, Python 3.10 and 3.13. The checkout is full-depth because some tests diff the repo against `origin/main`. +CI (`.github/workflows/ci.yml`) runs `ruff check`, `ruff format --check` and `pytest` on Ubuntu and macOS, Python 3.10 and 3.13. `.githooks/pre-push` runs the same three checks, then `scripts/check_suite.py` (the README's Development section describes it). Change what the review looks for in the skills, not in the script. ## Testing -- `tests/conftest.py` points `_CONFIG_ROOT` at a temp dir for the whole session, clears `HERDR_WORKSPACE_ID`, and builds the `temp_repo` fixture (a `feature` branch with a dirty tree and an untracked file). Server tests use a `TestClient` with `base_url="http://localhost"`. -- `tests/test_server.py` covers the routes. Its `fake_herdr` fixture puts a fake `herdr` on `PATH`. +- `tests/conftest.py` points `_CONFIG_ROOT` at a temp dir for the whole session, clears `HERDR_WORKSPACE_ID`, and builds the `temp_repo` fixture (a `feature` branch with a dirty tree and an untracked file). It also provides `_server_app` (a `TestClient` on `temp_repo` with `base_url="http://localhost"`) and `post_comment`, and after every test resets the comments, reviewed marks and active repo, so tests need no cleanup of their own. +- `tests/test_server.py` covers the routes that `test_comments.py` and `test_search.py` don't. Its `fake_herdr` fixture puts a fake `herdr` on `PATH`. `test_risk.py` covers `_score_risk` and `_order_files`. - `tests/test_tui.py` runs the real `DiffuiApp` under `App.run_test()` against a `LocalServer` on `temp_repo`. Tests drive the app with `asyncio.run` and wait with `until()`, because the server reaches the view through the watcher and SSE. - `test_diff.py`, `test_highlight.py`, `test_git_utils.py`, `test_events.py`, `test_agent_terminal.py` and `test_themes.py` cover the matching modules. - `test_check_suite.py` covers the verdict parsing and skip paths of `scripts/check_suite.py` with `subprocess` patched. It never starts `claude`. diff --git a/tests/test_events.py b/tests/test_events.py index d732709..0b675f2 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -129,7 +129,7 @@ async def broadcast_on_a_loop(): @pytest.fixture def git_reload(): - """The git-changed path with the repo reload and its side effects stubbed; the reload mock sets what it changes.""" + """Stub the reload a git change triggers. Give the yielded mock a side_effect to change the state a reload would.""" with ( patch("diffui.server.state.app_state.reload_repo_state") as reload, patch("diffui.server.events.clear_diff_cache"), diff --git a/tests/test_git_utils.py b/tests/test_git_utils.py index 1cc1afb..c82e8dd 100644 --- a/tests/test_git_utils.py +++ b/tests/test_git_utils.py @@ -95,14 +95,12 @@ def test_explicit_paths_resolve_once(self, temp_repo, copies): class TestDiscoverSiblingRepos: def test_no_git_dirs_returns_empty(self, tmp_path: Path): - (tmp_path / "parent").mkdir() child = tmp_path / "parent" / "child" child.mkdir() assert discover_sibling_repos(child) == [] def test_finds_sibling_git_repos(self, tmp_path: Path): - parent = tmp_path / "workspace" parent.mkdir() for name in ("repo_a", "repo_b"): @@ -119,11 +117,9 @@ def test_finds_sibling_git_repos(self, tmp_path: Path): class TestRepoHasChanges: def test_branch_with_commits_has_changes(self, temp_repo): - assert repo_has_changes(temp_repo) is True def test_untracked_file_alone_counts(self, tmp_path): - repo = tmp_path / "untracked-only" repo.mkdir() _git(repo, "init", "-q", "-b", "main") @@ -135,7 +131,6 @@ def test_untracked_file_alone_counts(self, tmp_path): class TestMergeBase: def test_stale_local_main_does_not_count_merged_commits(self, tmp_path): - repo = tmp_path / "stale-main" repo.mkdir() _git(repo, "init", "-q", "-b", "main") @@ -170,14 +165,12 @@ def test_missing_file_returns_empty(self, temp_repo): assert get_file_content("_definitely_missing_file_.xyz") == "" def test_binary_file_returns_empty(self, tmp_path: Path): - set_active_repo(tmp_path) binary = tmp_path / "data.bin" binary.write_bytes(b"\xff\xfe\x00\x01\x80") assert get_file_content("data.bin") == "" def test_text_file_returns_content(self, tmp_path: Path): - set_active_repo(tmp_path) (tmp_path / "hello.txt").write_text("hi there\n") assert get_file_content("hello.txt") == "hi there\n" @@ -191,12 +184,10 @@ def test_counts_committed_and_working_changes_but_not_untracked_files(self, temp class TestRepoRelative: def test_in_repo_path_returned_unchanged(self, temp_repo): - set_active_repo(temp_repo) assert repo_relative("app.py") == "app.py" def test_absolute_path_outside_repo_raises(self, temp_repo, tmp_path): - set_active_repo(temp_repo) outside = tmp_path / "secret.txt" outside.write_text("secret\n") @@ -204,13 +195,11 @@ def test_absolute_path_outside_repo_raises(self, temp_repo, tmp_path): repo_relative(str(outside)) def test_dotdot_escape_raises(self, temp_repo): - set_active_repo(temp_repo) with pytest.raises(PathOutsideRepo): repo_relative("../../etc/hostname") def test_symlink_pointing_outside_raises(self, temp_repo, tmp_path): - set_active_repo(temp_repo) outside = tmp_path / "target.txt" outside.write_text("secret\n") @@ -223,7 +212,6 @@ def test_symlink_pointing_outside_raises(self, temp_repo, tmp_path): link.unlink() def test_symlink_inside_repo_allowed(self, temp_repo): - set_active_repo(temp_repo) link = temp_repo / "alias.py" link.symlink_to(temp_repo / "app.py") @@ -235,7 +223,6 @@ def test_symlink_inside_repo_allowed(self, temp_repo): class TestJsonPersistence: def test_corrupt_file_is_moved_aside_and_default_returned(self, tmp_path): - path = tmp_path / "comments.json" path.write_text('{"a": [{"id"') assert _load_json(path, {}) == {} @@ -243,7 +230,6 @@ def test_corrupt_file_is_moved_aside_and_default_returned(self, tmp_path): assert (tmp_path / "comments.json.corrupt").read_text() == '{"a": [{"id"' def test_save_leaves_no_temp_file(self, tmp_path): - path = tmp_path / "comments.json" _save_json(path, {"a.py": [{"id": "1"}]}) assert _load_json(path, {}) == {"a.py": [{"id": "1"}]} diff --git a/tests/test_search.py b/tests/test_search.py index d3ab6b4..63e01cc 100644 --- a/tests/test_search.py +++ b/tests/test_search.py @@ -55,7 +55,6 @@ def search(q, scope="all"): @pytest.fixture def own_repo(self, tmp_path, temp_repo): - (tmp_path / ".gitignore").write_text("generated/\n") (tmp_path / "generated").mkdir() (tmp_path / "generated" / "out.py").write_text("needle\n") @@ -69,7 +68,6 @@ def own_repo(self, tmp_path, temp_repo): create_app([temp_repo]) def test_files_written_after_the_first_search_are_found(self, own_repo): - client, repo = own_repo def search(q): diff --git a/tests/test_server.py b/tests/test_server.py index 3027e86..69e736d 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -277,15 +277,7 @@ def test_branch(self, _server_app, temp_repo): class TestReviewModule: - def test_build_agent_context_no_comments(self): - - with patch.object(routes_review.app_state, "comments", {}): - result = routes_review._build_agent_context() - assert result[0] is None - assert result[1] == "No open comments" - def test_build_agent_context_with_comments(self): - comments = { "src/auth.py": [ { @@ -318,24 +310,20 @@ def test_build_agent_context_with_comments(self): assert "src/resolved.py" not in ctx def test_process_status_none(self): - assert _process_status(None) == {"running": False} def test_process_status_running(self): - proc = MagicMock() proc.poll.return_value = None proc.pid = 4242 assert _process_status(proc) == {"running": True, "pid": 4242} def test_process_status_finished(self): - proc = MagicMock() proc.poll.return_value = 0 assert _process_status(proc) == {"running": False, "exit_code": 0} def test_explain_already_running(self, _server_app): - running = MagicMock() running.poll.return_value = None with patch.object(routes_review, "_explain_process", running): @@ -346,7 +334,6 @@ def test_explain_already_running(self, _server_app): assert "already generating" in data["error"] def test_explain_unknown_agent(self, _server_app): - with ( patch.object(routes_review, "_explain_process", None), patch.object(routes_review.app_state, "agent_cli", "bogus-cli"), @@ -358,7 +345,6 @@ def test_explain_unknown_agent(self, _server_app): assert "Unknown agent CLI" in data["error"] def test_view_explanation_with_temp_file(self, _server_app): - # Resolve gettempdir so the module's startswith() guard matches the # symlink-resolved path (macOS /var -> /private/var). tmp_dir = Path(tempfile.gettempdir()).resolve() @@ -376,14 +362,12 @@ def test_view_explanation_with_temp_file(self, _server_app): tmp.unlink(missing_ok=True) def test_view_explanation_path_traversal_guard(self, _server_app): - with patch.object(routes_review, "_explain_output_path", "/etc/passwd"): r = _server_app.get("/api/explain/view") assert r.status_code == 400 assert "No explanation generated yet" in r.text def test_view_explanation_missing_file(self, _server_app): - tmp_dir = Path(tempfile.gettempdir()).resolve() missing = str(tmp_dir / "diffui-explain-does-not-exist.html") with ( @@ -495,7 +479,6 @@ def test_known_commit_sha_still_works(self, _server_app): class TestExplainViewGuard: def test_sibling_of_tempdir_is_rejected(self, _server_app, tmp_path): - evil = Path(f"{tempfile.gettempdir()}-evil") / "payload.html" with patch("diffui.server.routes_review._explain_output_path", str(evil)): r = _server_app.get("/api/explain/view") @@ -591,7 +574,6 @@ def test_paste_refuses_blocked_agent(self, _server_app, temp_repo, fake_herdr, m assert not [c for c in fake_herdr() if c[:2] == ["pane", "send-text"]] def test_reviewing_a_file_reports_sidebar_counts(self, _server_app, fake_herdr): - post_comment(_server_app) _server_app.post("/api/reviewed/app.py") # The watcher sees reviewed.json change and runs this; TestClient never starts the watcher. @@ -620,18 +602,15 @@ def test_reviewing_a_file_reports_sidebar_counts(self, _server_app, fake_herdr): ], ) def test_turn_tracker_starts_on_the_rest_to_work_edge(samples, starts): - tracker = TurnTracker() assert [i for i, statuses in enumerate(samples) if tracker.observe(statuses)] == starts class TestLastTurn: def _git(self, repo, *args): - return subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True, text=True).stdout def test_lists_only_files_changed_since_the_turn_started(self, _server_app, temp_repo, fake_herdr, monkeypatch): - reason = _server_app.get("/api/last-turn").json()["reason"] assert reason.startswith("No agent turn seen yet") assert _server_app.get("/api/files?view=last-turn").json() == [] @@ -679,7 +658,6 @@ def test_requests_from_other_sites_are_rejected(self, _server_app, headers, stat assert _server_app.get("/api/files", headers=headers).status_code == status def test_foreign_websocket_is_rejected(self, _server_app): - with ( pytest.raises(WebSocketDisconnect), _server_app.websocket_connect(