Debian Codegraph @

tests/unit_tests/test_external.py

raw
1 from __future__ import annotations
2
3 import sys
4 from contextlib import contextmanager
5 from pathlib import Path
6 from typing import Iterator, Sequence, cast
7
8 import pytest
9 from textual.app import App, SuspendNotSupported
10
11 from harlequin.exception import HarlequinExternalError
12 from harlequin.external import (
13 ExternalEdit,
14 launch_external_editor,
15 resolve_editor,
16 run_in_terminal,
17 split_command,
18 )
19
20
21 class FakeApp:
22 """The whole of what `run_in_terminal` uses of an App: a suspend()."""
23
24 def __init__(self, error: BaseException | None = None) -> None:
25 self.error = error
26 self.suspend_count = 0
27 self.resumed = False
28
29 @contextmanager
30 def suspend(self) -> Iterator[None]:
31 if self.error is not None:
32 raise self.error
33 self.suspend_count += 1
34 yield
35 self.resumed = True
36
37
38 @pytest.fixture
39 def fake_app() -> FakeApp:
40 return FakeApp()
41
42
43 @pytest.fixture(autouse=True)
44 def no_editor_in_environment(monkeypatch: pytest.MonkeyPatch) -> None:
45 monkeypatch.delenv("VISUAL", raising=False)
46 monkeypatch.delenv("EDITOR", raising=False)
47
48
49 def test_visual_wins_over_editor(monkeypatch: pytest.MonkeyPatch) -> None:
50 monkeypatch.setenv("VISUAL", "hx")
51 monkeypatch.setenv("EDITOR", "vim")
52 assert resolve_editor() == ["hx"]
53
54
55 def test_editor_is_used_when_visual_is_unset(monkeypatch: pytest.MonkeyPatch) -> None:
56 monkeypatch.setenv("EDITOR", "vim")
57 assert resolve_editor() == ["vim"]
58
59
60 def test_a_blank_variable_does_not_count(monkeypatch: pytest.MonkeyPatch) -> None:
61 monkeypatch.setenv("VISUAL", " ")
62 monkeypatch.setenv("EDITOR", "vim")
63 assert resolve_editor() == ["vim"]
64
65
66 def test_editor_flags_are_split(monkeypatch: pytest.MonkeyPatch) -> None:
67 monkeypatch.setenv("EDITOR", "code --wait")
68 assert resolve_editor() == ["code", "--wait"]
69
70
71 def test_no_editor_names_both_variables() -> None:
72 with pytest.raises(HarlequinExternalError) as excinfo:
73 resolve_editor()
74 assert "$VISUAL" in excinfo.value.msg
75 assert "$EDITOR" in excinfo.value.msg
76
77
78 def test_a_quoted_windows_path_is_one_token(monkeypatch: pytest.MonkeyPatch) -> None:
79 monkeypatch.setattr(sys, "platform", "win32")
80 assert split_command('"C:\\Program Files\\Editor\\ed.exe" --wait') == [
81 "C:\\Program Files\\Editor\\ed.exe",
82 "--wait",
83 ]
84
85
86 def test_run_in_terminal_suspends_and_returns_the_status(fake_app: FakeApp) -> None:
87 returncode = run_in_terminal(
88 cast("App[None]", fake_app), [sys.executable, "-c", "raise SystemExit(3)"]
89 )
90 assert returncode == 3
91 assert fake_app.suspend_count == 1
92 assert fake_app.resumed
93
94
95 def test_run_in_terminal_reports_a_terminal_that_cannot_suspend() -> None:
96 app = FakeApp(error=SuspendNotSupported("nope"))
97 with pytest.raises(HarlequinExternalError) as excinfo:
98 run_in_terminal(cast("App[None]", app), [sys.executable, "-c", ""])
99 assert "suspend" in excinfo.value.msg
100
101
102 def test_run_in_terminal_reports_a_program_it_cannot_start(fake_app: FakeApp) -> None:
103 with pytest.raises(HarlequinExternalError) as excinfo:
104 run_in_terminal(cast("App[None]", fake_app), ["harlequin-no-such-editor"])
105 assert "harlequin-no-such-editor" in excinfo.value.msg
106
107
108 def test_the_round_trip_is_a_sql_file(
109 monkeypatch: pytest.MonkeyPatch, fake_app: FakeApp
110 ) -> None:
111 monkeypatch.setenv("EDITOR", "ed --wait")
112 seen: list[Sequence[str]] = []
113
114 def fake_run_in_terminal(app: App, argv: Sequence[str]) -> int:
115 seen.append(argv)
116 path = Path(argv[-1])
117 assert path.read_text(encoding="utf-8") == "select 1"
118 path.write_text("select 2\n", encoding="utf-8")
119 return 0
120
121 monkeypatch.setattr("harlequin.external.run_in_terminal", fake_run_in_terminal)
122
123 edit = launch_external_editor(cast("App[None]", fake_app), "select 1")
124
125 assert edit == ExternalEdit(returncode=0, text="select 2\n")
126 assert list(seen[0][:2]) == ["ed", "--wait"]
127 assert seen[0][-1].endswith(".sql")
128 assert not Path(seen[0][-1]).exists()
129
130
131 def test_a_nonzero_exit_discards_the_edit(
132 monkeypatch: pytest.MonkeyPatch, fake_app: FakeApp
133 ) -> None:
134 monkeypatch.setenv("EDITOR", "ed")
135 paths: list[Path] = []
136
137 def fake_run_in_terminal(app: App, argv: Sequence[str]) -> int:
138 path = Path(argv[-1])
139 paths.append(path)
140 path.write_text("select 2", encoding="utf-8")
141 return 1
142
143 monkeypatch.setattr("harlequin.external.run_in_terminal", fake_run_in_terminal)
144
145 edit = launch_external_editor(cast("App[None]", fake_app), "select 1")
146
147 assert edit == ExternalEdit(returncode=1, text=None)
148 assert not paths[0].exists()
149
150
151 def test_crlf_does_not_come_back_in_the_buffer(
152 monkeypatch: pytest.MonkeyPatch, fake_app: FakeApp
153 ) -> None:
154 monkeypatch.setenv("EDITOR", "ed")
155
156 def fake_run_in_terminal(app: App, argv: Sequence[str]) -> int:
157 Path(argv[-1]).write_bytes(b"select 1\r\nfrom foo\r\n")
158 return 0
159
160 monkeypatch.setattr("harlequin.external.run_in_terminal", fake_run_in_terminal)
161
162 edit = launch_external_editor(cast("App[None]", fake_app), "select 1")
163
164 assert edit.text == "select 1\nfrom foo\n"
165
166
167 def test_the_temp_file_is_removed_after_an_error(
168 monkeypatch: pytest.MonkeyPatch, fake_app: FakeApp
169 ) -> None:
170 monkeypatch.setenv("EDITOR", "ed")
171 paths: list[Path] = []
172
173 def fake_run_in_terminal(app: App, argv: Sequence[str]) -> int:
174 paths.append(Path(argv[-1]))
175 raise HarlequinExternalError(msg="boom", title="boom")
176
177 monkeypatch.setattr("harlequin.external.run_in_terminal", fake_run_in_terminal)
178
179 with pytest.raises(HarlequinExternalError):
180 launch_external_editor(cast("App[None]", fake_app), "select 1")
181
182 assert not paths[0].exists()