Debian Codegraph @

tests/functional_tests/test_crash.py

raw
1 """What a user sees, and what survives, when Harlequin hits a bug in itself.
2
3 Injected through `_handle_exception` directly: the handler is the contract, and
4 finding a real crash to provoke would pin the test to whichever bug it used.
5 The assertions are on stderr, because that is where the message lands -- the
6 message pump is gone by then, so there is no screen to look at.
7 """
8
9 from __future__ import annotations
10
11 import asyncio
12 import pickle
13 import sqlite3
14 import threading
15 from pathlib import Path
16 from typing import Any
17 from unittest.mock import patch
18
19 import pytest
20 from rich.console import Console
21 from textual.widgets.text_area import Selection
22
23 import harlequin.app
24 from harlequin import Harlequin
25 from harlequin.adapter import HarlequinAdapter
26 from harlequin.app import QuerySubmitted
27 from harlequin.app_base import _as_markup
28 from harlequin.crash import ISSUE_URL, crash_message
29 from harlequin.editor_cache import BufferState, Cache, get_cache_file
30 from harlequin.exception import HarlequinCrashError, pretty_error_message
31 from harlequin.query import fetch
32 from tests.functional_tests.helpers import wait_for_editor
33
34
35 @pytest.fixture(autouse=True)
36 def mock_user_cache_dir(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
37 cache_dir = tmp_path / "cache"
38 monkeypatch.setattr("harlequin.editor_cache.user_cache_dir", lambda **_: cache_dir)
39 return cache_dir
40
41
42 def crash(app: Harlequin, error: Exception) -> None:
43 """Hand the handler an exception the way the message pump does.
44
45 From inside an `except` block: Textual's own renderer reads
46 `sys.exc_info()`, so an exception injected from outside one would exercise
47 a path no crash takes.
48 """
49 try:
50 raise error
51 except Exception as caught:
52 app._handle_exception(caught)
53
54
55 def panel_text(capsys: pytest.CaptureFixture[str]) -> str:
56 """What was printed, with the box drawn around it taken off."""
57 return "\n".join(
58 line.strip("│╭╮╰╯─ \t") for line in capsys.readouterr().err.splitlines()
59 )
60
61
62 def unwrapped(text: str) -> str:
63 """The same, on one line: rich folds a long path across two of them."""
64 return "".join(text.splitlines())
65
66
67 @pytest.mark.asyncio
68 async def test_a_crash_prints_a_panel_and_not_a_traceback(
69 app: Harlequin,
70 crash_reports_go_to_tmp: Path,
71 capsys: pytest.CaptureFixture[str],
72 ) -> None:
73 with pytest.raises(RuntimeError):
74 async with app.run_test() as pilot:
75 await wait_for_editor(pilot, app)
76 crash(app, RuntimeError("boom"))
77 await pilot.pause()
78
79 assert app.return_code == 1
80
81 (report,) = list(crash_reports_go_to_tmp.glob("crash-*.log"))
82 assert "RuntimeError" in report.read_text()
83
84 printed = panel_text(capsys)
85 assert "Harlequin crashed." in printed
86 assert "RuntimeError: boom" in printed
87 assert "Please report this crash to help improve Harlequin." in printed
88 assert str(report) in unwrapped(printed)
89 assert "Traceback (most recent call last)" not in printed
90
91
92 @pytest.mark.use_cache
93 @pytest.mark.asyncio
94 async def test_a_crash_saves_the_open_buffers(
95 app: Harlequin,
96 mock_user_cache_dir: Path,
97 crash_reports_go_to_tmp: Path,
98 capsys: pytest.CaptureFixture[str],
99 ) -> None:
100 with pytest.raises(RuntimeError):
101 async with app.run_test() as pilot:
102 editor = await wait_for_editor(pilot, app)
103 editor.text = "select 'work in progress'"
104 crash(app, RuntimeError("boom"))
105 await pilot.pause()
106
107 (recovered,) = list(mock_user_cache_dir.glob("recovered-*.pickle"))
108 cache = pickle.loads(recovered.read_bytes())
109 assert cache.buffers[0].text == "select 'work in progress'"
110 # the last clean quit's cache is untouched: if the recovered buffers are
111 # themselves the problem, that is still on disk
112 assert not get_cache_file().exists()
113
114 assert "Your buffers have been saved" in panel_text(capsys)
115
116
117 @pytest.mark.asyncio
118 async def test_the_report_holds_what_the_session_was(
119 duckdb_adapter: type[HarlequinAdapter],
120 crash_reports_go_to_tmp: Path,
121 ) -> None:
122 """Built the way `cli.py` builds it, which is where the adapter gets a name."""
123 app = Harlequin(
124 duckdb_adapter([":memory:"], no_init=True),
125 adapter_name="duckdb",
126 profile_name="warehouse",
127 )
128 with pytest.raises(RuntimeError):
129 async with app.run_test() as pilot:
130 editor = await wait_for_editor(pilot, app)
131 editor.text = "select 'reproduce me'"
132 crash(app, RuntimeError("boom"))
133 await pilot.pause()
134
135 (report,) = list(crash_reports_go_to_tmp.glob("crash-*.log"))
136 text = report.read_text()
137 assert "adapter: duckdb" in text
138 assert "adapter_class: DuckDbAdapter" in text
139 # the distribution, not the module: both bundled adapters ship inside
140 # `harlequin`, whose name their module never spells
141 assert "adapter_distribution: harlequin " in text
142 assert "profile: warehouse" in text
143 assert "connected: True" in text
144 assert "buffers: 1" in text
145 # the SQL is last, under a heading that says what it is
146 assert text.rstrip().endswith("select 'reproduce me'")
147
148
149 @pytest.mark.asyncio
150 async def test_a_crash_report_is_written_once(
151 app: Harlequin,
152 crash_reports_go_to_tmp: Path,
153 capsys: pytest.CaptureFixture[str],
154 ) -> None:
155 """The handler runs inside an `except` block, so it must not be able to
156 raise. A second exception returns without reporting again."""
157 with pytest.raises(RuntimeError):
158 async with app.run_test() as pilot:
159 await wait_for_editor(pilot, app)
160 crash(app, RuntimeError("boom"))
161 crash(app, RuntimeError("and again"))
162 await pilot.pause()
163
164 assert len(list(crash_reports_go_to_tmp.glob("crash-*.log"))) == 1
165 printed = panel_text(capsys)
166 assert printed.count("Harlequin crashed.") == 1
167 assert "and again" not in printed
168
169
170 @pytest.mark.asyncio
171 async def test_a_crash_is_reported_even_when_the_report_cannot_be_written(
172 app: Harlequin,
173 monkeypatch: pytest.MonkeyPatch,
174 capsys: pytest.CaptureFixture[str],
175 ) -> None:
176 def _raise(*_args: object, **_kwargs: object) -> None:
177 raise OSError("the log dir is gone")
178
179 monkeypatch.setattr("harlequin.app_base.write_crash_report", _raise)
180
181 with pytest.raises(RuntimeError):
182 async with app.run_test() as pilot:
183 await wait_for_editor(pilot, app)
184 crash(app, RuntimeError("boom"))
185 await pilot.pause()
186
187 assert app.return_code == 1
188 printed = panel_text(capsys)
189 assert "RuntimeError: boom" in printed
190 assert "Traceback (most recent call last)" not in printed
191
192
193 @pytest.mark.asyncio
194 async def test_the_traceback_is_still_printed_in_dev_mode(
195 app: Harlequin,
196 crash_reports_go_to_tmp: Path,
197 capsys: pytest.CaptureFixture[str],
198 ) -> None:
199 """`make serve`, i.e. `textual run --dev`: one code path, both audiences."""
200 with pytest.raises(RuntimeError):
201 async with app.run_test() as pilot:
202 await wait_for_editor(pilot, app)
203 app.features = frozenset({*app.features, "debug"})
204 crash(app, RuntimeError("boom"))
205 await pilot.pause()
206
207 printed = panel_text(capsys)
208 assert "Harlequin crashed." in printed
209 assert "Traceback (most recent call last)" in printed
210
211
212 def test_a_crash_before_the_app_is_mounted_saves_nothing(
213 duckdb_adapter: type[HarlequinAdapter],
214 ) -> None:
215 """`editor_collection` is created in compose(), not __init__."""
216 app = Harlequin(duckdb_adapter([":memory:"], no_init=True))
217
218 assert app._save_work_on_crash() is False
219 assert isinstance(app._crash_context(), dict)
220
221
222 @pytest.mark.use_cache
223 @pytest.mark.asyncio
224 async def test_a_crash_while_replaying_recovered_buffers_cannot_repeat(
225 app: Harlequin,
226 app_all_adapters: Harlequin,
227 mock_user_cache_dir: Path,
228 monkeypatch: pytest.MonkeyPatch,
229 crash_reports_go_to_tmp: Path,
230 ) -> None:
231 """The crash-loop guard, end to end: the poisoned file is spent by the
232 start that choked on it."""
233 poisoned = mock_user_cache_dir / "recovered-20260904T120000Z-99.pickle"
234 poisoned.parent.mkdir(parents=True, exist_ok=True)
235 poisoned.write_bytes(
236 pickle.dumps(
237 Cache(focus_index=0, buffers=[BufferState(Selection(), "select 1\n")])
238 )
239 )
240
241 async def _boom(*_args: object, **_kwargs: object) -> None:
242 raise RuntimeError("crash while replaying")
243
244 monkeypatch.setattr(
245 "harlequin.components.code_editor.EditorCollection.action_new_buffer", _boom
246 )
247 with pytest.raises(RuntimeError):
248 async with app.run_test() as pilot:
249 await pilot.pause()
250 await pilot.pause()
251
252 assert not poisoned.exists()
253 assert poisoned.with_suffix(".replayed").exists()
254
255 monkeypatch.undo()
256 async with app_all_adapters.run_test() as pilot:
257 editor = await wait_for_editor(pilot, app_all_adapters)
258 assert app_all_adapters.editor_collection.tab_count == 1
259 assert editor.text == ""
260
261
262 @pytest.mark.asyncio
263 async def test_a_crash_mid_fetch_keeps_the_query_it_was_running(
264 app: Harlequin,
265 crash_reports_go_to_tmp: Path,
266 query_log_path: Path,
267 ) -> None:
268 """And needs nothing from the handler to do it: the row was committed when
269 the statement was run, which is what the two-phase write is for."""
270 fetching = threading.Event()
271 release = threading.Event()
272 real_fetch = fetch
273
274 def slow_fetch(*args: Any, **kwargs: Any) -> Any:
275 fetching.set()
276 release.wait(timeout=10)
277 return real_fetch(*args, **kwargs)
278
279 try:
280 with pytest.raises(RuntimeError):
281 async with app.run_test() as pilot:
282 await wait_for_editor(pilot, app)
283 with patch.object(harlequin.app, "fetch", slow_fetch):
284 app.post_message(
285 QuerySubmitted(queries=["select 1 as a;"], limit=None)
286 )
287 assert await asyncio.get_running_loop().run_in_executor(
288 None, fetching.wait, 10
289 ), "the fetch never started"
290
291 crash(app, RuntimeError("boom"))
292
293 db = sqlite3.connect(query_log_path)
294 db.row_factory = sqlite3.Row
295 try:
296 (row,) = db.execute("select * from queries").fetchall()
297 finally:
298 db.close()
299 assert row["sql"] == "select 1 as a;"
300 # the rows it would have returned are what the crash cost
301 assert row["rows"] is None
302
303 await pilot.pause()
304 finally:
305 release.set()
306
307
308 def render_panel(message: str) -> str:
309 """The panel as a terminal receives it, escape sequences and all."""
310 console = Console(width=100, force_terminal=True, legacy_windows=False)
311 with console.capture() as capture:
312 console.print(
313 pretty_error_message(
314 HarlequinCrashError(_as_markup(message), title="Harlequin crashed.")
315 )
316 )
317 return capture.get()
318
319
320 def test_the_reporting_url_is_a_clickable_link() -> None:
321 """A bare URL is not clickable in every terminal; an OSC-8 link is."""
322 message = crash_message(Path("/tmp/crash.log"), RuntimeError("boom"), saved=False)
323
324 assert f"[link={ISSUE_URL}]{ISSUE_URL}[/link]" in _as_markup(message)
325
326 rendered = render_panel(message)
327 assert "\x1b]8;" in rendered # the escape a terminal makes clickable
328 assert ISSUE_URL in rendered # and the URL still readable where it isn't
329
330
331 def test_an_exception_whose_text_looks_like_markup_survives() -> None:
332 """The message quotes a driver, and a driver may put brackets in one."""
333 message = crash_message(
334 None, RuntimeError("no column [amount] in orders"), saved=False
335 )
336
337 assert "[amount]" in render_panel(message)