Debian Codegraph @

tests/unit_tests/test_crash.py

raw
1 from __future__ import annotations
2
3 from pathlib import Path
4
5 import pytest
6
7 from harlequin.crash import (
8 ACTIVE_BUFFER,
9 CRASH_REPORT_KEEP,
10 ISSUE_URL,
11 build_crash_report,
12 crash_message,
13 root_cause,
14 write_crash_report,
15 )
16 from harlequin.redact import REDACTED, hide_secrets_in
17
18
19 def raise_and_catch(error: BaseException) -> BaseException:
20 """An exception with a real traceback on it, as a handler would receive."""
21 try:
22 raise error
23 except BaseException as caught:
24 return caught
25
26
27 def test_the_report_names_what_a_maintainer_needs() -> None:
28 error = raise_and_catch(ValueError("no such column: foo"))
29
30 report = build_crash_report(error, {"adapter": "duckdb"})
31
32 assert "ValueError" in report
33 assert "no such column: foo" in report
34 assert "adapter: duckdb" in report
35 assert "raise error" in report # the frames
36 assert "version" in report
37 assert ISSUE_URL in report
38
39
40 def test_the_report_prints_no_local_variables() -> None:
41 """Textual's own handler renders with show_locals=True. That is what this
42 replaces."""
43
44 def frame_with_a_secret_local() -> None:
45 connection_string = "postgres://u:hunter2-and-more@host/db" # noqa: F841
46 raise ValueError("boom")
47
48 try:
49 frame_with_a_secret_local()
50 except ValueError as e:
51 report = build_crash_report(e, {})
52
53 assert "hunter2-and-more" not in report
54 assert "connection_string" not in report
55
56
57 def test_the_report_prints_no_registered_secret() -> None:
58 hide_secrets_in({"conn_str": ["postgres://u:hunter2-and-more@host/db"]})
59 error = raise_and_catch(
60 ValueError("could not connect to postgres://u:hunter2-and-more@host/db")
61 )
62
63 report = build_crash_report(error, {})
64
65 assert "hunter2-and-more" not in report
66 assert REDACTED in report
67
68
69 def test_the_report_masks_a_credential_typed_into_the_active_buffer() -> None:
70 """The report asks to be pasted into a public issue, and nothing registered
71 a credential the user wrote into a statement."""
72 error = raise_and_catch(ValueError("boom"))
73
74 report = build_crash_report(
75 error,
76 {
77 ACTIVE_BUFFER: (
78 "attach 'postgres://u:hunter2-and-more@warehouse/db' as w;\n"
79 "create secret (type s3, key_id 'AKIAEXAMPLE', secret 'sEcReT-value');"
80 )
81 },
82 )
83
84 assert "hunter2-and-more" not in report
85 assert "sEcReT-value" not in report
86 assert "AKIAEXAMPLE" not in report
87 # and the rest of the statement survives, which is what makes it worth having
88 assert "warehouse/db" in report
89 assert "attach" in report
90
91
92 def test_the_report_pastes_into_a_fenced_block() -> None:
93 """A report that carried its own fences would break out of the issue's."""
94 error = raise_and_catch(ValueError("boom"))
95
96 report = build_crash_report(error, {ACTIVE_BUFFER: "select 1"})
97
98 assert "```" not in report
99
100
101 def test_the_report_ends_with_the_active_buffer() -> None:
102 """Under a heading that says what it is: the user decides whether to paste it."""
103 error = raise_and_catch(ValueError("boom"))
104
105 report = build_crash_report(error, {"adapter": "duckdb", ACTIVE_BUFFER: "select 1"})
106
107 assert report.index("SQL IN THE ACTIVE BUFFER") > report.index("TRACEBACK")
108 assert report.rstrip().endswith("select 1")
109 # and not a second time, among the facts
110 assert report.count("select 1") == 1
111
112
113 def test_root_cause_unwraps_a_worker_failure() -> None:
114 """Two `@work` decorators reach the handler wrapped. A report naming
115 `WorkerFailed` is a useless report."""
116
117 class WorkerFailed(Exception):
118 def __init__(self, error: BaseException) -> None:
119 super().__init__("Worker raised exception")
120 self.error = error
121
122 cause = ValueError("the real problem")
123
124 assert root_cause(WorkerFailed(cause)) is cause
125 assert root_cause(cause) is cause
126
127
128 def test_the_report_names_both_halves_of_a_wrapped_error() -> None:
129 class WorkerFailed(Exception):
130 def __init__(self, error: BaseException) -> None:
131 super().__init__("Worker raised exception")
132 self.error = error
133
134 error = raise_and_catch(WorkerFailed(raise_and_catch(ValueError("boom"))))
135
136 report = build_crash_report(error, {})
137
138 assert report.index("boom") < report.index("RAISED AS")
139 assert "WorkerFailed" in report
140
141
142 def test_write_crash_report_keeps_the_newest(
143 crash_reports_go_to_tmp: Path,
144 ) -> None:
145 crash_reports_go_to_tmp.mkdir(parents=True, exist_ok=True)
146 for n in range(CRASH_REPORT_KEEP + 5):
147 (crash_reports_go_to_tmp / f"crash-2020010{n:02d}T000000Z-1.log").touch()
148
149 path = write_crash_report("a report")
150
151 assert path is not None
152 assert path.read_text() == "a report"
153 assert len(list(crash_reports_go_to_tmp.glob("crash-*.log"))) == CRASH_REPORT_KEEP
154 # a crash loop cannot destroy the evidence of the crash that started it
155 assert path.exists()
156
157
158 def test_write_crash_report_returns_none_when_it_cannot_write(
159 monkeypatch: pytest.MonkeyPatch, crash_reports_go_to_tmp: Path
160 ) -> None:
161 def _deny(*_args: object, **_kwargs: object) -> None:
162 raise PermissionError("nope")
163
164 monkeypatch.setattr(Path, "mkdir", _deny)
165
166 assert write_crash_report("a report") is None
167
168
169 def test_the_message_says_what_to_do_next(tmp_path: Path) -> None:
170 report_path = tmp_path / "crash.log"
171 error = raise_and_catch(ValueError("boom"))
172
173 message = crash_message(report_path, error, saved=True)
174
175 assert "ValueError: boom" in message
176 assert "Your buffers have been saved" in message
177 assert "Please report this crash to help improve Harlequin." in message
178 # the ask comes before the file it needs
179 assert message.index(ISSUE_URL) < message.index(str(report_path))
180 # and nothing tells the user to review either one; the report says that
181 # itself, where they can act on it
182 assert "review" not in message.lower()
183
184
185 def test_the_message_claims_no_save_that_did_not_happen() -> None:
186 error = raise_and_catch(ValueError("boom"))
187
188 message = crash_message(None, error, saved=False)
189
190 assert "saved" not in message
191 assert ISSUE_URL in message
192
193
194 def test_the_report_asks_the_user_to_redact_it() -> None:
195 """The masking reaches registered secrets and DSNs. The rest is theirs."""
196 error = raise_and_catch(ValueError("boom"))
197
198 report = build_crash_report(error, {ACTIVE_BUFFER: "select 1"})
199
200 assert "Review and redact as necessary" in report.splitlines()[2]