Debian Codegraph @

Lib/test/test_traceback.py

raw
1 """Test cases for traceback module"""
2
3 from collections import namedtuple
4 from io import StringIO
5 import linecache
6 import sys
7 import types
8 import inspect
9 import builtins
10 import unittest
11 import unittest.mock
12 import re
13 import tempfile
14 import random
15 import string
16 from test import support
17 import shutil
18 from test.support import (Error, captured_output, cpython_only, ALWAYS_EQ,
19 requires_debug_ranges, has_no_debug_ranges,
20 requires_subprocess)
21 from test.support.os_helper import TESTFN, temp_dir, unlink
22 from test.support.script_helper import assert_python_ok, assert_python_failure, make_script
23 from test.support.import_helper import forget
24 from test.support import force_not_colorized, force_not_colorized_test_class
25
26 import json
27 import textwrap
28 import traceback
29 from functools import partial
30 from pathlib import Path
31 import _colorize
32
33 MODULE_PREFIX = f'{__name__}.' if __name__ == '__main__' else ''
34
35 test_code = namedtuple('code', ['co_filename', 'co_name'])
36 test_code.co_positions = lambda _: iter([(6, 6, 0, 0)])
37 test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals'])
38 test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next', 'tb_lasti'])
39
40 color_overrides = {"reset": "z", "filename": "fn", "error_highlight": "E"}
41 colors = {
42 color_overrides.get(k, k[0].lower()): v
43 for k, v in _colorize.default_theme.traceback.items()
44 }
45
46
47 LEVENSHTEIN_DATA_FILE = Path(__file__).parent / 'levenshtein_examples.json'
48
49
50 class TracebackCases(unittest.TestCase):
51 # For now, a very minimal set of tests. I want to be sure that
52 # formatting of SyntaxErrors works based on changes for 2.1.
53 def setUp(self):
54 super().setUp()
55 self.colorize = _colorize.COLORIZE
56 _colorize.COLORIZE = False
57
58 def tearDown(self):
59 super().tearDown()
60 _colorize.COLORIZE = self.colorize
61
62 def get_exception_format(self, func, exc):
63 try:
64 func()
65 except exc as value:
66 return traceback.format_exception_only(exc, value)
67 else:
68 raise ValueError("call did not raise exception")
69
70 def syntax_error_with_caret(self):
71 compile("def fact(x):\n\treturn x!\n", "?", "exec")
72
73 def syntax_error_with_caret_2(self):
74 compile("1 +\n", "?", "exec")
75
76 def syntax_error_with_caret_range(self):
77 compile("f(x, y for y in range(30), z)", "?", "exec")
78
79 def syntax_error_bad_indentation(self):
80 compile("def spam():\n print(1)\n print(2)", "?", "exec")
81
82 def syntax_error_with_caret_non_ascii(self):
83 compile('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', "?", "exec")
84
85 def syntax_error_bad_indentation2(self):
86 compile(" print(2)", "?", "exec")
87
88 def tokenizer_error_with_caret_range(self):
89 compile("blech ( ", "?", "exec")
90
91 def test_caret(self):
92 err = self.get_exception_format(self.syntax_error_with_caret,
93 SyntaxError)
94 self.assertEqual(len(err), 4)
95 self.assertEqual(err[1].strip(), "return x!")
96 self.assertIn("^", err[2]) # third line has caret
97 self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place
98 self.assertEqual(err[2].count("^"), 1)
99
100 err = self.get_exception_format(self.syntax_error_with_caret_2,
101 SyntaxError)
102 self.assertIn("^", err[2]) # third line has caret
103 self.assertEqual(err[2].count('\n'), 1) # and no additional newline
104 self.assertEqual(err[1].find("+") + 1, err[2].find("^")) # in the right place
105 self.assertEqual(err[2].count("^"), 1)
106
107 err = self.get_exception_format(self.syntax_error_with_caret_non_ascii,
108 SyntaxError)
109 self.assertIn("^", err[2]) # third line has caret
110 self.assertEqual(err[2].count('\n'), 1) # and no additional newline
111 self.assertEqual(err[1].find("+") + 1, err[2].find("^")) # in the right place
112 self.assertEqual(err[2].count("^"), 1)
113
114 err = self.get_exception_format(self.syntax_error_with_caret_range,
115 SyntaxError)
116 self.assertIn("^", err[2]) # third line has caret
117 self.assertEqual(err[2].count('\n'), 1) # and no additional newline
118 self.assertEqual(err[1].find("y"), err[2].find("^")) # in the right place
119 self.assertEqual(err[2].count("^"), len("y for y in range(30)"))
120
121 err = self.get_exception_format(self.tokenizer_error_with_caret_range,
122 SyntaxError)
123 self.assertIn("^", err[2]) # third line has caret
124 self.assertEqual(err[2].count('\n'), 1) # and no additional newline
125 self.assertEqual(err[1].find("("), err[2].find("^")) # in the right place
126 self.assertEqual(err[2].count("^"), 1)
127
128 def test_nocaret(self):
129 exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
130 err = traceback.format_exception_only(SyntaxError, exc)
131 self.assertEqual(len(err), 3)
132 self.assertEqual(err[1].strip(), "bad syntax")
133
134 @force_not_colorized
135 def test_no_caret_with_no_debug_ranges_flag(self):
136 # Make sure that if `-X no_debug_ranges` is used, there are no carets
137 # in the traceback.
138 try:
139 with open(TESTFN, 'w') as f:
140 f.write("x = 1 / 0\n")
141
142 _, _, stderr = assert_python_failure(
143 '-X', 'no_debug_ranges', TESTFN)
144
145 lines = stderr.splitlines()
146 self.assertEqual(len(lines), 4)
147 self.assertEqual(lines[0], b'Traceback (most recent call last):')
148 self.assertIn(b'line 1, in <module>', lines[1])
149 self.assertEqual(lines[2], b' x = 1 / 0')
150 self.assertEqual(lines[3], b'ZeroDivisionError: division by zero')
151 finally:
152 unlink(TESTFN)
153
154 def test_no_caret_with_no_debug_ranges_flag_python_traceback(self):
155 code = textwrap.dedent("""
156 import traceback
157 try:
158 x = 1 / 0
159 except ZeroDivisionError:
160 traceback.print_exc()
161 """)
162 try:
163 with open(TESTFN, 'w') as f:
164 f.write(code)
165
166 _, _, stderr = assert_python_ok(
167 '-X', 'no_debug_ranges', TESTFN)
168
169 lines = stderr.splitlines()
170 self.assertEqual(len(lines), 4)
171 self.assertEqual(lines[0], b'Traceback (most recent call last):')
172 self.assertIn(b'line 4, in <module>', lines[1])
173 self.assertEqual(lines[2], b' x = 1 / 0')
174 self.assertEqual(lines[3], b'ZeroDivisionError: division by zero')
175 finally:
176 unlink(TESTFN)
177
178 def test_recursion_error_during_traceback(self):
179 code = textwrap.dedent("""
180 import sys
181 from weakref import ref
182
183 sys.setrecursionlimit(15)
184
185 def f():
186 ref(lambda: 0, [])
187 f()
188
189 try:
190 f()
191 except RecursionError:
192 pass
193 """)
194 try:
195 with open(TESTFN, 'w') as f:
196 f.write(code)
197
198 rc, _, _ = assert_python_ok(TESTFN)
199 self.assertEqual(rc, 0)
200 finally:
201 unlink(TESTFN)
202
203 def test_bad_indentation(self):
204 err = self.get_exception_format(self.syntax_error_bad_indentation,
205 IndentationError)
206 self.assertEqual(len(err), 4)
207 self.assertEqual(err[1].strip(), "print(2)")
208 self.assertIn("^", err[2])
209 self.assertEqual(err[1].find(")") + 1, err[2].find("^"))
210
211 # No caret for "unexpected indent"
212 err = self.get_exception_format(self.syntax_error_bad_indentation2,
213 IndentationError)
214 self.assertEqual(len(err), 3)
215 self.assertEqual(err[1].strip(), "print(2)")
216
217 def test_base_exception(self):
218 # Test that exceptions derived from BaseException are formatted right
219 e = KeyboardInterrupt()
220 lst = traceback.format_exception_only(e.__class__, e)
221 self.assertEqual(lst, ['KeyboardInterrupt\n'])
222
223 def test_format_exception_only_bad__str__(self):
224 class X(Exception):
225 def __str__(self):
226 1/0
227 err = traceback.format_exception_only(X, X())
228 self.assertEqual(len(err), 1)
229 str_value = '<exception str() failed>'
230 if X.__module__ in ('__main__', 'builtins'):
231 str_name = X.__qualname__
232 else:
233 str_name = '.'.join([X.__module__, X.__qualname__])
234 self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value))
235
236 def test_format_exception_group_without_show_group(self):
237 eg = ExceptionGroup('A', [ValueError('B')])
238 err = traceback.format_exception_only(eg)
239 self.assertEqual(err, ['ExceptionGroup: A (1 sub-exception)\n'])
240
241 def test_format_exception_group(self):
242 eg = ExceptionGroup('A', [ValueError('B')])
243 err = traceback.format_exception_only(eg, show_group=True)
244 self.assertEqual(err, [
245 'ExceptionGroup: A (1 sub-exception)\n',
246 ' ValueError: B\n',
247 ])
248
249 def test_format_base_exception_group(self):
250 eg = BaseExceptionGroup('A', [BaseException('B')])
251 err = traceback.format_exception_only(eg, show_group=True)
252 self.assertEqual(err, [
253 'BaseExceptionGroup: A (1 sub-exception)\n',
254 ' BaseException: B\n',
255 ])
256
257 def test_format_exception_group_with_note(self):
258 exc = ValueError('B')
259 exc.add_note('Note')
260 eg = ExceptionGroup('A', [exc])
261 err = traceback.format_exception_only(eg, show_group=True)
262 self.assertEqual(err, [
263 'ExceptionGroup: A (1 sub-exception)\n',
264 ' ValueError: B\n',
265 ' Note\n',
266 ])
267
268 def test_format_exception_group_explicit_class(self):
269 eg = ExceptionGroup('A', [ValueError('B')])
270 err = traceback.format_exception_only(ExceptionGroup, eg, show_group=True)
271 self.assertEqual(err, [
272 'ExceptionGroup: A (1 sub-exception)\n',
273 ' ValueError: B\n',
274 ])
275
276 def test_format_exception_group_multiple_exceptions(self):
277 eg = ExceptionGroup('A', [ValueError('B'), TypeError('C')])
278 err = traceback.format_exception_only(eg, show_group=True)
279 self.assertEqual(err, [
280 'ExceptionGroup: A (2 sub-exceptions)\n',
281 ' ValueError: B\n',
282 ' TypeError: C\n',
283 ])
284
285 def test_format_exception_group_multiline_messages(self):
286 eg = ExceptionGroup('A\n1', [ValueError('B\n2')])
287 err = traceback.format_exception_only(eg, show_group=True)
288 self.assertEqual(err, [
289 'ExceptionGroup: A\n1 (1 sub-exception)\n',
290 ' ValueError: B\n',
291 ' 2\n',
292 ])
293
294 def test_format_exception_group_multiline2_messages(self):
295 exc = ValueError('B\n\n2\n')
296 exc.add_note('\nC\n\n3')
297 eg = ExceptionGroup('A\n\n1\n', [exc, IndexError('D')])
298 err = traceback.format_exception_only(eg, show_group=True)
299 self.assertEqual(err, [
300 'ExceptionGroup: A\n\n1\n (2 sub-exceptions)\n',
301 ' ValueError: B\n',
302 ' \n',
303 ' 2\n',
304 ' \n',
305 ' \n', # first char of `note`
306 ' C\n',
307 ' \n',
308 ' 3\n', # note ends
309 ' IndexError: D\n',
310 ])
311
312 def test_format_exception_group_syntax_error(self):
313 exc = SyntaxError("error", ("x.py", 23, None, "bad syntax"))
314 eg = ExceptionGroup('A\n1', [exc])
315 err = traceback.format_exception_only(eg, show_group=True)
316 self.assertEqual(err, [
317 'ExceptionGroup: A\n1 (1 sub-exception)\n',
318 ' File "x.py", line 23\n',
319 ' bad syntax\n',
320 ' SyntaxError: error\n',
321 ])
322
323 def test_format_exception_group_nested_with_notes(self):
324 exc = IndexError('D')
325 exc.add_note('Note\nmultiline')
326 eg = ExceptionGroup('A', [
327 ValueError('B'),
328 ExceptionGroup('C', [exc, LookupError('E')]),
329 TypeError('F'),
330 ])
331 err = traceback.format_exception_only(eg, show_group=True)
332 self.assertEqual(err, [
333 'ExceptionGroup: A (3 sub-exceptions)\n',
334 ' ValueError: B\n',
335 ' ExceptionGroup: C (2 sub-exceptions)\n',
336 ' IndexError: D\n',
337 ' Note\n',
338 ' multiline\n',
339 ' LookupError: E\n',
340 ' TypeError: F\n',
341 ])
342
343 def test_format_exception_group_with_tracebacks(self):
344 def f():
345 try:
346 1 / 0
347 except ZeroDivisionError as e:
348 return e
349
350 def g():
351 try:
352 raise TypeError('g')
353 except TypeError as e:
354 return e
355
356 eg = ExceptionGroup('A', [
357 f(),
358 ExceptionGroup('B', [g()]),
359 ])
360 err = traceback.format_exception_only(eg, show_group=True)
361 self.assertEqual(err, [
362 'ExceptionGroup: A (2 sub-exceptions)\n',
363 ' ZeroDivisionError: division by zero\n',
364 ' ExceptionGroup: B (1 sub-exception)\n',
365 ' TypeError: g\n',
366 ])
367
368 def test_format_exception_group_with_cause(self):
369 def f():
370 try:
371 try:
372 1 / 0
373 except ZeroDivisionError:
374 raise ValueError(0)
375 except Exception as e:
376 return e
377
378 eg = ExceptionGroup('A', [f()])
379 err = traceback.format_exception_only(eg, show_group=True)
380 self.assertEqual(err, [
381 'ExceptionGroup: A (1 sub-exception)\n',
382 ' ValueError: 0\n',
383 ])
384
385 def test_format_exception_group_syntax_error_with_custom_values(self):
386 # See https://github.com/python/cpython/issues/128894
387 for exc in [
388 SyntaxError('error', 'abcd'),
389 SyntaxError('error', [None] * 4),
390 SyntaxError('error', (1, 2, 3, 4)),
391 SyntaxError('error', (1, 2, 3, 4)),
392 SyntaxError('error', (1, 'a', 'b', 2)),
393 # with end_lineno and end_offset:
394 SyntaxError('error', 'abcdef'),
395 SyntaxError('error', [None] * 6),
396 SyntaxError('error', (1, 2, 3, 4, 5, 6)),
397 SyntaxError('error', (1, 'a', 'b', 2, 'c', 'd')),
398 ]:
399 with self.subTest(exc=exc):
400 err = traceback.format_exception_only(exc, show_group=True)
401 # Should not raise an exception:
402 if exc.lineno is not None:
403 self.assertEqual(len(err), 2)
404 self.assertTrue(err[0].startswith(' File'))
405 else:
406 self.assertEqual(len(err), 1)
407 self.assertEqual(err[-1], 'SyntaxError: error\n')
408
409 @requires_subprocess()
410 @force_not_colorized
411 def test_encoded_file(self):
412 # Test that tracebacks are correctly printed for encoded source files:
413 # - correct line number (Issue2384)
414 # - respect file encoding (Issue3975)
415 import sys, subprocess
416
417 # The spawned subprocess has its stdout redirected to a PIPE, and its
418 # encoding may be different from the current interpreter, on Windows
419 # at least.
420 process = subprocess.Popen([sys.executable, "-c",
421 "import sys; print(sys.stdout.encoding)"],
422 stdout=subprocess.PIPE,
423 stderr=subprocess.STDOUT)
424 stdout, stderr = process.communicate()
425 output_encoding = str(stdout, 'ascii').splitlines()[0]
426
427 def do_test(firstlines, message, charset, lineno):
428 # Raise the message in a subprocess, and catch the output
429 try:
430 with open(TESTFN, "w", encoding=charset) as output:
431 output.write("""{0}if 1:
432 import traceback;
433 raise RuntimeError('{1}')
434 """.format(firstlines, message))
435
436 process = subprocess.Popen([sys.executable, TESTFN],
437 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
438 stdout, stderr = process.communicate()
439 stdout = stdout.decode(output_encoding).splitlines()
440 finally:
441 unlink(TESTFN)
442
443 # The source lines are encoded with the 'backslashreplace' handler
444 encoded_message = message.encode(output_encoding,
445 'backslashreplace')
446 # and we just decoded them with the output_encoding.
447 message_ascii = encoded_message.decode(output_encoding)
448
449 err_line = "raise RuntimeError('{0}')".format(message_ascii)
450 err_msg = "RuntimeError: {0}".format(message_ascii)
451
452 self.assertIn("line %s" % lineno, stdout[1])
453 self.assertEndsWith(stdout[2], err_line)
454 actual_err_msg = stdout[3]
455 self.assertEqual(actual_err_msg, err_msg)
456
457 do_test("", "foo", "ascii", 3)
458 for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"):
459 if charset == "ascii":
460 text = "foo"
461 elif charset == "GBK":
462 text = "\u4E02\u5100"
463 else:
464 text = "h\xe9 ho"
465 do_test("# coding: {0}\n".format(charset),
466 text, charset, 4)
467 do_test("#!shebang\n# coding: {0}\n".format(charset),
468 text, charset, 5)
469 do_test(" \t\f\n# coding: {0}\n".format(charset),
470 text, charset, 5)
471 # Issue #18960: coding spec should have no effect
472 do_test("x=0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5)
473
474 def test_print_traceback_at_exit(self):
475 # Issue #22599: Ensure that it is possible to use the traceback module
476 # to display an exception at Python exit
477 code = textwrap.dedent("""
478 import sys
479 import traceback
480
481 class PrintExceptionAtExit(object):
482 def __init__(self):
483 try:
484 x = 1 / 0
485 except Exception as e:
486 self.exc = e
487 # self.exc.__traceback__ contains frames:
488 # explicitly clear the reference to self in the current
489 # frame to break a reference cycle
490 self = None
491
492 def __del__(self):
493 traceback.print_exception(self.exc)
494
495 # Keep a reference in the module namespace to call the destructor
496 # when the module is unloaded
497 obj = PrintExceptionAtExit()
498 """)
499 rc, stdout, stderr = assert_python_ok('-c', code)
500 expected = [b'Traceback (most recent call last):',
501 b' File "<string>", line 8, in __init__',
502 b' x = 1 / 0',
503 b' ^^^^^',
504 b'ZeroDivisionError: division by zero']
505 self.assertEqual(stderr.splitlines(), expected)
506
507 @cpython_only
508 def test_lost_io_open(self):
509 # GH-142737: Display the traceback even if io.open is lost
510 crasher = textwrap.dedent("""\
511 import io
512 import traceback
513 # Trigger fallback mode
514 traceback._print_exception_bltin = None
515 del io.open
516 raise RuntimeError("should not crash")
517 """)
518
519 # Create a temporary script to exercise _Py_FindSourceFile
520 with temp_dir() as script_dir:
521 script = make_script(
522 script_dir=script_dir,
523 script_basename='tb_test_no_io_open',
524 source=crasher)
525 rc, stdout, stderr = assert_python_failure(script)
526
527 self.assertEqual(rc, 1) # Make sure it's not a crash
528
529 expected = [b'Traceback (most recent call last):',
530 f' File "{script}", line 6, in <module>'.encode(),
531 b'RuntimeError: should not crash']
532 self.assertEqual(stderr.splitlines(), expected)
533
534 def test_print_exception(self):
535 output = StringIO()
536 traceback.print_exception(
537 Exception, Exception("projector"), None, file=output
538 )
539 self.assertEqual(output.getvalue(), "Exception: projector\n")
540
541 def test_print_exception_exc(self):
542 output = StringIO()
543 traceback.print_exception(Exception("projector"), file=output)
544 self.assertEqual(output.getvalue(), "Exception: projector\n")
545
546 def test_print_last(self):
547 with support.swap_attr(sys, 'last_exc', ValueError(42)):
548 output = StringIO()
549 traceback.print_last(file=output)
550 self.assertEqual(output.getvalue(), "ValueError: 42\n")
551
552 def test_format_exception_exc(self):
553 e = Exception("projector")
554 output = traceback.format_exception(e)
555 self.assertEqual(output, ["Exception: projector\n"])
556 with self.assertRaisesRegex(ValueError, 'Both or neither'):
557 traceback.format_exception(e.__class__, e)
558 with self.assertRaisesRegex(ValueError, 'Both or neither'):
559 traceback.format_exception(e.__class__, tb=e.__traceback__)
560 with self.assertRaisesRegex(TypeError, 'required positional argument'):
561 traceback.format_exception(exc=e)
562
563 def test_format_exception_only_exc(self):
564 output = traceback.format_exception_only(Exception("projector"))
565 self.assertEqual(output, ["Exception: projector\n"])
566
567 def test_exception_is_None(self):
568 NONE_EXC_STRING = 'NoneType: None\n'
569 excfile = StringIO()
570 traceback.print_exception(None, file=excfile)
571 self.assertEqual(excfile.getvalue(), NONE_EXC_STRING)
572
573 excfile = StringIO()
574 traceback.print_exception(None, None, None, file=excfile)
575 self.assertEqual(excfile.getvalue(), NONE_EXC_STRING)
576
577 excfile = StringIO()
578 traceback.print_exc(None, file=excfile)
579 self.assertEqual(excfile.getvalue(), NONE_EXC_STRING)
580
581 self.assertEqual(traceback.format_exc(None), NONE_EXC_STRING)
582 self.assertEqual(traceback.format_exception(None), [NONE_EXC_STRING])
583 self.assertEqual(
584 traceback.format_exception(None, None, None), [NONE_EXC_STRING])
585 self.assertEqual(
586 traceback.format_exception_only(None), [NONE_EXC_STRING])
587 self.assertEqual(
588 traceback.format_exception_only(None, None), [NONE_EXC_STRING])
589
590 def test_signatures(self):
591 self.assertEqual(
592 str(inspect.signature(traceback.print_exception)),
593 ('(exc, /, value=<implicit>, tb=<implicit>, '
594 'limit=None, file=None, chain=True, **kwargs)'))
595
596 self.assertEqual(
597 str(inspect.signature(traceback.format_exception)),
598 ('(exc, /, value=<implicit>, tb=<implicit>, limit=None, '
599 'chain=True, **kwargs)'))
600
601 self.assertEqual(
602 str(inspect.signature(traceback.format_exception_only)),
603 '(exc, /, value=<implicit>, *, show_group=False, **kwargs)')
604
605
606 class PurePythonExceptionFormattingMixin:
607 def get_exception(self, callable, slice_start=0, slice_end=-1):
608 try:
609 callable()
610 except BaseException:
611 return traceback.format_exc().splitlines()[slice_start:slice_end]
612 else:
613 self.fail("No exception thrown.")
614
615 callable_line = get_exception.__code__.co_firstlineno + 2
616
617
618 class CAPIExceptionFormattingMixin:
619 LEGACY = 0
620
621 def get_exception(self, callable, slice_start=0, slice_end=-1):
622 from _testcapi import exception_print
623 try:
624 callable()
625 self.fail("No exception thrown.")
626 except Exception as e:
627 with captured_output("stderr") as tbstderr:
628 exception_print(e, self.LEGACY)
629 return tbstderr.getvalue().splitlines()[slice_start:slice_end]
630
631 callable_line = get_exception.__code__.co_firstlineno + 3
632
633 class CAPIExceptionFormattingLegacyMixin(CAPIExceptionFormattingMixin):
634 LEGACY = 1
635
636 @requires_debug_ranges()
637 class TracebackErrorLocationCaretTestBase:
638 """
639 Tests for printing code error expressions as part of PEP 657
640 """
641 def test_basic_caret(self):
642 # NOTE: In caret tests, "if True:" is used as a way to force indicator
643 # display, since the raising expression spans only part of the line.
644 def f():
645 if True: raise ValueError("basic caret tests")
646
647 lineno_f = f.__code__.co_firstlineno
648 expected_f = (
649 'Traceback (most recent call last):\n'
650 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
651 ' callable()\n'
652 ' ~~~~~~~~^^\n'
653 f' File "{__file__}", line {lineno_f+1}, in f\n'
654 ' if True: raise ValueError("basic caret tests")\n'
655 ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
656 )
657 result_lines = self.get_exception(f)
658 self.assertEqual(result_lines, expected_f.splitlines())
659
660 def test_line_with_unicode(self):
661 # Make sure that even if a line contains multi-byte unicode characters
662 # the correct carets are printed.
663 def f_with_unicode():
664 if True: raise ValueError("Ĥellö Wörld")
665
666 lineno_f = f_with_unicode.__code__.co_firstlineno
667 expected_f = (
668 'Traceback (most recent call last):\n'
669 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
670 ' callable()\n'
671 ' ~~~~~~~~^^\n'
672 f' File "{__file__}", line {lineno_f+1}, in f_with_unicode\n'
673 ' if True: raise ValueError("Ĥellö Wörld")\n'
674 ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
675 )
676 result_lines = self.get_exception(f_with_unicode)
677 self.assertEqual(result_lines, expected_f.splitlines())
678
679 def test_caret_in_type_annotation(self):
680 def f_with_type():
681 def foo(a: THIS_DOES_NOT_EXIST ) -> int:
682 return 0
683 foo.__annotations__
684
685 lineno_f = f_with_type.__code__.co_firstlineno
686 expected_f = (
687 'Traceback (most recent call last):\n'
688 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
689 ' callable()\n'
690 ' ~~~~~~~~^^\n'
691 f' File "{__file__}", line {lineno_f+3}, in f_with_type\n'
692 ' foo.__annotations__\n'
693 f' File "{__file__}", line {lineno_f+1}, in __annotate__\n'
694 ' def foo(a: THIS_DOES_NOT_EXIST ) -> int:\n'
695 ' ^^^^^^^^^^^^^^^^^^^\n'
696 )
697 result_lines = self.get_exception(f_with_type)
698 self.assertEqual(result_lines, expected_f.splitlines())
699
700 def test_caret_multiline_expression(self):
701 # Make sure no carets are printed for expressions spanning multiple
702 # lines.
703 def f_with_multiline():
704 if True: raise ValueError(
705 "error over multiple lines"
706 )
707
708 lineno_f = f_with_multiline.__code__.co_firstlineno
709 expected_f = (
710 'Traceback (most recent call last):\n'
711 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
712 ' callable()\n'
713 ' ~~~~~~~~^^\n'
714 f' File "{__file__}", line {lineno_f+1}, in f_with_multiline\n'
715 ' if True: raise ValueError(\n'
716 ' ^^^^^^^^^^^^^^^^^\n'
717 ' "error over multiple lines"\n'
718 ' ^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
719 ' )\n'
720 ' ^'
721 )
722 result_lines = self.get_exception(f_with_multiline)
723 self.assertEqual(result_lines, expected_f.splitlines())
724
725 def test_caret_multiline_expression_syntax_error(self):
726 # Make sure an expression spanning multiple lines that has
727 # a syntax error is correctly marked with carets.
728 code = textwrap.dedent("""
729 def foo(*args, **kwargs):
730 pass
731
732 a, b, c = 1, 2, 3
733
734 foo(a, z
735 for z in
736 range(10), b, c)
737 """)
738
739 def f_with_multiline():
740 # Need to defer the compilation until in self.get_exception(..)
741 return compile(code, "?", "exec")
742
743 lineno_f = f_with_multiline.__code__.co_firstlineno
744
745 expected_f = (
746 'Traceback (most recent call last):\n'
747 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
748 ' callable()\n'
749 ' ~~~~~~~~^^\n'
750 f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n'
751 ' return compile(code, "?", "exec")\n'
752 ' File "?", line 7\n'
753 ' foo(a, z\n'
754 ' ^'
755 )
756
757 result_lines = self.get_exception(f_with_multiline)
758 self.assertEqual(result_lines, expected_f.splitlines())
759
760 # Check custom error messages covering multiple lines
761 code = textwrap.dedent("""
762 dummy_call(
763 "dummy value"
764 foo="bar",
765 )
766 """)
767
768 def f_with_multiline():
769 # Need to defer the compilation until in self.get_exception(..)
770 return compile(code, "?", "exec")
771
772 lineno_f = f_with_multiline.__code__.co_firstlineno
773
774 expected_f = (
775 'Traceback (most recent call last):\n'
776 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
777 ' callable()\n'
778 ' ~~~~~~~~^^\n'
779 f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n'
780 ' return compile(code, "?", "exec")\n'
781 ' File "?", line 3\n'
782 ' "dummy value"\n'
783 ' ^^^^^^^^^^^^^'
784 )
785
786 result_lines = self.get_exception(f_with_multiline)
787 self.assertEqual(result_lines, expected_f.splitlines())
788
789 def test_caret_multiline_expression_bin_op(self):
790 # Make sure no carets are printed for expressions spanning multiple
791 # lines.
792 def f_with_multiline():
793 return (
794 2 + 1 /
795 0
796 )
797
798 lineno_f = f_with_multiline.__code__.co_firstlineno
799 expected_f = (
800 'Traceback (most recent call last):\n'
801 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
802 ' callable()\n'
803 ' ~~~~~~~~^^\n'
804 f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n'
805 ' 2 + 1 /\n'
806 ' ~~^\n'
807 ' 0\n'
808 ' ~'
809 )
810 result_lines = self.get_exception(f_with_multiline)
811 self.assertEqual(result_lines, expected_f.splitlines())
812
813 def test_caret_for_binary_operators(self):
814 def f_with_binary_operator():
815 divisor = 20
816 return 10 + divisor / 0 + 30
817
818 lineno_f = f_with_binary_operator.__code__.co_firstlineno
819 expected_error = (
820 'Traceback (most recent call last):\n'
821 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
822 ' callable()\n'
823 ' ~~~~~~~~^^\n'
824 f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n'
825 ' return 10 + divisor / 0 + 30\n'
826 ' ~~~~~~~~^~~\n'
827 )
828 result_lines = self.get_exception(f_with_binary_operator)
829 self.assertEqual(result_lines, expected_error.splitlines())
830
831 def test_caret_for_binary_operators_with_unicode(self):
832 def f_with_binary_operator():
833 áóí = 20
834 return 10 + áóí / 0 + 30
835
836 lineno_f = f_with_binary_operator.__code__.co_firstlineno
837 expected_error = (
838 'Traceback (most recent call last):\n'
839 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
840 ' callable()\n'
841 ' ~~~~~~~~^^\n'
842 f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n'
843 ' return 10 + áóí / 0 + 30\n'
844 ' ~~~~^~~\n'
845 )
846 result_lines = self.get_exception(f_with_binary_operator)
847 self.assertEqual(result_lines, expected_error.splitlines())
848
849 def test_caret_for_binary_operators_two_char(self):
850 def f_with_binary_operator():
851 divisor = 20
852 return 10 + divisor // 0 + 30
853
854 lineno_f = f_with_binary_operator.__code__.co_firstlineno
855 expected_error = (
856 'Traceback (most recent call last):\n'
857 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
858 ' callable()\n'
859 ' ~~~~~~~~^^\n'
860 f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n'
861 ' return 10 + divisor // 0 + 30\n'
862 ' ~~~~~~~~^^~~\n'
863 )
864 result_lines = self.get_exception(f_with_binary_operator)
865 self.assertEqual(result_lines, expected_error.splitlines())
866
867 def test_caret_for_binary_operators_with_spaces_and_parenthesis(self):
868 def f_with_binary_operator():
869 a = 1
870 b = c = ""
871 return ( a ) +b + c
872
873 lineno_f = f_with_binary_operator.__code__.co_firstlineno
874 expected_error = (
875 'Traceback (most recent call last):\n'
876 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
877 ' callable()\n'
878 ' ~~~~~~~~^^\n'
879 f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n'
880 ' return ( a ) +b + c\n'
881 ' ~~~~~~~~~~^~\n'
882 )
883 result_lines = self.get_exception(f_with_binary_operator)
884 self.assertEqual(result_lines, expected_error.splitlines())
885
886 def test_caret_for_binary_operators_multiline(self):
887 def f_with_binary_operator():
888 b = 1
889 c = ""
890 a = b \
891 +\
892 c # test
893 return a
894
895 lineno_f = f_with_binary_operator.__code__.co_firstlineno
896 expected_error = (
897 'Traceback (most recent call last):\n'
898 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
899 ' callable()\n'
900 ' ~~~~~~~~^^\n'
901 f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n'
902 ' a = b \\\n'
903 ' ~~~~~~\n'
904 ' +\\\n'
905 ' ^~\n'
906 ' c # test\n'
907 ' ~\n'
908 )
909 result_lines = self.get_exception(f_with_binary_operator)
910 self.assertEqual(result_lines, expected_error.splitlines())
911
912 def test_caret_for_binary_operators_multiline_two_char(self):
913 def f_with_binary_operator():
914 b = 1
915 c = ""
916 a = (
917 (b # test +
918 ) \
919 # +
920 << (c # test
921 \
922 ) # test
923 )
924 return a
925
926 lineno_f = f_with_binary_operator.__code__.co_firstlineno
927 expected_error = (
928 'Traceback (most recent call last):\n'
929 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
930 ' callable()\n'
931 ' ~~~~~~~~^^\n'
932 f' File "{__file__}", line {lineno_f+4}, in f_with_binary_operator\n'
933 ' (b # test +\n'
934 ' ~~~~~~~~~~~~\n'
935 ' ) \\\n'
936 ' ~~~~\n'
937 ' # +\n'
938 ' ~~~\n'
939 ' << (c # test\n'
940 ' ^^~~~~~~~~~~~\n'
941 ' \\\n'
942 ' ~\n'
943 ' ) # test\n'
944 ' ~\n'
945 )
946 result_lines = self.get_exception(f_with_binary_operator)
947 self.assertEqual(result_lines, expected_error.splitlines())
948
949 def test_caret_for_binary_operators_multiline_with_unicode(self):
950 def f_with_binary_operator():
951 b = 1
952 a = ("ááá" +
953 "áá") + b
954 return a
955
956 lineno_f = f_with_binary_operator.__code__.co_firstlineno
957 expected_error = (
958 'Traceback (most recent call last):\n'
959 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
960 ' callable()\n'
961 ' ~~~~~~~~^^\n'
962 f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n'
963 ' a = ("ááá" +\n'
964 ' ~~~~~~~~\n'
965 ' "áá") + b\n'
966 ' ~~~~~~^~~\n'
967 )
968 result_lines = self.get_exception(f_with_binary_operator)
969 self.assertEqual(result_lines, expected_error.splitlines())
970
971 def test_caret_for_subscript(self):
972 def f_with_subscript():
973 some_dict = {'x': {'y': None}}
974 return some_dict['x']['y']['z']
975
976 lineno_f = f_with_subscript.__code__.co_firstlineno
977 expected_error = (
978 'Traceback (most recent call last):\n'
979 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
980 ' callable()\n'
981 ' ~~~~~~~~^^\n'
982 f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n'
983 " return some_dict['x']['y']['z']\n"
984 ' ~~~~~~~~~~~~~~~~~~~^^^^^\n'
985 )
986 result_lines = self.get_exception(f_with_subscript)
987 self.assertEqual(result_lines, expected_error.splitlines())
988
989 def test_caret_for_subscript_unicode(self):
990 def f_with_subscript():
991 some_dict = {'ó': {'á': {'í': {'theta': 1}}}}
992 return some_dict['ó']['á']['í']['beta']
993
994 lineno_f = f_with_subscript.__code__.co_firstlineno
995 expected_error = (
996 'Traceback (most recent call last):\n'
997 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
998 ' callable()\n'
999 ' ~~~~~~~~^^\n'
1000 f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n'
1001 " return some_dict['ó']['á']['í']['beta']\n"
1002 ' ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^\n'
1003 )
1004 result_lines = self.get_exception(f_with_subscript)
1005 self.assertEqual(result_lines, expected_error.splitlines())
1006
1007 def test_caret_for_subscript_with_spaces_and_parenthesis(self):
1008 def f_with_binary_operator():
1009 a = []
1010 b = c = 1
1011 return b [ a ] + c
1012
1013 lineno_f = f_with_binary_operator.__code__.co_firstlineno
1014 expected_error = (
1015 'Traceback (most recent call last):\n'
1016 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1017 ' callable()\n'
1018 ' ~~~~~~~~^^\n'
1019 f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n'
1020 ' return b [ a ] + c\n'
1021 ' ~~~~~~^^^^^^^^^\n'
1022 )
1023 result_lines = self.get_exception(f_with_binary_operator)
1024 self.assertEqual(result_lines, expected_error.splitlines())
1025
1026 def test_caret_for_subscript_multiline(self):
1027 def f_with_subscript():
1028 bbbbb = {}
1029 ccc = 1
1030 ddd = 2
1031 b = bbbbb \
1032 [ ccc # test
1033
1034 + ddd \
1035
1036 ] # test
1037 return b
1038
1039 lineno_f = f_with_subscript.__code__.co_firstlineno
1040 expected_error = (
1041 'Traceback (most recent call last):\n'
1042 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1043 ' callable()\n'
1044 ' ~~~~~~~~^^\n'
1045 f' File "{__file__}", line {lineno_f+4}, in f_with_subscript\n'
1046 ' b = bbbbb \\\n'
1047 ' ~~~~~~~\n'
1048 ' [ ccc # test\n'
1049 ' ^^^^^^^^^^^^^\n'
1050 ' \n'
1051 ' \n'
1052 ' + ddd \\\n'
1053 ' ^^^^^^^^\n'
1054 ' \n'
1055 ' \n'
1056 ' ] # test\n'
1057 ' ^\n'
1058 )
1059 result_lines = self.get_exception(f_with_subscript)
1060 self.assertEqual(result_lines, expected_error.splitlines())
1061
1062 def test_caret_for_call(self):
1063 def f_with_call():
1064 def f1(a):
1065 def f2(b):
1066 raise RuntimeError("fail")
1067 return f2
1068 return f1("x")("y")("z")
1069
1070 lineno_f = f_with_call.__code__.co_firstlineno
1071 expected_error = (
1072 'Traceback (most recent call last):\n'
1073 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1074 ' callable()\n'
1075 ' ~~~~~~~~^^\n'
1076 f' File "{__file__}", line {lineno_f+5}, in f_with_call\n'
1077 ' return f1("x")("y")("z")\n'
1078 ' ~~~~~~~^^^^^\n'
1079 f' File "{__file__}", line {lineno_f+3}, in f2\n'
1080 ' raise RuntimeError("fail")\n'
1081 )
1082 result_lines = self.get_exception(f_with_call)
1083 self.assertEqual(result_lines, expected_error.splitlines())
1084
1085 def test_caret_for_call_unicode(self):
1086 def f_with_call():
1087 def f1(a):
1088 def f2(b):
1089 raise RuntimeError("fail")
1090 return f2
1091 return f1("ó")("á")
1092
1093 lineno_f = f_with_call.__code__.co_firstlineno
1094 expected_error = (
1095 'Traceback (most recent call last):\n'
1096 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1097 ' callable()\n'
1098 ' ~~~~~~~~^^\n'
1099 f' File "{__file__}", line {lineno_f+5}, in f_with_call\n'
1100 ' return f1("ó")("á")\n'
1101 ' ~~~~~~~^^^^^\n'
1102 f' File "{__file__}", line {lineno_f+3}, in f2\n'
1103 ' raise RuntimeError("fail")\n'
1104 )
1105 result_lines = self.get_exception(f_with_call)
1106 self.assertEqual(result_lines, expected_error.splitlines())
1107
1108 def test_caret_for_call_with_spaces_and_parenthesis(self):
1109 def f_with_binary_operator():
1110 def f(a):
1111 raise RuntimeError("fail")
1112 return f ( "x" ) + 2
1113
1114 lineno_f = f_with_binary_operator.__code__.co_firstlineno
1115 expected_error = (
1116 'Traceback (most recent call last):\n'
1117 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1118 ' callable()\n'
1119 ' ~~~~~~~~^^\n'
1120 f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n'
1121 ' return f ( "x" ) + 2\n'
1122 ' ~~~~~~^^^^^^^^^^^\n'
1123 f' File "{__file__}", line {lineno_f+2}, in f\n'
1124 ' raise RuntimeError("fail")\n'
1125 )
1126 result_lines = self.get_exception(f_with_binary_operator)
1127 self.assertEqual(result_lines, expected_error.splitlines())
1128
1129 def test_caret_for_call_multiline(self):
1130 def f_with_call():
1131 class C:
1132 def y(self, a):
1133 def f(b):
1134 raise RuntimeError("fail")
1135 return f
1136 def g(x):
1137 return C()
1138 a = (g(1).y)(
1139 2
1140 )(3)(4)
1141 return a
1142
1143 lineno_f = f_with_call.__code__.co_firstlineno
1144 expected_error = (
1145 'Traceback (most recent call last):\n'
1146 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1147 ' callable()\n'
1148 ' ~~~~~~~~^^\n'
1149 f' File "{__file__}", line {lineno_f+8}, in f_with_call\n'
1150 ' a = (g(1).y)(\n'
1151 ' ~~~~~~~~~\n'
1152 ' 2\n'
1153 ' ~\n'
1154 ' )(3)(4)\n'
1155 ' ~^^^\n'
1156 f' File "{__file__}", line {lineno_f+4}, in f\n'
1157 ' raise RuntimeError("fail")\n'
1158 )
1159 result_lines = self.get_exception(f_with_call)
1160 self.assertEqual(result_lines, expected_error.splitlines())
1161
1162 def test_many_lines(self):
1163 def f():
1164 x = 1
1165 if True: x += (
1166 "a" +
1167 "a"
1168 ) # test
1169
1170 lineno_f = f.__code__.co_firstlineno
1171 expected_error = (
1172 'Traceback (most recent call last):\n'
1173 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1174 ' callable()\n'
1175 ' ~~~~~~~~^^\n'
1176 f' File "{__file__}", line {lineno_f+2}, in f\n'
1177 ' if True: x += (\n'
1178 ' ^^^^^^\n'
1179 ' ...<2 lines>...\n'
1180 ' ) # test\n'
1181 ' ^\n'
1182 )
1183 result_lines = self.get_exception(f)
1184 self.assertEqual(result_lines, expected_error.splitlines())
1185
1186 def test_many_lines_no_caret(self):
1187 def f():
1188 x = 1
1189 x += (
1190 "a" +
1191 "a"
1192 )
1193
1194 lineno_f = f.__code__.co_firstlineno
1195 expected_error = (
1196 'Traceback (most recent call last):\n'
1197 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1198 ' callable()\n'
1199 ' ~~~~~~~~^^\n'
1200 f' File "{__file__}", line {lineno_f+2}, in f\n'
1201 ' x += (\n'
1202 ' ...<2 lines>...\n'
1203 ' )\n'
1204 )
1205 result_lines = self.get_exception(f)
1206 self.assertEqual(result_lines, expected_error.splitlines())
1207
1208 def test_many_lines_binary_op(self):
1209 def f_with_binary_operator():
1210 b = 1
1211 c = "a"
1212 a = (
1213 b +
1214 b
1215 ) + (
1216 c +
1217 c +
1218 c
1219 )
1220 return a
1221
1222 lineno_f = f_with_binary_operator.__code__.co_firstlineno
1223 expected_error = (
1224 'Traceback (most recent call last):\n'
1225 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1226 ' callable()\n'
1227 ' ~~~~~~~~^^\n'
1228 f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n'
1229 ' a = (\n'
1230 ' ~\n'
1231 ' b +\n'
1232 ' ~~~\n'
1233 ' b\n'
1234 ' ~\n'
1235 ' ) + (\n'
1236 ' ~~^~~\n'
1237 ' c +\n'
1238 ' ~~~\n'
1239 ' ...<2 lines>...\n'
1240 ' )\n'
1241 ' ~\n'
1242 )
1243 result_lines = self.get_exception(f_with_binary_operator)
1244 self.assertEqual(result_lines, expected_error.splitlines())
1245
1246 def test_traceback_specialization_with_syntax_error(self):
1247 bytecode = compile("1 / 0 / 1 / 2\n", TESTFN, "exec")
1248
1249 with open(TESTFN, "w") as file:
1250 # make the file's contents invalid
1251 file.write("1 $ 0 / 1 / 2\n")
1252 self.addCleanup(unlink, TESTFN)
1253
1254 func = partial(exec, bytecode)
1255 result_lines = self.get_exception(func)
1256
1257 lineno_f = bytecode.co_firstlineno
1258 expected_error = (
1259 'Traceback (most recent call last):\n'
1260 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1261 ' callable()\n'
1262 ' ~~~~~~~~^^\n'
1263 f' File "{TESTFN}", line {lineno_f}, in <module>\n'
1264 " 1 $ 0 / 1 / 2\n"
1265 ' ^^^^^\n'
1266 )
1267 self.assertEqual(result_lines, expected_error.splitlines())
1268
1269 def test_traceback_very_long_line(self):
1270 source = "if True: " + "a" * 256
1271 bytecode = compile(source, TESTFN, "exec")
1272
1273 with open(TESTFN, "w") as file:
1274 file.write(source)
1275 self.addCleanup(unlink, TESTFN)
1276
1277 func = partial(exec, bytecode)
1278 result_lines = self.get_exception(func)
1279
1280 lineno_f = bytecode.co_firstlineno
1281 expected_error = (
1282 'Traceback (most recent call last):\n'
1283 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1284 ' callable()\n'
1285 ' ~~~~~~~~^^\n'
1286 f' File "{TESTFN}", line {lineno_f}, in <module>\n'
1287 f' {source}\n'
1288 f' {" "*len("if True: ") + "^"*256}\n'
1289 )
1290 self.assertEqual(result_lines, expected_error.splitlines())
1291
1292 def test_secondary_caret_not_elided(self):
1293 # Always show a line's indicators if they include the secondary character.
1294 def f_with_subscript():
1295 some_dict = {'x': {'y': None}}
1296 some_dict['x']['y']['z']
1297
1298 lineno_f = f_with_subscript.__code__.co_firstlineno
1299 expected_error = (
1300 'Traceback (most recent call last):\n'
1301 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1302 ' callable()\n'
1303 ' ~~~~~~~~^^\n'
1304 f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n'
1305 " some_dict['x']['y']['z']\n"
1306 ' ~~~~~~~~~~~~~~~~~~~^^^^^\n'
1307 )
1308 result_lines = self.get_exception(f_with_subscript)
1309 self.assertEqual(result_lines, expected_error.splitlines())
1310
1311 def test_caret_exception_group(self):
1312 # Notably, this covers whether indicators handle margin strings correctly.
1313 # (Exception groups use margin strings to display vertical indicators.)
1314 # The implementation must account for both "indent" and "margin" offsets.
1315
1316 def exc():
1317 if True: raise ExceptionGroup("eg", [ValueError(1), TypeError(2)])
1318
1319 expected_error = (
1320 f' + Exception Group Traceback (most recent call last):\n'
1321 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
1322 f' | callable()\n'
1323 f' | ~~~~~~~~^^\n'
1324 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 1}, in exc\n'
1325 f' | if True: raise ExceptionGroup("eg", [ValueError(1), TypeError(2)])\n'
1326 f' | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
1327 f' | ExceptionGroup: eg (2 sub-exceptions)\n'
1328 f' +-+---------------- 1 ----------------\n'
1329 f' | ValueError: 1\n'
1330 f' +---------------- 2 ----------------\n'
1331 f' | TypeError: 2\n')
1332
1333 result_lines = self.get_exception(exc)
1334 self.assertEqual(result_lines, expected_error.splitlines())
1335
1336 def assertSpecialized(self, func, expected_specialization):
1337 result_lines = self.get_exception(func)
1338 specialization_line = result_lines[-1]
1339 self.assertEqual(specialization_line.lstrip(), expected_specialization)
1340
1341 def test_specialization_variations(self):
1342 self.assertSpecialized(lambda: 1/0,
1343 "~^~")
1344 self.assertSpecialized(lambda: 1/0/3,
1345 "~^~")
1346 self.assertSpecialized(lambda: 1 / 0,
1347 "~~^~~")
1348 self.assertSpecialized(lambda: 1 / 0 / 3,
1349 "~~^~~")
1350 self.assertSpecialized(lambda: 1/ 0,
1351 "~^~~")
1352 self.assertSpecialized(lambda: 1/ 0/3,
1353 "~^~~")
1354 self.assertSpecialized(lambda: 1 / 0,
1355 "~~~~~^~~~")
1356 self.assertSpecialized(lambda: 1 / 0 / 5,
1357 "~~~~~^~~~")
1358 self.assertSpecialized(lambda: 1 /0,
1359 "~~^~")
1360 self.assertSpecialized(lambda: 1//0,
1361 "~^^~")
1362 self.assertSpecialized(lambda: 1//0//4,
1363 "~^^~")
1364 self.assertSpecialized(lambda: 1 // 0,
1365 "~~^^~~")
1366 self.assertSpecialized(lambda: 1 // 0 // 4,
1367 "~~^^~~")
1368 self.assertSpecialized(lambda: 1 //0,
1369 "~~^^~")
1370 self.assertSpecialized(lambda: 1// 0,
1371 "~^^~~")
1372
1373 def test_decorator_application_lineno_correct(self):
1374 def dec_error(func):
1375 raise TypeError
1376 def dec_fine(func):
1377 return func
1378 def applydecs():
1379 @dec_error
1380 @dec_fine
1381 def g(): pass
1382 result_lines = self.get_exception(applydecs)
1383 lineno_applydescs = applydecs.__code__.co_firstlineno
1384 lineno_dec_error = dec_error.__code__.co_firstlineno
1385 expected_error = (
1386 'Traceback (most recent call last):\n'
1387 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1388 ' callable()\n'
1389 ' ~~~~~~~~^^\n'
1390 f' File "{__file__}", line {lineno_applydescs + 1}, in applydecs\n'
1391 ' @dec_error\n'
1392 ' ^^^^^^^^^\n'
1393 f' File "{__file__}", line {lineno_dec_error + 1}, in dec_error\n'
1394 ' raise TypeError\n'
1395 )
1396 self.assertEqual(result_lines, expected_error.splitlines())
1397
1398 def applydecs_class():
1399 @dec_error
1400 @dec_fine
1401 class A: pass
1402 result_lines = self.get_exception(applydecs_class)
1403 lineno_applydescs_class = applydecs_class.__code__.co_firstlineno
1404 expected_error = (
1405 'Traceback (most recent call last):\n'
1406 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
1407 ' callable()\n'
1408 ' ~~~~~~~~^^\n'
1409 f' File "{__file__}", line {lineno_applydescs_class + 1}, in applydecs_class\n'
1410 ' @dec_error\n'
1411 ' ^^^^^^^^^\n'
1412 f' File "{__file__}", line {lineno_dec_error + 1}, in dec_error\n'
1413 ' raise TypeError\n'
1414 )
1415 self.assertEqual(result_lines, expected_error.splitlines())
1416
1417 def test_multiline_method_call_a(self):
1418 def f():
1419 (None
1420 .method
1421 )()
1422 actual = self.get_exception(f)
1423 expected = [
1424 "Traceback (most recent call last):",
1425 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1426 " callable()",
1427 " ~~~~~~~~^^",
1428 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f",
1429 " .method",
1430 " ^^^^^^",
1431 ]
1432 self.assertEqual(actual, expected)
1433
1434 def test_multiline_method_call_b(self):
1435 def f():
1436 (None.
1437 method
1438 )()
1439 actual = self.get_exception(f)
1440 expected = [
1441 "Traceback (most recent call last):",
1442 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1443 " callable()",
1444 " ~~~~~~~~^^",
1445 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f",
1446 " method",
1447 ]
1448 self.assertEqual(actual, expected)
1449
1450 def test_multiline_method_call_c(self):
1451 def f():
1452 (None
1453 . method
1454 )()
1455 actual = self.get_exception(f)
1456 expected = [
1457 "Traceback (most recent call last):",
1458 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1459 " callable()",
1460 " ~~~~~~~~^^",
1461 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f",
1462 " . method",
1463 " ^^^^^^",
1464 ]
1465 self.assertEqual(actual, expected)
1466
1467 def test_wide_characters_unicode_with_problematic_byte_offset(self):
1468 def f():
1469 width
1470
1471 actual = self.get_exception(f)
1472 expected = [
1473 "Traceback (most recent call last):",
1474 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1475 " callable()",
1476 " ~~~~~~~~^^",
1477 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1478 " width",
1479 ]
1480 self.assertEqual(actual, expected)
1481
1482
1483 def test_byte_offset_with_wide_characters_middle(self):
1484 def f():
1485 width = 1
1486 raise ValueError(width)
1487
1488 actual = self.get_exception(f)
1489 expected = [
1490 "Traceback (most recent call last):",
1491 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1492 " callable()",
1493 " ~~~~~~~~^^",
1494 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f",
1495 " raise ValueError(width)",
1496 ]
1497 self.assertEqual(actual, expected)
1498
1499 def test_byte_offset_multiline(self):
1500 def f():
1501 www = 1
1502 th = 0
1503
1504 print(1, www(
1505 th))
1506
1507 actual = self.get_exception(f)
1508 expected = [
1509 "Traceback (most recent call last):",
1510 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1511 " callable()",
1512 " ~~~~~~~~^^",
1513 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 4}, in f",
1514 f" print(1, www(",
1515 f" ~~~~~~^",
1516 f" th))",
1517 f" ^^^^^",
1518 ]
1519 self.assertEqual(actual, expected)
1520
1521 def test_byte_offset_with_wide_characters_term_highlight(self):
1522 def f():
1523 说明说明 = 1
1524 şçöğıĤellö = 0 # not wide but still non-ascii
1525 return 说明说明 / şçöğıĤellö
1526
1527 actual = self.get_exception(f)
1528 expected = [
1529 f"Traceback (most recent call last):",
1530 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1531 f" callable()",
1532 f" ~~~~~~~~^^",
1533 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 3}, in f",
1534 f" return 说明说明 / şçöğıĤellö",
1535 f" ~~~~~~~~~^~~~~~~~~~~~",
1536 ]
1537 self.assertEqual(actual, expected)
1538
1539 def test_byte_offset_with_emojis_term_highlight(self):
1540 def f():
1541 return "✨🐍" + func_说明说明("📗🚛",
1542 "📗🚛") + "🐍"
1543
1544 actual = self.get_exception(f)
1545 expected = [
1546 f"Traceback (most recent call last):",
1547 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1548 f" callable()",
1549 f" ~~~~~~~~^^",
1550 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1551 f' return "✨🐍" + func_说明说明("📗🚛",',
1552 f" ^^^^^^^^^^^^^",
1553 ]
1554 self.assertEqual(actual, expected)
1555
1556 def test_byte_offset_wide_chars_subscript(self):
1557 def f():
1558 my_dct = {
1559 "✨🚛✨": {
1560 "说明": {
1561 "🐍🐍🐍": None
1562 }
1563 }
1564 }
1565 return my_dct["✨🚛✨"]["说明"]["🐍"]["说明"]["🐍🐍"]
1566
1567 actual = self.get_exception(f)
1568 expected = [
1569 f"Traceback (most recent call last):",
1570 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1571 f" callable()",
1572 f" ~~~~~~~~^^",
1573 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 8}, in f",
1574 f' return my_dct["✨🚛✨"]["说明"]["🐍"]["说明"]["🐍🐍"]',
1575 f" ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^",
1576 ]
1577 self.assertEqual(actual, expected)
1578
1579 def test_memory_error(self):
1580 def f():
1581 raise MemoryError()
1582
1583 actual = self.get_exception(f)
1584 expected = ['Traceback (most recent call last):',
1585 f' File "{__file__}", line {self.callable_line}, in get_exception',
1586 ' callable()',
1587 ' ~~~~~~~~^^',
1588 f' File "{__file__}", line {f.__code__.co_firstlineno + 1}, in f',
1589 ' raise MemoryError()']
1590 self.assertEqual(actual, expected)
1591
1592 def test_anchors_for_simple_return_statements_are_elided(self):
1593 def g():
1594 1/0
1595
1596 def f():
1597 return g()
1598
1599 result_lines = self.get_exception(f)
1600 expected = ['Traceback (most recent call last):',
1601 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1602 " callable()",
1603 " ~~~~~~~~^^",
1604 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1605 " return g()",
1606 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1607 " 1/0",
1608 " ~^~"
1609 ]
1610 self.assertEqual(result_lines, expected)
1611
1612 def g():
1613 1/0
1614
1615 def f():
1616 return g() + 1
1617
1618 result_lines = self.get_exception(f)
1619 expected = ['Traceback (most recent call last):',
1620 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1621 " callable()",
1622 " ~~~~~~~~^^",
1623 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1624 " return g() + 1",
1625 " ~^^",
1626 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1627 " 1/0",
1628 " ~^~"
1629 ]
1630 self.assertEqual(result_lines, expected)
1631
1632 def g(*args):
1633 1/0
1634
1635 def f():
1636 return g(1,
1637 2, 4,
1638 5)
1639
1640 result_lines = self.get_exception(f)
1641 expected = ['Traceback (most recent call last):',
1642 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1643 " callable()",
1644 " ~~~~~~~~^^",
1645 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1646 " return g(1,",
1647 " 2, 4,",
1648 " 5)",
1649 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1650 " 1/0",
1651 " ~^~"
1652 ]
1653 self.assertEqual(result_lines, expected)
1654
1655 def g(*args):
1656 1/0
1657
1658 def f():
1659 return g(1,
1660 2, 4,
1661 5) + 1
1662
1663 result_lines = self.get_exception(f)
1664 expected = ['Traceback (most recent call last):',
1665 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1666 " callable()",
1667 " ~~~~~~~~^^",
1668 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1669 " return g(1,",
1670 " ~^^^",
1671 " 2, 4,",
1672 " ^^^^^",
1673 " 5) + 1",
1674 " ^^",
1675 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1676 " 1/0",
1677 " ~^~"
1678 ]
1679 self.assertEqual(result_lines, expected)
1680
1681 def test_anchors_for_simple_assign_statements_are_elided(self):
1682 def g():
1683 1/0
1684
1685 def f():
1686 x = g()
1687
1688 result_lines = self.get_exception(f)
1689 expected = ['Traceback (most recent call last):',
1690 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1691 " callable()",
1692 " ~~~~~~~~^^",
1693 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1694 " x = g()",
1695 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1696 " 1/0",
1697 " ~^~"
1698 ]
1699 self.assertEqual(result_lines, expected)
1700
1701 def g(*args):
1702 1/0
1703
1704 def f():
1705 x = g(1,
1706 2, 3,
1707 4)
1708
1709 result_lines = self.get_exception(f)
1710 expected = ['Traceback (most recent call last):',
1711 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1712 " callable()",
1713 " ~~~~~~~~^^",
1714 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1715 " x = g(1,",
1716 " 2, 3,",
1717 " 4)",
1718 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1719 " 1/0",
1720 " ~^~"
1721 ]
1722 self.assertEqual(result_lines, expected)
1723
1724 def g():
1725 1/0
1726
1727 def f():
1728 x = y = g()
1729
1730 result_lines = self.get_exception(f)
1731 expected = ['Traceback (most recent call last):',
1732 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1733 " callable()",
1734 " ~~~~~~~~^^",
1735 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1736 " x = y = g()",
1737 " ~^^",
1738 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1739 " 1/0",
1740 " ~^~"
1741 ]
1742 self.assertEqual(result_lines, expected)
1743
1744 def g(*args):
1745 1/0
1746
1747 def f():
1748 x = y = g(1,
1749 2, 3,
1750 4)
1751
1752 result_lines = self.get_exception(f)
1753 expected = ['Traceback (most recent call last):',
1754 f" File \"{__file__}\", line {self.callable_line}, in get_exception",
1755 " callable()",
1756 " ~~~~~~~~^^",
1757 f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f",
1758 " x = y = g(1,",
1759 " ~^^^",
1760 " 2, 3,",
1761 " ^^^^^",
1762 " 4)",
1763 " ^^",
1764 f" File \"{__file__}\", line {g.__code__.co_firstlineno + 1}, in g",
1765 " 1/0",
1766 " ~^~"
1767 ]
1768 self.assertEqual(result_lines, expected)
1769
1770 class TestKeywordTypoSuggestions(unittest.TestCase):
1771 TYPO_CASES = [
1772 ("with block ad something:\n pass", "and"),
1773 ("fur a in b:\n pass", "for"),
1774 ("for a in b:\n pass\nelso:\n pass", "else"),
1775 ("whille True:\n pass", "while"),
1776 ("iff x > 5:\n pass", "if"),
1777 ("if x:\n pass\nelseif y:\n pass", "elif"),
1778 ("tyo:\n pass\nexcept y:\n pass", "try"),
1779 ("classe MyClass:\n pass", "class"),
1780 ("impor math", "import"),
1781 ("form x import y", "from"),
1782 ("defn calculate_sum(a, b):\n return a + b", "def"),
1783 ("def foo():\n returm result", "return"),
1784 ("lamda x: x ** 2", "lambda"),
1785 ("def foo():\n yeld i", "yield"),
1786 ("def foo():\n globel counter", "global"),
1787 ("frum math import sqrt", "from"),
1788 ("asynch def fetch_data():\n pass", "async"),
1789 ("async def foo():\n awaid fetch_data()", "await"),
1790 ('raisee ValueError("Error")', "raise"),
1791 ("[x for x\nin range(3)\nof x]", "if"),
1792 ("[123 fur x\nin range(3)\nif x]", "for"),
1793 ("for x im n:\n pass", "in"),
1794 ]
1795
1796 def test_keyword_suggestions_from_file(self):
1797 with tempfile.TemporaryDirectory() as script_dir:
1798 for i, (code, expected_kw) in enumerate(self.TYPO_CASES):
1799 with self.subTest(typo=expected_kw):
1800 source = textwrap.dedent(code).strip()
1801 script_name = make_script(script_dir, f"script_{i}", source)
1802 rc, stdout, stderr = assert_python_failure(script_name)
1803 stderr_text = stderr.decode('utf-8')
1804 self.assertIn(f"Did you mean '{expected_kw}'", stderr_text)
1805
1806 def test_keyword_suggestions_from_command_string(self):
1807 for code, expected_kw in self.TYPO_CASES:
1808 with self.subTest(typo=expected_kw):
1809 source = textwrap.dedent(code).strip()
1810 rc, stdout, stderr = assert_python_failure('-c', source)
1811 stderr_text = stderr.decode('utf-8')
1812 self.assertIn(f"Did you mean '{expected_kw}'", stderr_text)
1813
1814 @requires_debug_ranges()
1815 @force_not_colorized_test_class
1816 class PurePythonTracebackErrorCaretTests(
1817 PurePythonExceptionFormattingMixin,
1818 TracebackErrorLocationCaretTestBase,
1819 unittest.TestCase,
1820 ):
1821 """
1822 Same set of tests as above using the pure Python implementation of
1823 traceback printing in traceback.py.
1824 """
1825
1826
1827 @cpython_only
1828 @requires_debug_ranges()
1829 @force_not_colorized_test_class
1830 class CPythonTracebackErrorCaretTests(
1831 CAPIExceptionFormattingMixin,
1832 TracebackErrorLocationCaretTestBase,
1833 unittest.TestCase,
1834 ):
1835 """
1836 Same set of tests as above but with Python's internal traceback printing.
1837 """
1838
1839 @cpython_only
1840 @requires_debug_ranges()
1841 @force_not_colorized_test_class
1842 class CPythonTracebackLegacyErrorCaretTests(
1843 CAPIExceptionFormattingLegacyMixin,
1844 TracebackErrorLocationCaretTestBase,
1845 unittest.TestCase,
1846 ):
1847 """
1848 Same set of tests as above but with Python's legacy internal traceback printing.
1849 """
1850
1851
1852 class TracebackFormatMixin:
1853 DEBUG_RANGES = True
1854
1855 def some_exception(self):
1856 raise KeyError('blah')
1857
1858 def _filter_debug_ranges(self, expected):
1859 return [line for line in expected if not set(line.strip()) <= set("^~")]
1860
1861 def _maybe_filter_debug_ranges(self, expected):
1862 if not self.DEBUG_RANGES:
1863 return self._filter_debug_ranges(expected)
1864 return expected
1865
1866 @cpython_only
1867 def check_traceback_format(self, cleanup_func=None):
1868 from _testcapi import traceback_print
1869 try:
1870 self.some_exception()
1871 except KeyError as e:
1872 tb = e.__traceback__
1873 if cleanup_func is not None:
1874 # Clear the inner frames, not this one
1875 cleanup_func(tb.tb_next)
1876 traceback_fmt = 'Traceback (most recent call last):\n' + \
1877 ''.join(traceback.format_tb(tb))
1878 # clear caret lines from traceback_fmt since internal API does
1879 # not emit them
1880 traceback_fmt = "\n".join(
1881 self._filter_debug_ranges(traceback_fmt.splitlines())
1882 ) + "\n"
1883 file_ = StringIO()
1884 traceback_print(tb, file_)
1885 python_fmt = file_.getvalue()
1886 # Call all _tb and _exc functions
1887 with captured_output("stderr") as tbstderr:
1888 traceback.print_tb(tb)
1889 tbfile = StringIO()
1890 traceback.print_tb(tb, file=tbfile)
1891 with captured_output("stderr") as excstderr:
1892 traceback.print_exc()
1893 excfmt = traceback.format_exc()
1894 excfile = StringIO()
1895 traceback.print_exc(file=excfile)
1896 else:
1897 raise Error("unable to create test traceback string")
1898
1899 # Make sure that Python and the traceback module format the same thing
1900 self.assertEqual(traceback_fmt, python_fmt)
1901 # Now verify the _tb func output
1902 self.assertEqual(tbstderr.getvalue(), tbfile.getvalue())
1903 # Now verify the _exc func output
1904 self.assertEqual(excstderr.getvalue(), excfile.getvalue())
1905 self.assertEqual(excfmt, excfile.getvalue())
1906
1907 # Make sure that the traceback is properly indented.
1908 tb_lines = python_fmt.splitlines()
1909 banner = tb_lines[0]
1910 self.assertEqual(len(tb_lines), 5)
1911 location, source_line = tb_lines[-2], tb_lines[-1]
1912 self.assertStartsWith(banner, 'Traceback')
1913 self.assertStartsWith(location, ' File')
1914 self.assertStartsWith(source_line, ' raise')
1915
1916 def test_traceback_format(self):
1917 self.check_traceback_format()
1918
1919 def test_traceback_format_with_cleared_frames(self):
1920 # Check that traceback formatting also works with a clear()ed frame
1921 def cleanup_tb(tb):
1922 tb.tb_frame.clear()
1923 self.check_traceback_format(cleanup_tb)
1924
1925 def test_stack_format(self):
1926 # Verify _stack functions. Note we have to use _getframe(1) to
1927 # compare them without this frame appearing in the output
1928 with captured_output("stderr") as ststderr:
1929 traceback.print_stack(sys._getframe(1))
1930 stfile = StringIO()
1931 traceback.print_stack(sys._getframe(1), file=stfile)
1932 self.assertEqual(ststderr.getvalue(), stfile.getvalue())
1933
1934 stfmt = traceback.format_stack(sys._getframe(1))
1935
1936 self.assertEqual(ststderr.getvalue(), "".join(stfmt))
1937
1938 def test_print_stack(self):
1939 def prn():
1940 traceback.print_stack()
1941 with captured_output("stderr") as stderr:
1942 prn()
1943 lineno = prn.__code__.co_firstlineno
1944 self.assertEqual(stderr.getvalue().splitlines()[-4:], [
1945 ' File "%s", line %d, in test_print_stack' % (__file__, lineno+3),
1946 ' prn()',
1947 ' File "%s", line %d, in prn' % (__file__, lineno+1),
1948 ' traceback.print_stack()',
1949 ])
1950
1951 # issue 26823 - Shrink recursive tracebacks
1952 def _check_recursive_traceback_display(self, render_exc):
1953 # Always show full diffs when this test fails
1954 # Note that rearranging things may require adjusting
1955 # the relative line numbers in the expected tracebacks
1956 self.maxDiff = None
1957
1958 # Check hitting the recursion limit
1959 def f():
1960 f()
1961
1962 with captured_output("stderr") as stderr_f:
1963 try:
1964 f()
1965 except RecursionError:
1966 render_exc()
1967 else:
1968 self.fail("no recursion occurred")
1969
1970 lineno_f = f.__code__.co_firstlineno
1971 result_f = (
1972 'Traceback (most recent call last):\n'
1973 f' File "{__file__}", line {lineno_f+5}, in _check_recursive_traceback_display\n'
1974 ' f()\n'
1975 ' ~^^\n'
1976 f' File "{__file__}", line {lineno_f+1}, in f\n'
1977 ' f()\n'
1978 ' ~^^\n'
1979 f' File "{__file__}", line {lineno_f+1}, in f\n'
1980 ' f()\n'
1981 ' ~^^\n'
1982 f' File "{__file__}", line {lineno_f+1}, in f\n'
1983 ' f()\n'
1984 ' ~^^\n'
1985 # XXX: The following line changes depending on whether the tests
1986 # are run through the interactive interpreter or with -m
1987 # It also varies depending on the platform (stack size)
1988 # Fortunately, we don't care about exactness here, so we use regex
1989 r' \[Previous line repeated (\d+) more times\]' '\n'
1990 'RecursionError: maximum recursion depth exceeded\n'
1991 )
1992
1993 expected = self._maybe_filter_debug_ranges(result_f.splitlines())
1994 actual = stderr_f.getvalue().splitlines()
1995
1996 # Check the output text matches expectations
1997 # 2nd last line contains the repetition count
1998 self.assertEqual(actual[:-2], expected[:-2])
1999 self.assertRegex(actual[-2], expected[-2])
2000 # last line can have additional text appended
2001 self.assertIn(expected[-1], actual[-1])
2002
2003 # Check the recursion count is roughly as expected
2004 rec_limit = sys.getrecursionlimit()
2005 self.assertIn(int(re.search(r"\d+", actual[-2]).group()), range(rec_limit-60, rec_limit))
2006
2007 # Check a known (limited) number of recursive invocations
2008 def g(count=10):
2009 if count:
2010 return g(count-1) + 1
2011 raise ValueError
2012
2013 with captured_output("stderr") as stderr_g:
2014 try:
2015 g()
2016 except ValueError:
2017 render_exc()
2018 else:
2019 self.fail("no value error was raised")
2020
2021 lineno_g = g.__code__.co_firstlineno
2022 result_g = (
2023 f' File "{__file__}", line {lineno_g+2}, in g\n'
2024 ' return g(count-1) + 1\n'
2025 ' ~^^^^^^^^^\n'
2026 f' File "{__file__}", line {lineno_g+2}, in g\n'
2027 ' return g(count-1) + 1\n'
2028 ' ~^^^^^^^^^\n'
2029 f' File "{__file__}", line {lineno_g+2}, in g\n'
2030 ' return g(count-1) + 1\n'
2031 ' ~^^^^^^^^^\n'
2032 ' [Previous line repeated 7 more times]\n'
2033 f' File "{__file__}", line {lineno_g+3}, in g\n'
2034 ' raise ValueError\n'
2035 'ValueError\n'
2036 )
2037 tb_line = (
2038 'Traceback (most recent call last):\n'
2039 f' File "{__file__}", line {lineno_g+7}, in _check_recursive_traceback_display\n'
2040 ' g()\n'
2041 ' ~^^\n'
2042 )
2043 expected = self._maybe_filter_debug_ranges((tb_line + result_g).splitlines())
2044 actual = stderr_g.getvalue().splitlines()
2045 self.assertEqual(actual, expected)
2046
2047 # Check 2 different repetitive sections
2048 def h(count=10):
2049 if count:
2050 return h(count-1)
2051 g()
2052
2053 with captured_output("stderr") as stderr_h:
2054 try:
2055 h()
2056 except ValueError:
2057 render_exc()
2058 else:
2059 self.fail("no value error was raised")
2060
2061 lineno_h = h.__code__.co_firstlineno
2062 result_h = (
2063 'Traceback (most recent call last):\n'
2064 f' File "{__file__}", line {lineno_h+7}, in _check_recursive_traceback_display\n'
2065 ' h()\n'
2066 ' ~^^\n'
2067 f' File "{__file__}", line {lineno_h+2}, in h\n'
2068 ' return h(count-1)\n'
2069 f' File "{__file__}", line {lineno_h+2}, in h\n'
2070 ' return h(count-1)\n'
2071 f' File "{__file__}", line {lineno_h+2}, in h\n'
2072 ' return h(count-1)\n'
2073 ' [Previous line repeated 7 more times]\n'
2074 f' File "{__file__}", line {lineno_h+3}, in h\n'
2075 ' g()\n'
2076 ' ~^^\n'
2077 )
2078 expected = self._maybe_filter_debug_ranges((result_h + result_g).splitlines())
2079 actual = stderr_h.getvalue().splitlines()
2080 self.assertEqual(actual, expected)
2081
2082 # Check the boundary conditions. First, test just below the cutoff.
2083 with captured_output("stderr") as stderr_g:
2084 try:
2085 g(traceback._RECURSIVE_CUTOFF)
2086 except ValueError:
2087 render_exc()
2088 else:
2089 self.fail("no error raised")
2090 result_g = (
2091 f' File "{__file__}", line {lineno_g+2}, in g\n'
2092 ' return g(count-1) + 1\n'
2093 ' ~^^^^^^^^^\n'
2094 f' File "{__file__}", line {lineno_g+2}, in g\n'
2095 ' return g(count-1) + 1\n'
2096 ' ~^^^^^^^^^\n'
2097 f' File "{__file__}", line {lineno_g+2}, in g\n'
2098 ' return g(count-1) + 1\n'
2099 ' ~^^^^^^^^^\n'
2100 f' File "{__file__}", line {lineno_g+3}, in g\n'
2101 ' raise ValueError\n'
2102 'ValueError\n'
2103 )
2104 tb_line = (
2105 'Traceback (most recent call last):\n'
2106 f' File "{__file__}", line {lineno_g+77}, in _check_recursive_traceback_display\n'
2107 ' g(traceback._RECURSIVE_CUTOFF)\n'
2108 ' ~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
2109 )
2110 expected = self._maybe_filter_debug_ranges((tb_line + result_g).splitlines())
2111 actual = stderr_g.getvalue().splitlines()
2112 self.assertEqual(actual, expected)
2113
2114 # Second, test just above the cutoff.
2115 with captured_output("stderr") as stderr_g:
2116 try:
2117 g(traceback._RECURSIVE_CUTOFF + 1)
2118 except ValueError:
2119 render_exc()
2120 else:
2121 self.fail("no error raised")
2122 result_g = (
2123 f' File "{__file__}", line {lineno_g+2}, in g\n'
2124 ' return g(count-1) + 1\n'
2125 ' ~^^^^^^^^^\n'
2126 f' File "{__file__}", line {lineno_g+2}, in g\n'
2127 ' return g(count-1) + 1\n'
2128 ' ~^^^^^^^^^\n'
2129 f' File "{__file__}", line {lineno_g+2}, in g\n'
2130 ' return g(count-1) + 1\n'
2131 ' ~^^^^^^^^^\n'
2132 ' [Previous line repeated 1 more time]\n'
2133 f' File "{__file__}", line {lineno_g+3}, in g\n'
2134 ' raise ValueError\n'
2135 'ValueError\n'
2136 )
2137 tb_line = (
2138 'Traceback (most recent call last):\n'
2139 f' File "{__file__}", line {lineno_g+109}, in _check_recursive_traceback_display\n'
2140 ' g(traceback._RECURSIVE_CUTOFF + 1)\n'
2141 ' ~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n'
2142 )
2143 expected = self._maybe_filter_debug_ranges((tb_line + result_g).splitlines())
2144 actual = stderr_g.getvalue().splitlines()
2145 self.assertEqual(actual, expected)
2146
2147 @requires_debug_ranges()
2148 def test_recursive_traceback(self):
2149 if self.DEBUG_RANGES:
2150 self._check_recursive_traceback_display(traceback.print_exc)
2151 else:
2152 from _testcapi import exception_print
2153 def render_exc():
2154 exception_print(sys.exception())
2155 self._check_recursive_traceback_display(render_exc)
2156
2157 def test_format_stack(self):
2158 def fmt():
2159 return traceback.format_stack()
2160 result = fmt()
2161 lineno = fmt.__code__.co_firstlineno
2162 self.assertEqual(result[-2:], [
2163 ' File "%s", line %d, in test_format_stack\n'
2164 ' result = fmt()\n' % (__file__, lineno+2),
2165 ' File "%s", line %d, in fmt\n'
2166 ' return traceback.format_stack()\n' % (__file__, lineno+1),
2167 ])
2168
2169 @cpython_only
2170 def test_unhashable(self):
2171 from _testcapi import exception_print
2172
2173 class UnhashableException(Exception):
2174 def __eq__(self, other):
2175 return True
2176
2177 ex1 = UnhashableException('ex1')
2178 ex2 = UnhashableException('ex2')
2179 try:
2180 raise ex2 from ex1
2181 except UnhashableException:
2182 try:
2183 raise ex1
2184 except UnhashableException as e:
2185 exc_val = e
2186
2187 with captured_output("stderr") as stderr_f:
2188 exception_print(exc_val)
2189
2190 tb = stderr_f.getvalue().strip().splitlines()
2191 self.assertEqual(11, len(tb))
2192 self.assertEqual(context_message.strip(), tb[5])
2193 self.assertIn('UnhashableException: ex2', tb[3])
2194 self.assertIn('UnhashableException: ex1', tb[10])
2195
2196 def deep_eg(self):
2197 e = TypeError(1)
2198 for i in range(2000):
2199 e = ExceptionGroup('eg', [e])
2200 return e
2201
2202 @cpython_only
2203 @support.skip_emscripten_stack_overflow()
2204 def test_exception_group_deep_recursion_capi(self):
2205 from _testcapi import exception_print
2206 LIMIT = 75
2207 eg = self.deep_eg()
2208 with captured_output("stderr") as stderr_f:
2209 with support.infinite_recursion(max_depth=LIMIT):
2210 exception_print(eg)
2211 output = stderr_f.getvalue()
2212 self.assertIn('ExceptionGroup', output)
2213 self.assertLessEqual(output.count('ExceptionGroup'), LIMIT)
2214
2215 @support.skip_emscripten_stack_overflow()
2216 def test_exception_group_deep_recursion_traceback(self):
2217 LIMIT = 75
2218 eg = self.deep_eg()
2219 with captured_output("stderr") as stderr_f:
2220 with support.infinite_recursion(max_depth=LIMIT):
2221 traceback.print_exception(type(eg), eg, eg.__traceback__)
2222 output = stderr_f.getvalue()
2223 self.assertIn('ExceptionGroup', output)
2224 self.assertLessEqual(output.count('ExceptionGroup'), LIMIT)
2225
2226 @cpython_only
2227 def test_print_exception_bad_type_capi(self):
2228 from _testcapi import exception_print
2229 with captured_output("stderr") as stderr:
2230 with support.catch_unraisable_exception():
2231 exception_print(42)
2232 self.assertEqual(
2233 stderr.getvalue(),
2234 ('TypeError: print_exception(): '
2235 'Exception expected for value, int found\n')
2236 )
2237
2238 def test_print_exception_bad_type_python(self):
2239 msg = "Exception expected for value, int found"
2240 with self.assertRaisesRegex(TypeError, msg):
2241 traceback.print_exception(42)
2242
2243
2244 cause_message = (
2245 "\nThe above exception was the direct cause "
2246 "of the following exception:\n\n")
2247
2248 context_message = (
2249 "\nDuring handling of the above exception, "
2250 "another exception occurred:\n\n")
2251
2252 boundaries = re.compile(
2253 '(%s|%s)' % (re.escape(cause_message), re.escape(context_message)))
2254
2255 @force_not_colorized_test_class
2256 class TestTracebackFormat(unittest.TestCase, TracebackFormatMixin):
2257 pass
2258
2259 @cpython_only
2260 @force_not_colorized_test_class
2261 class TestFallbackTracebackFormat(unittest.TestCase, TracebackFormatMixin):
2262 DEBUG_RANGES = False
2263 def setUp(self) -> None:
2264 self.original_unraisable_hook = sys.unraisablehook
2265 sys.unraisablehook = lambda *args: None
2266 self.original_hook = traceback._print_exception_bltin
2267 traceback._print_exception_bltin = lambda *args: 1/0
2268 return super().setUp()
2269
2270 def tearDown(self) -> None:
2271 traceback._print_exception_bltin = self.original_hook
2272 sys.unraisablehook = self.original_unraisable_hook
2273 return super().tearDown()
2274
2275 class BaseExceptionReportingTests:
2276
2277 def get_exception(self, exception_or_callable):
2278 if isinstance(exception_or_callable, BaseException):
2279 return exception_or_callable
2280 try:
2281 exception_or_callable()
2282 except Exception as e:
2283 return e
2284
2285 callable_line = get_exception.__code__.co_firstlineno + 4
2286
2287 def zero_div(self):
2288 1/0 # In zero_div
2289
2290 def check_zero_div(self, msg):
2291 lines = msg.splitlines()
2292 if has_no_debug_ranges():
2293 self.assertStartsWith(lines[-3], ' File')
2294 self.assertIn('1/0 # In zero_div', lines[-2])
2295 else:
2296 self.assertStartsWith(lines[-4], ' File')
2297 self.assertIn('1/0 # In zero_div', lines[-3])
2298 self.assertStartsWith(lines[-1], 'ZeroDivisionError')
2299
2300 def test_simple(self):
2301 try:
2302 1/0 # Marker
2303 except ZeroDivisionError as _:
2304 e = _
2305 lines = self.get_report(e).splitlines()
2306 if has_no_debug_ranges():
2307 self.assertEqual(len(lines), 4)
2308 self.assertStartsWith(lines[3], 'ZeroDivisionError')
2309 else:
2310 self.assertEqual(len(lines), 5)
2311 self.assertStartsWith(lines[4], 'ZeroDivisionError')
2312 self.assertStartsWith(lines[0], 'Traceback')
2313 self.assertStartsWith(lines[1], ' File')
2314 self.assertIn('1/0 # Marker', lines[2])
2315
2316 def test_cause(self):
2317 def inner_raise():
2318 try:
2319 self.zero_div()
2320 except ZeroDivisionError as e:
2321 raise KeyError from e
2322 def outer_raise():
2323 inner_raise() # Marker
2324 blocks = boundaries.split(self.get_report(outer_raise))
2325 self.assertEqual(len(blocks), 3)
2326 self.assertEqual(blocks[1], cause_message)
2327 self.check_zero_div(blocks[0])
2328 self.assertIn('inner_raise() # Marker', blocks[2])
2329
2330 def test_context(self):
2331 def inner_raise():
2332 try:
2333 self.zero_div()
2334 except ZeroDivisionError:
2335 raise KeyError
2336 def outer_raise():
2337 inner_raise() # Marker
2338 blocks = boundaries.split(self.get_report(outer_raise))
2339 self.assertEqual(len(blocks), 3)
2340 self.assertEqual(blocks[1], context_message)
2341 self.check_zero_div(blocks[0])
2342 self.assertIn('inner_raise() # Marker', blocks[2])
2343
2344 def test_context_suppression(self):
2345 try:
2346 try:
2347 raise Exception
2348 except Exception:
2349 raise ZeroDivisionError from None
2350 except ZeroDivisionError as _:
2351 e = _
2352 lines = self.get_report(e).splitlines()
2353 self.assertEqual(len(lines), 4)
2354 self.assertStartsWith(lines[3], 'ZeroDivisionError')
2355 self.assertStartsWith(lines[0], 'Traceback')
2356 self.assertStartsWith(lines[1], ' File')
2357 self.assertIn('ZeroDivisionError from None', lines[2])
2358
2359 def test_cause_and_context(self):
2360 # When both a cause and a context are set, only the cause should be
2361 # displayed and the context should be muted.
2362 def inner_raise():
2363 try:
2364 self.zero_div()
2365 except ZeroDivisionError as _e:
2366 e = _e
2367 try:
2368 xyzzy
2369 except NameError:
2370 raise KeyError from e
2371 def outer_raise():
2372 inner_raise() # Marker
2373 blocks = boundaries.split(self.get_report(outer_raise))
2374 self.assertEqual(len(blocks), 3)
2375 self.assertEqual(blocks[1], cause_message)
2376 self.check_zero_div(blocks[0])
2377 self.assertIn('inner_raise() # Marker', blocks[2])
2378
2379 def test_cause_recursive(self):
2380 def inner_raise():
2381 try:
2382 try:
2383 self.zero_div()
2384 except ZeroDivisionError as e:
2385 z = e
2386 raise KeyError from e
2387 except KeyError as e:
2388 raise z from e
2389 def outer_raise():
2390 inner_raise() # Marker
2391 blocks = boundaries.split(self.get_report(outer_raise))
2392 self.assertEqual(len(blocks), 3)
2393 self.assertEqual(blocks[1], cause_message)
2394 # The first block is the KeyError raised from the ZeroDivisionError
2395 self.assertIn('raise KeyError from e', blocks[0])
2396 self.assertNotIn('1/0', blocks[0])
2397 # The second block (apart from the boundary) is the ZeroDivisionError
2398 # re-raised from the KeyError
2399 self.assertIn('inner_raise() # Marker', blocks[2])
2400 self.check_zero_div(blocks[2])
2401
2402 def test_syntax_error_offset_at_eol(self):
2403 # See #10186.
2404 def e():
2405 raise SyntaxError('', ('', 0, 5, 'hello'))
2406 msg = self.get_report(e).splitlines()
2407 self.assertEqual(msg[-2], " ^")
2408 def e():
2409 exec("x = 5 | 4 |")
2410 msg = self.get_report(e).splitlines()
2411 self.assertEqual(msg[-2], ' ^')
2412
2413 def test_syntax_error_no_lineno(self):
2414 # See #34463.
2415
2416 # Without filename
2417 e = SyntaxError('bad syntax')
2418 msg = self.get_report(e).splitlines()
2419 self.assertEqual(msg,
2420 ['SyntaxError: bad syntax'])
2421 e.lineno = 100
2422 msg = self.get_report(e).splitlines()
2423 self.assertEqual(msg,
2424 [' File "<string>", line 100', 'SyntaxError: bad syntax'])
2425
2426 # With filename
2427 e = SyntaxError('bad syntax')
2428 e.filename = 'myfile.py'
2429
2430 msg = self.get_report(e).splitlines()
2431 self.assertEqual(msg,
2432 ['SyntaxError: bad syntax (myfile.py)'])
2433 e.lineno = 100
2434 msg = self.get_report(e).splitlines()
2435 self.assertEqual(msg,
2436 [' File "myfile.py", line 100', 'SyntaxError: bad syntax'])
2437
2438 def test_message_none(self):
2439 # A message that looks like "None" should not be treated specially
2440 err = self.get_report(Exception(None))
2441 self.assertIn('Exception: None\n', err)
2442 err = self.get_report(Exception('None'))
2443 self.assertIn('Exception: None\n', err)
2444 err = self.get_report(Exception())
2445 self.assertIn('Exception\n', err)
2446 err = self.get_report(Exception(''))
2447 self.assertIn('Exception\n', err)
2448
2449 def test_syntax_error_various_offsets(self):
2450 for offset in range(-5, 10):
2451 for add in [0, 2]:
2452 text = " " * add + "text%d" % offset
2453 expected = [' File "file.py", line 1']
2454 if offset < 1:
2455 expected.append(" %s" % text.lstrip())
2456 elif offset <= 6:
2457 expected.append(" %s" % text.lstrip())
2458 # Set the caret length to match the length of the text minus the offset.
2459 caret_length = max(1, len(text.lstrip()) - offset + 1)
2460 expected.append(" %s%s" % (" " * (offset - 1), "^" * caret_length))
2461 else:
2462 caret_length = max(1, len(text.lstrip()) - 4)
2463 expected.append(" %s" % text.lstrip())
2464 expected.append(" %s%s" % (" " * 5, "^" * caret_length))
2465 expected.append("SyntaxError: msg")
2466 expected.append("")
2467 err = self.get_report(SyntaxError("msg", ("file.py", 1, offset + add, text)))
2468 exp = "\n".join(expected)
2469 self.assertEqual(exp, err)
2470
2471 def test_exception_with_note(self):
2472 e = ValueError(123)
2473 vanilla = self.get_report(e)
2474
2475 e.add_note('My Note')
2476 self.assertEqual(self.get_report(e), vanilla + 'My Note\n')
2477
2478 del e.__notes__
2479 e.add_note('')
2480 self.assertEqual(self.get_report(e), vanilla + '\n')
2481
2482 del e.__notes__
2483 e.add_note('Your Note')
2484 self.assertEqual(self.get_report(e), vanilla + 'Your Note\n')
2485
2486 del e.__notes__
2487 self.assertEqual(self.get_report(e), vanilla)
2488
2489 def test_exception_with_invalid_notes(self):
2490 e = ValueError(123)
2491 vanilla = self.get_report(e)
2492
2493 # non-sequence __notes__
2494 class BadThing:
2495 def __str__(self):
2496 return 'bad str'
2497
2498 def __repr__(self):
2499 return 'bad repr'
2500
2501 # unprintable, non-sequence __notes__
2502 class Unprintable:
2503 def __repr__(self):
2504 raise ValueError('bad value')
2505
2506 e.__notes__ = BadThing()
2507 notes_repr = 'bad repr'
2508 self.assertEqual(self.get_report(e), vanilla + notes_repr + '\n')
2509
2510 e.__notes__ = Unprintable()
2511 err_msg = '<__notes__ repr() failed>'
2512 self.assertEqual(self.get_report(e), vanilla + err_msg + '\n')
2513
2514 # non-string item in the __notes__ sequence
2515 e.__notes__ = [BadThing(), 'Final Note']
2516 bad_note = 'bad str'
2517 self.assertEqual(self.get_report(e), vanilla + bad_note + '\nFinal Note\n')
2518
2519 # unprintable, non-string item in the __notes__ sequence
2520 e.__notes__ = [Unprintable(), 'Final Note']
2521 err_msg = '<note str() failed>'
2522 self.assertEqual(self.get_report(e), vanilla + err_msg + '\nFinal Note\n')
2523
2524 e.__notes__ = "please do not explode me"
2525 err_msg = "'please do not explode me'"
2526 self.assertEqual(self.get_report(e), vanilla + err_msg + '\n')
2527
2528 e.__notes__ = b"please do not show me as numbers"
2529 err_msg = "b'please do not show me as numbers'"
2530 self.assertEqual(self.get_report(e), vanilla + err_msg + '\n')
2531
2532 # an exception with a broken __getattr__ raising a non expected error
2533 class BrokenException(Exception):
2534 broken = False
2535 def __getattr__(self, name):
2536 if self.broken:
2537 raise ValueError(f'no {name}')
2538
2539 e = BrokenException(123)
2540 vanilla = self.get_report(e)
2541 e.broken = True
2542 self.assertEqual(
2543 self.get_report(e),
2544 vanilla + "Ignored error getting __notes__: ValueError('no __notes__')\n")
2545
2546 def test_exception_with_multiple_notes(self):
2547 for e in [ValueError(42), SyntaxError('bad syntax')]:
2548 with self.subTest(e=e):
2549 vanilla = self.get_report(e)
2550
2551 e.add_note('Note 1')
2552 e.add_note('Note 2')
2553 e.add_note('Note 3')
2554
2555 self.assertEqual(
2556 self.get_report(e),
2557 vanilla + 'Note 1\n' + 'Note 2\n' + 'Note 3\n')
2558
2559 del e.__notes__
2560 e.add_note('Note 4')
2561 del e.__notes__
2562 e.add_note('Note 5')
2563 e.add_note('Note 6')
2564
2565 self.assertEqual(
2566 self.get_report(e),
2567 vanilla + 'Note 5\n' + 'Note 6\n')
2568
2569 def test_exception_qualname(self):
2570 class A:
2571 class B:
2572 class X(Exception):
2573 def __str__(self):
2574 return "I am X"
2575
2576 err = self.get_report(A.B.X())
2577 str_value = 'I am X'
2578 str_name = '.'.join([A.B.X.__module__, A.B.X.__qualname__])
2579 exp = "%s: %s\n" % (str_name, str_value)
2580 self.assertEqual(exp, MODULE_PREFIX + err)
2581
2582 def test_exception_modulename(self):
2583 class X(Exception):
2584 def __str__(self):
2585 return "I am X"
2586
2587 for modulename in '__main__', 'builtins', 'some_module':
2588 X.__module__ = modulename
2589 with self.subTest(modulename=modulename):
2590 err = self.get_report(X())
2591 str_value = 'I am X'
2592 if modulename in ['builtins', '__main__']:
2593 str_name = X.__qualname__
2594 else:
2595 str_name = '.'.join([X.__module__, X.__qualname__])
2596 exp = "%s: %s\n" % (str_name, str_value)
2597 self.assertEqual(exp, err)
2598
2599 def test_exception_angle_bracketed_filename(self):
2600 src = textwrap.dedent("""
2601 try:
2602 raise ValueError(42)
2603 except Exception as e:
2604 exc = e
2605 """)
2606
2607 code = compile(src, "<does not exist>", "exec")
2608 g, l = {}, {}
2609 exec(code, g, l)
2610 err = self.get_report(l['exc'])
2611 exp = ' File "<does not exist>", line 3, in <module>\nValueError: 42\n'
2612 self.assertIn(exp, err)
2613
2614 def test_exception_modulename_not_unicode(self):
2615 class X(Exception):
2616 def __str__(self):
2617 return "I am X"
2618
2619 X.__module__ = 42
2620
2621 err = self.get_report(X())
2622 exp = f'<unknown>.{X.__qualname__}: I am X\n'
2623 self.assertEqual(exp, err)
2624
2625 def test_exception_bad__str__(self):
2626 class X(Exception):
2627 def __str__(self):
2628 1/0
2629 err = self.get_report(X())
2630 str_value = '<exception str() failed>'
2631 str_name = '.'.join([X.__module__, X.__qualname__])
2632 self.assertEqual(MODULE_PREFIX + err, f"{str_name}: {str_value}\n")
2633
2634
2635 # #### Exception Groups ####
2636
2637 def test_exception_group_basic(self):
2638 def exc():
2639 raise ExceptionGroup("eg", [ValueError(1), TypeError(2)])
2640
2641 expected = (
2642 f' + Exception Group Traceback (most recent call last):\n'
2643 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
2644 f' | exception_or_callable()\n'
2645 f' | ~~~~~~~~~~~~~~~~~~~~~^^\n'
2646 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 1}, in exc\n'
2647 f' | raise ExceptionGroup("eg", [ValueError(1), TypeError(2)])\n'
2648 f' | ExceptionGroup: eg (2 sub-exceptions)\n'
2649 f' +-+---------------- 1 ----------------\n'
2650 f' | ValueError: 1\n'
2651 f' +---------------- 2 ----------------\n'
2652 f' | TypeError: 2\n'
2653 f' +------------------------------------\n')
2654
2655 report = self.get_report(exc)
2656 self.assertEqual(report, expected)
2657
2658 def test_exception_group_cause(self):
2659 def exc():
2660 EG = ExceptionGroup
2661 try:
2662 raise EG("eg1", [ValueError(1), TypeError(2)])
2663 except Exception as e:
2664 raise EG("eg2", [ValueError(3), TypeError(4)]) from e
2665
2666 expected = (f' + Exception Group Traceback (most recent call last):\n'
2667 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 3}, in exc\n'
2668 f' | raise EG("eg1", [ValueError(1), TypeError(2)])\n'
2669 f' | ExceptionGroup: eg1 (2 sub-exceptions)\n'
2670 f' +-+---------------- 1 ----------------\n'
2671 f' | ValueError: 1\n'
2672 f' +---------------- 2 ----------------\n'
2673 f' | TypeError: 2\n'
2674 f' +------------------------------------\n'
2675 f'\n'
2676 f'The above exception was the direct cause of the following exception:\n'
2677 f'\n'
2678 f' + Exception Group Traceback (most recent call last):\n'
2679 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
2680 f' | exception_or_callable()\n'
2681 f' | ~~~~~~~~~~~~~~~~~~~~~^^\n'
2682 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n'
2683 f' | raise EG("eg2", [ValueError(3), TypeError(4)]) from e\n'
2684 f' | ExceptionGroup: eg2 (2 sub-exceptions)\n'
2685 f' +-+---------------- 1 ----------------\n'
2686 f' | ValueError: 3\n'
2687 f' +---------------- 2 ----------------\n'
2688 f' | TypeError: 4\n'
2689 f' +------------------------------------\n')
2690
2691 report = self.get_report(exc)
2692 self.assertEqual(report, expected)
2693
2694 def test_exception_group_context_with_context(self):
2695 def exc():
2696 EG = ExceptionGroup
2697 try:
2698 try:
2699 raise EG("eg1", [ValueError(1), TypeError(2)])
2700 except EG:
2701 raise EG("eg2", [ValueError(3), TypeError(4)])
2702 except EG:
2703 raise ImportError(5)
2704
2705 expected = (
2706 f' + Exception Group Traceback (most recent call last):\n'
2707 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 4}, in exc\n'
2708 f' | raise EG("eg1", [ValueError(1), TypeError(2)])\n'
2709 f' | ExceptionGroup: eg1 (2 sub-exceptions)\n'
2710 f' +-+---------------- 1 ----------------\n'
2711 f' | ValueError: 1\n'
2712 f' +---------------- 2 ----------------\n'
2713 f' | TypeError: 2\n'
2714 f' +------------------------------------\n'
2715 f'\n'
2716 f'During handling of the above exception, another exception occurred:\n'
2717 f'\n'
2718 f' + Exception Group Traceback (most recent call last):\n'
2719 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 6}, in exc\n'
2720 f' | raise EG("eg2", [ValueError(3), TypeError(4)])\n'
2721 f' | ExceptionGroup: eg2 (2 sub-exceptions)\n'
2722 f' +-+---------------- 1 ----------------\n'
2723 f' | ValueError: 3\n'
2724 f' +---------------- 2 ----------------\n'
2725 f' | TypeError: 4\n'
2726 f' +------------------------------------\n'
2727 f'\n'
2728 f'During handling of the above exception, another exception occurred:\n'
2729 f'\n'
2730 f'Traceback (most recent call last):\n'
2731 f' File "{__file__}", line {self.callable_line}, in get_exception\n'
2732 f' exception_or_callable()\n'
2733 f' ~~~~~~~~~~~~~~~~~~~~~^^\n'
2734 f' File "{__file__}", line {exc.__code__.co_firstlineno + 8}, in exc\n'
2735 f' raise ImportError(5)\n'
2736 f'ImportError: 5\n')
2737
2738 report = self.get_report(exc)
2739 self.assertEqual(report, expected)
2740
2741 def test_exception_group_nested(self):
2742 def exc():
2743 EG = ExceptionGroup
2744 VE = ValueError
2745 TE = TypeError
2746 try:
2747 try:
2748 raise EG("nested", [TE(2), TE(3)])
2749 except Exception as e:
2750 exc = e
2751 raise EG("eg", [VE(1), exc, VE(4)])
2752 except EG:
2753 raise EG("top", [VE(5)])
2754
2755 expected = (f' + Exception Group Traceback (most recent call last):\n'
2756 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 9}, in exc\n'
2757 f' | raise EG("eg", [VE(1), exc, VE(4)])\n'
2758 f' | ExceptionGroup: eg (3 sub-exceptions)\n'
2759 f' +-+---------------- 1 ----------------\n'
2760 f' | ValueError: 1\n'
2761 f' +---------------- 2 ----------------\n'
2762 f' | Exception Group Traceback (most recent call last):\n'
2763 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 6}, in exc\n'
2764 f' | raise EG("nested", [TE(2), TE(3)])\n'
2765 f' | ExceptionGroup: nested (2 sub-exceptions)\n'
2766 f' +-+---------------- 1 ----------------\n'
2767 f' | TypeError: 2\n'
2768 f' +---------------- 2 ----------------\n'
2769 f' | TypeError: 3\n'
2770 f' +------------------------------------\n'
2771 f' +---------------- 3 ----------------\n'
2772 f' | ValueError: 4\n'
2773 f' +------------------------------------\n'
2774 f'\n'
2775 f'During handling of the above exception, another exception occurred:\n'
2776 f'\n'
2777 f' + Exception Group Traceback (most recent call last):\n'
2778 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
2779 f' | exception_or_callable()\n'
2780 f' | ~~~~~~~~~~~~~~~~~~~~~^^\n'
2781 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 11}, in exc\n'
2782 f' | raise EG("top", [VE(5)])\n'
2783 f' | ExceptionGroup: top (1 sub-exception)\n'
2784 f' +-+---------------- 1 ----------------\n'
2785 f' | ValueError: 5\n'
2786 f' +------------------------------------\n')
2787
2788 report = self.get_report(exc)
2789 self.assertEqual(report, expected)
2790
2791 def test_exception_group_width_limit(self):
2792 excs = []
2793 for i in range(1000):
2794 excs.append(ValueError(i))
2795 eg = ExceptionGroup('eg', excs)
2796
2797 expected = (' | ExceptionGroup: eg (1000 sub-exceptions)\n'
2798 ' +-+---------------- 1 ----------------\n'
2799 ' | ValueError: 0\n'
2800 ' +---------------- 2 ----------------\n'
2801 ' | ValueError: 1\n'
2802 ' +---------------- 3 ----------------\n'
2803 ' | ValueError: 2\n'
2804 ' +---------------- 4 ----------------\n'
2805 ' | ValueError: 3\n'
2806 ' +---------------- 5 ----------------\n'
2807 ' | ValueError: 4\n'
2808 ' +---------------- 6 ----------------\n'
2809 ' | ValueError: 5\n'
2810 ' +---------------- 7 ----------------\n'
2811 ' | ValueError: 6\n'
2812 ' +---------------- 8 ----------------\n'
2813 ' | ValueError: 7\n'
2814 ' +---------------- 9 ----------------\n'
2815 ' | ValueError: 8\n'
2816 ' +---------------- 10 ----------------\n'
2817 ' | ValueError: 9\n'
2818 ' +---------------- 11 ----------------\n'
2819 ' | ValueError: 10\n'
2820 ' +---------------- 12 ----------------\n'
2821 ' | ValueError: 11\n'
2822 ' +---------------- 13 ----------------\n'
2823 ' | ValueError: 12\n'
2824 ' +---------------- 14 ----------------\n'
2825 ' | ValueError: 13\n'
2826 ' +---------------- 15 ----------------\n'
2827 ' | ValueError: 14\n'
2828 ' +---------------- ... ----------------\n'
2829 ' | and 985 more exceptions\n'
2830 ' +------------------------------------\n')
2831
2832 report = self.get_report(eg)
2833 self.assertEqual(report, expected)
2834
2835 def test_exception_group_depth_limit(self):
2836 exc = TypeError('bad type')
2837 for i in range(1000):
2838 exc = ExceptionGroup(
2839 f'eg{i}',
2840 [ValueError(i), exc, ValueError(-i)])
2841
2842 expected = (' | ExceptionGroup: eg999 (3 sub-exceptions)\n'
2843 ' +-+---------------- 1 ----------------\n'
2844 ' | ValueError: 999\n'
2845 ' +---------------- 2 ----------------\n'
2846 ' | ExceptionGroup: eg998 (3 sub-exceptions)\n'
2847 ' +-+---------------- 1 ----------------\n'
2848 ' | ValueError: 998\n'
2849 ' +---------------- 2 ----------------\n'
2850 ' | ExceptionGroup: eg997 (3 sub-exceptions)\n'
2851 ' +-+---------------- 1 ----------------\n'
2852 ' | ValueError: 997\n'
2853 ' +---------------- 2 ----------------\n'
2854 ' | ExceptionGroup: eg996 (3 sub-exceptions)\n'
2855 ' +-+---------------- 1 ----------------\n'
2856 ' | ValueError: 996\n'
2857 ' +---------------- 2 ----------------\n'
2858 ' | ExceptionGroup: eg995 (3 sub-exceptions)\n'
2859 ' +-+---------------- 1 ----------------\n'
2860 ' | ValueError: 995\n'
2861 ' +---------------- 2 ----------------\n'
2862 ' | ExceptionGroup: eg994 (3 sub-exceptions)\n'
2863 ' +-+---------------- 1 ----------------\n'
2864 ' | ValueError: 994\n'
2865 ' +---------------- 2 ----------------\n'
2866 ' | ExceptionGroup: eg993 (3 sub-exceptions)\n'
2867 ' +-+---------------- 1 ----------------\n'
2868 ' | ValueError: 993\n'
2869 ' +---------------- 2 ----------------\n'
2870 ' | ExceptionGroup: eg992 (3 sub-exceptions)\n'
2871 ' +-+---------------- 1 ----------------\n'
2872 ' | ValueError: 992\n'
2873 ' +---------------- 2 ----------------\n'
2874 ' | ExceptionGroup: eg991 (3 sub-exceptions)\n'
2875 ' +-+---------------- 1 ----------------\n'
2876 ' | ValueError: 991\n'
2877 ' +---------------- 2 ----------------\n'
2878 ' | ExceptionGroup: eg990 (3 sub-exceptions)\n'
2879 ' +-+---------------- 1 ----------------\n'
2880 ' | ValueError: 990\n'
2881 ' +---------------- 2 ----------------\n'
2882 ' | ... (max_group_depth is 10)\n'
2883 ' +---------------- 3 ----------------\n'
2884 ' | ValueError: -990\n'
2885 ' +------------------------------------\n'
2886 ' +---------------- 3 ----------------\n'
2887 ' | ValueError: -991\n'
2888 ' +------------------------------------\n'
2889 ' +---------------- 3 ----------------\n'
2890 ' | ValueError: -992\n'
2891 ' +------------------------------------\n'
2892 ' +---------------- 3 ----------------\n'
2893 ' | ValueError: -993\n'
2894 ' +------------------------------------\n'
2895 ' +---------------- 3 ----------------\n'
2896 ' | ValueError: -994\n'
2897 ' +------------------------------------\n'
2898 ' +---------------- 3 ----------------\n'
2899 ' | ValueError: -995\n'
2900 ' +------------------------------------\n'
2901 ' +---------------- 3 ----------------\n'
2902 ' | ValueError: -996\n'
2903 ' +------------------------------------\n'
2904 ' +---------------- 3 ----------------\n'
2905 ' | ValueError: -997\n'
2906 ' +------------------------------------\n'
2907 ' +---------------- 3 ----------------\n'
2908 ' | ValueError: -998\n'
2909 ' +------------------------------------\n'
2910 ' +---------------- 3 ----------------\n'
2911 ' | ValueError: -999\n'
2912 ' +------------------------------------\n')
2913
2914 report = self.get_report(exc)
2915 self.assertEqual(report, expected)
2916
2917 def test_exception_group_with_notes(self):
2918 def exc():
2919 try:
2920 excs = []
2921 for msg in ['bad value', 'terrible value']:
2922 try:
2923 raise ValueError(msg)
2924 except ValueError as e:
2925 e.add_note(f'the {msg}')
2926 excs.append(e)
2927 raise ExceptionGroup("nested", excs)
2928 except ExceptionGroup as e:
2929 e.add_note(('>> Multi line note\n'
2930 '>> Because I am such\n'
2931 '>> an important exception.\n'
2932 '>> empty lines work too\n'
2933 '\n'
2934 '(that was an empty line)'))
2935 raise
2936
2937 expected = (f' + Exception Group Traceback (most recent call last):\n'
2938 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
2939 f' | exception_or_callable()\n'
2940 f' | ~~~~~~~~~~~~~~~~~~~~~^^\n'
2941 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 9}, in exc\n'
2942 f' | raise ExceptionGroup("nested", excs)\n'
2943 f' | ExceptionGroup: nested (2 sub-exceptions)\n'
2944 f' | >> Multi line note\n'
2945 f' | >> Because I am such\n'
2946 f' | >> an important exception.\n'
2947 f' | >> empty lines work too\n'
2948 f' | \n'
2949 f' | (that was an empty line)\n'
2950 f' +-+---------------- 1 ----------------\n'
2951 f' | Traceback (most recent call last):\n'
2952 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n'
2953 f' | raise ValueError(msg)\n'
2954 f' | ValueError: bad value\n'
2955 f' | the bad value\n'
2956 f' +---------------- 2 ----------------\n'
2957 f' | Traceback (most recent call last):\n'
2958 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n'
2959 f' | raise ValueError(msg)\n'
2960 f' | ValueError: terrible value\n'
2961 f' | the terrible value\n'
2962 f' +------------------------------------\n')
2963
2964 report = self.get_report(exc)
2965 self.assertEqual(report, expected)
2966
2967 def test_exception_group_with_multiple_notes(self):
2968 def exc():
2969 try:
2970 excs = []
2971 for msg in ['bad value', 'terrible value']:
2972 try:
2973 raise ValueError(msg)
2974 except ValueError as e:
2975 e.add_note(f'the {msg}')
2976 e.add_note(f'Goodbye {msg}')
2977 excs.append(e)
2978 raise ExceptionGroup("nested", excs)
2979 except ExceptionGroup as e:
2980 e.add_note(('>> Multi line note\n'
2981 '>> Because I am such\n'
2982 '>> an important exception.\n'
2983 '>> empty lines work too\n'
2984 '\n'
2985 '(that was an empty line)'))
2986 e.add_note('Goodbye!')
2987 raise
2988
2989 expected = (f' + Exception Group Traceback (most recent call last):\n'
2990 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
2991 f' | exception_or_callable()\n'
2992 f' | ~~~~~~~~~~~~~~~~~~~~~^^\n'
2993 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 10}, in exc\n'
2994 f' | raise ExceptionGroup("nested", excs)\n'
2995 f' | ExceptionGroup: nested (2 sub-exceptions)\n'
2996 f' | >> Multi line note\n'
2997 f' | >> Because I am such\n'
2998 f' | >> an important exception.\n'
2999 f' | >> empty lines work too\n'
3000 f' | \n'
3001 f' | (that was an empty line)\n'
3002 f' | Goodbye!\n'
3003 f' +-+---------------- 1 ----------------\n'
3004 f' | Traceback (most recent call last):\n'
3005 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n'
3006 f' | raise ValueError(msg)\n'
3007 f' | ValueError: bad value\n'
3008 f' | the bad value\n'
3009 f' | Goodbye bad value\n'
3010 f' +---------------- 2 ----------------\n'
3011 f' | Traceback (most recent call last):\n'
3012 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n'
3013 f' | raise ValueError(msg)\n'
3014 f' | ValueError: terrible value\n'
3015 f' | the terrible value\n'
3016 f' | Goodbye terrible value\n'
3017 f' +------------------------------------\n')
3018
3019 report = self.get_report(exc)
3020 self.assertEqual(report, expected)
3021
3022 def test_exception_group_wrapped_naked(self):
3023 # See gh-128799
3024
3025 def exc():
3026 try:
3027 raise Exception(42)
3028 except* Exception as e:
3029 raise
3030
3031 expected = (f' + Exception Group Traceback (most recent call last):\n'
3032 f' | File "{__file__}", line {self.callable_line}, in get_exception\n'
3033 f' | exception_or_callable()\n'
3034 f' | ~~~~~~~~~~~~~~~~~~~~~^^\n'
3035 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 3}, in exc\n'
3036 f' | except* Exception as e:\n'
3037 f' | raise\n'
3038 f' | ExceptionGroup: (1 sub-exception)\n'
3039 f' +-+---------------- 1 ----------------\n'
3040 f' | Traceback (most recent call last):\n'
3041 f' | File "{__file__}", line {exc.__code__.co_firstlineno + 2}, in exc\n'
3042 f' | raise Exception(42)\n'
3043 f' | Exception: 42\n'
3044 f' +------------------------------------\n')
3045
3046 report = self.get_report(exc)
3047 self.assertEqual(report, expected)
3048
3049 def test_KeyboardInterrupt_at_first_line_of_frame(self):
3050 # see GH-93249
3051 def f():
3052 return sys._getframe()
3053
3054 tb_next = None
3055 frame = f()
3056 lasti = 0
3057 lineno = f.__code__.co_firstlineno
3058 tb = types.TracebackType(tb_next, frame, lasti, lineno)
3059
3060 exc = KeyboardInterrupt()
3061 exc.__traceback__ = tb
3062
3063 expected = (f'Traceback (most recent call last):\n'
3064 f' File "{__file__}", line {lineno}, in f\n'
3065 f' def f():\n'
3066 f'\n'
3067 f'KeyboardInterrupt\n')
3068
3069 report = self.get_report(exc)
3070 # remove trailing writespace:
3071 report = '\n'.join([l.rstrip() for l in report.split('\n')])
3072 self.assertEqual(report, expected)
3073
3074
3075 @force_not_colorized_test_class
3076 class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
3077 #
3078 # This checks reporting through the 'traceback' module, with both
3079 # format_exception() and print_exception().
3080 #
3081
3082 def get_report(self, e):
3083 e = self.get_exception(e)
3084 s = ''.join(
3085 traceback.format_exception(type(e), e, e.__traceback__))
3086 with captured_output("stderr") as sio:
3087 traceback.print_exception(type(e), e, e.__traceback__)
3088 self.assertEqual(sio.getvalue(), s)
3089 return s
3090
3091
3092 @force_not_colorized_test_class
3093 class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase):
3094 #
3095 # This checks built-in reporting by the interpreter.
3096 #
3097
3098 @cpython_only
3099 def get_report(self, e):
3100 from _testcapi import exception_print
3101 e = self.get_exception(e)
3102 with captured_output("stderr") as s:
3103 exception_print(e)
3104 return s.getvalue()
3105
3106
3107 class LimitTests(unittest.TestCase):
3108
3109 ''' Tests for limit argument.
3110 It's enough to test extact_tb, extract_stack and format_exception '''
3111
3112 def last_raises1(self):
3113 raise Exception('Last raised')
3114
3115 def last_raises2(self):
3116 self.last_raises1()
3117
3118 def last_raises3(self):
3119 self.last_raises2()
3120
3121 def last_raises4(self):
3122 self.last_raises3()
3123
3124 def last_raises5(self):
3125 self.last_raises4()
3126
3127 def last_returns_frame1(self):
3128 return sys._getframe()
3129
3130 def last_returns_frame2(self):
3131 return self.last_returns_frame1()
3132
3133 def last_returns_frame3(self):
3134 return self.last_returns_frame2()
3135
3136 def last_returns_frame4(self):
3137 return self.last_returns_frame3()
3138
3139 def last_returns_frame5(self):
3140 return self.last_returns_frame4()
3141
3142 def test_extract_stack(self):
3143 frame = self.last_returns_frame5()
3144 def extract(**kwargs):
3145 return traceback.extract_stack(frame, **kwargs)
3146 def assertEqualExcept(actual, expected, ignore):
3147 self.assertEqual(actual[:ignore], expected[:ignore])
3148 self.assertEqual(actual[ignore+1:], expected[ignore+1:])
3149 self.assertEqual(len(actual), len(expected))
3150
3151 with support.swap_attr(sys, 'tracebacklimit', 1000):
3152 nolim = extract()
3153 self.assertGreater(len(nolim), 5)
3154 self.assertEqual(extract(limit=2), nolim[-2:])
3155 assertEqualExcept(extract(limit=100), nolim[-100:], -5-1)
3156 self.assertEqual(extract(limit=-2), nolim[:2])
3157 assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1)
3158 self.assertEqual(extract(limit=0), [])
3159 del sys.tracebacklimit
3160 assertEqualExcept(extract(), nolim, -5-1)
3161 sys.tracebacklimit = 2
3162 self.assertEqual(extract(), nolim[-2:])
3163 self.assertEqual(extract(limit=3), nolim[-3:])
3164 self.assertEqual(extract(limit=-3), nolim[:3])
3165 sys.tracebacklimit = 0
3166 self.assertEqual(extract(), [])
3167 sys.tracebacklimit = -1
3168 self.assertEqual(extract(), [])
3169
3170 def test_extract_tb(self):
3171 try:
3172 self.last_raises5()
3173 except Exception as e:
3174 tb = e.__traceback__
3175 def extract(**kwargs):
3176 return traceback.extract_tb(tb, **kwargs)
3177
3178 with support.swap_attr(sys, 'tracebacklimit', 1000):
3179 nolim = extract()
3180 self.assertEqual(len(nolim), 5+1)
3181 self.assertEqual(extract(limit=2), nolim[:2])
3182 self.assertEqual(extract(limit=10), nolim)
3183 self.assertEqual(extract(limit=-2), nolim[-2:])
3184 self.assertEqual(extract(limit=-10), nolim)
3185 self.assertEqual(extract(limit=0), [])
3186 del sys.tracebacklimit
3187 self.assertEqual(extract(), nolim)
3188 sys.tracebacklimit = 2
3189 self.assertEqual(extract(), nolim[:2])
3190 self.assertEqual(extract(limit=3), nolim[:3])
3191 self.assertEqual(extract(limit=-3), nolim[-3:])
3192 sys.tracebacklimit = 0
3193 self.assertEqual(extract(), [])
3194 sys.tracebacklimit = -1
3195 self.assertEqual(extract(), [])
3196
3197 def test_format_exception(self):
3198 try:
3199 self.last_raises5()
3200 except Exception as e:
3201 exc = e
3202 # [1:-1] to exclude "Traceback (...)" header and
3203 # exception type and value
3204 def extract(**kwargs):
3205 return traceback.format_exception(exc, **kwargs)[1:-1]
3206
3207 with support.swap_attr(sys, 'tracebacklimit', 1000):
3208 nolim = extract()
3209 self.assertEqual(len(nolim), 5+1)
3210 self.assertEqual(extract(limit=2), nolim[:2])
3211 self.assertEqual(extract(limit=10), nolim)
3212 self.assertEqual(extract(limit=-2), nolim[-2:])
3213 self.assertEqual(extract(limit=-10), nolim)
3214 self.assertEqual(extract(limit=0), [])
3215 del sys.tracebacklimit
3216 self.assertEqual(extract(), nolim)
3217 sys.tracebacklimit = 2
3218 self.assertEqual(extract(), nolim[:2])
3219 self.assertEqual(extract(limit=3), nolim[:3])
3220 self.assertEqual(extract(limit=-3), nolim[-3:])
3221 sys.tracebacklimit = 0
3222 self.assertEqual(extract(), [])
3223 sys.tracebacklimit = -1
3224 self.assertEqual(extract(), [])
3225
3226
3227 class MiscTracebackCases(unittest.TestCase):
3228 #
3229 # Check non-printing functions in traceback module
3230 #
3231
3232 def test_clear(self):
3233 def outer():
3234 middle()
3235 def middle():
3236 inner()
3237 def inner():
3238 i = 1
3239 1/0
3240
3241 try:
3242 outer()
3243 except BaseException as e:
3244 tb = e.__traceback__
3245
3246 # Initial assertion: there's one local in the inner frame.
3247 inner_frame = tb.tb_next.tb_next.tb_next.tb_frame
3248 self.assertEqual(len(inner_frame.f_locals), 1)
3249
3250 # Clear traceback frames
3251 traceback.clear_frames(tb)
3252
3253 # Local variable dict should now be empty.
3254 self.assertEqual(len(inner_frame.f_locals), 0)
3255
3256 def test_extract_stack(self):
3257 def extract():
3258 return traceback.extract_stack()
3259 result = extract()
3260 lineno = extract.__code__.co_firstlineno
3261 self.assertEqual(result[-2:], [
3262 (__file__, lineno+2, 'test_extract_stack', 'result = extract()'),
3263 (__file__, lineno+1, 'extract', 'return traceback.extract_stack()'),
3264 ])
3265 self.assertEqual(len(result[0]), 4)
3266
3267
3268 class TestFrame(unittest.TestCase):
3269
3270 def test_basics(self):
3271 linecache.clearcache()
3272 linecache.lazycache("f", globals())
3273 f = traceback.FrameSummary("f", 1, "dummy")
3274 self.assertEqual(f,
3275 ("f", 1, "dummy", '"""Test cases for traceback module"""'))
3276 self.assertEqual(tuple(f),
3277 ("f", 1, "dummy", '"""Test cases for traceback module"""'))
3278 self.assertEqual(f, traceback.FrameSummary("f", 1, "dummy"))
3279 self.assertEqual(f, tuple(f))
3280 # Since tuple.__eq__ doesn't support FrameSummary, the equality
3281 # operator fallbacks to FrameSummary.__eq__.
3282 self.assertEqual(tuple(f), f)
3283 self.assertIsNone(f.locals)
3284 self.assertNotEqual(f, object())
3285 self.assertEqual(f, ALWAYS_EQ)
3286
3287 def test_lazy_lines(self):
3288 linecache.clearcache()
3289 f = traceback.FrameSummary("f", 1, "dummy", lookup_line=False)
3290 self.assertEqual(None, f._lines)
3291 linecache.lazycache("f", globals())
3292 self.assertEqual(
3293 '"""Test cases for traceback module"""',
3294 f.line)
3295
3296 def test_no_line(self):
3297 f = traceback.FrameSummary("f", None, "dummy")
3298 self.assertEqual(f.line, None)
3299
3300 def test_explicit_line(self):
3301 f = traceback.FrameSummary("f", 1, "dummy", line="line")
3302 self.assertEqual("line", f.line)
3303
3304 def test_len(self):
3305 f = traceback.FrameSummary("f", 1, "dummy", line="line")
3306 self.assertEqual(len(f), 4)
3307
3308
3309 class TestStack(unittest.TestCase):
3310
3311 def test_walk_stack(self):
3312 def deeper():
3313 return list(traceback.walk_stack(None))
3314 s1, s2 = list(traceback.walk_stack(None)), deeper()
3315 self.assertEqual(len(s2) - len(s1), 1)
3316 self.assertEqual(s2[1:], s1)
3317
3318 def test_walk_innermost_frame(self):
3319 def inner():
3320 return list(traceback.walk_stack(None))
3321 frames = inner()
3322 innermost_frame, _ = frames[0]
3323 self.assertEqual(innermost_frame.f_code.co_name, "inner")
3324
3325 def test_walk_tb(self):
3326 try:
3327 1/0
3328 except Exception as e:
3329 tb = e.__traceback__
3330 s = list(traceback.walk_tb(tb))
3331 self.assertEqual(len(s), 1)
3332
3333 def test_extract_stack(self):
3334 s = traceback.StackSummary.extract(traceback.walk_stack(None))
3335 self.assertIsInstance(s, traceback.StackSummary)
3336
3337 def test_extract_stack_limit(self):
3338 s = traceback.StackSummary.extract(traceback.walk_stack(None), limit=5)
3339 self.assertEqual(len(s), 5)
3340
3341 def test_extract_stack_lookup_lines(self):
3342 linecache.clearcache()
3343 linecache.updatecache('/foo.py', globals())
3344 c = test_code('/foo.py', 'method')
3345 f = test_frame(c, None, None)
3346 s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=True)
3347 linecache.clearcache()
3348 self.assertEqual(s[0].line, "import sys")
3349
3350 def test_extract_stackup_deferred_lookup_lines(self):
3351 linecache.clearcache()
3352 c = test_code('/foo.py', 'method')
3353 f = test_frame(c, None, None)
3354 s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=False)
3355 self.assertEqual({}, linecache.cache)
3356 linecache.updatecache('/foo.py', globals())
3357 self.assertEqual(s[0].line, "import sys")
3358
3359 def test_from_list(self):
3360 s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')])
3361 self.assertEqual(
3362 [' File "foo.py", line 1, in fred\n line\n'],
3363 s.format())
3364
3365 def test_from_list_edited_stack(self):
3366 s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')])
3367 s[0] = ('foo.py', 2, 'fred', 'line')
3368 s2 = traceback.StackSummary.from_list(s)
3369 self.assertEqual(
3370 [' File "foo.py", line 2, in fred\n line\n'],
3371 s2.format())
3372
3373 def test_format_smoke(self):
3374 # For detailed tests see the format_list tests, which consume the same
3375 # code.
3376 s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')])
3377 self.assertEqual(
3378 [' File "foo.py", line 1, in fred\n line\n'],
3379 s.format())
3380
3381 def test_locals(self):
3382 linecache.updatecache('/foo.py', globals())
3383 c = test_code('/foo.py', 'method')
3384 f = test_frame(c, globals(), {'something': 1})
3385 s = traceback.StackSummary.extract(iter([(f, 6)]), capture_locals=True)
3386 self.assertEqual(s[0].locals, {'something': '1'})
3387
3388 def test_no_locals(self):
3389 linecache.updatecache('/foo.py', globals())
3390 c = test_code('/foo.py', 'method')
3391 f = test_frame(c, globals(), {'something': 1})
3392 s = traceback.StackSummary.extract(iter([(f, 6)]))
3393 self.assertEqual(s[0].locals, None)
3394
3395 def test_format_locals(self):
3396 def some_inner(k, v):
3397 a = 1
3398 b = 2
3399 return traceback.StackSummary.extract(
3400 traceback.walk_stack(None), capture_locals=True, limit=1)
3401 s = some_inner(3, 4)
3402 self.assertEqual(
3403 [' File "%s", line %d, in some_inner\n'
3404 ' return traceback.StackSummary.extract(\n'
3405 ' a = 1\n'
3406 ' b = 2\n'
3407 ' k = 3\n'
3408 ' v = 4\n' % (__file__, some_inner.__code__.co_firstlineno + 3)
3409 ], s.format())
3410
3411 def test_custom_format_frame(self):
3412 class CustomStackSummary(traceback.StackSummary):
3413 def format_frame_summary(self, frame_summary, colorize=False):
3414 return f'{frame_summary.filename}:{frame_summary.lineno}'
3415
3416 def some_inner():
3417 return CustomStackSummary.extract(
3418 traceback.walk_stack(None), limit=1)
3419
3420 s = some_inner()
3421 self.assertEqual(
3422 s.format(),
3423 [f'{__file__}:{some_inner.__code__.co_firstlineno + 1}'])
3424
3425 def test_dropping_frames(self):
3426 def f():
3427 1/0
3428
3429 def g():
3430 try:
3431 f()
3432 except Exception as e:
3433 return e.__traceback__
3434
3435 tb = g()
3436
3437 class Skip_G(traceback.StackSummary):
3438 def format_frame_summary(self, frame_summary, colorize=False):
3439 if frame_summary.name == 'g':
3440 return None
3441 return super().format_frame_summary(frame_summary)
3442
3443 stack = Skip_G.extract(
3444 traceback.walk_tb(tb)).format()
3445
3446 self.assertEqual(len(stack), 1)
3447 lno = f.__code__.co_firstlineno + 1
3448 self.assertEqual(
3449 stack[0],
3450 f' File "{__file__}", line {lno}, in f\n 1/0\n'
3451 )
3452
3453 def test_summary_should_show_carets(self):
3454 # See: https://github.com/python/cpython/issues/122353
3455
3456 # statement to execute and to get a ZeroDivisionError for a traceback
3457 statement = "abcdef = 1 / 0 and 2.0"
3458 colno = statement.index('1 / 0')
3459 end_colno = colno + len('1 / 0')
3460
3461 # Actual line to use when rendering the traceback
3462 # and whose AST will be extracted (it will be empty).
3463 cached_line = '# this line will be used during rendering'
3464 self.addCleanup(unlink, TESTFN)
3465 with open(TESTFN, "w") as file:
3466 file.write(cached_line)
3467 linecache.updatecache(TESTFN, {})
3468
3469 try:
3470 exec(compile(statement, TESTFN, "exec"))
3471 except ZeroDivisionError as exc:
3472 # This is the simplest way to create a StackSummary
3473 # whose FrameSummary items have their column offsets.
3474 s = traceback.TracebackException.from_exception(exc).stack
3475 self.assertIsInstance(s, traceback.StackSummary)
3476 with unittest.mock.patch.object(s, '_should_show_carets',
3477 wraps=s._should_show_carets) as ff:
3478 self.assertEqual(len(s), 2)
3479 self.assertListEqual(
3480 s.format_frame_summary(s[1]).splitlines(),
3481 [
3482 f' File "{TESTFN}", line 1, in <module>',
3483 f' {cached_line}'
3484 ]
3485 )
3486 ff.assert_called_with(colno, end_colno, [cached_line], None)
3487
3488 class Unrepresentable:
3489 def __repr__(self) -> str:
3490 raise Exception("Unrepresentable")
3491
3492
3493 # Used in test_dont_swallow_cause_or_context_of_falsey_exception and
3494 # test_dont_swallow_subexceptions_of_falsey_exceptiongroup.
3495 class FalseyException(Exception):
3496 def __bool__(self):
3497 return False
3498
3499
3500 class FalseyExceptionGroup(ExceptionGroup):
3501 def __bool__(self):
3502 return False
3503
3504
3505 class TestTracebackException(unittest.TestCase):
3506 def do_test_smoke(self, exc, expected_type_str):
3507 try:
3508 raise exc
3509 except Exception as e:
3510 exc_obj = e
3511 exc = traceback.TracebackException.from_exception(e)
3512 expected_stack = traceback.StackSummary.extract(
3513 traceback.walk_tb(e.__traceback__))
3514 self.assertEqual(None, exc.__cause__)
3515 self.assertEqual(None, exc.__context__)
3516 self.assertEqual(False, exc.__suppress_context__)
3517 self.assertEqual(expected_stack, exc.stack)
3518 with self.assertWarns(DeprecationWarning):
3519 self.assertEqual(type(exc_obj), exc.exc_type)
3520 self.assertEqual(expected_type_str, exc.exc_type_str)
3521 self.assertEqual(str(exc_obj), str(exc))
3522
3523 def test_smoke_builtin(self):
3524 self.do_test_smoke(ValueError(42), 'ValueError')
3525
3526 def test_smoke_user_exception(self):
3527 class MyException(Exception):
3528 pass
3529
3530 if __name__ == '__main__':
3531 expected = ('TestTracebackException.'
3532 'test_smoke_user_exception.<locals>.MyException')
3533 else:
3534 expected = ('test.test_traceback.TestTracebackException.'
3535 'test_smoke_user_exception.<locals>.MyException')
3536 self.do_test_smoke(MyException('bad things happened'), expected)
3537
3538 def test_from_exception(self):
3539 # Check all the parameters are accepted.
3540 def foo():
3541 1/0
3542 try:
3543 foo()
3544 except Exception as e:
3545 exc_obj = e
3546 tb = e.__traceback__
3547 self.expected_stack = traceback.StackSummary.extract(
3548 traceback.walk_tb(tb), limit=1, lookup_lines=False,
3549 capture_locals=True)
3550 self.exc = traceback.TracebackException.from_exception(
3551 e, limit=1, lookup_lines=False, capture_locals=True)
3552 expected_stack = self.expected_stack
3553 exc = self.exc
3554 self.assertEqual(None, exc.__cause__)
3555 self.assertEqual(None, exc.__context__)
3556 self.assertEqual(False, exc.__suppress_context__)
3557 self.assertEqual(expected_stack, exc.stack)
3558 with self.assertWarns(DeprecationWarning):
3559 self.assertEqual(type(exc_obj), exc.exc_type)
3560 self.assertEqual(type(exc_obj).__name__, exc.exc_type_str)
3561 self.assertEqual(str(exc_obj), str(exc))
3562
3563 def test_cause(self):
3564 try:
3565 try:
3566 1/0
3567 finally:
3568 exc = sys.exception()
3569 exc_context = traceback.TracebackException.from_exception(exc)
3570 cause = Exception("cause")
3571 raise Exception("uh oh") from cause
3572 except Exception as e:
3573 exc_obj = e
3574 exc = traceback.TracebackException.from_exception(e)
3575 expected_stack = traceback.StackSummary.extract(
3576 traceback.walk_tb(e.__traceback__))
3577 exc_cause = traceback.TracebackException(Exception, cause, None)
3578 self.assertEqual(exc_cause, exc.__cause__)
3579 self.assertEqual(exc_context, exc.__context__)
3580 self.assertEqual(True, exc.__suppress_context__)
3581 self.assertEqual(expected_stack, exc.stack)
3582 with self.assertWarns(DeprecationWarning):
3583 self.assertEqual(type(exc_obj), exc.exc_type)
3584 self.assertEqual(type(exc_obj).__name__, exc.exc_type_str)
3585 self.assertEqual(str(exc_obj), str(exc))
3586
3587 def test_context(self):
3588 try:
3589 try:
3590 1/0
3591 finally:
3592 exc = sys.exception()
3593 exc_context = traceback.TracebackException.from_exception(exc)
3594 raise Exception("uh oh")
3595 except Exception as e:
3596 exc_obj = e
3597 exc = traceback.TracebackException.from_exception(e)
3598 expected_stack = traceback.StackSummary.extract(
3599 traceback.walk_tb(e.__traceback__))
3600 self.assertEqual(None, exc.__cause__)
3601 self.assertEqual(exc_context, exc.__context__)
3602 self.assertEqual(False, exc.__suppress_context__)
3603 self.assertEqual(expected_stack, exc.stack)
3604 with self.assertWarns(DeprecationWarning):
3605 self.assertEqual(type(exc_obj), exc.exc_type)
3606 self.assertEqual(type(exc_obj).__name__, exc.exc_type_str)
3607 self.assertEqual(str(exc_obj), str(exc))
3608
3609 def test_long_context_chain(self):
3610 def f():
3611 try:
3612 1/0
3613 except ZeroDivisionError:
3614 f()
3615
3616 try:
3617 f()
3618 except RecursionError as e:
3619 exc_obj = e
3620 else:
3621 self.fail("Exception not raised")
3622
3623 te = traceback.TracebackException.from_exception(exc_obj)
3624 res = list(te.format())
3625
3626 # many ZeroDiv errors followed by the RecursionError
3627 self.assertGreater(len(res), sys.getrecursionlimit())
3628 self.assertGreater(
3629 len([l for l in res if 'ZeroDivisionError:' in l]),
3630 sys.getrecursionlimit() * 0.5)
3631 self.assertIn(
3632 "RecursionError: maximum recursion depth exceeded", res[-1])
3633
3634 def test_compact_with_cause(self):
3635 try:
3636 try:
3637 1/0
3638 finally:
3639 cause = Exception("cause")
3640 raise Exception("uh oh") from cause
3641 except Exception as e:
3642 exc_obj = e
3643 exc = traceback.TracebackException.from_exception(exc_obj, compact=True)
3644 expected_stack = traceback.StackSummary.extract(
3645 traceback.walk_tb(exc_obj.__traceback__))
3646 exc_cause = traceback.TracebackException(Exception, cause, None)
3647 self.assertEqual(exc_cause, exc.__cause__)
3648 self.assertEqual(None, exc.__context__)
3649 self.assertEqual(True, exc.__suppress_context__)
3650 self.assertEqual(expected_stack, exc.stack)
3651 with self.assertWarns(DeprecationWarning):
3652 self.assertEqual(type(exc_obj), exc.exc_type)
3653 self.assertEqual(type(exc_obj).__name__, exc.exc_type_str)
3654 self.assertEqual(str(exc_obj), str(exc))
3655
3656 def test_compact_no_cause(self):
3657 try:
3658 try:
3659 1/0
3660 finally:
3661 exc = sys.exception()
3662 exc_context = traceback.TracebackException.from_exception(exc)
3663 raise Exception("uh oh")
3664 except Exception as e:
3665 exc_obj = e
3666 exc = traceback.TracebackException.from_exception(e, compact=True)
3667 expected_stack = traceback.StackSummary.extract(
3668 traceback.walk_tb(exc_obj.__traceback__))
3669 self.assertEqual(None, exc.__cause__)
3670 self.assertEqual(exc_context, exc.__context__)
3671 self.assertEqual(False, exc.__suppress_context__)
3672 self.assertEqual(expected_stack, exc.stack)
3673 with self.assertWarns(DeprecationWarning):
3674 self.assertEqual(type(exc_obj), exc.exc_type)
3675 self.assertEqual(type(exc_obj).__name__, exc.exc_type_str)
3676 self.assertEqual(str(exc_obj), str(exc))
3677
3678 def test_no_save_exc_type(self):
3679 try:
3680 1/0
3681 except Exception as e:
3682 exc = e
3683
3684 te = traceback.TracebackException.from_exception(
3685 exc, save_exc_type=False)
3686 with self.assertWarns(DeprecationWarning):
3687 self.assertIsNone(te.exc_type)
3688
3689 def test_no_refs_to_exception_and_traceback_objects(self):
3690 exc_obj = None
3691 try:
3692 1/0
3693 except Exception as e:
3694 exc_obj = e
3695
3696 refcnt1 = sys.getrefcount(exc_obj)
3697 refcnt2 = sys.getrefcount(exc_obj.__traceback__)
3698 exc = traceback.TracebackException.from_exception(exc_obj)
3699 self.assertEqual(sys.getrefcount(exc_obj), refcnt1)
3700 self.assertEqual(sys.getrefcount(exc_obj.__traceback__), refcnt2)
3701
3702 def test_comparison_basic(self):
3703 try:
3704 1/0
3705 except Exception as e:
3706 exc_obj = e
3707 exc = traceback.TracebackException.from_exception(exc_obj)
3708 exc2 = traceback.TracebackException.from_exception(exc_obj)
3709 self.assertIsNot(exc, exc2)
3710 self.assertEqual(exc, exc2)
3711 self.assertNotEqual(exc, object())
3712 self.assertEqual(exc, ALWAYS_EQ)
3713
3714 def test_comparison_params_variations(self):
3715 def raise_exc():
3716 try:
3717 raise ValueError('bad value')
3718 except ValueError:
3719 raise
3720
3721 def raise_with_locals():
3722 x, y = 1, 2
3723 raise_exc()
3724
3725 try:
3726 raise_with_locals()
3727 except Exception as e:
3728 exc_obj = e
3729
3730 exc = traceback.TracebackException.from_exception(exc_obj)
3731 exc1 = traceback.TracebackException.from_exception(exc_obj, limit=10)
3732 exc2 = traceback.TracebackException.from_exception(exc_obj, limit=2)
3733
3734 self.assertEqual(exc, exc1) # limit=10 gets all frames
3735 self.assertNotEqual(exc, exc2) # limit=2 truncates the output
3736
3737 # locals change the output
3738 exc3 = traceback.TracebackException.from_exception(exc_obj, capture_locals=True)
3739 self.assertNotEqual(exc, exc3)
3740
3741 # there are no locals in the innermost frame
3742 exc4 = traceback.TracebackException.from_exception(exc_obj, limit=-1)
3743 exc5 = traceback.TracebackException.from_exception(exc_obj, limit=-1, capture_locals=True)
3744 self.assertEqual(exc4, exc5)
3745
3746 # there are locals in the next-to-innermost frame
3747 exc6 = traceback.TracebackException.from_exception(exc_obj, limit=-2)
3748 exc7 = traceback.TracebackException.from_exception(exc_obj, limit=-2, capture_locals=True)
3749 self.assertNotEqual(exc6, exc7)
3750
3751 def test_comparison_equivalent_exceptions_are_equal(self):
3752 excs = []
3753 for _ in range(2):
3754 try:
3755 1/0
3756 except Exception as e:
3757 excs.append(traceback.TracebackException.from_exception(e))
3758 self.assertEqual(excs[0], excs[1])
3759 self.assertEqual(list(excs[0].format()), list(excs[1].format()))
3760
3761 def test_unhashable(self):
3762 class UnhashableException(Exception):
3763 def __eq__(self, other):
3764 return True
3765
3766 ex1 = UnhashableException('ex1')
3767 ex2 = UnhashableException('ex2')
3768 try:
3769 raise ex2 from ex1
3770 except UnhashableException:
3771 try:
3772 raise ex1
3773 except UnhashableException as e:
3774 exc_obj = e
3775 exc = traceback.TracebackException.from_exception(exc_obj)
3776 formatted = list(exc.format())
3777 self.assertIn('UnhashableException: ex2\n', formatted[2])
3778 self.assertIn('UnhashableException: ex1\n', formatted[6])
3779
3780 def test_limit(self):
3781 def recurse(n):
3782 if n:
3783 recurse(n-1)
3784 else:
3785 1/0
3786 try:
3787 recurse(10)
3788 except Exception as e:
3789 exc = traceback.TracebackException.from_exception(e, limit=5)
3790 expected_stack = traceback.StackSummary.extract(
3791 traceback.walk_tb(e.__traceback__), limit=5)
3792 self.assertEqual(expected_stack, exc.stack)
3793
3794 def test_lookup_lines(self):
3795 linecache.clearcache()
3796 e = Exception("uh oh")
3797 c = test_code('/foo.py', 'method')
3798 f = test_frame(c, None, None)
3799 tb = test_tb(f, 6, None, 0)
3800 exc = traceback.TracebackException(Exception, e, tb, lookup_lines=False)
3801 self.assertEqual(linecache.cache, {})
3802 linecache.updatecache('/foo.py', globals())
3803 self.assertEqual(exc.stack[0].line, "import sys")
3804
3805 def test_locals(self):
3806 linecache.updatecache('/foo.py', globals())
3807 e = Exception("uh oh")
3808 c = test_code('/foo.py', 'method')
3809 f = test_frame(c, globals(), {'something': 1, 'other': 'string', 'unrepresentable': Unrepresentable()})
3810 tb = test_tb(f, 6, None, 0)
3811 exc = traceback.TracebackException(
3812 Exception, e, tb, capture_locals=True)
3813 self.assertEqual(
3814 exc.stack[0].locals,
3815 {'something': '1', 'other': "'string'", 'unrepresentable': '<local repr() failed>'})
3816
3817 def test_no_locals(self):
3818 linecache.updatecache('/foo.py', globals())
3819 e = Exception("uh oh")
3820 c = test_code('/foo.py', 'method')
3821 f = test_frame(c, globals(), {'something': 1})
3822 tb = test_tb(f, 6, None, 0)
3823 exc = traceback.TracebackException(Exception, e, tb)
3824 self.assertEqual(exc.stack[0].locals, None)
3825
3826 def test_traceback_header(self):
3827 # do not print a traceback header if exc_traceback is None
3828 # see issue #24695
3829 exc = traceback.TracebackException(Exception, Exception("haven"), None)
3830 self.assertEqual(list(exc.format()), ["Exception: haven\n"])
3831
3832 @requires_debug_ranges()
3833 def test_print(self):
3834 def f():
3835 x = 12
3836 try:
3837 x/0
3838 except Exception as e:
3839 return e
3840 exc = traceback.TracebackException.from_exception(f(), capture_locals=True)
3841 output = StringIO()
3842 exc.print(file=output)
3843 self.assertEqual(
3844 output.getvalue().split('\n')[-5:],
3845 [' x/0',
3846 ' ~^~',
3847 ' x = 12',
3848 'ZeroDivisionError: division by zero',
3849 ''])
3850
3851 def test_dont_swallow_cause_or_context_of_falsey_exception(self):
3852 # see gh-132308: Ensure that __cause__ or __context__ attributes of exceptions
3853 # that evaluate as falsey are included in the output. For falsey term,
3854 # see https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
3855
3856 try:
3857 raise FalseyException from KeyError
3858 except FalseyException as e:
3859 self.assertIn(cause_message, traceback.format_exception(e))
3860
3861 try:
3862 try:
3863 1/0
3864 except ZeroDivisionError:
3865 raise FalseyException
3866 except FalseyException as e:
3867 self.assertIn(context_message, traceback.format_exception(e))
3868
3869
3870 class TestTracebackException_ExceptionGroups(unittest.TestCase):
3871 def setUp(self):
3872 super().setUp()
3873 self.eg = self._get_exception_group()
3874
3875 def _get_exception_group(self):
3876 def f():
3877 1/0
3878
3879 def g(v):
3880 raise ValueError(v)
3881
3882 self.lno_f = f.__code__.co_firstlineno
3883 self.lno_g = g.__code__.co_firstlineno
3884
3885 try:
3886 try:
3887 try:
3888 f()
3889 except Exception as e:
3890 exc1 = e
3891 try:
3892 g(42)
3893 except Exception as e:
3894 exc2 = e
3895 raise ExceptionGroup("eg1", [exc1, exc2])
3896 except ExceptionGroup as e:
3897 exc3 = e
3898 try:
3899 g(24)
3900 except Exception as e:
3901 exc4 = e
3902 raise ExceptionGroup("eg2", [exc3, exc4])
3903 except ExceptionGroup as eg:
3904 return eg
3905 self.fail('Exception Not Raised')
3906
3907 def test_exception_group_construction(self):
3908 eg = self.eg
3909 teg1 = traceback.TracebackException(type(eg), eg, eg.__traceback__)
3910 teg2 = traceback.TracebackException.from_exception(eg)
3911 self.assertIsNot(teg1, teg2)
3912 self.assertEqual(teg1, teg2)
3913
3914 def test_exception_group_format_exception_only(self):
3915 teg = traceback.TracebackException.from_exception(self.eg)
3916 formatted = ''.join(teg.format_exception_only()).split('\n')
3917 expected = "ExceptionGroup: eg2 (2 sub-exceptions)\n".split('\n')
3918
3919 self.assertEqual(formatted, expected)
3920
3921 def test_exception_group_format_exception_onlyi_recursive(self):
3922 teg = traceback.TracebackException.from_exception(self.eg)
3923 formatted = ''.join(teg.format_exception_only(show_group=True)).split('\n')
3924 expected = [
3925 'ExceptionGroup: eg2 (2 sub-exceptions)',
3926 ' ExceptionGroup: eg1 (2 sub-exceptions)',
3927 ' ZeroDivisionError: division by zero',
3928 ' ValueError: 42',
3929 ' ValueError: 24',
3930 ''
3931 ]
3932
3933 self.assertEqual(formatted, expected)
3934
3935 def test_exception_group_format(self):
3936 teg = traceback.TracebackException.from_exception(self.eg)
3937
3938 formatted = ''.join(teg.format()).split('\n')
3939 lno_f = self.lno_f
3940 lno_g = self.lno_g
3941
3942 expected = [
3943 f' + Exception Group Traceback (most recent call last):',
3944 f' | File "{__file__}", line {lno_g+23}, in _get_exception_group',
3945 f' | raise ExceptionGroup("eg2", [exc3, exc4])',
3946 f' | ExceptionGroup: eg2 (2 sub-exceptions)',
3947 f' +-+---------------- 1 ----------------',
3948 f' | Exception Group Traceback (most recent call last):',
3949 f' | File "{__file__}", line {lno_g+16}, in _get_exception_group',
3950 f' | raise ExceptionGroup("eg1", [exc1, exc2])',
3951 f' | ExceptionGroup: eg1 (2 sub-exceptions)',
3952 f' +-+---------------- 1 ----------------',
3953 f' | Traceback (most recent call last):',
3954 f' | File "{__file__}", line {lno_g+9}, in _get_exception_group',
3955 f' | f()',
3956 f' | ~^^',
3957 f' | File "{__file__}", line {lno_f+1}, in f',
3958 f' | 1/0',
3959 f' | ~^~',
3960 f' | ZeroDivisionError: division by zero',
3961 f' +---------------- 2 ----------------',
3962 f' | Traceback (most recent call last):',
3963 f' | File "{__file__}", line {lno_g+13}, in _get_exception_group',
3964 f' | g(42)',
3965 f' | ~^^^^',
3966 f' | File "{__file__}", line {lno_g+1}, in g',
3967 f' | raise ValueError(v)',
3968 f' | ValueError: 42',
3969 f' +------------------------------------',
3970 f' +---------------- 2 ----------------',
3971 f' | Traceback (most recent call last):',
3972 f' | File "{__file__}", line {lno_g+20}, in _get_exception_group',
3973 f' | g(24)',
3974 f' | ~^^^^',
3975 f' | File "{__file__}", line {lno_g+1}, in g',
3976 f' | raise ValueError(v)',
3977 f' | ValueError: 24',
3978 f' +------------------------------------',
3979 f'']
3980
3981 self.assertEqual(formatted, expected)
3982
3983 def test_max_group_width(self):
3984 excs1 = []
3985 excs2 = []
3986 for i in range(3):
3987 excs1.append(ValueError(i))
3988 for i in range(10):
3989 excs2.append(TypeError(i))
3990
3991 EG = ExceptionGroup
3992 eg = EG('eg', [EG('eg1', excs1), EG('eg2', excs2)])
3993
3994 teg = traceback.TracebackException.from_exception(eg, max_group_width=2)
3995 formatted = ''.join(teg.format()).split('\n')
3996
3997 expected = [
3998 ' | ExceptionGroup: eg (2 sub-exceptions)',
3999 ' +-+---------------- 1 ----------------',
4000 ' | ExceptionGroup: eg1 (3 sub-exceptions)',
4001 ' +-+---------------- 1 ----------------',
4002 ' | ValueError: 0',
4003 ' +---------------- 2 ----------------',
4004 ' | ValueError: 1',
4005 ' +---------------- ... ----------------',
4006 ' | and 1 more exception',
4007 ' +------------------------------------',
4008 ' +---------------- 2 ----------------',
4009 ' | ExceptionGroup: eg2 (10 sub-exceptions)',
4010 ' +-+---------------- 1 ----------------',
4011 ' | TypeError: 0',
4012 ' +---------------- 2 ----------------',
4013 ' | TypeError: 1',
4014 ' +---------------- ... ----------------',
4015 ' | and 8 more exceptions',
4016 ' +------------------------------------',
4017 '']
4018
4019 self.assertEqual(formatted, expected)
4020
4021 def test_max_group_depth(self):
4022 exc = TypeError('bad type')
4023 for i in range(3):
4024 exc = ExceptionGroup('exc', [ValueError(-i), exc, ValueError(i)])
4025
4026 teg = traceback.TracebackException.from_exception(exc, max_group_depth=2)
4027 formatted = ''.join(teg.format()).split('\n')
4028
4029 expected = [
4030 ' | ExceptionGroup: exc (3 sub-exceptions)',
4031 ' +-+---------------- 1 ----------------',
4032 ' | ValueError: -2',
4033 ' +---------------- 2 ----------------',
4034 ' | ExceptionGroup: exc (3 sub-exceptions)',
4035 ' +-+---------------- 1 ----------------',
4036 ' | ValueError: -1',
4037 ' +---------------- 2 ----------------',
4038 ' | ... (max_group_depth is 2)',
4039 ' +---------------- 3 ----------------',
4040 ' | ValueError: 1',
4041 ' +------------------------------------',
4042 ' +---------------- 3 ----------------',
4043 ' | ValueError: 2',
4044 ' +------------------------------------',
4045 '']
4046
4047 self.assertEqual(formatted, expected)
4048
4049 def test_comparison(self):
4050 try:
4051 raise self.eg
4052 except ExceptionGroup as e:
4053 exc = e
4054 for _ in range(5):
4055 try:
4056 raise exc
4057 except Exception as e:
4058 exc_obj = e
4059 exc = traceback.TracebackException.from_exception(exc_obj)
4060 exc2 = traceback.TracebackException.from_exception(exc_obj)
4061 exc3 = traceback.TracebackException.from_exception(exc_obj, limit=300)
4062 ne = traceback.TracebackException.from_exception(exc_obj, limit=3)
4063 self.assertIsNot(exc, exc2)
4064 self.assertEqual(exc, exc2)
4065 self.assertEqual(exc, exc3)
4066 self.assertNotEqual(exc, ne)
4067 self.assertNotEqual(exc, object())
4068 self.assertEqual(exc, ALWAYS_EQ)
4069
4070 def test_dont_swallow_subexceptions_of_falsey_exceptiongroup(self):
4071 # see gh-132308: Ensure that subexceptions of exception groups
4072 # that evaluate as falsey are displayed in the output. For falsey term,
4073 # see https://docs.python.org/3/library/stdtypes.html#truth-value-testing.
4074
4075 try:
4076 raise FalseyExceptionGroup("Gih", (KeyError(), NameError()))
4077 except Exception as ee:
4078 str_exc = ''.join(traceback.format_exception(ee))
4079 self.assertIn('+---------------- 1 ----------------', str_exc)
4080 self.assertIn('+---------------- 2 ----------------', str_exc)
4081
4082 # Test with a falsey exception, in last position, as sub-exceptions.
4083 msg = 'bool'
4084 try:
4085 raise FalseyExceptionGroup("Gah", (KeyError(), FalseyException(msg)))
4086 except Exception as ee:
4087 str_exc = traceback.format_exception(ee)
4088 self.assertIn(f'{FalseyException.__name__}: {msg}', str_exc[-2])
4089
4090
4091 global_for_suggestions = None
4092
4093
4094 class SuggestionFormattingTestBase:
4095 def get_suggestion(self, obj, attr_name=None):
4096 if attr_name is not None:
4097 def callable():
4098 getattr(obj, attr_name)
4099 else:
4100 callable = obj
4101
4102 result_lines = self.get_exception(
4103 callable, slice_start=-1, slice_end=None
4104 )
4105 return result_lines[0]
4106
4107 def test_getattr_suggestions(self):
4108 class Substitution:
4109 noise = more_noise = a = bc = None
4110 blech = None
4111
4112 class Elimination:
4113 noise = more_noise = a = bc = None
4114 blch = None
4115
4116 class Addition:
4117 noise = more_noise = a = bc = None
4118 bluchin = None
4119
4120 class SubstitutionOverElimination:
4121 blach = None
4122 bluc = None
4123
4124 class SubstitutionOverAddition:
4125 blach = None
4126 bluchi = None
4127
4128 class EliminationOverAddition:
4129 blucha = None
4130 bluc = None
4131
4132 class CaseChangeOverSubstitution:
4133 Luch = None
4134 fluch = None
4135 BLuch = None
4136
4137 for cls, suggestion in [
4138 (Addition, "'bluchin'?"),
4139 (Substitution, "'blech'?"),
4140 (Elimination, "'blch'?"),
4141 (Addition, "'bluchin'?"),
4142 (SubstitutionOverElimination, "'blach'?"),
4143 (SubstitutionOverAddition, "'blach'?"),
4144 (EliminationOverAddition, "'bluc'?"),
4145 (CaseChangeOverSubstitution, "'BLuch'?"),
4146 ]:
4147 actual = self.get_suggestion(cls(), 'bluch')
4148 self.assertIn(suggestion, actual)
4149
4150 def test_getattr_suggestions_underscored(self):
4151 class A:
4152 bluch = None
4153
4154 self.assertIn("'bluch'", self.get_suggestion(A(), 'blach'))
4155 self.assertIn("'bluch'", self.get_suggestion(A(), '_luch'))
4156 self.assertIn("'bluch'", self.get_suggestion(A(), '_bluch'))
4157
4158 class B:
4159 _bluch = None
4160 def method(self, name):
4161 getattr(self, name)
4162
4163 self.assertIn("'_bluch'", self.get_suggestion(B(), '_blach'))
4164 self.assertIn("'_bluch'", self.get_suggestion(B(), '_luch'))
4165 self.assertNotIn("'_bluch'", self.get_suggestion(B(), 'bluch'))
4166
4167 self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, '_blach')))
4168 self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, '_luch')))
4169 self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, 'bluch')))
4170
4171 def test_getattr_suggestions_with_custom___dir__(self):
4172 class M(type):
4173 def __dir__(cls):
4174 return [None, "fox"]
4175
4176 class C0:
4177 def __dir__(self):
4178 return [..., "bluch"]
4179
4180 class C1(C0, metaclass=M):
4181 pass
4182
4183 self.assertNotIn("'bluch'", self.get_suggestion(C0, "blach"))
4184 self.assertIn("'bluch'", self.get_suggestion(C0(), "blach"))
4185
4186 self.assertIn("'fox'", self.get_suggestion(C1, "foo"))
4187 self.assertNotIn("'fox'", self.get_suggestion(C1(), "foo"))
4188
4189 self.assertNotIn("'bluch'", self.get_suggestion(C1, "blach"))
4190 self.assertIn("'bluch'", self.get_suggestion(C1(), "blach"))
4191
4192 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
4193 class A:
4194 blech = None
4195
4196 actual = self.get_suggestion(A(), 'somethingverywrong')
4197 self.assertNotIn("blech", actual)
4198
4199 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
4200 class MyClass:
4201 vvv = mom = w = id = pytho = None
4202
4203 for name in ("b", "v", "m", "py"):
4204 with self.subTest(name=name):
4205 actual = self.get_suggestion(MyClass, name)
4206 self.assertNotIn("Did you mean", actual)
4207 self.assertNotIn("'vvv", actual)
4208 self.assertNotIn("'mom'", actual)
4209 self.assertNotIn("'id'", actual)
4210 self.assertNotIn("'w'", actual)
4211 self.assertNotIn("'pytho'", actual)
4212
4213 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
4214 class A:
4215 blech = None
4216 # A class with a very big __dict__ will not be considered
4217 # for suggestions.
4218 for index in range(2000):
4219 setattr(A, f"index_{index}", None)
4220
4221 actual = self.get_suggestion(A(), 'bluch')
4222 self.assertNotIn("blech", actual)
4223
4224 def test_getattr_suggestions_no_args(self):
4225 class A:
4226 blech = None
4227 def __getattr__(self, attr):
4228 raise AttributeError()
4229
4230 actual = self.get_suggestion(A(), 'bluch')
4231 self.assertIn("blech", actual)
4232
4233 class A:
4234 blech = None
4235 def __getattr__(self, attr):
4236 raise AttributeError
4237
4238 actual = self.get_suggestion(A(), 'bluch')
4239 self.assertIn("blech", actual)
4240
4241 def test_getattr_suggestions_invalid_args(self):
4242 class NonStringifyClass:
4243 __str__ = None
4244 __repr__ = None
4245
4246 class A:
4247 blech = None
4248 def __getattr__(self, attr):
4249 raise AttributeError(NonStringifyClass())
4250
4251 class B:
4252 blech = None
4253 def __getattr__(self, attr):
4254 raise AttributeError("Error", 23)
4255
4256 class C:
4257 blech = None
4258 def __getattr__(self, attr):
4259 raise AttributeError(23)
4260
4261 for cls in [A, B, C]:
4262 actual = self.get_suggestion(cls(), 'bluch')
4263 self.assertIn("blech", actual)
4264
4265 def test_getattr_suggestions_for_same_name(self):
4266 class A:
4267 def __dir__(self):
4268 return ['blech']
4269 actual = self.get_suggestion(A(), 'blech')
4270 self.assertNotIn("Did you mean", actual)
4271
4272 def test_attribute_error_with_failing_dict(self):
4273 class T:
4274 bluch = 1
4275 def __dir__(self):
4276 raise AttributeError("oh no!")
4277
4278 actual = self.get_suggestion(T(), 'blich')
4279 self.assertNotIn("blech", actual)
4280 self.assertNotIn("oh no!", actual)
4281
4282 def test_attribute_error_with_non_string_candidates(self):
4283 class T:
4284 bluch = 1
4285
4286 instance = T()
4287 instance.__dict__[0] = 1
4288 actual = self.get_suggestion(instance, 'blich')
4289 self.assertIn("bluch", actual)
4290
4291 def test_attribute_error_with_bad_name(self):
4292 def raise_attribute_error_with_bad_name():
4293 raise AttributeError(name=12, obj=23)
4294
4295 result_lines = self.get_exception(
4296 raise_attribute_error_with_bad_name, slice_start=-1, slice_end=None
4297 )
4298 self.assertNotIn("?", result_lines[-1])
4299
4300 def test_attribute_error_inside_nested_getattr(self):
4301 class A:
4302 bluch = 1
4303
4304 class B:
4305 def __getattribute__(self, attr):
4306 a = A()
4307 return a.blich
4308
4309 actual = self.get_suggestion(B(), 'something')
4310 self.assertIn("Did you mean", actual)
4311 self.assertIn("bluch", actual)
4312
4313 def make_module(self, code):
4314 tmpdir = Path(tempfile.mkdtemp())
4315 self.addCleanup(shutil.rmtree, tmpdir)
4316
4317 sys.path.append(str(tmpdir))
4318 self.addCleanup(sys.path.pop)
4319
4320 mod_name = ''.join(random.choices(string.ascii_letters, k=16))
4321 module = tmpdir / (mod_name + ".py")
4322 module.write_text(code)
4323
4324 return mod_name
4325
4326 def get_import_from_suggestion(self, code, name):
4327 modname = self.make_module(code)
4328
4329 def callable():
4330 try:
4331 exec(f"from {modname} import {name}")
4332 except ImportError as e:
4333 raise e from None
4334 except Exception as e:
4335 self.fail(f"Expected ImportError but got {type(e)}")
4336 self.addCleanup(forget, modname)
4337
4338 result_lines = self.get_exception(
4339 callable, slice_start=-1, slice_end=None
4340 )
4341 return result_lines[0]
4342
4343 def test_import_from_suggestions(self):
4344 substitution = textwrap.dedent("""\
4345 noise = more_noise = a = bc = None
4346 blech = None
4347 """)
4348
4349 elimination = textwrap.dedent("""
4350 noise = more_noise = a = bc = None
4351 blch = None
4352 """)
4353
4354 addition = textwrap.dedent("""
4355 noise = more_noise = a = bc = None
4356 bluchin = None
4357 """)
4358
4359 substitutionOverElimination = textwrap.dedent("""
4360 blach = None
4361 bluc = None
4362 """)
4363
4364 substitutionOverAddition = textwrap.dedent("""
4365 blach = None
4366 bluchi = None
4367 """)
4368
4369 eliminationOverAddition = textwrap.dedent("""
4370 blucha = None
4371 bluc = None
4372 """)
4373
4374 caseChangeOverSubstitution = textwrap.dedent("""
4375 Luch = None
4376 fluch = None
4377 BLuch = None
4378 """)
4379
4380 for code, suggestion in [
4381 (addition, "'bluchin'?"),
4382 (substitution, "'blech'?"),
4383 (elimination, "'blch'?"),
4384 (addition, "'bluchin'?"),
4385 (substitutionOverElimination, "'blach'?"),
4386 (substitutionOverAddition, "'blach'?"),
4387 (eliminationOverAddition, "'bluc'?"),
4388 (caseChangeOverSubstitution, "'BLuch'?"),
4389 ]:
4390 actual = self.get_import_from_suggestion(code, 'bluch')
4391 self.assertIn(suggestion, actual)
4392
4393 def test_import_from_suggestions_underscored(self):
4394 code = "bluch = None"
4395 self.assertIn("'bluch'", self.get_import_from_suggestion(code, 'blach'))
4396 self.assertIn("'bluch'", self.get_import_from_suggestion(code, '_luch'))
4397 self.assertIn("'bluch'", self.get_import_from_suggestion(code, '_bluch'))
4398
4399 code = "_bluch = None"
4400 self.assertIn("'_bluch'", self.get_import_from_suggestion(code, '_blach'))
4401 self.assertIn("'_bluch'", self.get_import_from_suggestion(code, '_luch'))
4402 self.assertNotIn("'_bluch'", self.get_import_from_suggestion(code, 'bluch'))
4403
4404 def test_import_from_suggestions_non_string(self):
4405 modWithNonStringAttr = textwrap.dedent("""\
4406 globals()[0] = 1
4407 bluch = 1
4408 """)
4409 self.assertIn("'bluch'", self.get_import_from_suggestion(modWithNonStringAttr, 'blech'))
4410
4411 def test_import_from_suggestions_do_not_trigger_for_long_attributes(self):
4412 code = "blech = None"
4413
4414 actual = self.get_suggestion(code, 'somethingverywrong')
4415 self.assertNotIn("blech", actual)
4416
4417 def test_import_from_error_bad_suggestions_do_not_trigger_for_small_names(self):
4418 code = "vvv = mom = w = id = pytho = None"
4419
4420 for name in ("b", "v", "m", "py"):
4421 with self.subTest(name=name):
4422 actual = self.get_import_from_suggestion(code, name)
4423 self.assertNotIn("Did you mean", actual)
4424 self.assertNotIn("'vvv'", actual)
4425 self.assertNotIn("'mom'", actual)
4426 self.assertNotIn("'id'", actual)
4427 self.assertNotIn("'w'", actual)
4428 self.assertNotIn("'pytho'", actual)
4429
4430 def test_import_from_suggestions_do_not_trigger_for_big_namespaces(self):
4431 # A module with lots of names will not be considered for suggestions.
4432 chunks = [f"index_{index} = " for index in range(200)]
4433 chunks.append(" None")
4434 code = " ".join(chunks)
4435 actual = self.get_import_from_suggestion(code, 'bluch')
4436 self.assertNotIn("blech", actual)
4437
4438 def test_import_from_error_with_bad_name(self):
4439 def raise_attribute_error_with_bad_name():
4440 raise ImportError(name=12, obj=23, name_from=11)
4441
4442 result_lines = self.get_exception(
4443 raise_attribute_error_with_bad_name, slice_start=-1, slice_end=None
4444 )
4445 self.assertNotIn("?", result_lines[-1])
4446
4447 def test_name_error_suggestions(self):
4448 def Substitution():
4449 noise = more_noise = a = bc = None
4450 blech = None
4451 print(bluch)
4452
4453 def Elimination():
4454 noise = more_noise = a = bc = None
4455 blch = None
4456 print(bluch)
4457
4458 def Addition():
4459 noise = more_noise = a = bc = None
4460 bluchin = None
4461 print(bluch)
4462
4463 def SubstitutionOverElimination():
4464 blach = None
4465 bluc = None
4466 print(bluch)
4467
4468 def SubstitutionOverAddition():
4469 blach = None
4470 bluchi = None
4471 print(bluch)
4472
4473 def EliminationOverAddition():
4474 blucha = None
4475 bluc = None
4476 print(bluch)
4477
4478 for func, suggestion in [(Substitution, "'blech'?"),
4479 (Elimination, "'blch'?"),
4480 (Addition, "'bluchin'?"),
4481 (EliminationOverAddition, "'blucha'?"),
4482 (SubstitutionOverElimination, "'blach'?"),
4483 (SubstitutionOverAddition, "'blach'?")]:
4484 actual = self.get_suggestion(func)
4485 self.assertIn(suggestion, actual)
4486
4487 def test_name_error_suggestions_from_globals(self):
4488 def func():
4489 print(global_for_suggestio)
4490 actual = self.get_suggestion(func)
4491 self.assertIn("'global_for_suggestions'?", actual)
4492
4493 def test_name_error_suggestions_from_builtins(self):
4494 def func():
4495 print(ZeroDivisionErrrrr)
4496 actual = self.get_suggestion(func)
4497 self.assertIn("'ZeroDivisionError'?", actual)
4498
4499 def test_name_error_suggestions_from_builtins_when_builtins_is_module(self):
4500 def func():
4501 custom_globals = globals().copy()
4502 custom_globals["__builtins__"] = builtins
4503 print(eval("ZeroDivisionErrrrr", custom_globals))
4504 actual = self.get_suggestion(func)
4505 self.assertIn("'ZeroDivisionError'?", actual)
4506
4507 def test_name_error_suggestions_with_non_string_candidates(self):
4508 def func():
4509 abc = 1
4510 custom_globals = globals().copy()
4511 custom_globals[0] = 1
4512 print(eval("abv", custom_globals, locals()))
4513 actual = self.get_suggestion(func)
4514 self.assertIn("abc", actual)
4515
4516 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
4517 def func():
4518 somethingverywronghehehehehehe = None
4519 print(somethingverywronghe)
4520 actual = self.get_suggestion(func)
4521 self.assertNotIn("somethingverywronghehe", actual)
4522
4523 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
4524
4525 def f_b():
4526 vvv = mom = w = id = pytho = None
4527 b
4528
4529 def f_v():
4530 vvv = mom = w = id = pytho = None
4531 v
4532
4533 def f_m():
4534 vvv = mom = w = id = pytho = None
4535 m
4536
4537 def f_py():
4538 vvv = mom = w = id = pytho = None
4539 py
4540
4541 for name, func in (("b", f_b), ("v", f_v), ("m", f_m), ("py", f_py)):
4542 with self.subTest(name=name):
4543 actual = self.get_suggestion(func)
4544 self.assertNotIn("you mean", actual)
4545 self.assertNotIn("vvv", actual)
4546 self.assertNotIn("mom", actual)
4547 self.assertNotIn("'id'", actual)
4548 self.assertNotIn("'w'", actual)
4549 self.assertNotIn("'pytho'", actual)
4550
4551 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
4552 def func():
4553 # Mutating locals() is unreliable, so we need to do it by hand
4554 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
4555 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
4556 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
4557 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
4558 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
4559 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
4560 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
4561 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
4562 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
4563 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
4564 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
4565 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
4566 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
4567 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
4568 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
4569 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
4570 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
4571 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
4572 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
4573 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
4574 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
4575 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
4576 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
4577 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
4578 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
4579 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
4580 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
4581 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
4582 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
4583 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
4584 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
4585 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
4586 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
4587 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
4588 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
4589 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
4590 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
4591 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
4592 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
4593 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
4594 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
4595 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
4596 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
4597 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
4598 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
4599 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
4600 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
4601 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
4602 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
4603 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
4604 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
4605 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
4606 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
4607 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
4608 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
4609 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
4610 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
4611 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
4612 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
4613 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
4614 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
4615 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
4616 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
4617 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
4618 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
4619 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
4620 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
4621 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
4622 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
4623 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
4624 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
4625 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
4626 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
4627 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
4628 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
4629 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
4630 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
4631 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
4632 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
4633 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
4634 = None
4635 print(a0)
4636
4637 actual = self.get_suggestion(func)
4638 self.assertNotRegex(actual, r"NameError.*a1")
4639
4640 def test_name_error_with_custom_exceptions(self):
4641 def func():
4642 blech = None
4643 raise NameError()
4644
4645 actual = self.get_suggestion(func)
4646 self.assertNotIn("blech", actual)
4647
4648 def func():
4649 blech = None
4650 raise NameError
4651
4652 actual = self.get_suggestion(func)
4653 self.assertNotIn("blech", actual)
4654
4655 def test_name_error_with_instance(self):
4656 class A:
4657 def __init__(self):
4658 self.blech = None
4659 def foo(self):
4660 blich = 1
4661 x = blech
4662
4663 instance = A()
4664 actual = self.get_suggestion(instance.foo)
4665 self.assertIn("self.blech", actual)
4666
4667 def test_unbound_local_error_with_instance(self):
4668 class A:
4669 def __init__(self):
4670 self.blech = None
4671 def foo(self):
4672 blich = 1
4673 x = blech
4674 blech = 1
4675
4676 instance = A()
4677 actual = self.get_suggestion(instance.foo)
4678 self.assertNotIn("self.blech", actual)
4679
4680 def test_unbound_local_error_with_side_effect(self):
4681 # gh-132385
4682 class A:
4683 def __getattr__(self, key):
4684 if key == 'foo':
4685 raise AttributeError('foo')
4686 if key == 'spam':
4687 raise ValueError('spam')
4688
4689 def bar(self):
4690 foo
4691 def baz(self):
4692 spam
4693
4694 suggestion = self.get_suggestion(A().bar)
4695 self.assertNotIn('self.', suggestion)
4696 self.assertIn("'foo'", suggestion)
4697
4698 suggestion = self.get_suggestion(A().baz)
4699 self.assertNotIn('self.', suggestion)
4700 self.assertIn("'spam'", suggestion)
4701
4702 def test_unbound_local_error_does_not_match(self):
4703 def func():
4704 something = 3
4705 print(somethong)
4706 somethong = 3
4707
4708 actual = self.get_suggestion(func)
4709 self.assertNotIn("something", actual)
4710
4711 def test_name_error_for_stdlib_modules(self):
4712 def func():
4713 stream = io.StringIO()
4714
4715 actual = self.get_suggestion(func)
4716 self.assertIn("forget to import 'io'", actual)
4717
4718 def test_name_error_for_private_stdlib_modules(self):
4719 def func():
4720 stream = _io.StringIO()
4721
4722 actual = self.get_suggestion(func)
4723 self.assertIn("forget to import '_io'", actual)
4724
4725
4726
4727 class PurePythonSuggestionFormattingTests(
4728 PurePythonExceptionFormattingMixin,
4729 SuggestionFormattingTestBase,
4730 unittest.TestCase,
4731 ):
4732 """
4733 Same set of tests as above using the pure Python implementation of
4734 traceback printing in traceback.py.
4735 """
4736
4737
4738 @cpython_only
4739 class CPythonSuggestionFormattingTests(
4740 CAPIExceptionFormattingMixin,
4741 SuggestionFormattingTestBase,
4742 unittest.TestCase,
4743 ):
4744 """
4745 Same set of tests as above but with Python's internal traceback printing.
4746 """
4747
4748
4749 class MiscTest(unittest.TestCase):
4750
4751 def test_all(self):
4752 expected = set()
4753 for name in dir(traceback):
4754 if name.startswith('_'):
4755 continue
4756 module_object = getattr(traceback, name)
4757 if getattr(module_object, '__module__', None) == 'traceback':
4758 expected.add(name)
4759 self.assertCountEqual(traceback.__all__, expected)
4760
4761 def test_levenshtein_distance(self):
4762 # copied from _testinternalcapi.test_edit_cost
4763 # to also exercise the Python implementation
4764
4765 def CHECK(a, b, expected):
4766 actual = traceback._levenshtein_distance(a, b, 4044)
4767 self.assertEqual(actual, expected)
4768
4769 CHECK("", "", 0)
4770 CHECK("", "a", 2)
4771 CHECK("a", "A", 1)
4772 CHECK("Apple", "Aple", 2)
4773 CHECK("Banana", "B@n@n@", 6)
4774 CHECK("Cherry", "Cherry!", 2)
4775 CHECK("---0---", "------", 2)
4776 CHECK("abc", "y", 6)
4777 CHECK("aa", "bb", 4)
4778 CHECK("aaaaa", "AAAAA", 5)
4779 CHECK("wxyz", "wXyZ", 2)
4780 CHECK("wxyz", "wXyZ123", 8)
4781 CHECK("Python", "Java", 12)
4782 CHECK("Java", "C#", 8)
4783 CHECK("AbstractFoobarManager", "abstract_foobar_manager", 3+2*2)
4784 CHECK("CPython", "PyPy", 10)
4785 CHECK("CPython", "pypy", 11)
4786 CHECK("AttributeError", "AttributeErrop", 2)
4787 CHECK("AttributeError", "AttributeErrorTests", 10)
4788 CHECK("ABA", "AAB", 4)
4789
4790 @support.requires_resource('cpu')
4791 def test_levenshtein_distance_short_circuit(self):
4792 if not LEVENSHTEIN_DATA_FILE.is_file():
4793 self.fail(
4794 f"{LEVENSHTEIN_DATA_FILE} is missing."
4795 f" Run `make regen-test-levenshtein`"
4796 )
4797
4798 with LEVENSHTEIN_DATA_FILE.open("r") as f:
4799 examples = json.load(f)
4800 for a, b, expected in examples:
4801 res1 = traceback._levenshtein_distance(a, b, 1000)
4802 self.assertEqual(res1, expected, msg=(a, b))
4803
4804 for threshold in [expected, expected + 1, expected + 2]:
4805 # big enough thresholds shouldn't change the result
4806 res2 = traceback._levenshtein_distance(a, b, threshold)
4807 self.assertEqual(res2, expected, msg=(a, b, threshold))
4808
4809 for threshold in range(expected):
4810 # for small thresholds, the only piece of information
4811 # we receive is "strings not close enough".
4812 res3 = traceback._levenshtein_distance(a, b, threshold)
4813 self.assertGreater(res3, threshold, msg=(a, b, threshold))
4814
4815 @cpython_only
4816 def test_suggestions_extension(self):
4817 # Check that the C extension is available
4818 import _suggestions
4819
4820 self.assertEqual(
4821 _suggestions._generate_suggestions(
4822 ["hello", "world"],
4823 "hell"
4824 ),
4825 "hello"
4826 )
4827 self.assertEqual(
4828 _suggestions._generate_suggestions(
4829 ["hovercraft"],
4830 "eels"
4831 ),
4832 None
4833 )
4834
4835 # gh-131936: _generate_suggestions() doesn't accept list subclasses
4836 class MyList(list):
4837 pass
4838
4839 with self.assertRaises(TypeError):
4840 _suggestions._generate_suggestions(MyList(), "")
4841
4842
4843
4844
4845 class TestColorizedTraceback(unittest.TestCase):
4846 maxDiff = None
4847
4848 def test_colorized_traceback(self):
4849 def foo(*args):
4850 x = {'a':{'b': None}}
4851 y = x['a']['b']['c']
4852
4853 def baz2(*args):
4854 return (lambda *args: foo(*args))(1,2,3,4)
4855
4856 def baz1(*args):
4857 return baz2(1,2,3,4)
4858
4859 def bar():
4860 return baz1(1,
4861 2,3
4862 ,4)
4863 try:
4864 bar()
4865 except Exception as e:
4866 exc = traceback.TracebackException.from_exception(
4867 e, capture_locals=True
4868 )
4869 lines = "".join(exc.format(colorize=True))
4870 red = colors["e"]
4871 boldr = colors["E"]
4872 reset = colors["z"]
4873 self.assertIn("y = " + red + "x['a']['b']" + reset + boldr + "['c']" + reset, lines)
4874 self.assertIn("return " + red + "(lambda *args: foo(*args))" + reset + boldr + "(1,2,3,4)" + reset, lines)
4875 self.assertIn("return (lambda *args: " + red + "foo" + reset + boldr + "(*args)" + reset + ")(1,2,3,4)", lines)
4876 self.assertIn("return baz2(1,2,3,4)", lines)
4877 self.assertIn("return baz1(1,\n 2,3\n ,4)", lines)
4878 self.assertIn(red + "bar" + reset + boldr + "()" + reset, lines)
4879
4880 def test_colorized_syntax_error(self):
4881 try:
4882 compile("a $ b", "<string>", "exec")
4883 except SyntaxError as e:
4884 exc = traceback.TracebackException.from_exception(
4885 e, capture_locals=True
4886 )
4887 actual = "".join(exc.format(colorize=True))
4888 def expected(t, m, fn, l, f, E, e, z):
4889 return "".join(
4890 [
4891 f' File {fn}"<string>"{z}, line {l}1{z}\n',
4892 f' a {E}${z} b\n',
4893 f' {E}^{z}\n',
4894 f'{t}SyntaxError{z}: {m}invalid syntax{z}\n'
4895 ]
4896 )
4897 self.assertIn(expected(**colors), actual)
4898
4899 def test_colorized_traceback_is_the_default(self):
4900 def foo():
4901 1/0
4902
4903 from _testcapi import exception_print
4904 try:
4905 foo()
4906 self.fail("No exception thrown.")
4907 except Exception as e:
4908 with captured_output("stderr") as tbstderr:
4909 with unittest.mock.patch('_colorize.can_colorize', return_value=True):
4910 exception_print(e)
4911 actual = tbstderr.getvalue().splitlines()
4912
4913 lno_foo = foo.__code__.co_firstlineno
4914 def expected(t, m, fn, l, f, E, e, z):
4915 return [
4916 'Traceback (most recent call last):',
4917 f' File {fn}"{__file__}"{z}, '
4918 f'line {l}{lno_foo+5}{z}, in {f}test_colorized_traceback_is_the_default{z}',
4919 f' {e}foo{z}{E}(){z}',
4920 f' {e}~~~{z}{E}^^{z}',
4921 f' File {fn}"{__file__}"{z}, '
4922 f'line {l}{lno_foo+1}{z}, in {f}foo{z}',
4923 f' {e}1{z}{E}/{z}{e}0{z}',
4924 f' {e}~{z}{E}^{z}{e}~{z}',
4925 f'{t}ZeroDivisionError{z}: {m}division by zero{z}',
4926 ]
4927 self.assertEqual(actual, expected(**colors))
4928
4929 def test_colorized_traceback_from_exception_group(self):
4930 def foo():
4931 exceptions = []
4932 try:
4933 1 / 0
4934 except ZeroDivisionError as inner_exc:
4935 exceptions.append(inner_exc)
4936 raise ExceptionGroup("test", exceptions)
4937
4938 try:
4939 foo()
4940 except Exception as e:
4941 exc = traceback.TracebackException.from_exception(
4942 e, capture_locals=True
4943 )
4944
4945 lno_foo = foo.__code__.co_firstlineno
4946 actual = "".join(exc.format(colorize=True)).splitlines()
4947 def expected(t, m, fn, l, f, E, e, z):
4948 return [
4949 f" + Exception Group Traceback (most recent call last):",
4950 f' | File {fn}"{__file__}"{z}, line {l}{lno_foo+9}{z}, in {f}test_colorized_traceback_from_exception_group{z}',
4951 f' | {e}foo{z}{E}(){z}',
4952 f' | {e}~~~{z}{E}^^{z}',
4953 f" | e = ExceptionGroup('test', [ZeroDivisionError('division by zero')])",
4954 f" | foo = {foo}",
4955 f' | self = <{__name__}.TestColorizedTraceback testMethod=test_colorized_traceback_from_exception_group>',
4956 f' | File {fn}"{__file__}"{z}, line {l}{lno_foo+6}{z}, in {f}foo{z}',
4957 f' | raise ExceptionGroup("test", exceptions)',
4958 f" | exceptions = [ZeroDivisionError('division by zero')]",
4959 f' | {t}ExceptionGroup{z}: {m}test (1 sub-exception){z}',
4960 f' +-+---------------- 1 ----------------',
4961 f' | Traceback (most recent call last):',
4962 f' | File {fn}"{__file__}"{z}, line {l}{lno_foo+3}{z}, in {f}foo{z}',
4963 f' | {e}1 {z}{E}/{z}{e} 0{z}',
4964 f' | {e}~~{z}{E}^{z}{e}~~{z}',
4965 f" | exceptions = [ZeroDivisionError('division by zero')]",
4966 f' | {t}ZeroDivisionError{z}: {m}division by zero{z}',
4967 f' +------------------------------------',
4968 ]
4969 self.assertEqual(actual, expected(**colors))
4970
4971 if __name__ == "__main__":
4972 unittest.main()