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