Debian Codegraph @

tests/test_traceback.py

raw
1 import io
2 import re
3 import sys
4 from typing import List
5
6 import pytest
7
8 from rich.console import Console
9 from rich.theme import Theme
10 from rich.traceback import Traceback, install
11
12
13 def test_handler():
14 console = Console(file=io.StringIO(), width=100, color_system=None)
15 expected_old_handler = sys.excepthook
16
17 def level1():
18 level2()
19
20 def level2():
21 return 1 / 0
22
23 try:
24 old_handler = install(console=console)
25 try:
26 level1()
27 except Exception:
28 exc_type, exc_value, traceback = sys.exc_info()
29 sys.excepthook(exc_type, exc_value, traceback)
30 rendered_exception = console.file.getvalue()
31 print(repr(rendered_exception))
32 assert "Traceback" in rendered_exception
33 assert "ZeroDivisionError" in rendered_exception
34
35 frame_blank_line_possible_preambles = (
36 # Start of the stack rendering:
37 "╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮",
38 # Each subsequent frame (starting with the file name) should then be preceded with a blank line:
39 "│" + (" " * 98) + "│",
40 )
41 for frame_start in re.finditer(
42 "^│ .+rich/tests/test_traceback.py:",
43 rendered_exception,
44 flags=re.MULTILINE,
45 ):
46 frame_start_index = frame_start.start()
47 for preamble in frame_blank_line_possible_preambles:
48 preamble_start, preamble_end = (
49 frame_start_index - len(preamble) - 1,
50 frame_start_index - 1,
51 )
52 if rendered_exception[preamble_start:preamble_end] == preamble:
53 break
54 else:
55 pytest.fail(
56 f"Frame {frame_start[0]} doesn't have the expected preamble"
57 )
58 finally:
59 sys.excepthook = old_handler
60 assert old_handler == expected_old_handler
61
62
63 def test_capture():
64 try:
65 1 / 0
66 except Exception:
67 tb = Traceback()
68 assert tb.trace.stacks[0].exc_type == "ZeroDivisionError"
69
70
71 def test_no_exception():
72 with pytest.raises(ValueError):
73 tb = Traceback()
74
75
76 def get_exception() -> Traceback:
77 def bar(a):
78 print(1 / a)
79
80 def foo(a):
81 bar(a)
82
83 try:
84 try:
85 foo(0)
86 except:
87 foobarbaz
88 except:
89 tb = Traceback()
90 return tb
91
92
93 def test_print_exception():
94 console = Console(width=100, file=io.StringIO())
95 try:
96 1 / 0
97 except Exception:
98 console.print_exception()
99 exception_text = console.file.getvalue()
100 assert "ZeroDivisionError" in exception_text
101
102
103 def test_print_exception_no_msg():
104 console = Console(width=100, file=io.StringIO())
105 try:
106 raise RuntimeError
107 except Exception:
108 console.print_exception()
109 exception_text = console.file.getvalue()
110 assert "RuntimeError" in exception_text
111 assert "RuntimeError:" not in exception_text
112
113
114 def test_print_exception_locals():
115 console = Console(width=100, file=io.StringIO())
116 try:
117 1 / 0
118 except Exception:
119 console.print_exception(show_locals=True)
120 exception_text = console.file.getvalue()
121 print(exception_text)
122 assert "ZeroDivisionError" in exception_text
123 assert "locals" in exception_text
124 assert "console = <console width=100 None>" in exception_text
125
126
127 def test_syntax_error():
128 console = Console(width=100, file=io.StringIO())
129 try:
130 # raises SyntaxError: unexpected EOF while parsing
131 eval("(2+2")
132 except SyntaxError:
133 console.print_exception()
134 exception_text = console.file.getvalue()
135 assert "SyntaxError" in exception_text
136
137
138 def test_nested_exception():
139 console = Console(width=100, file=io.StringIO())
140 value_error_message = "ValueError because of ZeroDivisionError"
141
142 try:
143 try:
144 1 / 0
145 except ZeroDivisionError:
146 raise ValueError(value_error_message)
147 except Exception:
148 console.print_exception()
149 exception_text = console.file.getvalue()
150
151 text_should_contain = [
152 value_error_message,
153 "ZeroDivisionError",
154 "ValueError",
155 "During handling of the above exception",
156 ]
157
158 for msg in text_should_contain:
159 assert msg in exception_text
160
161 # ZeroDivisionError should come before ValueError
162 assert exception_text.find("ZeroDivisionError") < exception_text.find("ValueError")
163
164
165 def test_caused_exception():
166 console = Console(width=100, file=io.StringIO())
167 value_error_message = "ValueError caused by ZeroDivisionError"
168
169 try:
170 try:
171 1 / 0
172 except ZeroDivisionError as e:
173 raise ValueError(value_error_message) from e
174 except Exception:
175 console.print_exception()
176 exception_text = console.file.getvalue()
177
178 text_should_contain = [
179 value_error_message,
180 "ZeroDivisionError",
181 "ValueError",
182 "The above exception was the direct cause",
183 ]
184
185 for msg in text_should_contain:
186 assert msg in exception_text
187
188 # ZeroDivisionError should come before ValueError
189 assert exception_text.find("ZeroDivisionError") < exception_text.find("ValueError")
190
191
192 def test_filename_with_bracket():
193 console = Console(width=100, file=io.StringIO())
194 try:
195 exec(compile("1/0", filename="<string>", mode="exec"))
196 except Exception:
197 console.print_exception()
198 exception_text = console.file.getvalue()
199 assert "<string>" in exception_text
200
201
202 def test_filename_not_a_file():
203 console = Console(width=100, file=io.StringIO())
204 try:
205 exec(compile("1/0", filename="string", mode="exec"))
206 except Exception:
207 console.print_exception()
208 exception_text = console.file.getvalue()
209 assert "string" in exception_text
210
211
212 @pytest.mark.skipif(sys.platform == "win32", reason="renders different on windows")
213 def test_traceback_console_theme_applies():
214 """
215 Ensure that themes supplied via Console init work on Tracebacks.
216 Regression test for https://github.com/Textualize/rich/issues/1786
217 """
218 r, g, b = 123, 234, 123
219 console = Console(
220 force_terminal=True,
221 _environ={"COLORTERM": "truecolor"},
222 theme=Theme({"traceback.title": f"rgb({r},{g},{b})"}),
223 )
224
225 console.begin_capture()
226 try:
227 1 / 0
228 except Exception:
229 console.print_exception()
230
231 result = console.end_capture()
232
233 assert f"\\x1b[38;2;{r};{g};{b}mTraceback \\x1b[0m" in repr(result)
234
235
236 def test_broken_str():
237 class BrokenStr(Exception):
238 def __str__(self):
239 1 / 0
240
241 console = Console(width=100, file=io.StringIO())
242 try:
243 raise BrokenStr()
244 except Exception:
245 console.print_exception()
246 result = console.file.getvalue()
247 print(result)
248 assert "<exception str() failed>" in result
249
250
251 def test_guess_lexer():
252 assert Traceback._guess_lexer("foo.py", "code") == "python"
253 code_python = "#! usr/bin/env python\nimport this"
254 assert Traceback._guess_lexer("foo", code_python) == "python"
255 assert Traceback._guess_lexer("foo", "foo\nbnar") == "text"
256
257
258 def test_guess_lexer_yaml_j2():
259 # https://github.com/Textualize/rich/issues/2018
260 code = """\
261 foobar:
262 something: {{ raiser() }}
263 else: {{ 5 + 5 }}
264 """
265 assert Traceback._guess_lexer("test.yaml.j2", code) in ("text", "YAML+Jinja")
266
267
268 def test_recursive():
269 def foo(n):
270 return bar(n)
271
272 def bar(n):
273 return foo(n)
274
275 console = Console(width=100, file=io.StringIO())
276 try:
277 foo(1)
278 except Exception:
279 console.print_exception(max_frames=6)
280 result = console.file.getvalue()
281 print(result)
282 assert "frames hidden" in result
283 assert result.count("in foo") < 4
284
285
286 def test_suppress():
287 try:
288 1 / 0
289 except Exception:
290 traceback = Traceback(suppress=[pytest, "foo"])
291 assert len(traceback.suppress) == 2
292 assert "pytest" in traceback.suppress[0]
293 assert "foo" in traceback.suppress[1]
294
295
296 @pytest.mark.parametrize(
297 "rich_traceback_omit_for_level2,expected_frames_length,expected_frame_names",
298 (
299 # fmt: off
300 [True, 3, ["test_rich_traceback_omit_optional_local_flag", "level1", "level3"]],
301 [False, 4, ["test_rich_traceback_omit_optional_local_flag", "level1", "level2", "level3"]],
302 # fmt: on
303 ),
304 )
305 def test_rich_traceback_omit_optional_local_flag(
306 rich_traceback_omit_for_level2: bool,
307 expected_frames_length: int,
308 expected_frame_names: List[str],
309 ):
310 def level1():
311 return level2()
312
313 def level2():
314 # true-ish values are enough to trigger the opt-out:
315 _rich_traceback_omit = 1 if rich_traceback_omit_for_level2 else 0
316 return level3()
317
318 def level3():
319 return 1 / 0
320
321 try:
322 level1()
323 except Exception:
324 exc_type, exc_value, traceback = sys.exc_info()
325 trace = Traceback.from_exception(exc_type, exc_value, traceback).trace
326 frames = trace.stacks[0].frames
327 assert len(frames) == expected_frames_length
328 frame_names = [f.name for f in frames]
329 assert frame_names == expected_frame_names
330
331
332 @pytest.mark.skipif(
333 sys.version_info.minor >= 11, reason="Not applicable after Python 3.11"
334 )
335 def test_traceback_finely_grained_missing() -> None:
336 """Before 3.11, the last_instruction should be None"""
337 try:
338 1 / 0
339 except:
340 traceback = Traceback()
341 last_instruction = traceback.trace.stacks[-1].frames[-1].last_instruction
342 assert last_instruction is None
343
344
345 @pytest.mark.skipif(
346 sys.version_info.minor < 11, reason="Not applicable before Python 3.11"
347 )
348 def test_traceback_finely_grained() -> None:
349 """Check that last instruction is populated."""
350 try:
351 1 / 0
352 except:
353 traceback = Traceback()
354 last_instruction = traceback.trace.stacks[-1].frames[-1].last_instruction
355 assert last_instruction is not None
356 assert isinstance(last_instruction, tuple)
357 assert len(last_instruction) == 2
358 start, end = last_instruction
359 print(start, end)
360 assert start[0] == end[0]
361
362
363 @pytest.mark.skipif(
364 sys.version_info.minor < 11, reason="Not supported before Python 3.11"
365 )
366 def test_notes() -> None:
367 """Check traceback captures __note__."""
368 try:
369 1 / 0
370 except Exception as error:
371 error.add_note("Hello")
372 error.add_note("World")
373 traceback = Traceback()
374
375 assert traceback.trace.stacks[0].notes == ["Hello", "World"]
376
377
378 def test_recursive_exception() -> None:
379 """Regression test for https://github.com/Textualize/rich/issues/3708
380
381 Test this doesn't create an infinite loop.
382
383 """
384 console = Console()
385
386 def foo() -> None:
387 try:
388 raise RuntimeError("Hello")
389 except Exception as e:
390 raise e from e
391
392 def bar() -> None:
393 try:
394 foo()
395 except Exception as e:
396 assert e is e.__cause__
397 console.print_exception(show_locals=True)
398
399 bar()