| 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 unittest |
| 10 |
import re |
| 11 |
from test import support |
| 12 |
from test.support import (Error, captured_output, cpython_only, ALWAYS_EQ, |
| 13 |
requires_debug_ranges, has_no_debug_ranges, |
| 14 |
requires_subprocess, impl_detail) |
| 15 |
from test.support.os_helper import TESTFN, unlink |
| 16 |
from test.support.script_helper import assert_python_ok, assert_python_failure |
| 17 |
|
| 18 |
import os |
| 19 |
import textwrap |
| 20 |
import traceback |
| 21 |
from functools import partial |
| 22 |
|
| 23 |
MODULE_PREFIX = f'{__name__}.' if __name__ == '__main__' else '' |
| 24 |
|
| 25 |
test_code = namedtuple('code', ['co_filename', 'co_name']) |
| 26 |
test_code.co_positions = lambda _: iter([(6, 6, 0, 0)]) |
| 27 |
test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals']) |
| 28 |
test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next', 'tb_lasti']) |
| 29 |
|
| 30 |
|
| 31 |
def fixme(reason): |
| 32 |
|
| 33 |
def decorator(test): |
| 34 |
return cpython_only(test) |
| 35 |
return decorator |
| 36 |
|
| 37 |
class TracebackCases(unittest.TestCase): |
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
def get_exception_format(self, func, exc): |
| 42 |
try: |
| 43 |
func() |
| 44 |
except exc as value: |
| 45 |
return traceback.format_exception_only(exc, value) |
| 46 |
else: |
| 47 |
raise ValueError("call did not raise exception") |
| 48 |
|
| 49 |
def syntax_error_with_caret(self): |
| 50 |
compile("def fact(x):\n\treturn x!\n", "?", "exec") |
| 51 |
|
| 52 |
def syntax_error_with_caret_2(self): |
| 53 |
compile("1 +\n", "?", "exec") |
| 54 |
|
| 55 |
def syntax_error_with_caret_range(self): |
| 56 |
compile("f(x, y for y in range(30), z)", "?", "exec") |
| 57 |
|
| 58 |
def syntax_error_bad_indentation(self): |
| 59 |
compile("def spam():\n print(1)\n print(2)", "?", "exec") |
| 60 |
|
| 61 |
def syntax_error_with_caret_non_ascii(self): |
| 62 |
compile('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', "?", "exec") |
| 63 |
|
| 64 |
def syntax_error_bad_indentation2(self): |
| 65 |
compile(" print(2)", "?", "exec") |
| 66 |
|
| 67 |
def tokenizer_error_with_caret_range(self): |
| 68 |
compile("blech ( ", "?", "exec") |
| 69 |
|
| 70 |
def test_caret(self): |
| 71 |
err = self.get_exception_format(self.syntax_error_with_caret, |
| 72 |
SyntaxError) |
| 73 |
self.assertEqual(len(err), 4) |
| 74 |
self.assertTrue(err[1].strip() == "return x!") |
| 75 |
self.assertIn("^", err[2]) |
| 76 |
self.assertEqual(err[1].find("!"), err[2].find("^")) |
| 77 |
self.assertEqual(err[2].count("^"), 1) |
| 78 |
|
| 79 |
err = self.get_exception_format(self.syntax_error_with_caret_2, |
| 80 |
SyntaxError) |
| 81 |
self.assertIn("^", err[2]) |
| 82 |
self.assertEqual(err[2].count('\n'), 1) |
| 83 |
self.assertEqual(err[1].find("+") + 1, err[2].find("^")) |
| 84 |
self.assertEqual(err[2].count("^"), 1) |
| 85 |
|
| 86 |
err = self.get_exception_format(self.syntax_error_with_caret_non_ascii, |
| 87 |
SyntaxError) |
| 88 |
self.assertIn("^", err[2]) |
| 89 |
self.assertEqual(err[2].count('\n'), 1) |
| 90 |
self.assertEqual(err[1].find("+") + 1, err[2].find("^")) |
| 91 |
self.assertEqual(err[2].count("^"), 1) |
| 92 |
|
| 93 |
err = self.get_exception_format(self.syntax_error_with_caret_range, |
| 94 |
SyntaxError) |
| 95 |
self.assertIn("^", err[2]) |
| 96 |
self.assertEqual(err[2].count('\n'), 1) |
| 97 |
self.assertEqual(err[1].find("y"), err[2].find("^")) |
| 98 |
self.assertEqual(err[2].count("^"), len("y for y in range(30)")) |
| 99 |
|
| 100 |
err = self.get_exception_format(self.tokenizer_error_with_caret_range, |
| 101 |
SyntaxError) |
| 102 |
self.assertIn("^", err[2]) |
| 103 |
self.assertEqual(err[2].count('\n'), 1) |
| 104 |
self.assertEqual(err[1].find("("), err[2].find("^")) |
| 105 |
self.assertEqual(err[2].count("^"), 1) |
| 106 |
|
| 107 |
def test_nocaret(self): |
| 108 |
exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) |
| 109 |
err = traceback.format_exception_only(SyntaxError, exc) |
| 110 |
self.assertEqual(len(err), 3) |
| 111 |
self.assertEqual(err[1].strip(), "bad syntax") |
| 112 |
|
| 113 |
@fixme(reason='no -X nodebug_ranges in PyPy') |
| 114 |
def test_no_caret_with_no_debug_ranges_flag(self): |
| 115 |
|
| 116 |
|
| 117 |
try: |
| 118 |
with open(TESTFN, 'w') as f: |
| 119 |
f.write("x = 1 / 0\n") |
| 120 |
|
| 121 |
_, _, stderr = assert_python_failure( |
| 122 |
'-X', 'no_debug_ranges', TESTFN) |
| 123 |
|
| 124 |
lines = stderr.splitlines() |
| 125 |
self.assertEqual(len(lines), 4) |
| 126 |
self.assertEqual(lines[0], b'Traceback (most recent call last):') |
| 127 |
self.assertIn(b'line 1, in <module>', lines[1]) |
| 128 |
self.assertEqual(lines[2], b' x = 1 / 0') |
| 129 |
self.assertEqual(lines[3], b'ZeroDivisionError: division by zero') |
| 130 |
finally: |
| 131 |
unlink(TESTFN) |
| 132 |
|
| 133 |
@fixme(reason='no -X nodebug_ranges in PyPy') |
| 134 |
def test_no_caret_with_no_debug_ranges_flag_python_traceback(self): |
| 135 |
code = textwrap.dedent(""" |
| 136 |
import traceback |
| 137 |
try: |
| 138 |
x = 1 / 0 |
| 139 |
except: |
| 140 |
traceback.print_exc() |
| 141 |
""") |
| 142 |
try: |
| 143 |
with open(TESTFN, 'w') as f: |
| 144 |
f.write(code) |
| 145 |
|
| 146 |
_, _, stderr = assert_python_ok( |
| 147 |
'-X', 'no_debug_ranges', TESTFN) |
| 148 |
|
| 149 |
lines = stderr.splitlines() |
| 150 |
self.assertEqual(len(lines), 4) |
| 151 |
self.assertEqual(lines[0], b'Traceback (most recent call last):') |
| 152 |
self.assertIn(b'line 4, in <module>', lines[1]) |
| 153 |
self.assertEqual(lines[2], b' x = 1 / 0') |
| 154 |
self.assertEqual(lines[3], b'ZeroDivisionError: division by zero') |
| 155 |
finally: |
| 156 |
unlink(TESTFN) |
| 157 |
|
| 158 |
def test_recursion_error_during_traceback(self): |
| 159 |
code = textwrap.dedent(""" |
| 160 |
import sys |
| 161 |
from weakref import ref |
| 162 |
|
| 163 |
sys.setrecursionlimit(15) |
| 164 |
|
| 165 |
def f(): |
| 166 |
ref(lambda: 0, []) |
| 167 |
f() |
| 168 |
|
| 169 |
try: |
| 170 |
f() |
| 171 |
except RecursionError: |
| 172 |
pass |
| 173 |
""") |
| 174 |
try: |
| 175 |
with open(TESTFN, 'w') as f: |
| 176 |
f.write(code) |
| 177 |
|
| 178 |
rc, _, _ = assert_python_ok(TESTFN) |
| 179 |
self.assertEqual(rc, 0) |
| 180 |
finally: |
| 181 |
unlink(TESTFN) |
| 182 |
|
| 183 |
def test_bad_indentation(self): |
| 184 |
err = self.get_exception_format(self.syntax_error_bad_indentation, |
| 185 |
IndentationError) |
| 186 |
self.assertEqual(len(err), 4) |
| 187 |
self.assertEqual(err[1].strip(), "print(2)") |
| 188 |
self.assertIn("^", err[2]) |
| 189 |
if sys.implementation.name == 'pypy': |
| 190 |
self.assertEqual(err[1].find("p"), err[2].find("^")) |
| 191 |
else: |
| 192 |
self.assertEqual(err[1].find(")") + 1, err[2].find("^")) |
| 193 |
|
| 194 |
|
| 195 |
err = self.get_exception_format(self.syntax_error_bad_indentation2, |
| 196 |
IndentationError) |
| 197 |
self.assertEqual(len(err), 3) |
| 198 |
self.assertEqual(err[1].strip(), "print(2)") |
| 199 |
|
| 200 |
def test_base_exception(self): |
| 201 |
|
| 202 |
e = KeyboardInterrupt() |
| 203 |
lst = traceback.format_exception_only(e.__class__, e) |
| 204 |
self.assertEqual(lst, ['KeyboardInterrupt\n']) |
| 205 |
|
| 206 |
def test_format_exception_only_bad__str__(self): |
| 207 |
class X(Exception): |
| 208 |
def __str__(self): |
| 209 |
1/0 |
| 210 |
err = traceback.format_exception_only(X, X()) |
| 211 |
self.assertEqual(len(err), 1) |
| 212 |
str_value = '<exception str() failed>' |
| 213 |
if X.__module__ in ('__main__', 'builtins'): |
| 214 |
str_name = X.__qualname__ |
| 215 |
else: |
| 216 |
str_name = '.'.join([X.__module__, X.__qualname__]) |
| 217 |
self.assertEqual(err[0], "%s: %s\n" % (str_name, str_value)) |
| 218 |
|
| 219 |
@requires_subprocess() |
| 220 |
def test_encoded_file(self): |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
import sys, subprocess |
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
process = subprocess.Popen([sys.executable, "-c", |
| 230 |
"import sys; print(sys.stdout.encoding)"], |
| 231 |
stdout=subprocess.PIPE, |
| 232 |
stderr=subprocess.STDOUT) |
| 233 |
stdout, stderr = process.communicate() |
| 234 |
output_encoding = str(stdout, 'ascii').splitlines()[0] |
| 235 |
|
| 236 |
def do_test(firstlines, message, charset, lineno): |
| 237 |
|
| 238 |
try: |
| 239 |
with open(TESTFN, "w", encoding=charset) as output: |
| 240 |
output.write("""{0}if 1: |
| 241 |
import traceback; |
| 242 |
raise RuntimeError('{1}') |
| 243 |
""".format(firstlines, message)) |
| 244 |
|
| 245 |
process = subprocess.Popen([sys.executable, TESTFN], |
| 246 |
stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
| 247 |
stdout, stderr = process.communicate() |
| 248 |
stdout = stdout.decode(output_encoding).splitlines() |
| 249 |
finally: |
| 250 |
unlink(TESTFN) |
| 251 |
|
| 252 |
|
| 253 |
encoded_message = message.encode(output_encoding, |
| 254 |
'backslashreplace') |
| 255 |
|
| 256 |
message_ascii = encoded_message.decode(output_encoding) |
| 257 |
|
| 258 |
err_line = "raise RuntimeError('{0}')".format(message_ascii) |
| 259 |
err_msg = "RuntimeError: {0}".format(message_ascii) |
| 260 |
|
| 261 |
self.assertIn(("line %s" % lineno), stdout[1], |
| 262 |
"Invalid line number: {0!r} instead of {1}".format( |
| 263 |
stdout[1], lineno)) |
| 264 |
self.assertTrue(stdout[2].endswith(err_line), |
| 265 |
"Invalid traceback line: {0!r} instead of {1!r}".format( |
| 266 |
stdout[2], err_line)) |
| 267 |
actual_err_msg = stdout[3] |
| 268 |
self.assertTrue(actual_err_msg == err_msg, |
| 269 |
"Invalid error message: {0!r} instead of {1!r}".format( |
| 270 |
actual_err_msg, err_msg)) |
| 271 |
|
| 272 |
do_test("", "foo", "ascii", 3) |
| 273 |
for charset in ("ascii", "iso-8859-1", "utf-8", "GBK"): |
| 274 |
if charset == "ascii": |
| 275 |
text = "foo" |
| 276 |
elif charset == "GBK": |
| 277 |
text = "\u4E02\u5100" |
| 278 |
else: |
| 279 |
text = "h\xe9 ho" |
| 280 |
do_test("# coding: {0}\n".format(charset), |
| 281 |
text, charset, 4) |
| 282 |
do_test("#!shebang\n# coding: {0}\n".format(charset), |
| 283 |
text, charset, 5) |
| 284 |
do_test(" \t\f\n# coding: {0}\n".format(charset), |
| 285 |
text, charset, 5) |
| 286 |
|
| 287 |
do_test("x=0\n# coding: GBK\n", "h\xe9 ho", 'utf-8', 5) |
| 288 |
|
| 289 |
@impl_detail(pypy=False) |
| 290 |
def test_print_traceback_at_exit(self): |
| 291 |
|
| 292 |
|
| 293 |
code = textwrap.dedent(""" |
| 294 |
import sys |
| 295 |
import traceback |
| 296 |
|
| 297 |
class PrintExceptionAtExit(object): |
| 298 |
def __init__(self): |
| 299 |
try: |
| 300 |
x = 1 / 0 |
| 301 |
except Exception: |
| 302 |
self.exc_info = sys.exc_info() |
| 303 |
# self.exc_info[1] (traceback) contains frames: |
| 304 |
# explicitly clear the reference to self in the current |
| 305 |
# frame to break a reference cycle |
| 306 |
self = None |
| 307 |
|
| 308 |
def __del__(self): |
| 309 |
traceback.print_exception(*self.exc_info) |
| 310 |
|
| 311 |
# Keep a reference in the module namespace to call the destructor |
| 312 |
# when the module is unloaded |
| 313 |
obj = PrintExceptionAtExit() |
| 314 |
""") |
| 315 |
rc, stdout, stderr = assert_python_ok('-c', code) |
| 316 |
expected = [b'Traceback (most recent call last):', |
| 317 |
b' File "<string>", line 8, in __init__', |
| 318 |
b'ZeroDivisionError: division by zero'] |
| 319 |
self.assertEqual(stderr.splitlines(), expected) |
| 320 |
|
| 321 |
def test_print_exception(self): |
| 322 |
output = StringIO() |
| 323 |
traceback.print_exception( |
| 324 |
Exception, Exception("projector"), None, file=output |
| 325 |
) |
| 326 |
self.assertEqual(output.getvalue(), "Exception: projector\n") |
| 327 |
|
| 328 |
def test_print_exception_exc(self): |
| 329 |
output = StringIO() |
| 330 |
traceback.print_exception(Exception("projector"), file=output) |
| 331 |
self.assertEqual(output.getvalue(), "Exception: projector\n") |
| 332 |
|
| 333 |
def test_format_exception_exc(self): |
| 334 |
e = Exception("projector") |
| 335 |
output = traceback.format_exception(e) |
| 336 |
self.assertEqual(output, ["Exception: projector\n"]) |
| 337 |
with self.assertRaisesRegex(ValueError, 'Both or neither'): |
| 338 |
traceback.format_exception(e.__class__, e) |
| 339 |
with self.assertRaisesRegex(ValueError, 'Both or neither'): |
| 340 |
traceback.format_exception(e.__class__, tb=e.__traceback__) |
| 341 |
with self.assertRaisesRegex(TypeError, 'positional-only'): |
| 342 |
traceback.format_exception(exc=e) |
| 343 |
|
| 344 |
def test_format_exception_only_exc(self): |
| 345 |
output = traceback.format_exception_only(Exception("projector")) |
| 346 |
self.assertEqual(output, ["Exception: projector\n"]) |
| 347 |
|
| 348 |
def test_exception_is_None(self): |
| 349 |
NONE_EXC_STRING = 'NoneType: None\n' |
| 350 |
excfile = StringIO() |
| 351 |
traceback.print_exception(None, file=excfile) |
| 352 |
self.assertEqual(excfile.getvalue(), NONE_EXC_STRING) |
| 353 |
|
| 354 |
excfile = StringIO() |
| 355 |
traceback.print_exception(None, None, None, file=excfile) |
| 356 |
self.assertEqual(excfile.getvalue(), NONE_EXC_STRING) |
| 357 |
|
| 358 |
excfile = StringIO() |
| 359 |
traceback.print_exc(None, file=excfile) |
| 360 |
self.assertEqual(excfile.getvalue(), NONE_EXC_STRING) |
| 361 |
|
| 362 |
self.assertEqual(traceback.format_exc(None), NONE_EXC_STRING) |
| 363 |
self.assertEqual(traceback.format_exception(None), [NONE_EXC_STRING]) |
| 364 |
self.assertEqual( |
| 365 |
traceback.format_exception(None, None, None), [NONE_EXC_STRING]) |
| 366 |
self.assertEqual( |
| 367 |
traceback.format_exception_only(None), [NONE_EXC_STRING]) |
| 368 |
self.assertEqual( |
| 369 |
traceback.format_exception_only(None, None), [NONE_EXC_STRING]) |
| 370 |
|
| 371 |
def test_signatures(self): |
| 372 |
|
| 373 |
self.assertEqual( |
| 374 |
str(inspect.signature(traceback.print_exception)), |
| 375 |
('(exc, /, value=<implicit>, tb=<implicit>, ' |
| 376 |
'limit=None, file=None, chain=True)')) |
| 377 |
|
| 378 |
self.assertEqual( |
| 379 |
str(inspect.signature(traceback.format_exception)), |
| 380 |
('(exc, /, value=<implicit>, tb=<implicit>, limit=None, ' |
| 381 |
'chain=True, colorize=False)')) |
| 382 |
|
| 383 |
self.assertEqual( |
| 384 |
str(inspect.signature(traceback.format_exception_only)), |
| 385 |
'(exc, /, value=<implicit>, colorize=False)') |
| 386 |
|
| 387 |
|
| 388 |
@fixme(reason='PyPy caret implementation is slightly different') |
| 389 |
@requires_debug_ranges() |
| 390 |
class TracebackErrorLocationCaretTests(unittest.TestCase): |
| 391 |
""" |
| 392 |
Tests for printing code error expressions as part of PEP 657 |
| 393 |
""" |
| 394 |
def get_exception(self, callable): |
| 395 |
try: |
| 396 |
callable() |
| 397 |
self.fail("No exception thrown.") |
| 398 |
except: |
| 399 |
return traceback.format_exc().splitlines()[:-1] |
| 400 |
|
| 401 |
callable_line = get_exception.__code__.co_firstlineno + 2 |
| 402 |
|
| 403 |
def test_basic_caret(self): |
| 404 |
|
| 405 |
|
| 406 |
def f(): |
| 407 |
if True: raise ValueError("basic caret tests") |
| 408 |
|
| 409 |
lineno_f = f.__code__.co_firstlineno |
| 410 |
expected_f = ( |
| 411 |
'Traceback (most recent call last):\n' |
| 412 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 413 |
' callable()\n' |
| 414 |
f' File "{__file__}", line {lineno_f+1}, in f\n' |
| 415 |
' if True: raise ValueError("basic caret tests")\n' |
| 416 |
' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' |
| 417 |
) |
| 418 |
result_lines = self.get_exception(f) |
| 419 |
self.assertEqual(result_lines, expected_f.splitlines()) |
| 420 |
|
| 421 |
def test_line_with_unicode(self): |
| 422 |
|
| 423 |
|
| 424 |
def f_with_unicode(): |
| 425 |
if True: raise ValueError("Ĥellö Wörld") |
| 426 |
|
| 427 |
lineno_f = f_with_unicode.__code__.co_firstlineno |
| 428 |
expected_f = ( |
| 429 |
'Traceback (most recent call last):\n' |
| 430 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 431 |
' callable()\n' |
| 432 |
f' File "{__file__}", line {lineno_f+1}, in f_with_unicode\n' |
| 433 |
' if True: raise ValueError("Ĥellö Wörld")\n' |
| 434 |
' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' |
| 435 |
) |
| 436 |
result_lines = self.get_exception(f_with_unicode) |
| 437 |
self.assertEqual(result_lines, expected_f.splitlines()) |
| 438 |
|
| 439 |
def test_caret_in_type_annotation(self): |
| 440 |
def f_with_type(): |
| 441 |
def foo(a: THIS_DOES_NOT_EXIST ) -> int: |
| 442 |
return 0 |
| 443 |
|
| 444 |
lineno_f = f_with_type.__code__.co_firstlineno |
| 445 |
expected_f = ( |
| 446 |
'Traceback (most recent call last):\n' |
| 447 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 448 |
' callable()\n' |
| 449 |
f' File "{__file__}", line {lineno_f+1}, in f_with_type\n' |
| 450 |
' def foo(a: THIS_DOES_NOT_EXIST ) -> int:\n' |
| 451 |
' ^^^^^^^^^^^^^^^^^^^\n' |
| 452 |
) |
| 453 |
result_lines = self.get_exception(f_with_type) |
| 454 |
self.assertEqual(result_lines, expected_f.splitlines()) |
| 455 |
|
| 456 |
def test_caret_multiline_expression(self): |
| 457 |
|
| 458 |
|
| 459 |
def f_with_multiline(): |
| 460 |
if True: raise ValueError( |
| 461 |
"error over multiple lines" |
| 462 |
) |
| 463 |
|
| 464 |
lineno_f = f_with_multiline.__code__.co_firstlineno |
| 465 |
expected_f = ( |
| 466 |
'Traceback (most recent call last):\n' |
| 467 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 468 |
' callable()\n' |
| 469 |
f' File "{__file__}", line {lineno_f+1}, in f_with_multiline\n' |
| 470 |
' if True: raise ValueError(\n' |
| 471 |
' ^^^^^^^^^^^^^^^^^' |
| 472 |
) |
| 473 |
result_lines = self.get_exception(f_with_multiline) |
| 474 |
self.assertEqual(result_lines, expected_f.splitlines()) |
| 475 |
|
| 476 |
def test_caret_multiline_expression_syntax_error(self): |
| 477 |
|
| 478 |
|
| 479 |
code = textwrap.dedent(""" |
| 480 |
def foo(*args, **kwargs): |
| 481 |
pass |
| 482 |
|
| 483 |
a, b, c = 1, 2, 3 |
| 484 |
|
| 485 |
foo(a, z |
| 486 |
for z in |
| 487 |
range(10), b, c) |
| 488 |
""") |
| 489 |
|
| 490 |
def f_with_multiline(): |
| 491 |
|
| 492 |
return compile(code, "?", "exec") |
| 493 |
|
| 494 |
lineno_f = f_with_multiline.__code__.co_firstlineno |
| 495 |
|
| 496 |
expected_f = ( |
| 497 |
'Traceback (most recent call last):\n' |
| 498 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 499 |
' callable()\n' |
| 500 |
f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n' |
| 501 |
' return compile(code, "?", "exec")\n' |
| 502 |
' ^^^^^^^^^^^^^^^^^^^^^^^^^^\n' |
| 503 |
' File "?", line 7\n' |
| 504 |
' foo(a, z\n' |
| 505 |
' ^' |
| 506 |
) |
| 507 |
|
| 508 |
result_lines = self.get_exception(f_with_multiline) |
| 509 |
self.assertEqual(result_lines, expected_f.splitlines()) |
| 510 |
|
| 511 |
def test_caret_multiline_expression_bin_op(self): |
| 512 |
|
| 513 |
|
| 514 |
def f_with_multiline(): |
| 515 |
return ( |
| 516 |
2 + 1 / |
| 517 |
0 |
| 518 |
) |
| 519 |
|
| 520 |
lineno_f = f_with_multiline.__code__.co_firstlineno |
| 521 |
expected_f = ( |
| 522 |
'Traceback (most recent call last):\n' |
| 523 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 524 |
' callable()\n' |
| 525 |
f' File "{__file__}", line {lineno_f+2}, in f_with_multiline\n' |
| 526 |
' 2 + 1 /\n' |
| 527 |
' ^^^' |
| 528 |
) |
| 529 |
result_lines = self.get_exception(f_with_multiline) |
| 530 |
self.assertEqual(result_lines, expected_f.splitlines()) |
| 531 |
|
| 532 |
def test_caret_for_binary_operators(self): |
| 533 |
def f_with_binary_operator(): |
| 534 |
divisor = 20 |
| 535 |
return 10 + divisor / 0 + 30 |
| 536 |
|
| 537 |
lineno_f = f_with_binary_operator.__code__.co_firstlineno |
| 538 |
expected_error = ( |
| 539 |
'Traceback (most recent call last):\n' |
| 540 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 541 |
' callable()\n' |
| 542 |
f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n' |
| 543 |
' return 10 + divisor / 0 + 30\n' |
| 544 |
' ~~~~~~~~^~~\n' |
| 545 |
) |
| 546 |
result_lines = self.get_exception(f_with_binary_operator) |
| 547 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 548 |
|
| 549 |
def test_caret_for_binary_operators_with_unicode(self): |
| 550 |
def f_with_binary_operator(): |
| 551 |
áóí = 20 |
| 552 |
return 10 + áóí / 0 + 30 |
| 553 |
|
| 554 |
lineno_f = f_with_binary_operator.__code__.co_firstlineno |
| 555 |
expected_error = ( |
| 556 |
'Traceback (most recent call last):\n' |
| 557 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 558 |
' callable()\n' |
| 559 |
f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n' |
| 560 |
' return 10 + áóí / 0 + 30\n' |
| 561 |
' ~~~~^~~\n' |
| 562 |
) |
| 563 |
result_lines = self.get_exception(f_with_binary_operator) |
| 564 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 565 |
|
| 566 |
def test_caret_for_binary_operators_two_char(self): |
| 567 |
def f_with_binary_operator(): |
| 568 |
divisor = 20 |
| 569 |
return 10 + divisor // 0 + 30 |
| 570 |
|
| 571 |
lineno_f = f_with_binary_operator.__code__.co_firstlineno |
| 572 |
expected_error = ( |
| 573 |
'Traceback (most recent call last):\n' |
| 574 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 575 |
' callable()\n' |
| 576 |
f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n' |
| 577 |
' return 10 + divisor // 0 + 30\n' |
| 578 |
' ~~~~~~~~^^~~\n' |
| 579 |
) |
| 580 |
result_lines = self.get_exception(f_with_binary_operator) |
| 581 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 582 |
|
| 583 |
def test_caret_for_binary_operators_with_spaces_and_parenthesis(self): |
| 584 |
def f_with_binary_operator(): |
| 585 |
a = 1 |
| 586 |
b = "" |
| 587 |
return ( a ) + b |
| 588 |
|
| 589 |
lineno_f = f_with_binary_operator.__code__.co_firstlineno |
| 590 |
expected_error = ( |
| 591 |
'Traceback (most recent call last):\n' |
| 592 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 593 |
' callable()\n' |
| 594 |
f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n' |
| 595 |
' return ( a ) + b\n' |
| 596 |
' ~~~~~~~~~~^~~\n' |
| 597 |
) |
| 598 |
result_lines = self.get_exception(f_with_binary_operator) |
| 599 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 600 |
|
| 601 |
def test_caret_for_subscript(self): |
| 602 |
def f_with_subscript(): |
| 603 |
some_dict = {'x': {'y': None}} |
| 604 |
return some_dict['x']['y']['z'] |
| 605 |
|
| 606 |
lineno_f = f_with_subscript.__code__.co_firstlineno |
| 607 |
expected_error = ( |
| 608 |
'Traceback (most recent call last):\n' |
| 609 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 610 |
' callable()\n' |
| 611 |
f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n' |
| 612 |
" return some_dict['x']['y']['z']\n" |
| 613 |
' ~~~~~~~~~~~~~~~~~~~^^^^^\n' |
| 614 |
) |
| 615 |
result_lines = self.get_exception(f_with_subscript) |
| 616 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 617 |
|
| 618 |
def test_caret_for_subscript_unicode(self): |
| 619 |
def f_with_subscript(): |
| 620 |
some_dict = {'ó': {'á': {'í': {'theta': 1}}}} |
| 621 |
return some_dict['ó']['á']['í']['beta'] |
| 622 |
|
| 623 |
lineno_f = f_with_subscript.__code__.co_firstlineno |
| 624 |
expected_error = ( |
| 625 |
'Traceback (most recent call last):\n' |
| 626 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 627 |
' callable()\n' |
| 628 |
f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n' |
| 629 |
" return some_dict['ó']['á']['í']['beta']\n" |
| 630 |
' ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^\n' |
| 631 |
) |
| 632 |
result_lines = self.get_exception(f_with_subscript) |
| 633 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 634 |
|
| 635 |
def test_caret_for_subscript_with_spaces_and_parenthesis(self): |
| 636 |
def f_with_binary_operator(): |
| 637 |
a = [] |
| 638 |
b = c = 1 |
| 639 |
return b [ a ] + c |
| 640 |
|
| 641 |
lineno_f = f_with_binary_operator.__code__.co_firstlineno |
| 642 |
expected_error = ( |
| 643 |
'Traceback (most recent call last):\n' |
| 644 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 645 |
' callable()\n' |
| 646 |
f' File "{__file__}", line {lineno_f+3}, in f_with_binary_operator\n' |
| 647 |
' return b [ a ] + c\n' |
| 648 |
' ~~~~~~^^^^^^^^^\n' |
| 649 |
) |
| 650 |
result_lines = self.get_exception(f_with_binary_operator) |
| 651 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 652 |
|
| 653 |
def test_caret_for_failed_assertion(self): |
| 654 |
def f_assert(): |
| 655 |
test = 3 |
| 656 |
assert test == 1 and test == 2, "Bug found?" |
| 657 |
|
| 658 |
lineno_f = f_assert.__code__.co_firstlineno |
| 659 |
expected_error = ( |
| 660 |
'Traceback (most recent call last):\n' |
| 661 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 662 |
' callable()\n' |
| 663 |
f' File "{__file__}", line {lineno_f+2}, in f_assert\n' |
| 664 |
' assert test == 1 and test == 2, "Bug found?"\n' |
| 665 |
' ^^^^^^^^^^^^^^^^^^^^^^^\n' |
| 666 |
) |
| 667 |
result_lines = self.get_exception(f_assert) |
| 668 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 669 |
|
| 670 |
def test_traceback_specialization_with_syntax_error(self): |
| 671 |
bytecode = compile("1 / 0 / 1 / 2\n", TESTFN, "exec") |
| 672 |
|
| 673 |
with open(TESTFN, "w") as file: |
| 674 |
|
| 675 |
file.write("1 $ 0 / 1 / 2\n") |
| 676 |
self.addCleanup(unlink, TESTFN) |
| 677 |
|
| 678 |
func = partial(exec, bytecode) |
| 679 |
result_lines = self.get_exception(func) |
| 680 |
|
| 681 |
lineno_f = bytecode.co_firstlineno |
| 682 |
expected_error = ( |
| 683 |
'Traceback (most recent call last):\n' |
| 684 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 685 |
' callable()\n' |
| 686 |
f' File "{TESTFN}", line {lineno_f}, in <module>\n' |
| 687 |
" 1 $ 0 / 1 / 2\n" |
| 688 |
' ^^^^^\n' |
| 689 |
) |
| 690 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 691 |
|
| 692 |
def test_traceback_very_long_line(self): |
| 693 |
source = "if True: " + "a" * 256 |
| 694 |
bytecode = compile(source, TESTFN, "exec") |
| 695 |
|
| 696 |
with open(TESTFN, "w") as file: |
| 697 |
file.write(source) |
| 698 |
self.addCleanup(unlink, TESTFN) |
| 699 |
|
| 700 |
func = partial(exec, bytecode) |
| 701 |
result_lines = self.get_exception(func) |
| 702 |
|
| 703 |
lineno_f = bytecode.co_firstlineno |
| 704 |
expected_error = ( |
| 705 |
'Traceback (most recent call last):\n' |
| 706 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 707 |
' callable()\n' |
| 708 |
f' File "{TESTFN}", line {lineno_f}, in <module>\n' |
| 709 |
f' {source}\n' |
| 710 |
f' {" "*len("if True: ") + "^"*256}\n' |
| 711 |
) |
| 712 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 713 |
|
| 714 |
def test_secondary_caret_not_elided(self): |
| 715 |
|
| 716 |
def f_with_subscript(): |
| 717 |
some_dict = {'x': {'y': None}} |
| 718 |
some_dict['x']['y']['z'] |
| 719 |
|
| 720 |
lineno_f = f_with_subscript.__code__.co_firstlineno |
| 721 |
expected_error = ( |
| 722 |
'Traceback (most recent call last):\n' |
| 723 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 724 |
' callable()\n' |
| 725 |
f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n' |
| 726 |
" some_dict['x']['y']['z']\n" |
| 727 |
' ~~~~~~~~~~~~~~~~~~~^^^^^\n' |
| 728 |
) |
| 729 |
result_lines = self.get_exception(f_with_subscript) |
| 730 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 731 |
|
| 732 |
def test_caret_exception_group(self): |
| 733 |
|
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
def exc(): |
| 738 |
if True: raise ExceptionGroup("eg", [ValueError(1), TypeError(2)]) |
| 739 |
|
| 740 |
expected_error = ( |
| 741 |
f' + Exception Group Traceback (most recent call last):\n' |
| 742 |
f' | File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 743 |
f' | callable()\n' |
| 744 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 1}, in exc\n' |
| 745 |
f' | if True: raise ExceptionGroup("eg", [ValueError(1), TypeError(2)])\n' |
| 746 |
f' | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n' |
| 747 |
f' | ExceptionGroup: eg (2 sub-exceptions)\n' |
| 748 |
f' +-+---------------- 1 ----------------\n' |
| 749 |
f' | ValueError: 1\n' |
| 750 |
f' +---------------- 2 ----------------\n' |
| 751 |
f' | TypeError: 2\n') |
| 752 |
|
| 753 |
result_lines = self.get_exception(exc) |
| 754 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 755 |
|
| 756 |
def assertSpecialized(self, func, expected_specialization): |
| 757 |
result_lines = self.get_exception(func) |
| 758 |
specialization_line = result_lines[-1] |
| 759 |
self.assertEqual(specialization_line.lstrip(), expected_specialization) |
| 760 |
|
| 761 |
def test_specialization_variations(self): |
| 762 |
self.assertSpecialized(lambda: 1/0, |
| 763 |
"~^~") |
| 764 |
self.assertSpecialized(lambda: 1/0/3, |
| 765 |
"~^~") |
| 766 |
self.assertSpecialized(lambda: 1 / 0, |
| 767 |
"~~^~~") |
| 768 |
self.assertSpecialized(lambda: 1 / 0 / 3, |
| 769 |
"~~^~~") |
| 770 |
self.assertSpecialized(lambda: 1/ 0, |
| 771 |
"~^~~") |
| 772 |
self.assertSpecialized(lambda: 1/ 0/3, |
| 773 |
"~^~~") |
| 774 |
self.assertSpecialized(lambda: 1 / 0, |
| 775 |
"~~~~~^~~~") |
| 776 |
self.assertSpecialized(lambda: 1 / 0 / 5, |
| 777 |
"~~~~~^~~~") |
| 778 |
self.assertSpecialized(lambda: 1 /0, |
| 779 |
"~~^~") |
| 780 |
self.assertSpecialized(lambda: 1//0, |
| 781 |
"~^^~") |
| 782 |
self.assertSpecialized(lambda: 1//0//4, |
| 783 |
"~^^~") |
| 784 |
self.assertSpecialized(lambda: 1 // 0, |
| 785 |
"~~^^~~") |
| 786 |
self.assertSpecialized(lambda: 1 // 0 // 4, |
| 787 |
"~~^^~~") |
| 788 |
self.assertSpecialized(lambda: 1 //0, |
| 789 |
"~~^^~") |
| 790 |
self.assertSpecialized(lambda: 1// 0, |
| 791 |
"~^^~~") |
| 792 |
|
| 793 |
def test_decorator_application_lineno_correct(self): |
| 794 |
def dec_error(func): |
| 795 |
raise TypeError |
| 796 |
def dec_fine(func): |
| 797 |
return func |
| 798 |
def applydecs(): |
| 799 |
@dec_error |
| 800 |
@dec_fine |
| 801 |
def g(): pass |
| 802 |
result_lines = self.get_exception(applydecs) |
| 803 |
lineno_applydescs = applydecs.__code__.co_firstlineno |
| 804 |
lineno_dec_error = dec_error.__code__.co_firstlineno |
| 805 |
expected_error = ( |
| 806 |
'Traceback (most recent call last):\n' |
| 807 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 808 |
' callable()\n' |
| 809 |
f' File "{__file__}", line {lineno_applydescs + 1}, in applydecs\n' |
| 810 |
' @dec_error\n' |
| 811 |
' ^^^^^^^^^\n' |
| 812 |
f' File "{__file__}", line {lineno_dec_error + 1}, in dec_error\n' |
| 813 |
' raise TypeError\n' |
| 814 |
) |
| 815 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 816 |
|
| 817 |
def applydecs_class(): |
| 818 |
@dec_error |
| 819 |
@dec_fine |
| 820 |
class A: pass |
| 821 |
result_lines = self.get_exception(applydecs_class) |
| 822 |
lineno_applydescs_class = applydecs_class.__code__.co_firstlineno |
| 823 |
expected_error = ( |
| 824 |
'Traceback (most recent call last):\n' |
| 825 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 826 |
' callable()\n' |
| 827 |
f' File "{__file__}", line {lineno_applydescs_class + 1}, in applydecs_class\n' |
| 828 |
' @dec_error\n' |
| 829 |
' ^^^^^^^^^\n' |
| 830 |
f' File "{__file__}", line {lineno_dec_error + 1}, in dec_error\n' |
| 831 |
' raise TypeError\n' |
| 832 |
) |
| 833 |
self.assertEqual(result_lines, expected_error.splitlines()) |
| 834 |
|
| 835 |
def test_multiline_method_call_a(self): |
| 836 |
def f(): |
| 837 |
(None |
| 838 |
.method |
| 839 |
)() |
| 840 |
actual = self.get_exception(f) |
| 841 |
expected = [ |
| 842 |
f"Traceback (most recent call last):", |
| 843 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 844 |
f" callable()", |
| 845 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f", |
| 846 |
f" .method", |
| 847 |
f" ^^^^^^", |
| 848 |
] |
| 849 |
self.assertEqual(actual, expected) |
| 850 |
|
| 851 |
def test_multiline_method_call_b(self): |
| 852 |
def f(): |
| 853 |
(None. |
| 854 |
method |
| 855 |
)() |
| 856 |
actual = self.get_exception(f) |
| 857 |
expected = [ |
| 858 |
f"Traceback (most recent call last):", |
| 859 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 860 |
f" callable()", |
| 861 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f", |
| 862 |
f" method", |
| 863 |
] |
| 864 |
self.assertEqual(actual, expected) |
| 865 |
|
| 866 |
@cpython_only |
| 867 |
def test_multiline_method_call_c(self): |
| 868 |
|
| 869 |
def f(): |
| 870 |
(None |
| 871 |
. method |
| 872 |
)() |
| 873 |
actual = self.get_exception(f) |
| 874 |
expected = [ |
| 875 |
f"Traceback (most recent call last):", |
| 876 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 877 |
f" callable()", |
| 878 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f", |
| 879 |
f" . method", |
| 880 |
f" ^^^^^^", |
| 881 |
] |
| 882 |
self.assertEqual(actual, expected) |
| 883 |
|
| 884 |
def test_wide_characters_unicode_with_problematic_byte_offset(self): |
| 885 |
def f(): |
| 886 |
width |
| 887 |
|
| 888 |
actual = self.get_exception(f) |
| 889 |
expected = [ |
| 890 |
f"Traceback (most recent call last):", |
| 891 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 892 |
f" callable()", |
| 893 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f", |
| 894 |
f" width", |
| 895 |
] |
| 896 |
self.assertEqual(actual, expected) |
| 897 |
|
| 898 |
|
| 899 |
def test_byte_offset_with_wide_characters_middle(self): |
| 900 |
def f(): |
| 901 |
width = 1 |
| 902 |
raise ValueError(width) |
| 903 |
|
| 904 |
actual = self.get_exception(f) |
| 905 |
expected = [ |
| 906 |
f"Traceback (most recent call last):", |
| 907 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 908 |
f" callable()", |
| 909 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 2}, in f", |
| 910 |
f" raise ValueError(width)", |
| 911 |
] |
| 912 |
self.assertEqual(actual, expected) |
| 913 |
|
| 914 |
def test_byte_offset_multiline(self): |
| 915 |
def f(): |
| 916 |
www = 1 |
| 917 |
th = 0 |
| 918 |
|
| 919 |
print(1, www( |
| 920 |
th)) |
| 921 |
|
| 922 |
actual = self.get_exception(f) |
| 923 |
expected = [ |
| 924 |
f"Traceback (most recent call last):", |
| 925 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 926 |
f" callable()", |
| 927 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 4}, in f", |
| 928 |
f" print(1, www(", |
| 929 |
f" ^^^^^^^", |
| 930 |
] |
| 931 |
self.assertEqual(actual, expected) |
| 932 |
|
| 933 |
def test_byte_offset_with_wide_characters_term_highlight(self): |
| 934 |
def f(): |
| 935 |
说明说明 = 1 |
| 936 |
şçöğıĤelln-ascii |
| 937 |
return 说明说明 / şçöğıĤellö |
| 938 |
|
| 939 |
actual = self.get_exception(f) |
| 940 |
expected = [ |
| 941 |
f"Traceback (most recent call last):", |
| 942 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 943 |
f" callable()", |
| 944 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 3}, in f", |
| 945 |
f" return 说明说明 / şçöğıĤellö", |
| 946 |
f" ~~~~~~~~~^~~~~~~~~~~~", |
| 947 |
] |
| 948 |
self.assertEqual(actual, expected) |
| 949 |
|
| 950 |
def test_byte_offset_with_emojis_term_highlight(self): |
| 951 |
def f(): |
| 952 |
return "✨🐍" + func_说明说明("📗🚛", |
| 953 |
"📗🚛") + "🐍" |
| 954 |
|
| 955 |
actual = self.get_exception(f) |
| 956 |
expected = [ |
| 957 |
f"Traceback (most recent call last):", |
| 958 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 959 |
f" callable()", |
| 960 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 1}, in f", |
| 961 |
f' return "✨🐍" + func_说明说明("📗🚛",', |
| 962 |
f" ^^^^^^^^^^^^^", |
| 963 |
] |
| 964 |
self.assertEqual(actual, expected) |
| 965 |
|
| 966 |
def test_byte_offset_wide_chars_subscript(self): |
| 967 |
def f(): |
| 968 |
my_dct = { |
| 969 |
"✨🚛✨": { |
| 970 |
"说明": { |
| 971 |
"🐍🐍🐍": None |
| 972 |
} |
| 973 |
} |
| 974 |
} |
| 975 |
return my_dct["✨🚛✨"]["说明"]["🐍"]["说明"]["🐍🐍"] |
| 976 |
|
| 977 |
actual = self.get_exception(f) |
| 978 |
expected = [ |
| 979 |
f"Traceback (most recent call last):", |
| 980 |
f" File \"{__file__}\", line {self.callable_line}, in get_exception", |
| 981 |
f" callable()", |
| 982 |
f" File \"{__file__}\", line {f.__code__.co_firstlineno + 8}, in f", |
| 983 |
f' return my_dct["✨🚛✨"]["说明"]["🐍"]["说明"]["🐍🐍"]', |
| 984 |
f" ~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^", |
| 985 |
] |
| 986 |
self.assertEqual(actual, expected) |
| 987 |
|
| 988 |
|
| 989 |
@cpython_only |
| 990 |
@requires_debug_ranges() |
| 991 |
class CPythonTracebackErrorCaretTests(TracebackErrorLocationCaretTests): |
| 992 |
""" |
| 993 |
Same set of tests as above but with Python's internal traceback printing. |
| 994 |
""" |
| 995 |
def get_exception(self, callable): |
| 996 |
from _testcapi import exception_print |
| 997 |
try: |
| 998 |
callable() |
| 999 |
self.fail("No exception thrown.") |
| 1000 |
except Exception as e: |
| 1001 |
with captured_output("stderr") as tbstderr: |
| 1002 |
exception_print(e) |
| 1003 |
return tbstderr.getvalue().splitlines()[:-1] |
| 1004 |
|
| 1005 |
callable_line = get_exception.__code__.co_firstlineno + 3 |
| 1006 |
|
| 1007 |
|
| 1008 |
class TracebackFormatTests(unittest.TestCase): |
| 1009 |
|
| 1010 |
def some_exception(self): |
| 1011 |
raise KeyError('blah') |
| 1012 |
|
| 1013 |
@cpython_only |
| 1014 |
def check_traceback_format(self, cleanup_func=None): |
| 1015 |
from _testcapi import traceback_print |
| 1016 |
try: |
| 1017 |
self.some_exception() |
| 1018 |
except KeyError: |
| 1019 |
type_, value, tb = sys.exc_info() |
| 1020 |
if cleanup_func is not None: |
| 1021 |
|
| 1022 |
cleanup_func(tb.tb_next) |
| 1023 |
traceback_fmt = 'Traceback (most recent call last):\n' + \ |
| 1024 |
''.join(traceback.format_tb(tb)) |
| 1025 |
file_ = StringIO() |
| 1026 |
traceback_print(tb, file_) |
| 1027 |
python_fmt = file_.getvalue() |
| 1028 |
|
| 1029 |
with captured_output("stderr") as tbstderr: |
| 1030 |
traceback.print_tb(tb) |
| 1031 |
tbfile = StringIO() |
| 1032 |
traceback.print_tb(tb, file=tbfile) |
| 1033 |
with captured_output("stderr") as excstderr: |
| 1034 |
traceback.print_exc() |
| 1035 |
excfmt = traceback.format_exc() |
| 1036 |
excfile = StringIO() |
| 1037 |
traceback.print_exc(file=excfile) |
| 1038 |
else: |
| 1039 |
raise Error("unable to create test traceback string") |
| 1040 |
|
| 1041 |
|
| 1042 |
self.assertEqual(traceback_fmt, python_fmt) |
| 1043 |
|
| 1044 |
self.assertEqual(tbstderr.getvalue(), tbfile.getvalue()) |
| 1045 |
|
| 1046 |
self.assertEqual(excstderr.getvalue(), excfile.getvalue()) |
| 1047 |
self.assertEqual(excfmt, excfile.getvalue()) |
| 1048 |
|
| 1049 |
|
| 1050 |
tb_lines = python_fmt.splitlines() |
| 1051 |
banner = tb_lines[0] |
| 1052 |
self.assertEqual(len(tb_lines), 5) |
| 1053 |
location, source_line = tb_lines[-2], tb_lines[-1] |
| 1054 |
self.assertTrue(banner.startswith('Traceback')) |
| 1055 |
self.assertTrue(location.startswith(' File')) |
| 1056 |
self.assertTrue(source_line.startswith(' raise')) |
| 1057 |
|
| 1058 |
def test_traceback_format(self): |
| 1059 |
self.check_traceback_format() |
| 1060 |
|
| 1061 |
def test_traceback_format_with_cleared_frames(self): |
| 1062 |
|
| 1063 |
def cleanup_tb(tb): |
| 1064 |
tb.tb_frame.clear() |
| 1065 |
self.check_traceback_format(cleanup_tb) |
| 1066 |
|
| 1067 |
def test_stack_format(self): |
| 1068 |
|
| 1069 |
|
| 1070 |
with captured_output("stderr") as ststderr: |
| 1071 |
traceback.print_stack(sys._getframe(1)) |
| 1072 |
stfile = StringIO() |
| 1073 |
traceback.print_stack(sys._getframe(1), file=stfile) |
| 1074 |
self.assertEqual(ststderr.getvalue(), stfile.getvalue()) |
| 1075 |
|
| 1076 |
stfmt = traceback.format_stack(sys._getframe(1)) |
| 1077 |
|
| 1078 |
self.assertEqual(ststderr.getvalue(), "".join(stfmt)) |
| 1079 |
|
| 1080 |
def test_print_stack(self): |
| 1081 |
def prn(): |
| 1082 |
traceback.print_stack() |
| 1083 |
with captured_output("stderr") as stderr: |
| 1084 |
prn() |
| 1085 |
lineno = prn.__code__.co_firstlineno |
| 1086 |
self.assertEqual(stderr.getvalue().splitlines()[-4:], [ |
| 1087 |
' File "%s", line %d, in test_print_stack' % (__file__, lineno+3), |
| 1088 |
' prn()', |
| 1089 |
' File "%s", line %d, in prn' % (__file__, lineno+1), |
| 1090 |
' traceback.print_stack()', |
| 1091 |
]) |
| 1092 |
|
| 1093 |
|
| 1094 |
def _check_recursive_traceback_display(self, render_exc): |
| 1095 |
|
| 1096 |
|
| 1097 |
|
| 1098 |
self.maxDiff = None |
| 1099 |
|
| 1100 |
|
| 1101 |
def f(): |
| 1102 |
f() |
| 1103 |
|
| 1104 |
with captured_output("stderr") as stderr_f: |
| 1105 |
try: |
| 1106 |
f() |
| 1107 |
except RecursionError: |
| 1108 |
render_exc() |
| 1109 |
else: |
| 1110 |
self.fail("no recursion occurred") |
| 1111 |
|
| 1112 |
lineno_f = f.__code__.co_firstlineno |
| 1113 |
result_f = ( |
| 1114 |
'Traceback (most recent call last):\n' |
| 1115 |
f' File "{__file__}", line {lineno_f+5}, in _check_recursive_traceback_display\n' |
| 1116 |
' f()\n' |
| 1117 |
f' File "{__file__}", line {lineno_f+1}, in f\n' |
| 1118 |
' f()\n' |
| 1119 |
f' File "{__file__}", line {lineno_f+1}, in f\n' |
| 1120 |
' f()\n' |
| 1121 |
f' File "{__file__}", line {lineno_f+1}, in f\n' |
| 1122 |
' f()\n' |
| 1123 |
|
| 1124 |
|
| 1125 |
|
| 1126 |
|
| 1127 |
r' \[Previous line repeated (\d+) more times\]' '\n' |
| 1128 |
'RecursionError: maximum recursion depth exceeded\n' |
| 1129 |
) |
| 1130 |
|
| 1131 |
expected = result_f.splitlines() |
| 1132 |
actual = stderr_f.getvalue().splitlines() |
| 1133 |
|
| 1134 |
|
| 1135 |
|
| 1136 |
self.assertEqual(actual[:-2], expected[:-2]) |
| 1137 |
self.assertRegex(actual[-2], expected[-2]) |
| 1138 |
|
| 1139 |
self.assertIn(expected[-1], actual[-1]) |
| 1140 |
|
| 1141 |
|
| 1142 |
rec_limit = sys.getrecursionlimit() |
| 1143 |
|
| 1144 |
self.assertIn(int(re.search(r"\d+", actual[-2]).group()), range(rec_limit-60, rec_limit+1000)) |
| 1145 |
|
| 1146 |
|
| 1147 |
def g(count=10): |
| 1148 |
if count: |
| 1149 |
return g(count-1) |
| 1150 |
raise ValueError |
| 1151 |
|
| 1152 |
with captured_output("stderr") as stderr_g: |
| 1153 |
try: |
| 1154 |
g() |
| 1155 |
except ValueError: |
| 1156 |
render_exc() |
| 1157 |
else: |
| 1158 |
self.fail("no value error was raised") |
| 1159 |
|
| 1160 |
lineno_g = g.__code__.co_firstlineno |
| 1161 |
result_g = ( |
| 1162 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1163 |
' return g(count-1)\n' |
| 1164 |
' ^^^^^^^^^^\n' |
| 1165 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1166 |
' return g(count-1)\n' |
| 1167 |
' ^^^^^^^^^^\n' |
| 1168 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1169 |
' return g(count-1)\n' |
| 1170 |
' ^^^^^^^^^^\n' |
| 1171 |
' [Previous line repeated 7 more times]\n' |
| 1172 |
f' File "{__file__}", line {lineno_g+3}, in g\n' |
| 1173 |
' raise ValueError\n' |
| 1174 |
'ValueError\n' |
| 1175 |
) |
| 1176 |
tb_line = ( |
| 1177 |
'Traceback (most recent call last):\n' |
| 1178 |
f' File "{__file__}", line {lineno_g+7}, in _check_recursive_traceback_display\n' |
| 1179 |
' g()\n' |
| 1180 |
) |
| 1181 |
expected = (tb_line + result_g).splitlines() |
| 1182 |
actual = stderr_g.getvalue().splitlines() |
| 1183 |
self.assertEqual(actual, expected) |
| 1184 |
|
| 1185 |
|
| 1186 |
def h(count=10): |
| 1187 |
if count: |
| 1188 |
return h(count-1) |
| 1189 |
g() |
| 1190 |
|
| 1191 |
with captured_output("stderr") as stderr_h: |
| 1192 |
try: |
| 1193 |
h() |
| 1194 |
except ValueError: |
| 1195 |
render_exc() |
| 1196 |
else: |
| 1197 |
self.fail("no value error was raised") |
| 1198 |
|
| 1199 |
lineno_h = h.__code__.co_firstlineno |
| 1200 |
result_h = ( |
| 1201 |
'Traceback (most recent call last):\n' |
| 1202 |
f' File "{__file__}", line {lineno_h+7}, in _check_recursive_traceback_display\n' |
| 1203 |
' h()\n' |
| 1204 |
f' File "{__file__}", line {lineno_h+2}, in h\n' |
| 1205 |
' return h(count-1)\n' |
| 1206 |
' ^^^^^^^^^^\n' |
| 1207 |
f' File "{__file__}", line {lineno_h+2}, in h\n' |
| 1208 |
' return h(count-1)\n' |
| 1209 |
' ^^^^^^^^^^\n' |
| 1210 |
f' File "{__file__}", line {lineno_h+2}, in h\n' |
| 1211 |
' return h(count-1)\n' |
| 1212 |
' ^^^^^^^^^^\n' |
| 1213 |
' [Previous line repeated 7 more times]\n' |
| 1214 |
f' File "{__file__}", line {lineno_h+3}, in h\n' |
| 1215 |
' g()\n' |
| 1216 |
) |
| 1217 |
expected = (result_h + result_g).splitlines() |
| 1218 |
actual = stderr_h.getvalue().splitlines() |
| 1219 |
self.assertEqual(actual, expected) |
| 1220 |
|
| 1221 |
|
| 1222 |
with captured_output("stderr") as stderr_g: |
| 1223 |
try: |
| 1224 |
g(traceback._RECURSIVE_CUTOFF) |
| 1225 |
except ValueError: |
| 1226 |
render_exc() |
| 1227 |
else: |
| 1228 |
self.fail("no error raised") |
| 1229 |
result_g = ( |
| 1230 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1231 |
' return g(count-1)\n' |
| 1232 |
' ^^^^^^^^^^\n' |
| 1233 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1234 |
' return g(count-1)\n' |
| 1235 |
' ^^^^^^^^^^\n' |
| 1236 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1237 |
' return g(count-1)\n' |
| 1238 |
' ^^^^^^^^^^\n' |
| 1239 |
f' File "{__file__}", line {lineno_g+3}, in g\n' |
| 1240 |
' raise ValueError\n' |
| 1241 |
'ValueError\n' |
| 1242 |
) |
| 1243 |
tb_line = ( |
| 1244 |
'Traceback (most recent call last):\n' |
| 1245 |
f' File "{__file__}", line {lineno_g+77}, in _check_recursive_traceback_display\n' |
| 1246 |
' g(traceback._RECURSIVE_CUTOFF)\n' |
| 1247 |
) |
| 1248 |
expected = (tb_line + result_g).splitlines() |
| 1249 |
actual = stderr_g.getvalue().splitlines() |
| 1250 |
self.assertEqual(actual, expected) |
| 1251 |
|
| 1252 |
|
| 1253 |
with captured_output("stderr") as stderr_g: |
| 1254 |
try: |
| 1255 |
g(traceback._RECURSIVE_CUTOFF + 1) |
| 1256 |
except ValueError: |
| 1257 |
render_exc() |
| 1258 |
else: |
| 1259 |
self.fail("no error raised") |
| 1260 |
result_g = ( |
| 1261 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1262 |
' return g(count-1)\n' |
| 1263 |
' ^^^^^^^^^^\n' |
| 1264 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1265 |
' return g(count-1)\n' |
| 1266 |
' ^^^^^^^^^^\n' |
| 1267 |
f' File "{__file__}", line {lineno_g+2}, in g\n' |
| 1268 |
' return g(count-1)\n' |
| 1269 |
' ^^^^^^^^^^\n' |
| 1270 |
' [Previous line repeated 1 more time]\n' |
| 1271 |
f' File "{__file__}", line {lineno_g+3}, in g\n' |
| 1272 |
' raise ValueError\n' |
| 1273 |
'ValueError\n' |
| 1274 |
) |
| 1275 |
tb_line = ( |
| 1276 |
'Traceback (most recent call last):\n' |
| 1277 |
f' File "{__file__}", line {lineno_g+108}, in _check_recursive_traceback_display\n' |
| 1278 |
' g(traceback._RECURSIVE_CUTOFF + 1)\n' |
| 1279 |
) |
| 1280 |
expected = (tb_line + result_g).splitlines() |
| 1281 |
actual = stderr_g.getvalue().splitlines() |
| 1282 |
self.assertEqual(actual, expected) |
| 1283 |
|
| 1284 |
@requires_debug_ranges() |
| 1285 |
def test_recursive_traceback_python(self): |
| 1286 |
self._check_recursive_traceback_display(traceback.print_exc) |
| 1287 |
|
| 1288 |
@cpython_only |
| 1289 |
@requires_debug_ranges() |
| 1290 |
def test_recursive_traceback_cpython_internal(self): |
| 1291 |
from _testcapi import exception_print |
| 1292 |
def render_exc(): |
| 1293 |
exc_type, exc_value, exc_tb = sys.exc_info() |
| 1294 |
exception_print(exc_value) |
| 1295 |
self._check_recursive_traceback_display(render_exc) |
| 1296 |
|
| 1297 |
def test_format_stack(self): |
| 1298 |
def fmt(): |
| 1299 |
return traceback.format_stack() |
| 1300 |
result = fmt() |
| 1301 |
lineno = fmt.__code__.co_firstlineno |
| 1302 |
self.assertEqual(result[-2:], [ |
| 1303 |
' File "%s", line %d, in test_format_stack\n' |
| 1304 |
' result = fmt()\n' % (__file__, lineno+2), |
| 1305 |
' File "%s", line %d, in fmt\n' |
| 1306 |
' return traceback.format_stack()\n' % (__file__, lineno+1), |
| 1307 |
]) |
| 1308 |
|
| 1309 |
@cpython_only |
| 1310 |
def test_unhashable(self): |
| 1311 |
from _testcapi import exception_print |
| 1312 |
|
| 1313 |
class UnhashableException(Exception): |
| 1314 |
def __eq__(self, other): |
| 1315 |
return True |
| 1316 |
|
| 1317 |
ex1 = UnhashableException('ex1') |
| 1318 |
ex2 = UnhashableException('ex2') |
| 1319 |
try: |
| 1320 |
raise ex2 from ex1 |
| 1321 |
except UnhashableException: |
| 1322 |
try: |
| 1323 |
raise ex1 |
| 1324 |
except UnhashableException: |
| 1325 |
exc_type, exc_val, exc_tb = sys.exc_info() |
| 1326 |
|
| 1327 |
with captured_output("stderr") as stderr_f: |
| 1328 |
exception_print(exc_val) |
| 1329 |
|
| 1330 |
tb = stderr_f.getvalue().strip().splitlines() |
| 1331 |
self.assertEqual(11, len(tb)) |
| 1332 |
self.assertEqual(context_message.strip(), tb[5]) |
| 1333 |
self.assertIn('UnhashableException: ex2', tb[3]) |
| 1334 |
self.assertIn('UnhashableException: ex1', tb[10]) |
| 1335 |
|
| 1336 |
def deep_eg(self): |
| 1337 |
e = TypeError(1) |
| 1338 |
for i in range(2000): |
| 1339 |
e = ExceptionGroup('eg', [e]) |
| 1340 |
return e |
| 1341 |
|
| 1342 |
@cpython_only |
| 1343 |
def test_exception_group_deep_recursion_capi(self): |
| 1344 |
from _testcapi import exception_print |
| 1345 |
LIMIT = 75 |
| 1346 |
eg = self.deep_eg() |
| 1347 |
with captured_output("stderr") as stderr_f: |
| 1348 |
with support.infinite_recursion(max_depth=LIMIT): |
| 1349 |
exception_print(eg) |
| 1350 |
output = stderr_f.getvalue() |
| 1351 |
self.assertIn('ExceptionGroup', output) |
| 1352 |
self.assertLessEqual(output.count('ExceptionGroup'), LIMIT) |
| 1353 |
|
| 1354 |
def test_exception_group_deep_recursion_traceback(self): |
| 1355 |
LIMIT = 75 |
| 1356 |
eg = self.deep_eg() |
| 1357 |
with captured_output("stderr") as stderr_f: |
| 1358 |
with support.infinite_recursion(max_depth=LIMIT): |
| 1359 |
traceback.print_exception(type(eg), eg, eg.__traceback__) |
| 1360 |
output = stderr_f.getvalue() |
| 1361 |
self.assertIn('ExceptionGroup', output) |
| 1362 |
self.assertLessEqual(output.count('ExceptionGroup'), LIMIT) |
| 1363 |
|
| 1364 |
@cpython_only |
| 1365 |
def test_print_exception_bad_type_capi(self): |
| 1366 |
from _testcapi import exception_print |
| 1367 |
with captured_output("stderr") as stderr: |
| 1368 |
exception_print(42) |
| 1369 |
self.assertEqual( |
| 1370 |
stderr.getvalue(), |
| 1371 |
('TypeError: print_exception(): ' |
| 1372 |
'Exception expected for value, int found\n') |
| 1373 |
) |
| 1374 |
|
| 1375 |
def test_print_exception_bad_type_python(self): |
| 1376 |
msg = "Exception expected for value, int found" |
| 1377 |
with self.assertRaisesRegex(TypeError, msg): |
| 1378 |
traceback.print_exception(42) |
| 1379 |
|
| 1380 |
|
| 1381 |
cause_message = ( |
| 1382 |
"\nThe above exception was the direct cause " |
| 1383 |
"of the following exception:\n\n") |
| 1384 |
|
| 1385 |
context_message = ( |
| 1386 |
"\nDuring handling of the above exception, " |
| 1387 |
"another exception occurred:\n\n") |
| 1388 |
|
| 1389 |
boundaries = re.compile( |
| 1390 |
'(%s|%s)' % (re.escape(cause_message), re.escape(context_message))) |
| 1391 |
|
| 1392 |
class BaseExceptionReportingTests: |
| 1393 |
|
| 1394 |
def get_exception(self, exception_or_callable): |
| 1395 |
if isinstance(exception_or_callable, BaseException): |
| 1396 |
return exception_or_callable |
| 1397 |
try: |
| 1398 |
exception_or_callable() |
| 1399 |
except Exception as e: |
| 1400 |
return e |
| 1401 |
|
| 1402 |
callable_line = get_exception.__code__.co_firstlineno + 4 |
| 1403 |
|
| 1404 |
def zero_div(self): |
| 1405 |
1/0 |
| 1406 |
|
| 1407 |
def check_zero_div(self, msg): |
| 1408 |
lines = msg.splitlines() |
| 1409 |
if has_no_debug_ranges(): |
| 1410 |
self.assertTrue(lines[-3].startswith(' File')) |
| 1411 |
self.assertIn('1/0 # In zero_div', lines[-2]) |
| 1412 |
else: |
| 1413 |
self.assertTrue(lines[-4].startswith(' File')) |
| 1414 |
self.assertIn('1/0 # In zero_div', lines[-3]) |
| 1415 |
self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1]) |
| 1416 |
|
| 1417 |
def test_simple(self): |
| 1418 |
try: |
| 1419 |
1/0 |
| 1420 |
except ZeroDivisionError as _: |
| 1421 |
e = _ |
| 1422 |
lines = self.get_report(e).splitlines() |
| 1423 |
if has_no_debug_ranges(): |
| 1424 |
self.assertEqual(len(lines), 4) |
| 1425 |
self.assertTrue(lines[3].startswith('ZeroDivisionError')) |
| 1426 |
else: |
| 1427 |
self.assertEqual(len(lines), 5) |
| 1428 |
self.assertTrue(lines[4].startswith('ZeroDivisionError')) |
| 1429 |
self.assertTrue(lines[0].startswith('Traceback')) |
| 1430 |
self.assertTrue(lines[1].startswith(' File')) |
| 1431 |
self.assertIn('1/0 # Marker', lines[2]) |
| 1432 |
|
| 1433 |
def test_cause(self): |
| 1434 |
def inner_raise(): |
| 1435 |
try: |
| 1436 |
self.zero_div() |
| 1437 |
except ZeroDivisionError as e: |
| 1438 |
raise KeyError from e |
| 1439 |
def outer_raise(): |
| 1440 |
inner_raise() |
| 1441 |
blocks = boundaries.split(self.get_report(outer_raise)) |
| 1442 |
self.assertEqual(len(blocks), 3) |
| 1443 |
self.assertEqual(blocks[1], cause_message) |
| 1444 |
self.check_zero_div(blocks[0]) |
| 1445 |
self.assertIn('inner_raise() # Marker', blocks[2]) |
| 1446 |
|
| 1447 |
def test_context(self): |
| 1448 |
def inner_raise(): |
| 1449 |
try: |
| 1450 |
self.zero_div() |
| 1451 |
except ZeroDivisionError: |
| 1452 |
raise KeyError |
| 1453 |
def outer_raise(): |
| 1454 |
inner_raise() |
| 1455 |
blocks = boundaries.split(self.get_report(outer_raise)) |
| 1456 |
self.assertEqual(len(blocks), 3) |
| 1457 |
self.assertEqual(blocks[1], context_message) |
| 1458 |
self.check_zero_div(blocks[0]) |
| 1459 |
self.assertIn('inner_raise() # Marker', blocks[2]) |
| 1460 |
|
| 1461 |
def test_context_suppression(self): |
| 1462 |
try: |
| 1463 |
try: |
| 1464 |
raise Exception |
| 1465 |
except: |
| 1466 |
raise ZeroDivisionError from None |
| 1467 |
except ZeroDivisionError as _: |
| 1468 |
e = _ |
| 1469 |
lines = self.get_report(e).splitlines() |
| 1470 |
self.assertEqual(len(lines), 4) |
| 1471 |
self.assertTrue(lines[3].startswith('ZeroDivisionError')) |
| 1472 |
self.assertTrue(lines[0].startswith('Traceback')) |
| 1473 |
self.assertTrue(lines[1].startswith(' File')) |
| 1474 |
self.assertIn('ZeroDivisionError from None', lines[2]) |
| 1475 |
|
| 1476 |
def test_cause_and_context(self): |
| 1477 |
|
| 1478 |
|
| 1479 |
def inner_raise(): |
| 1480 |
try: |
| 1481 |
self.zero_div() |
| 1482 |
except ZeroDivisionError as _e: |
| 1483 |
e = _e |
| 1484 |
try: |
| 1485 |
xyzzy |
| 1486 |
except NameError: |
| 1487 |
raise KeyError from e |
| 1488 |
def outer_raise(): |
| 1489 |
inner_raise() |
| 1490 |
blocks = boundaries.split(self.get_report(outer_raise)) |
| 1491 |
self.assertEqual(len(blocks), 3) |
| 1492 |
self.assertEqual(blocks[1], cause_message) |
| 1493 |
self.check_zero_div(blocks[0]) |
| 1494 |
self.assertIn('inner_raise() # Marker', blocks[2]) |
| 1495 |
|
| 1496 |
def test_cause_recursive(self): |
| 1497 |
def inner_raise(): |
| 1498 |
try: |
| 1499 |
try: |
| 1500 |
self.zero_div() |
| 1501 |
except ZeroDivisionError as e: |
| 1502 |
z = e |
| 1503 |
raise KeyError from e |
| 1504 |
except KeyError as e: |
| 1505 |
raise z from e |
| 1506 |
def outer_raise(): |
| 1507 |
inner_raise() |
| 1508 |
blocks = boundaries.split(self.get_report(outer_raise)) |
| 1509 |
self.assertEqual(len(blocks), 3) |
| 1510 |
self.assertEqual(blocks[1], cause_message) |
| 1511 |
|
| 1512 |
self.assertIn('raise KeyError from e', blocks[0]) |
| 1513 |
self.assertNotIn('1/0', blocks[0]) |
| 1514 |
|
| 1515 |
|
| 1516 |
self.assertIn('inner_raise() # Marker', blocks[2]) |
| 1517 |
self.check_zero_div(blocks[2]) |
| 1518 |
|
| 1519 |
def test_syntax_error_offset_at_eol(self): |
| 1520 |
|
| 1521 |
def e(): |
| 1522 |
raise SyntaxError('', ('', 0, 5, 'hello')) |
| 1523 |
msg = self.get_report(e).splitlines() |
| 1524 |
self.assertEqual(msg[-2], " ^") |
| 1525 |
def e(): |
| 1526 |
exec("x = 5 | 4 |") |
| 1527 |
msg = self.get_report(e).splitlines() |
| 1528 |
self.assertEqual(msg[-2], ' ^') |
| 1529 |
|
| 1530 |
def test_syntax_error_no_lineno(self): |
| 1531 |
|
| 1532 |
|
| 1533 |
|
| 1534 |
e = SyntaxError('bad syntax') |
| 1535 |
msg = self.get_report(e).splitlines() |
| 1536 |
self.assertEqual(msg, |
| 1537 |
['SyntaxError: bad syntax']) |
| 1538 |
e.lineno = 100 |
| 1539 |
msg = self.get_report(e).splitlines() |
| 1540 |
self.assertEqual(msg, |
| 1541 |
[' File "<string>", line 100', 'SyntaxError: bad syntax']) |
| 1542 |
|
| 1543 |
|
| 1544 |
e = SyntaxError('bad syntax') |
| 1545 |
e.filename = 'myfile.py' |
| 1546 |
|
| 1547 |
msg = self.get_report(e).splitlines() |
| 1548 |
self.assertEqual(msg, |
| 1549 |
['SyntaxError: bad syntax (myfile.py)']) |
| 1550 |
e.lineno = 100 |
| 1551 |
msg = self.get_report(e).splitlines() |
| 1552 |
self.assertEqual(msg, |
| 1553 |
[' File "myfile.py", line 100', 'SyntaxError: bad syntax']) |
| 1554 |
|
| 1555 |
def test_message_none(self): |
| 1556 |
|
| 1557 |
err = self.get_report(Exception(None)) |
| 1558 |
self.assertIn('Exception: None\n', err) |
| 1559 |
err = self.get_report(Exception('None')) |
| 1560 |
self.assertIn('Exception: None\n', err) |
| 1561 |
err = self.get_report(Exception()) |
| 1562 |
self.assertIn('Exception\n', err) |
| 1563 |
err = self.get_report(Exception('')) |
| 1564 |
self.assertIn('Exception\n', err) |
| 1565 |
|
| 1566 |
def test_syntax_error_various_offsets(self): |
| 1567 |
for offset in range(-5, 10): |
| 1568 |
for add in [0, 2]: |
| 1569 |
text = " "*add + "text%d" % offset |
| 1570 |
expected = [' File "file.py", line 1'] |
| 1571 |
if offset < 1: |
| 1572 |
expected.append(" %s" % text.lstrip()) |
| 1573 |
elif offset <= 6: |
| 1574 |
expected.append(" %s" % text.lstrip()) |
| 1575 |
expected.append(" %s^" % (" "*(offset-1))) |
| 1576 |
else: |
| 1577 |
expected.append(" %s" % text.lstrip()) |
| 1578 |
expected.append(" %s^" % (" "*5)) |
| 1579 |
expected.append("SyntaxError: msg") |
| 1580 |
expected.append("") |
| 1581 |
err = self.get_report(SyntaxError("msg", ("file.py", 1, offset+add, text))) |
| 1582 |
exp = "\n".join(expected) |
| 1583 |
self.assertEqual(exp, err) |
| 1584 |
|
| 1585 |
def test_exception_with_note(self): |
| 1586 |
e = ValueError(123) |
| 1587 |
vanilla = self.get_report(e) |
| 1588 |
|
| 1589 |
e.add_note('My Note') |
| 1590 |
self.assertEqual(self.get_report(e), vanilla + 'My Note\n') |
| 1591 |
|
| 1592 |
del e.__notes__ |
| 1593 |
e.add_note('') |
| 1594 |
self.assertEqual(self.get_report(e), vanilla + '\n') |
| 1595 |
|
| 1596 |
del e.__notes__ |
| 1597 |
e.add_note('Your Note') |
| 1598 |
self.assertEqual(self.get_report(e), vanilla + 'Your Note\n') |
| 1599 |
|
| 1600 |
del e.__notes__ |
| 1601 |
self.assertEqual(self.get_report(e), vanilla) |
| 1602 |
|
| 1603 |
def test_exception_with_invalid_notes(self): |
| 1604 |
e = ValueError(123) |
| 1605 |
vanilla = self.get_report(e) |
| 1606 |
|
| 1607 |
|
| 1608 |
class BadThing: |
| 1609 |
def __str__(self): |
| 1610 |
return 'bad str' |
| 1611 |
|
| 1612 |
def __repr__(self): |
| 1613 |
return 'bad repr' |
| 1614 |
|
| 1615 |
|
| 1616 |
class Unprintable: |
| 1617 |
def __repr__(self): |
| 1618 |
raise ValueError('bad value') |
| 1619 |
|
| 1620 |
e.__notes__ = BadThing() |
| 1621 |
notes_repr = 'bad repr' |
| 1622 |
self.assertEqual(self.get_report(e), vanilla + notes_repr) |
| 1623 |
|
| 1624 |
e.__notes__ = Unprintable() |
| 1625 |
err_msg = '<__notes__ repr() failed>' |
| 1626 |
self.assertEqual(self.get_report(e), vanilla + err_msg) |
| 1627 |
|
| 1628 |
|
| 1629 |
e.__notes__ = [BadThing(), 'Final Note'] |
| 1630 |
bad_note = 'bad str' |
| 1631 |
self.assertEqual(self.get_report(e), vanilla + bad_note + '\nFinal Note\n') |
| 1632 |
|
| 1633 |
|
| 1634 |
e.__notes__ = [Unprintable(), 'Final Note'] |
| 1635 |
err_msg = '<note str() failed>' |
| 1636 |
self.assertEqual(self.get_report(e), vanilla + err_msg + '\nFinal Note\n') |
| 1637 |
|
| 1638 |
|
| 1639 |
class BrokenException(Exception): |
| 1640 |
broken = False |
| 1641 |
def __getattr__(self, name): |
| 1642 |
if self.broken: |
| 1643 |
raise ValueError(f'no {name}') |
| 1644 |
raise AttributeError(name) |
| 1645 |
|
| 1646 |
e = BrokenException(123) |
| 1647 |
vanilla = self.get_report(e) |
| 1648 |
e.broken = True |
| 1649 |
self.assertEqual( |
| 1650 |
self.get_report(e), |
| 1651 |
vanilla + "Ignored error getting __notes__: ValueError('no __notes__')\n") |
| 1652 |
|
| 1653 |
def test_exception_with_multiple_notes(self): |
| 1654 |
for e in [ValueError(42), SyntaxError('bad syntax')]: |
| 1655 |
with self.subTest(e=e): |
| 1656 |
vanilla = self.get_report(e) |
| 1657 |
|
| 1658 |
e.add_note('Note 1') |
| 1659 |
e.add_note('Note 2') |
| 1660 |
e.add_note('Note 3') |
| 1661 |
|
| 1662 |
self.assertEqual( |
| 1663 |
self.get_report(e), |
| 1664 |
vanilla + 'Note 1\n' + 'Note 2\n' + 'Note 3\n') |
| 1665 |
|
| 1666 |
del e.__notes__ |
| 1667 |
e.add_note('Note 4') |
| 1668 |
del e.__notes__ |
| 1669 |
e.add_note('Note 5') |
| 1670 |
e.add_note('Note 6') |
| 1671 |
|
| 1672 |
self.assertEqual( |
| 1673 |
self.get_report(e), |
| 1674 |
vanilla + 'Note 5\n' + 'Note 6\n') |
| 1675 |
|
| 1676 |
def test_exception_qualname(self): |
| 1677 |
class A: |
| 1678 |
class B: |
| 1679 |
class X(Exception): |
| 1680 |
def __str__(self): |
| 1681 |
return "I am X" |
| 1682 |
|
| 1683 |
err = self.get_report(A.B.X()) |
| 1684 |
str_value = 'I am X' |
| 1685 |
str_name = '.'.join([A.B.X.__module__, A.B.X.__qualname__]) |
| 1686 |
exp = "%s: %s\n" % (str_name, str_value) |
| 1687 |
self.assertEqual(exp, MODULE_PREFIX + err) |
| 1688 |
|
| 1689 |
def test_exception_modulename(self): |
| 1690 |
class X(Exception): |
| 1691 |
def __str__(self): |
| 1692 |
return "I am X" |
| 1693 |
|
| 1694 |
for modulename in '__main__', 'builtins', 'some_module': |
| 1695 |
X.__module__ = modulename |
| 1696 |
with self.subTest(modulename=modulename): |
| 1697 |
err = self.get_report(X()) |
| 1698 |
str_value = 'I am X' |
| 1699 |
if modulename in ['builtins', '__main__']: |
| 1700 |
str_name = X.__qualname__ |
| 1701 |
else: |
| 1702 |
str_name = '.'.join([X.__module__, X.__qualname__]) |
| 1703 |
exp = "%s: %s\n" % (str_name, str_value) |
| 1704 |
self.assertEqual(exp, err) |
| 1705 |
|
| 1706 |
def test_exception_modulename_not_unicode(self): |
| 1707 |
class X(Exception): |
| 1708 |
def __str__(self): |
| 1709 |
return "I am X" |
| 1710 |
|
| 1711 |
X.__module__ = 42 |
| 1712 |
|
| 1713 |
err = self.get_report(X()) |
| 1714 |
exp = f'<unknown>.{X.__qualname__}: I am X\n' |
| 1715 |
self.assertEqual(exp, err) |
| 1716 |
|
| 1717 |
def test_exception_bad__str__(self): |
| 1718 |
class X(Exception): |
| 1719 |
def __str__(self): |
| 1720 |
1/0 |
| 1721 |
err = self.get_report(X()) |
| 1722 |
str_value = '<exception str() failed>' |
| 1723 |
str_name = '.'.join([X.__module__, X.__qualname__]) |
| 1724 |
self.assertEqual(MODULE_PREFIX + err, f"{str_name}: {str_value}\n") |
| 1725 |
|
| 1726 |
|
| 1727 |
|
| 1728 |
|
| 1729 |
def test_exception_group_basic(self): |
| 1730 |
def exc(): |
| 1731 |
raise ExceptionGroup("eg", [ValueError(1), TypeError(2)]) |
| 1732 |
|
| 1733 |
expected = ( |
| 1734 |
f' + Exception Group Traceback (most recent call last):\n' |
| 1735 |
f' | File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 1736 |
f' | exception_or_callable()\n' |
| 1737 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 1}, in exc\n' |
| 1738 |
f' | raise ExceptionGroup("eg", [ValueError(1), TypeError(2)])\n' |
| 1739 |
f' | ExceptionGroup: eg (2 sub-exceptions)\n' |
| 1740 |
f' +-+---------------- 1 ----------------\n' |
| 1741 |
f' | ValueError: 1\n' |
| 1742 |
f' +---------------- 2 ----------------\n' |
| 1743 |
f' | TypeError: 2\n' |
| 1744 |
f' +------------------------------------\n') |
| 1745 |
|
| 1746 |
report = self.get_report(exc) |
| 1747 |
self.assertEqual(report, expected) |
| 1748 |
|
| 1749 |
def test_exception_group_cause(self): |
| 1750 |
def exc(): |
| 1751 |
EG = ExceptionGroup |
| 1752 |
try: |
| 1753 |
raise EG("eg1", [ValueError(1), TypeError(2)]) |
| 1754 |
except Exception as e: |
| 1755 |
raise EG("eg2", [ValueError(3), TypeError(4)]) from e |
| 1756 |
|
| 1757 |
expected = (f' + Exception Group Traceback (most recent call last):\n' |
| 1758 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 3}, in exc\n' |
| 1759 |
f' | raise EG("eg1", [ValueError(1), TypeError(2)])\n' |
| 1760 |
f' | ExceptionGroup: eg1 (2 sub-exceptions)\n' |
| 1761 |
f' +-+---------------- 1 ----------------\n' |
| 1762 |
f' | ValueError: 1\n' |
| 1763 |
f' +---------------- 2 ----------------\n' |
| 1764 |
f' | TypeError: 2\n' |
| 1765 |
f' +------------------------------------\n' |
| 1766 |
f'\n' |
| 1767 |
f'The above exception was the direct cause of the following exception:\n' |
| 1768 |
f'\n' |
| 1769 |
f' + Exception Group Traceback (most recent call last):\n' |
| 1770 |
f' | File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 1771 |
f' | exception_or_callable()\n' |
| 1772 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n' |
| 1773 |
f' | raise EG("eg2", [ValueError(3), TypeError(4)]) from e\n' |
| 1774 |
f' | ExceptionGroup: eg2 (2 sub-exceptions)\n' |
| 1775 |
f' +-+---------------- 1 ----------------\n' |
| 1776 |
f' | ValueError: 3\n' |
| 1777 |
f' +---------------- 2 ----------------\n' |
| 1778 |
f' | TypeError: 4\n' |
| 1779 |
f' +------------------------------------\n') |
| 1780 |
|
| 1781 |
report = self.get_report(exc) |
| 1782 |
self.assertEqual(report, expected) |
| 1783 |
|
| 1784 |
def test_exception_group_context_with_context(self): |
| 1785 |
def exc(): |
| 1786 |
EG = ExceptionGroup |
| 1787 |
try: |
| 1788 |
try: |
| 1789 |
raise EG("eg1", [ValueError(1), TypeError(2)]) |
| 1790 |
except: |
| 1791 |
raise EG("eg2", [ValueError(3), TypeError(4)]) |
| 1792 |
except: |
| 1793 |
raise ImportError(5) |
| 1794 |
|
| 1795 |
expected = ( |
| 1796 |
f' + Exception Group Traceback (most recent call last):\n' |
| 1797 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 4}, in exc\n' |
| 1798 |
f' | raise EG("eg1", [ValueError(1), TypeError(2)])\n' |
| 1799 |
f' | ExceptionGroup: eg1 (2 sub-exceptions)\n' |
| 1800 |
f' +-+---------------- 1 ----------------\n' |
| 1801 |
f' | ValueError: 1\n' |
| 1802 |
f' +---------------- 2 ----------------\n' |
| 1803 |
f' | TypeError: 2\n' |
| 1804 |
f' +------------------------------------\n' |
| 1805 |
f'\n' |
| 1806 |
f'During handling of the above exception, another exception occurred:\n' |
| 1807 |
f'\n' |
| 1808 |
f' + Exception Group Traceback (most recent call last):\n' |
| 1809 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 6}, in exc\n' |
| 1810 |
f' | raise EG("eg2", [ValueError(3), TypeError(4)])\n' |
| 1811 |
f' | ExceptionGroup: eg2 (2 sub-exceptions)\n' |
| 1812 |
f' +-+---------------- 1 ----------------\n' |
| 1813 |
f' | ValueError: 3\n' |
| 1814 |
f' +---------------- 2 ----------------\n' |
| 1815 |
f' | TypeError: 4\n' |
| 1816 |
f' +------------------------------------\n' |
| 1817 |
f'\n' |
| 1818 |
f'During handling of the above exception, another exception occurred:\n' |
| 1819 |
f'\n' |
| 1820 |
f'Traceback (most recent call last):\n' |
| 1821 |
f' File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 1822 |
f' exception_or_callable()\n' |
| 1823 |
f' File "{__file__}", line {exc.__code__.co_firstlineno + 8}, in exc\n' |
| 1824 |
f' raise ImportError(5)\n' |
| 1825 |
f'ImportError: 5\n') |
| 1826 |
|
| 1827 |
report = self.get_report(exc) |
| 1828 |
self.assertEqual(report, expected) |
| 1829 |
|
| 1830 |
def test_exception_group_nested(self): |
| 1831 |
def exc(): |
| 1832 |
EG = ExceptionGroup |
| 1833 |
VE = ValueError |
| 1834 |
TE = TypeError |
| 1835 |
try: |
| 1836 |
try: |
| 1837 |
raise EG("nested", [TE(2), TE(3)]) |
| 1838 |
except Exception as e: |
| 1839 |
exc = e |
| 1840 |
raise EG("eg", [VE(1), exc, VE(4)]) |
| 1841 |
except: |
| 1842 |
raise EG("top", [VE(5)]) |
| 1843 |
|
| 1844 |
expected = (f' + Exception Group Traceback (most recent call last):\n' |
| 1845 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 9}, in exc\n' |
| 1846 |
f' | raise EG("eg", [VE(1), exc, VE(4)])\n' |
| 1847 |
f' | ExceptionGroup: eg (3 sub-exceptions)\n' |
| 1848 |
f' +-+---------------- 1 ----------------\n' |
| 1849 |
f' | ValueError: 1\n' |
| 1850 |
f' +---------------- 2 ----------------\n' |
| 1851 |
f' | Exception Group Traceback (most recent call last):\n' |
| 1852 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 6}, in exc\n' |
| 1853 |
f' | raise EG("nested", [TE(2), TE(3)])\n' |
| 1854 |
f' | ExceptionGroup: nested (2 sub-exceptions)\n' |
| 1855 |
f' +-+---------------- 1 ----------------\n' |
| 1856 |
f' | TypeError: 2\n' |
| 1857 |
f' +---------------- 2 ----------------\n' |
| 1858 |
f' | TypeError: 3\n' |
| 1859 |
f' +------------------------------------\n' |
| 1860 |
f' +---------------- 3 ----------------\n' |
| 1861 |
f' | ValueError: 4\n' |
| 1862 |
f' +------------------------------------\n' |
| 1863 |
f'\n' |
| 1864 |
f'During handling of the above exception, another exception occurred:\n' |
| 1865 |
f'\n' |
| 1866 |
f' + Exception Group Traceback (most recent call last):\n' |
| 1867 |
f' | File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 1868 |
f' | exception_or_callable()\n' |
| 1869 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 11}, in exc\n' |
| 1870 |
f' | raise EG("top", [VE(5)])\n' |
| 1871 |
f' | ExceptionGroup: top (1 sub-exception)\n' |
| 1872 |
f' +-+---------------- 1 ----------------\n' |
| 1873 |
f' | ValueError: 5\n' |
| 1874 |
f' +------------------------------------\n') |
| 1875 |
|
| 1876 |
report = self.get_report(exc) |
| 1877 |
self.assertEqual(report, expected) |
| 1878 |
|
| 1879 |
def test_exception_group_width_limit(self): |
| 1880 |
excs = [] |
| 1881 |
for i in range(1000): |
| 1882 |
excs.append(ValueError(i)) |
| 1883 |
eg = ExceptionGroup('eg', excs) |
| 1884 |
|
| 1885 |
expected = (' | ExceptionGroup: eg (1000 sub-exceptions)\n' |
| 1886 |
' +-+---------------- 1 ----------------\n' |
| 1887 |
' | ValueError: 0\n' |
| 1888 |
' +---------------- 2 ----------------\n' |
| 1889 |
' | ValueError: 1\n' |
| 1890 |
' +---------------- 3 ----------------\n' |
| 1891 |
' | ValueError: 2\n' |
| 1892 |
' +---------------- 4 ----------------\n' |
| 1893 |
' | ValueError: 3\n' |
| 1894 |
' +---------------- 5 ----------------\n' |
| 1895 |
' | ValueError: 4\n' |
| 1896 |
' +---------------- 6 ----------------\n' |
| 1897 |
' | ValueError: 5\n' |
| 1898 |
' +---------------- 7 ----------------\n' |
| 1899 |
' | ValueError: 6\n' |
| 1900 |
' +---------------- 8 ----------------\n' |
| 1901 |
' | ValueError: 7\n' |
| 1902 |
' +---------------- 9 ----------------\n' |
| 1903 |
' | ValueError: 8\n' |
| 1904 |
' +---------------- 10 ----------------\n' |
| 1905 |
' | ValueError: 9\n' |
| 1906 |
' +---------------- 11 ----------------\n' |
| 1907 |
' | ValueError: 10\n' |
| 1908 |
' +---------------- 12 ----------------\n' |
| 1909 |
' | ValueError: 11\n' |
| 1910 |
' +---------------- 13 ----------------\n' |
| 1911 |
' | ValueError: 12\n' |
| 1912 |
' +---------------- 14 ----------------\n' |
| 1913 |
' | ValueError: 13\n' |
| 1914 |
' +---------------- 15 ----------------\n' |
| 1915 |
' | ValueError: 14\n' |
| 1916 |
' +---------------- ... ----------------\n' |
| 1917 |
' | and 985 more exceptions\n' |
| 1918 |
' +------------------------------------\n') |
| 1919 |
|
| 1920 |
report = self.get_report(eg) |
| 1921 |
self.assertEqual(report, expected) |
| 1922 |
|
| 1923 |
def test_exception_group_depth_limit(self): |
| 1924 |
exc = TypeError('bad type') |
| 1925 |
for i in range(1000): |
| 1926 |
exc = ExceptionGroup( |
| 1927 |
f'eg{i}', |
| 1928 |
[ValueError(i), exc, ValueError(-i)]) |
| 1929 |
|
| 1930 |
expected = (' | ExceptionGroup: eg999 (3 sub-exceptions)\n' |
| 1931 |
' +-+---------------- 1 ----------------\n' |
| 1932 |
' | ValueError: 999\n' |
| 1933 |
' +---------------- 2 ----------------\n' |
| 1934 |
' | ExceptionGroup: eg998 (3 sub-exceptions)\n' |
| 1935 |
' +-+---------------- 1 ----------------\n' |
| 1936 |
' | ValueError: 998\n' |
| 1937 |
' +---------------- 2 ----------------\n' |
| 1938 |
' | ExceptionGroup: eg997 (3 sub-exceptions)\n' |
| 1939 |
' +-+---------------- 1 ----------------\n' |
| 1940 |
' | ValueError: 997\n' |
| 1941 |
' +---------------- 2 ----------------\n' |
| 1942 |
' | ExceptionGroup: eg996 (3 sub-exceptions)\n' |
| 1943 |
' +-+---------------- 1 ----------------\n' |
| 1944 |
' | ValueError: 996\n' |
| 1945 |
' +---------------- 2 ----------------\n' |
| 1946 |
' | ExceptionGroup: eg995 (3 sub-exceptions)\n' |
| 1947 |
' +-+---------------- 1 ----------------\n' |
| 1948 |
' | ValueError: 995\n' |
| 1949 |
' +---------------- 2 ----------------\n' |
| 1950 |
' | ExceptionGroup: eg994 (3 sub-exceptions)\n' |
| 1951 |
' +-+---------------- 1 ----------------\n' |
| 1952 |
' | ValueError: 994\n' |
| 1953 |
' +---------------- 2 ----------------\n' |
| 1954 |
' | ExceptionGroup: eg993 (3 sub-exceptions)\n' |
| 1955 |
' +-+---------------- 1 ----------------\n' |
| 1956 |
' | ValueError: 993\n' |
| 1957 |
' +---------------- 2 ----------------\n' |
| 1958 |
' | ExceptionGroup: eg992 (3 sub-exceptions)\n' |
| 1959 |
' +-+---------------- 1 ----------------\n' |
| 1960 |
' | ValueError: 992\n' |
| 1961 |
' +---------------- 2 ----------------\n' |
| 1962 |
' | ExceptionGroup: eg991 (3 sub-exceptions)\n' |
| 1963 |
' +-+---------------- 1 ----------------\n' |
| 1964 |
' | ValueError: 991\n' |
| 1965 |
' +---------------- 2 ----------------\n' |
| 1966 |
' | ExceptionGroup: eg990 (3 sub-exceptions)\n' |
| 1967 |
' +-+---------------- 1 ----------------\n' |
| 1968 |
' | ValueError: 990\n' |
| 1969 |
' +---------------- 2 ----------------\n' |
| 1970 |
' | ... (max_group_depth is 10)\n' |
| 1971 |
' +---------------- 3 ----------------\n' |
| 1972 |
' | ValueError: -990\n' |
| 1973 |
' +------------------------------------\n' |
| 1974 |
' +---------------- 3 ----------------\n' |
| 1975 |
' | ValueError: -991\n' |
| 1976 |
' +------------------------------------\n' |
| 1977 |
' +---------------- 3 ----------------\n' |
| 1978 |
' | ValueError: -992\n' |
| 1979 |
' +------------------------------------\n' |
| 1980 |
' +---------------- 3 ----------------\n' |
| 1981 |
' | ValueError: -993\n' |
| 1982 |
' +------------------------------------\n' |
| 1983 |
' +---------------- 3 ----------------\n' |
| 1984 |
' | ValueError: -994\n' |
| 1985 |
' +------------------------------------\n' |
| 1986 |
' +---------------- 3 ----------------\n' |
| 1987 |
' | ValueError: -995\n' |
| 1988 |
' +------------------------------------\n' |
| 1989 |
' +---------------- 3 ----------------\n' |
| 1990 |
' | ValueError: -996\n' |
| 1991 |
' +------------------------------------\n' |
| 1992 |
' +---------------- 3 ----------------\n' |
| 1993 |
' | ValueError: -997\n' |
| 1994 |
' +------------------------------------\n' |
| 1995 |
' +---------------- 3 ----------------\n' |
| 1996 |
' | ValueError: -998\n' |
| 1997 |
' +------------------------------------\n' |
| 1998 |
' +---------------- 3 ----------------\n' |
| 1999 |
' | ValueError: -999\n' |
| 2000 |
' +------------------------------------\n') |
| 2001 |
|
| 2002 |
report = self.get_report(exc) |
| 2003 |
self.assertEqual(report, expected) |
| 2004 |
|
| 2005 |
def test_exception_group_with_notes(self): |
| 2006 |
def exc(): |
| 2007 |
try: |
| 2008 |
excs = [] |
| 2009 |
for msg in ['bad value', 'terrible value']: |
| 2010 |
try: |
| 2011 |
raise ValueError(msg) |
| 2012 |
except ValueError as e: |
| 2013 |
e.add_note(f'the {msg}') |
| 2014 |
excs.append(e) |
| 2015 |
raise ExceptionGroup("nested", excs) |
| 2016 |
except ExceptionGroup as e: |
| 2017 |
e.add_note(('>> Multi line note\n' |
| 2018 |
'>> Because I am such\n' |
| 2019 |
'>> an important exception.\n' |
| 2020 |
'>> empty lines work too\n' |
| 2021 |
'\n' |
| 2022 |
'(that was an empty line)')) |
| 2023 |
raise |
| 2024 |
|
| 2025 |
expected = (f' + Exception Group Traceback (most recent call last):\n' |
| 2026 |
f' | File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 2027 |
f' | exception_or_callable()\n' |
| 2028 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 9}, in exc\n' |
| 2029 |
f' | raise ExceptionGroup("nested", excs)\n' |
| 2030 |
f' | ExceptionGroup: nested (2 sub-exceptions)\n' |
| 2031 |
f' | >> Multi line note\n' |
| 2032 |
f' | >> Because I am such\n' |
| 2033 |
f' | >> an important exception.\n' |
| 2034 |
f' | >> empty lines work too\n' |
| 2035 |
f' | \n' |
| 2036 |
f' | (that was an empty line)\n' |
| 2037 |
f' +-+---------------- 1 ----------------\n' |
| 2038 |
f' | Traceback (most recent call last):\n' |
| 2039 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n' |
| 2040 |
f' | raise ValueError(msg)\n' |
| 2041 |
f' | ValueError: bad value\n' |
| 2042 |
f' | the bad value\n' |
| 2043 |
f' +---------------- 2 ----------------\n' |
| 2044 |
f' | Traceback (most recent call last):\n' |
| 2045 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n' |
| 2046 |
f' | raise ValueError(msg)\n' |
| 2047 |
f' | ValueError: terrible value\n' |
| 2048 |
f' | the terrible value\n' |
| 2049 |
f' +------------------------------------\n') |
| 2050 |
|
| 2051 |
report = self.get_report(exc) |
| 2052 |
self.assertEqual(report, expected) |
| 2053 |
|
| 2054 |
def test_exception_group_with_multiple_notes(self): |
| 2055 |
def exc(): |
| 2056 |
try: |
| 2057 |
excs = [] |
| 2058 |
for msg in ['bad value', 'terrible value']: |
| 2059 |
try: |
| 2060 |
raise ValueError(msg) |
| 2061 |
except ValueError as e: |
| 2062 |
e.add_note(f'the {msg}') |
| 2063 |
e.add_note(f'Goodbye {msg}') |
| 2064 |
excs.append(e) |
| 2065 |
raise ExceptionGroup("nested", excs) |
| 2066 |
except ExceptionGroup as e: |
| 2067 |
e.add_note(('>> Multi line note\n' |
| 2068 |
'>> Because I am such\n' |
| 2069 |
'>> an important exception.\n' |
| 2070 |
'>> empty lines work too\n' |
| 2071 |
'\n' |
| 2072 |
'(that was an empty line)')) |
| 2073 |
e.add_note('Goodbye!') |
| 2074 |
raise |
| 2075 |
|
| 2076 |
expected = (f' + Exception Group Traceback (most recent call last):\n' |
| 2077 |
f' | File "{__file__}", line {self.callable_line}, in get_exception\n' |
| 2078 |
f' | exception_or_callable()\n' |
| 2079 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 10}, in exc\n' |
| 2080 |
f' | raise ExceptionGroup("nested", excs)\n' |
| 2081 |
f' | ExceptionGroup: nested (2 sub-exceptions)\n' |
| 2082 |
f' | >> Multi line note\n' |
| 2083 |
f' | >> Because I am such\n' |
| 2084 |
f' | >> an important exception.\n' |
| 2085 |
f' | >> empty lines work too\n' |
| 2086 |
f' | \n' |
| 2087 |
f' | (that was an empty line)\n' |
| 2088 |
f' | Goodbye!\n' |
| 2089 |
f' +-+---------------- 1 ----------------\n' |
| 2090 |
f' | Traceback (most recent call last):\n' |
| 2091 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n' |
| 2092 |
f' | raise ValueError(msg)\n' |
| 2093 |
f' | ValueError: bad value\n' |
| 2094 |
f' | the bad value\n' |
| 2095 |
f' | Goodbye bad value\n' |
| 2096 |
f' +---------------- 2 ----------------\n' |
| 2097 |
f' | Traceback (most recent call last):\n' |
| 2098 |
f' | File "{__file__}", line {exc.__code__.co_firstlineno + 5}, in exc\n' |
| 2099 |
f' | raise ValueError(msg)\n' |
| 2100 |
f' | ValueError: terrible value\n' |
| 2101 |
f' | the terrible value\n' |
| 2102 |
f' | Goodbye terrible value\n' |
| 2103 |
f' +------------------------------------\n') |
| 2104 |
|
| 2105 |
report = self.get_report(exc) |
| 2106 |
self.assertEqual(report, expected) |
| 2107 |
|
| 2108 |
@cpython_only |
| 2109 |
def test_KeyboardInterrupt_at_first_line_of_frame(self): |
| 2110 |
|
| 2111 |
def f(): |
| 2112 |
return sys._getframe() |
| 2113 |
|
| 2114 |
tb_next = None |
| 2115 |
frame = f() |
| 2116 |
lasti = 0 |
| 2117 |
lineno = f.__code__.co_firstlineno |
| 2118 |
tb = types.TracebackType(tb_next, frame, lasti, lineno) |
| 2119 |
|
| 2120 |
exc = KeyboardInterrupt() |
| 2121 |
exc.__traceback__ = tb |
| 2122 |
|
| 2123 |
expected = (f'Traceback (most recent call last):\n' |
| 2124 |
f' File "{__file__}", line {lineno}, in f\n' |
| 2125 |
f' def f():\n' |
| 2126 |
f'\n' |
| 2127 |
f'KeyboardInterrupt\n') |
| 2128 |
|
| 2129 |
report = self.get_report(exc) |
| 2130 |
|
| 2131 |
report = '\n'.join([l.rstrip() for l in report.split('\n')]) |
| 2132 |
self.assertEqual(report, expected) |
| 2133 |
|
| 2134 |
|
| 2135 |
class PyExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): |
| 2136 |
|
| 2137 |
|
| 2138 |
|
| 2139 |
|
| 2140 |
|
| 2141 |
def get_report(self, e): |
| 2142 |
e = self.get_exception(e) |
| 2143 |
s = ''.join( |
| 2144 |
traceback.format_exception(type(e), e, e.__traceback__)) |
| 2145 |
with captured_output("stderr") as sio: |
| 2146 |
traceback.print_exception(type(e), e, e.__traceback__) |
| 2147 |
self.assertEqual(sio.getvalue(), s) |
| 2148 |
return s |
| 2149 |
|
| 2150 |
|
| 2151 |
class CExcReportingTests(BaseExceptionReportingTests, unittest.TestCase): |
| 2152 |
|
| 2153 |
|
| 2154 |
|
| 2155 |
|
| 2156 |
@cpython_only |
| 2157 |
def get_report(self, e): |
| 2158 |
from _testcapi import exception_print |
| 2159 |
e = self.get_exception(e) |
| 2160 |
with captured_output("stderr") as s: |
| 2161 |
exception_print(e) |
| 2162 |
return s.getvalue() |
| 2163 |
|
| 2164 |
|
| 2165 |
class LimitTests(unittest.TestCase): |
| 2166 |
|
| 2167 |
''' Tests for limit argument. |
| 2168 |
It's enough to test extact_tb, extract_stack and format_exception ''' |
| 2169 |
|
| 2170 |
def last_raises1(self): |
| 2171 |
raise Exception('Last raised') |
| 2172 |
|
| 2173 |
def last_raises2(self): |
| 2174 |
self.last_raises1() |
| 2175 |
|
| 2176 |
def last_raises3(self): |
| 2177 |
self.last_raises2() |
| 2178 |
|
| 2179 |
def last_raises4(self): |
| 2180 |
self.last_raises3() |
| 2181 |
|
| 2182 |
def last_raises5(self): |
| 2183 |
self.last_raises4() |
| 2184 |
|
| 2185 |
def last_returns_frame1(self): |
| 2186 |
return sys._getframe() |
| 2187 |
|
| 2188 |
def last_returns_frame2(self): |
| 2189 |
return self.last_returns_frame1() |
| 2190 |
|
| 2191 |
def last_returns_frame3(self): |
| 2192 |
return self.last_returns_frame2() |
| 2193 |
|
| 2194 |
def last_returns_frame4(self): |
| 2195 |
return self.last_returns_frame3() |
| 2196 |
|
| 2197 |
def last_returns_frame5(self): |
| 2198 |
return self.last_returns_frame4() |
| 2199 |
|
| 2200 |
def test_extract_stack(self): |
| 2201 |
frame = self.last_returns_frame5() |
| 2202 |
def extract(**kwargs): |
| 2203 |
return traceback.extract_stack(frame, **kwargs) |
| 2204 |
def assertEqualExcept(actual, expected, ignore): |
| 2205 |
self.assertEqual(actual[:ignore], expected[:ignore]) |
| 2206 |
self.assertEqual(actual[ignore+1:], expected[ignore+1:]) |
| 2207 |
self.assertEqual(len(actual), len(expected)) |
| 2208 |
|
| 2209 |
with support.swap_attr(sys, 'tracebacklimit', 1000): |
| 2210 |
nolim = extract() |
| 2211 |
self.assertGreater(len(nolim), 5) |
| 2212 |
self.assertEqual(extract(limit=2), nolim[-2:]) |
| 2213 |
assertEqualExcept(extract(limit=100), nolim[-100:], -5-1) |
| 2214 |
self.assertEqual(extract(limit=-2), nolim[:2]) |
| 2215 |
assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1) |
| 2216 |
self.assertEqual(extract(limit=0), []) |
| 2217 |
del sys.tracebacklimit |
| 2218 |
assertEqualExcept(extract(), nolim, -5-1) |
| 2219 |
sys.tracebacklimit = 2 |
| 2220 |
self.assertEqual(extract(), nolim[-2:]) |
| 2221 |
self.assertEqual(extract(limit=3), nolim[-3:]) |
| 2222 |
self.assertEqual(extract(limit=-3), nolim[:3]) |
| 2223 |
sys.tracebacklimit = 0 |
| 2224 |
self.assertEqual(extract(), []) |
| 2225 |
sys.tracebacklimit = -1 |
| 2226 |
self.assertEqual(extract(), []) |
| 2227 |
|
| 2228 |
def test_extract_tb(self): |
| 2229 |
try: |
| 2230 |
self.last_raises5() |
| 2231 |
except Exception: |
| 2232 |
exc_type, exc_value, tb = sys.exc_info() |
| 2233 |
def extract(**kwargs): |
| 2234 |
return traceback.extract_tb(tb, **kwargs) |
| 2235 |
|
| 2236 |
with support.swap_attr(sys, 'tracebacklimit', 1000): |
| 2237 |
nolim = extract() |
| 2238 |
self.assertEqual(len(nolim), 5+1) |
| 2239 |
self.assertEqual(extract(limit=2), nolim[:2]) |
| 2240 |
self.assertEqual(extract(limit=10), nolim) |
| 2241 |
self.assertEqual(extract(limit=-2), nolim[-2:]) |
| 2242 |
self.assertEqual(extract(limit=-10), nolim) |
| 2243 |
self.assertEqual(extract(limit=0), []) |
| 2244 |
del sys.tracebacklimit |
| 2245 |
self.assertEqual(extract(), nolim) |
| 2246 |
sys.tracebacklimit = 2 |
| 2247 |
self.assertEqual(extract(), nolim[:2]) |
| 2248 |
self.assertEqual(extract(limit=3), nolim[:3]) |
| 2249 |
self.assertEqual(extract(limit=-3), nolim[-3:]) |
| 2250 |
sys.tracebacklimit = 0 |
| 2251 |
self.assertEqual(extract(), []) |
| 2252 |
sys.tracebacklimit = -1 |
| 2253 |
self.assertEqual(extract(), []) |
| 2254 |
|
| 2255 |
def test_format_exception(self): |
| 2256 |
try: |
| 2257 |
self.last_raises5() |
| 2258 |
except Exception: |
| 2259 |
exc_type, exc_value, tb = sys.exc_info() |
| 2260 |
|
| 2261 |
|
| 2262 |
def extract(**kwargs): |
| 2263 |
return traceback.format_exception(exc_type, exc_value, tb, **kwargs)[1:-1] |
| 2264 |
|
| 2265 |
with support.swap_attr(sys, 'tracebacklimit', 1000): |
| 2266 |
nolim = extract() |
| 2267 |
self.assertEqual(len(nolim), 5+1) |
| 2268 |
self.assertEqual(extract(limit=2), nolim[:2]) |
| 2269 |
self.assertEqual(extract(limit=10), nolim) |
| 2270 |
self.assertEqual(extract(limit=-2), nolim[-2:]) |
| 2271 |
self.assertEqual(extract(limit=-10), nolim) |
| 2272 |
self.assertEqual(extract(limit=0), []) |
| 2273 |
del sys.tracebacklimit |
| 2274 |
self.assertEqual(extract(), nolim) |
| 2275 |
sys.tracebacklimit = 2 |
| 2276 |
self.assertEqual(extract(), nolim[:2]) |
| 2277 |
self.assertEqual(extract(limit=3), nolim[:3]) |
| 2278 |
self.assertEqual(extract(limit=-3), nolim[-3:]) |
| 2279 |
sys.tracebacklimit = 0 |
| 2280 |
self.assertEqual(extract(), []) |
| 2281 |
sys.tracebacklimit = -1 |
| 2282 |
self.assertEqual(extract(), []) |
| 2283 |
|
| 2284 |
|
| 2285 |
class MiscTracebackCases(unittest.TestCase): |
| 2286 |
|
| 2287 |
|
| 2288 |
|
| 2289 |
|
| 2290 |
def test_clear(self): |
| 2291 |
def outer(): |
| 2292 |
middle() |
| 2293 |
def middle(): |
| 2294 |
inner() |
| 2295 |
def inner(): |
| 2296 |
i = 1 |
| 2297 |
1/0 |
| 2298 |
|
| 2299 |
try: |
| 2300 |
outer() |
| 2301 |
except: |
| 2302 |
type_, value, tb = sys.exc_info() |
| 2303 |
|
| 2304 |
|
| 2305 |
inner_frame = tb.tb_next.tb_next.tb_next.tb_frame |
| 2306 |
self.assertEqual(len(inner_frame.f_locals), 1) |
| 2307 |
|
| 2308 |
|
| 2309 |
traceback.clear_frames(tb) |
| 2310 |
|
| 2311 |
|
| 2312 |
self.assertEqual(len(inner_frame.f_locals), 0) |
| 2313 |
|
| 2314 |
def test_extract_stack(self): |
| 2315 |
def extract(): |
| 2316 |
return traceback.extract_stack() |
| 2317 |
result = extract() |
| 2318 |
lineno = extract.__code__.co_firstlineno |
| 2319 |
self.assertEqual(result[-2:], [ |
| 2320 |
(__file__, lineno+2, 'test_extract_stack', 'result = extract()'), |
| 2321 |
(__file__, lineno+1, 'extract', 'return traceback.extract_stack()'), |
| 2322 |
]) |
| 2323 |
self.assertEqual(len(result[0]), 4) |
| 2324 |
|
| 2325 |
|
| 2326 |
class TestFrame(unittest.TestCase): |
| 2327 |
|
| 2328 |
def test_basics(self): |
| 2329 |
linecache.clearcache() |
| 2330 |
linecache.lazycache("f", globals()) |
| 2331 |
f = traceback.FrameSummary("f", 1, "dummy") |
| 2332 |
self.assertEqual(f, |
| 2333 |
("f", 1, "dummy", '"""Test cases for traceback module"""')) |
| 2334 |
self.assertEqual(tuple(f), |
| 2335 |
("f", 1, "dummy", '"""Test cases for traceback module"""')) |
| 2336 |
self.assertEqual(f, traceback.FrameSummary("f", 1, "dummy")) |
| 2337 |
self.assertEqual(f, tuple(f)) |
| 2338 |
|
| 2339 |
|
| 2340 |
self.assertEqual(tuple(f), f) |
| 2341 |
self.assertIsNone(f.locals) |
| 2342 |
self.assertNotEqual(f, object()) |
| 2343 |
self.assertEqual(f, ALWAYS_EQ) |
| 2344 |
|
| 2345 |
def test_lazy_lines(self): |
| 2346 |
linecache.clearcache() |
| 2347 |
f = traceback.FrameSummary("f", 1, "dummy", lookup_line=False) |
| 2348 |
self.assertEqual(None, f._line) |
| 2349 |
linecache.lazycache("f", globals()) |
| 2350 |
self.assertEqual( |
| 2351 |
'"""Test cases for traceback module"""', |
| 2352 |
f.line) |
| 2353 |
|
| 2354 |
def test_no_line(self): |
| 2355 |
f = traceback.FrameSummary("f", None, "dummy") |
| 2356 |
self.assertEqual(f.line, None) |
| 2357 |
|
| 2358 |
def test_explicit_line(self): |
| 2359 |
f = traceback.FrameSummary("f", 1, "dummy", line="line") |
| 2360 |
self.assertEqual("line", f.line) |
| 2361 |
|
| 2362 |
def test_len(self): |
| 2363 |
f = traceback.FrameSummary("f", 1, "dummy", line="line") |
| 2364 |
self.assertEqual(len(f), 4) |
| 2365 |
|
| 2366 |
|
| 2367 |
class TestStack(unittest.TestCase): |
| 2368 |
|
| 2369 |
@cpython_only |
| 2370 |
def test_walk_stack(self): |
| 2371 |
def deeper(): |
| 2372 |
return list(traceback.walk_stack(None)) |
| 2373 |
s1 = list(traceback.walk_stack(None)) |
| 2374 |
s2 = deeper() |
| 2375 |
self.assertEqual(len(s2) - len(s1), 1) |
| 2376 |
self.assertEqual(s2[1:], s1) |
| 2377 |
|
| 2378 |
def test_walk_tb(self): |
| 2379 |
try: |
| 2380 |
1/0 |
| 2381 |
except Exception: |
| 2382 |
_, _, tb = sys.exc_info() |
| 2383 |
s = list(traceback.walk_tb(tb)) |
| 2384 |
self.assertEqual(len(s), 1) |
| 2385 |
|
| 2386 |
def test_extract_stack(self): |
| 2387 |
s = traceback.StackSummary.extract(traceback.walk_stack(None)) |
| 2388 |
self.assertIsInstance(s, traceback.StackSummary) |
| 2389 |
|
| 2390 |
def test_extract_stack_limit(self): |
| 2391 |
s = traceback.StackSummary.extract(traceback.walk_stack(None), limit=5) |
| 2392 |
self.assertEqual(len(s), 5) |
| 2393 |
|
| 2394 |
def test_extract_stack_lookup_lines(self): |
| 2395 |
linecache.clearcache() |
| 2396 |
linecache.updatecache('/foo.py', globals()) |
| 2397 |
c = test_code('/foo.py', 'method') |
| 2398 |
f = test_frame(c, None, None) |
| 2399 |
s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=True) |
| 2400 |
linecache.clearcache() |
| 2401 |
self.assertEqual(s[0].line, "import sys") |
| 2402 |
|
| 2403 |
def test_extract_stackup_deferred_lookup_lines(self): |
| 2404 |
linecache.clearcache() |
| 2405 |
c = test_code('/foo.py', 'method') |
| 2406 |
f = test_frame(c, None, None) |
| 2407 |
s = traceback.StackSummary.extract(iter([(f, 6)]), lookup_lines=False) |
| 2408 |
self.assertEqual({}, linecache.cache) |
| 2409 |
linecache.updatecache('/foo.py', globals()) |
| 2410 |
self.assertEqual(s[0].line, "import sys") |
| 2411 |
|
| 2412 |
def test_from_list(self): |
| 2413 |
s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')]) |
| 2414 |
self.assertEqual( |
| 2415 |
[' File "foo.py", line 1, in fred\n line\n'], |
| 2416 |
s.format()) |
| 2417 |
|
| 2418 |
def test_from_list_edited_stack(self): |
| 2419 |
s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')]) |
| 2420 |
s[0] = ('foo.py', 2, 'fred', 'line') |
| 2421 |
s2 = traceback.StackSummary.from_list(s) |
| 2422 |
self.assertEqual( |
| 2423 |
[' File "foo.py", line 2, in fred\n line\n'], |
| 2424 |
s2.format()) |
| 2425 |
|
| 2426 |
def test_format_smoke(self): |
| 2427 |
|
| 2428 |
|
| 2429 |
s = traceback.StackSummary.from_list([('foo.py', 1, 'fred', 'line')]) |
| 2430 |
self.assertEqual( |
| 2431 |
[' File "foo.py", line 1, in fred\n line\n'], |
| 2432 |
s.format()) |
| 2433 |
|
| 2434 |
def test_locals(self): |
| 2435 |
linecache.updatecache('/foo.py', globals()) |
| 2436 |
c = test_code('/foo.py', 'method') |
| 2437 |
f = test_frame(c, globals(), {'something': 1}) |
| 2438 |
s = traceback.StackSummary.extract(iter([(f, 6)]), capture_locals=True) |
| 2439 |
self.assertEqual(s[0].locals, {'something': '1'}) |
| 2440 |
|
| 2441 |
def test_no_locals(self): |
| 2442 |
linecache.updatecache('/foo.py', globals()) |
| 2443 |
c = test_code('/foo.py', 'method') |
| 2444 |
f = test_frame(c, globals(), {'something': 1}) |
| 2445 |
s = traceback.StackSummary.extract(iter([(f, 6)])) |
| 2446 |
self.assertEqual(s[0].locals, None) |
| 2447 |
|
| 2448 |
def test_format_locals(self): |
| 2449 |
def some_inner(k, v): |
| 2450 |
a = 1 |
| 2451 |
b = 2 |
| 2452 |
return traceback.StackSummary.extract( |
| 2453 |
traceback.walk_stack(None), capture_locals=True, limit=1) |
| 2454 |
s = some_inner(3, 4) |
| 2455 |
self.assertEqual( |
| 2456 |
[' File "%s", line %d, in some_inner\n' |
| 2457 |
' return traceback.StackSummary.extract(\n' |
| 2458 |
' a = 1\n' |
| 2459 |
' b = 2\n' |
| 2460 |
' k = 3\n' |
| 2461 |
' v = 4\n' % (__file__, some_inner.__code__.co_firstlineno + 3) |
| 2462 |
], s.format()) |
| 2463 |
|
| 2464 |
def test_custom_format_frame(self): |
| 2465 |
class CustomStackSummary(traceback.StackSummary): |
| 2466 |
def format_frame_summary(self, frame_summary, **kwargs): |
| 2467 |
return f'{frame_summary.filename}:{frame_summary.lineno}' |
| 2468 |
|
| 2469 |
def some_inner(): |
| 2470 |
return CustomStackSummary.extract( |
| 2471 |
traceback.walk_stack(None), limit=1) |
| 2472 |
|
| 2473 |
s = some_inner() |
| 2474 |
self.assertEqual( |
| 2475 |
s.format(), |
| 2476 |
[f'{__file__}:{some_inner.__code__.co_firstlineno + 1}']) |
| 2477 |
|
| 2478 |
@cpython_only |
| 2479 |
def test_dropping_frames(self): |
| 2480 |
def f(): |
| 2481 |
1/0 |
| 2482 |
|
| 2483 |
def g(): |
| 2484 |
try: |
| 2485 |
f() |
| 2486 |
except: |
| 2487 |
return sys.exc_info() |
| 2488 |
|
| 2489 |
exc_info = g() |
| 2490 |
|
| 2491 |
class Skip_G(traceback.StackSummary): |
| 2492 |
def format_frame_summary(self, frame_summary, **kwargs): |
| 2493 |
if frame_summary.name == 'g': |
| 2494 |
return None |
| 2495 |
return super().format_frame_summary(frame_summary, **kwargs) |
| 2496 |
|
| 2497 |
stack = Skip_G.extract( |
| 2498 |
traceback.walk_tb(exc_info[2])).format() |
| 2499 |
|
| 2500 |
self.assertEqual(len(stack), 1) |
| 2501 |
lno = f.__code__.co_firstlineno + 1 |
| 2502 |
self.assertEqual( |
| 2503 |
stack[0], |
| 2504 |
f' File "{__file__}", line {lno}, in f\n 1/0\n' |
| 2505 |
) |
| 2506 |
|
| 2507 |
|
| 2508 |
class TestTracebackException(unittest.TestCase): |
| 2509 |
|
| 2510 |
def test_smoke(self): |
| 2511 |
try: |
| 2512 |
1/0 |
| 2513 |
except Exception: |
| 2514 |
exc_info = sys.exc_info() |
| 2515 |
exc = traceback.TracebackException(*exc_info) |
| 2516 |
expected_stack = traceback.StackSummary.extract( |
| 2517 |
traceback.walk_tb(exc_info[2])) |
| 2518 |
self.assertEqual(None, exc.__cause__) |
| 2519 |
self.assertEqual(None, exc.__context__) |
| 2520 |
self.assertEqual(False, exc.__suppress_context__) |
| 2521 |
self.assertEqual(expected_stack, exc.stack) |
| 2522 |
self.assertEqual(exc_info[0], exc.exc_type) |
| 2523 |
self.assertEqual(str(exc_info[1]), str(exc)) |
| 2524 |
|
| 2525 |
def test_from_exception(self): |
| 2526 |
|
| 2527 |
def foo(): |
| 2528 |
1/0 |
| 2529 |
try: |
| 2530 |
foo() |
| 2531 |
except Exception as e: |
| 2532 |
exc_info = sys.exc_info() |
| 2533 |
self.expected_stack = traceback.StackSummary.extract( |
| 2534 |
traceback.walk_tb(exc_info[2]), limit=1, lookup_lines=False, |
| 2535 |
capture_locals=True) |
| 2536 |
self.exc = traceback.TracebackException.from_exception( |
| 2537 |
e, limit=1, lookup_lines=False, capture_locals=True) |
| 2538 |
expected_stack = self.expected_stack |
| 2539 |
exc = self.exc |
| 2540 |
self.assertEqual(None, exc.__cause__) |
| 2541 |
self.assertEqual(None, exc.__context__) |
| 2542 |
self.assertEqual(False, exc.__suppress_context__) |
| 2543 |
self.assertEqual(expected_stack, exc.stack) |
| 2544 |
self.assertEqual(exc_info[0], exc.exc_type) |
| 2545 |
self.assertEqual(str(exc_info[1]), str(exc)) |
| 2546 |
|
| 2547 |
def test_cause(self): |
| 2548 |
try: |
| 2549 |
try: |
| 2550 |
1/0 |
| 2551 |
finally: |
| 2552 |
exc_info_context = sys.exc_info() |
| 2553 |
exc_context = traceback.TracebackException(*exc_info_context) |
| 2554 |
cause = Exception("cause") |
| 2555 |
raise Exception("uh oh") from cause |
| 2556 |
except Exception: |
| 2557 |
exc_info = sys.exc_info() |
| 2558 |
exc = traceback.TracebackException(*exc_info) |
| 2559 |
expected_stack = traceback.StackSummary.extract( |
| 2560 |
traceback.walk_tb(exc_info[2])) |
| 2561 |
exc_cause = traceback.TracebackException(Exception, cause, None) |
| 2562 |
self.assertEqual(exc_cause, exc.__cause__) |
| 2563 |
self.assertEqual(exc_context, exc.__context__) |
| 2564 |
self.assertEqual(True, exc.__suppress_context__) |
| 2565 |
self.assertEqual(expected_stack, exc.stack) |
| 2566 |
self.assertEqual(exc_info[0], exc.exc_type) |
| 2567 |
self.assertEqual(str(exc_info[1]), str(exc)) |
| 2568 |
|
| 2569 |
def test_context(self): |
| 2570 |
try: |
| 2571 |
try: |
| 2572 |
1/0 |
| 2573 |
finally: |
| 2574 |
exc_info_context = sys.exc_info() |
| 2575 |
exc_context = traceback.TracebackException(*exc_info_context) |
| 2576 |
raise Exception("uh oh") |
| 2577 |
except Exception: |
| 2578 |
exc_info = sys.exc_info() |
| 2579 |
exc = traceback.TracebackException(*exc_info) |
| 2580 |
expected_stack = traceback.StackSummary.extract( |
| 2581 |
traceback.walk_tb(exc_info[2])) |
| 2582 |
self.assertEqual(None, exc.__cause__) |
| 2583 |
self.assertEqual(exc_context, exc.__context__) |
| 2584 |
self.assertEqual(False, exc.__suppress_context__) |
| 2585 |
self.assertEqual(expected_stack, exc.stack) |
| 2586 |
self.assertEqual(exc_info[0], exc.exc_type) |
| 2587 |
self.assertEqual(str(exc_info[1]), str(exc)) |
| 2588 |
|
| 2589 |
def test_long_context_chain(self): |
| 2590 |
def f(): |
| 2591 |
try: |
| 2592 |
1/0 |
| 2593 |
except: |
| 2594 |
f() |
| 2595 |
|
| 2596 |
try: |
| 2597 |
f() |
| 2598 |
except RecursionError: |
| 2599 |
exc_info = sys.exc_info() |
| 2600 |
else: |
| 2601 |
self.fail("Exception not raised") |
| 2602 |
|
| 2603 |
te = traceback.TracebackException(*exc_info) |
| 2604 |
res = list(te.format()) |
| 2605 |
|
| 2606 |
|
| 2607 |
self.assertGreater(len(res), sys.getrecursionlimit()) |
| 2608 |
self.assertGreater( |
| 2609 |
len([l for l in res if 'ZeroDivisionError:' in l]), |
| 2610 |
sys.getrecursionlimit() * 0.5) |
| 2611 |
self.assertIn( |
| 2612 |
"RecursionError: maximum recursion depth exceeded", res[-1]) |
| 2613 |
|
| 2614 |
def test_compact_with_cause(self): |
| 2615 |
try: |
| 2616 |
try: |
| 2617 |
1/0 |
| 2618 |
finally: |
| 2619 |
cause = Exception("cause") |
| 2620 |
raise Exception("uh oh") from cause |
| 2621 |
except Exception: |
| 2622 |
exc_info = sys.exc_info() |
| 2623 |
exc = traceback.TracebackException(*exc_info, compact=True) |
| 2624 |
expected_stack = traceback.StackSummary.extract( |
| 2625 |
traceback.walk_tb(exc_info[2])) |
| 2626 |
exc_cause = traceback.TracebackException(Exception, cause, None) |
| 2627 |
self.assertEqual(exc_cause, exc.__cause__) |
| 2628 |
self.assertEqual(None, exc.__context__) |
| 2629 |
self.assertEqual(True, exc.__suppress_context__) |
| 2630 |
self.assertEqual(expected_stack, exc.stack) |
| 2631 |
self.assertEqual(exc_info[0], exc.exc_type) |
| 2632 |
self.assertEqual(str(exc_info[1]), str(exc)) |
| 2633 |
|
| 2634 |
def test_compact_no_cause(self): |
| 2635 |
try: |
| 2636 |
try: |
| 2637 |
1/0 |
| 2638 |
finally: |
| 2639 |
exc_info_context = sys.exc_info() |
| 2640 |
exc_context = traceback.TracebackException(*exc_info_context) |
| 2641 |
raise Exception("uh oh") |
| 2642 |
except Exception: |
| 2643 |
exc_info = sys.exc_info() |
| 2644 |
exc = traceback.TracebackException(*exc_info, compact=True) |
| 2645 |
expected_stack = traceback.StackSummary.extract( |
| 2646 |
traceback.walk_tb(exc_info[2])) |
| 2647 |
self.assertEqual(None, exc.__cause__) |
| 2648 |
self.assertEqual(exc_context, exc.__context__) |
| 2649 |
self.assertEqual(False, exc.__suppress_context__) |
| 2650 |
self.assertEqual(expected_stack, exc.stack) |
| 2651 |
self.assertEqual(exc_info[0], exc.exc_type) |
| 2652 |
self.assertEqual(str(exc_info[1]), str(exc)) |
| 2653 |
|
| 2654 |
@cpython_only |
| 2655 |
def test_no_refs_to_exception_and_traceback_objects(self): |
| 2656 |
try: |
| 2657 |
1/0 |
| 2658 |
except Exception: |
| 2659 |
exc_info = sys.exc_info() |
| 2660 |
|
| 2661 |
refcnt1 = sys.getrefcount(exc_info[1]) |
| 2662 |
refcnt2 = sys.getrefcount(exc_info[2]) |
| 2663 |
exc = traceback.TracebackException(*exc_info) |
| 2664 |
self.assertEqual(sys.getrefcount(exc_info[1]), refcnt1) |
| 2665 |
self.assertEqual(sys.getrefcount(exc_info[2]), refcnt2) |
| 2666 |
|
| 2667 |
def test_comparison_basic(self): |
| 2668 |
try: |
| 2669 |
1/0 |
| 2670 |
except Exception: |
| 2671 |
exc_info = sys.exc_info() |
| 2672 |
exc = traceback.TracebackException(*exc_info) |
| 2673 |
exc2 = traceback.TracebackException(*exc_info) |
| 2674 |
self.assertIsNot(exc, exc2) |
| 2675 |
self.assertEqual(exc, exc2) |
| 2676 |
self.assertNotEqual(exc, object()) |
| 2677 |
self.assertEqual(exc, ALWAYS_EQ) |
| 2678 |
|
| 2679 |
def test_comparison_params_variations(self): |
| 2680 |
def raise_exc(): |
| 2681 |
try: |
| 2682 |
raise ValueError('bad value') |
| 2683 |
except: |
| 2684 |
raise |
| 2685 |
|
| 2686 |
def raise_with_locals(): |
| 2687 |
x, y = 1, 2 |
| 2688 |
raise_exc() |
| 2689 |
|
| 2690 |
try: |
| 2691 |
raise_with_locals() |
| 2692 |
except Exception: |
| 2693 |
exc_info = sys.exc_info() |
| 2694 |
|
| 2695 |
exc = traceback.TracebackException(*exc_info) |
| 2696 |
exc1 = traceback.TracebackException(*exc_info, limit=10) |
| 2697 |
exc2 = traceback.TracebackException(*exc_info, limit=2) |
| 2698 |
|
| 2699 |
self.assertEqual(exc, exc1) |
| 2700 |
self.assertNotEqual(exc, exc2) |
| 2701 |
|
| 2702 |
|
| 2703 |
exc3 = traceback.TracebackException(*exc_info, capture_locals=True) |
| 2704 |
self.assertNotEqual(exc, exc3) |
| 2705 |
|
| 2706 |
|
| 2707 |
exc4 = traceback.TracebackException(*exc_info, limit=-1) |
| 2708 |
exc5 = traceback.TracebackException(*exc_info, limit=-1, capture_locals=True) |
| 2709 |
self.assertEqual(exc4, exc5) |
| 2710 |
|
| 2711 |
|
| 2712 |
exc6 = traceback.TracebackException(*exc_info, limit=-2) |
| 2713 |
exc7 = traceback.TracebackException(*exc_info, limit=-2, capture_locals=True) |
| 2714 |
self.assertNotEqual(exc6, exc7) |
| 2715 |
|
| 2716 |
def test_comparison_equivalent_exceptions_are_equal(self): |
| 2717 |
excs = [] |
| 2718 |
for _ in range(2): |
| 2719 |
try: |
| 2720 |
1/0 |
| 2721 |
except: |
| 2722 |
excs.append(traceback.TracebackException(*sys.exc_info())) |
| 2723 |
self.assertEqual(excs[0], excs[1]) |
| 2724 |
self.assertEqual(list(excs[0].format()), list(excs[1].format())) |
| 2725 |
|
| 2726 |
def test_unhashable(self): |
| 2727 |
class UnhashableException(Exception): |
| 2728 |
def __eq__(self, other): |
| 2729 |
return True |
| 2730 |
|
| 2731 |
ex1 = UnhashableException('ex1') |
| 2732 |
ex2 = UnhashableException('ex2') |
| 2733 |
try: |
| 2734 |
raise ex2 from ex1 |
| 2735 |
except UnhashableException: |
| 2736 |
try: |
| 2737 |
raise ex1 |
| 2738 |
except UnhashableException: |
| 2739 |
exc_info = sys.exc_info() |
| 2740 |
exc = traceback.TracebackException(*exc_info) |
| 2741 |
formatted = list(exc.format()) |
| 2742 |
self.assertIn('UnhashableException: ex2\n', formatted[2]) |
| 2743 |
self.assertIn('UnhashableException: ex1\n', formatted[6]) |
| 2744 |
|
| 2745 |
def test_limit(self): |
| 2746 |
def recurse(n): |
| 2747 |
if n: |
| 2748 |
recurse(n-1) |
| 2749 |
else: |
| 2750 |
1/0 |
| 2751 |
try: |
| 2752 |
recurse(10) |
| 2753 |
except Exception: |
| 2754 |
exc_info = sys.exc_info() |
| 2755 |
exc = traceback.TracebackException(*exc_info, limit=5) |
| 2756 |
expected_stack = traceback.StackSummary.extract( |
| 2757 |
traceback.walk_tb(exc_info[2]), limit=5) |
| 2758 |
self.assertEqual(expected_stack, exc.stack) |
| 2759 |
|
| 2760 |
def test_lookup_lines(self): |
| 2761 |
linecache.clearcache() |
| 2762 |
e = Exception("uh oh") |
| 2763 |
c = test_code('/foo.py', 'method') |
| 2764 |
f = test_frame(c, None, None) |
| 2765 |
tb = test_tb(f, 6, None, 0) |
| 2766 |
exc = traceback.TracebackException(Exception, e, tb, lookup_lines=False) |
| 2767 |
self.assertEqual(linecache.cache, {}) |
| 2768 |
linecache.updatecache('/foo.py', globals()) |
| 2769 |
self.assertEqual(exc.stack[0].line, "import sys") |
| 2770 |
|
| 2771 |
def test_locals(self): |
| 2772 |
linecache.updatecache('/foo.py', globals()) |
| 2773 |
e = Exception("uh oh") |
| 2774 |
c = test_code('/foo.py', 'method') |
| 2775 |
f = test_frame(c, globals(), {'something': 1, 'other': 'string'}) |
| 2776 |
tb = test_tb(f, 6, None, 0) |
| 2777 |
exc = traceback.TracebackException( |
| 2778 |
Exception, e, tb, capture_locals=True) |
| 2779 |
self.assertEqual( |
| 2780 |
exc.stack[0].locals, {'something': '1', 'other': "'string'"}) |
| 2781 |
|
| 2782 |
def test_no_locals(self): |
| 2783 |
linecache.updatecache('/foo.py', globals()) |
| 2784 |
e = Exception("uh oh") |
| 2785 |
c = test_code('/foo.py', 'method') |
| 2786 |
f = test_frame(c, globals(), {'something': 1}) |
| 2787 |
tb = test_tb(f, 6, None, 0) |
| 2788 |
exc = traceback.TracebackException(Exception, e, tb) |
| 2789 |
self.assertEqual(exc.stack[0].locals, None) |
| 2790 |
|
| 2791 |
def test_traceback_header(self): |
| 2792 |
|
| 2793 |
|
| 2794 |
exc = traceback.TracebackException(Exception, Exception("haven"), None) |
| 2795 |
self.assertEqual(list(exc.format()), ["Exception: haven\n"]) |
| 2796 |
|
| 2797 |
@requires_debug_ranges() |
| 2798 |
def test_print(self): |
| 2799 |
def f(): |
| 2800 |
x = 12 |
| 2801 |
try: |
| 2802 |
x/0 |
| 2803 |
except Exception: |
| 2804 |
return sys.exc_info() |
| 2805 |
exc = traceback.TracebackException(*f(), capture_locals=True) |
| 2806 |
output = StringIO() |
| 2807 |
exc.print(file=output) |
| 2808 |
self.assertEqual( |
| 2809 |
output.getvalue().split('\n')[-5:], |
| 2810 |
[' x/0', |
| 2811 |
' ~^~', |
| 2812 |
' x = 12', |
| 2813 |
'ZeroDivisionError: division by zero', |
| 2814 |
'']) |
| 2815 |
|
| 2816 |
|
| 2817 |
class TestTracebackException_ExceptionGroups(unittest.TestCase): |
| 2818 |
def setUp(self): |
| 2819 |
super().setUp() |
| 2820 |
self.eg_info = self._get_exception_group() |
| 2821 |
|
| 2822 |
def _get_exception_group(self): |
| 2823 |
def f(): |
| 2824 |
1/0 |
| 2825 |
|
| 2826 |
def g(v): |
| 2827 |
raise ValueError(v) |
| 2828 |
|
| 2829 |
self.lno_f = f.__code__.co_firstlineno |
| 2830 |
self.lno_g = g.__code__.co_firstlineno |
| 2831 |
|
| 2832 |
try: |
| 2833 |
try: |
| 2834 |
try: |
| 2835 |
f() |
| 2836 |
except Exception as e: |
| 2837 |
exc1 = e |
| 2838 |
try: |
| 2839 |
g(42) |
| 2840 |
except Exception as e: |
| 2841 |
exc2 = e |
| 2842 |
raise ExceptionGroup("eg1", [exc1, exc2]) |
| 2843 |
except ExceptionGroup as e: |
| 2844 |
exc3 = e |
| 2845 |
try: |
| 2846 |
g(24) |
| 2847 |
except Exception as e: |
| 2848 |
exc4 = e |
| 2849 |
raise ExceptionGroup("eg2", [exc3, exc4]) |
| 2850 |
except ExceptionGroup: |
| 2851 |
return sys.exc_info() |
| 2852 |
self.fail('Exception Not Raised') |
| 2853 |
|
| 2854 |
def test_exception_group_construction(self): |
| 2855 |
eg_info = self.eg_info |
| 2856 |
teg1 = traceback.TracebackException(*eg_info) |
| 2857 |
teg2 = traceback.TracebackException.from_exception(eg_info[1]) |
| 2858 |
self.assertIsNot(teg1, teg2) |
| 2859 |
self.assertEqual(teg1, teg2) |
| 2860 |
|
| 2861 |
def test_exception_group_format_exception_only(self): |
| 2862 |
teg = traceback.TracebackException(*self.eg_info) |
| 2863 |
formatted = ''.join(teg.format_exception_only()).split('\n') |
| 2864 |
expected = "ExceptionGroup: eg2 (2 sub-exceptions)\n".split('\n') |
| 2865 |
|
| 2866 |
self.assertEqual(formatted, expected) |
| 2867 |
|
| 2868 |
def test_exception_group_format(self): |
| 2869 |
teg = traceback.TracebackException(*self.eg_info) |
| 2870 |
|
| 2871 |
formatted = ''.join(teg.format()).split('\n') |
| 2872 |
lno_f = self.lno_f |
| 2873 |
lno_g = self.lno_g |
| 2874 |
|
| 2875 |
expected = [ |
| 2876 |
f' + Exception Group Traceback (most recent call last):', |
| 2877 |
f' | File "{__file__}", line {lno_g+23}, in _get_exception_group', |
| 2878 |
f' | raise ExceptionGroup("eg2", [exc3, exc4])', |
| 2879 |
f' | ExceptionGroup: eg2 (2 sub-exceptions)', |
| 2880 |
f' +-+---------------- 1 ----------------', |
| 2881 |
f' | Exception Group Traceback (most recent call last):', |
| 2882 |
f' | File "{__file__}", line {lno_g+16}, in _get_exception_group', |
| 2883 |
f' | raise ExceptionGroup("eg1", [exc1, exc2])', |
| 2884 |
f' | ExceptionGroup: eg1 (2 sub-exceptions)', |
| 2885 |
f' +-+---------------- 1 ----------------', |
| 2886 |
f' | Traceback (most recent call last):', |
| 2887 |
f' | File "{__file__}", line {lno_g+9}, in _get_exception_group', |
| 2888 |
f' | f()', |
| 2889 |
f' | File "{__file__}", line {lno_f+1}, in f', |
| 2890 |
f' | 1/0', |
| 2891 |
f' | ~^~', |
| 2892 |
f' | ZeroDivisionError: division by zero', |
| 2893 |
f' +---------------- 2 ----------------', |
| 2894 |
f' | Traceback (most recent call last):', |
| 2895 |
f' | File "{__file__}", line {lno_g+13}, in _get_exception_group', |
| 2896 |
f' | g(42)', |
| 2897 |
f' | File "{__file__}", line {lno_g+1}, in g', |
| 2898 |
f' | raise ValueError(v)', |
| 2899 |
f' | ValueError: 42', |
| 2900 |
f' +------------------------------------', |
| 2901 |
f' +---------------- 2 ----------------', |
| 2902 |
f' | Traceback (most recent call last):', |
| 2903 |
f' | File "{__file__}", line {lno_g+20}, in _get_exception_group', |
| 2904 |
f' | g(24)', |
| 2905 |
f' | File "{__file__}", line {lno_g+1}, in g', |
| 2906 |
f' | raise ValueError(v)', |
| 2907 |
f' | ValueError: 24', |
| 2908 |
f' +------------------------------------', |
| 2909 |
f''] |
| 2910 |
|
| 2911 |
self.assertEqual(formatted, expected) |
| 2912 |
|
| 2913 |
def test_max_group_width(self): |
| 2914 |
excs1 = [] |
| 2915 |
excs2 = [] |
| 2916 |
for i in range(3): |
| 2917 |
excs1.append(ValueError(i)) |
| 2918 |
for i in range(10): |
| 2919 |
excs2.append(TypeError(i)) |
| 2920 |
|
| 2921 |
EG = ExceptionGroup |
| 2922 |
eg = EG('eg', [EG('eg1', excs1), EG('eg2', excs2)]) |
| 2923 |
|
| 2924 |
teg = traceback.TracebackException.from_exception(eg, max_group_width=2) |
| 2925 |
formatted = ''.join(teg.format()).split('\n') |
| 2926 |
|
| 2927 |
expected = [ |
| 2928 |
f' | ExceptionGroup: eg (2 sub-exceptions)', |
| 2929 |
f' +-+---------------- 1 ----------------', |
| 2930 |
f' | ExceptionGroup: eg1 (3 sub-exceptions)', |
| 2931 |
f' +-+---------------- 1 ----------------', |
| 2932 |
f' | ValueError: 0', |
| 2933 |
f' +---------------- 2 ----------------', |
| 2934 |
f' | ValueError: 1', |
| 2935 |
f' +---------------- ... ----------------', |
| 2936 |
f' | and 1 more exception', |
| 2937 |
f' +------------------------------------', |
| 2938 |
f' +---------------- 2 ----------------', |
| 2939 |
f' | ExceptionGroup: eg2 (10 sub-exceptions)', |
| 2940 |
f' +-+---------------- 1 ----------------', |
| 2941 |
f' | TypeError: 0', |
| 2942 |
f' +---------------- 2 ----------------', |
| 2943 |
f' | TypeError: 1', |
| 2944 |
f' +---------------- ... ----------------', |
| 2945 |
f' | and 8 more exceptions', |
| 2946 |
f' +------------------------------------', |
| 2947 |
f''] |
| 2948 |
|
| 2949 |
self.assertEqual(formatted, expected) |
| 2950 |
|
| 2951 |
def test_max_group_depth(self): |
| 2952 |
exc = TypeError('bad type') |
| 2953 |
for i in range(3): |
| 2954 |
exc = ExceptionGroup('exc', [ValueError(-i), exc, ValueError(i)]) |
| 2955 |
|
| 2956 |
teg = traceback.TracebackException.from_exception(exc, max_group_depth=2) |
| 2957 |
formatted = ''.join(teg.format()).split('\n') |
| 2958 |
|
| 2959 |
expected = [ |
| 2960 |
f' | ExceptionGroup: exc (3 sub-exceptions)', |
| 2961 |
f' +-+---------------- 1 ----------------', |
| 2962 |
f' | ValueError: -2', |
| 2963 |
f' +---------------- 2 ----------------', |
| 2964 |
f' | ExceptionGroup: exc (3 sub-exceptions)', |
| 2965 |
f' +-+---------------- 1 ----------------', |
| 2966 |
f' | ValueError: -1', |
| 2967 |
f' +---------------- 2 ----------------', |
| 2968 |
f' | ... (max_group_depth is 2)', |
| 2969 |
f' +---------------- 3 ----------------', |
| 2970 |
f' | ValueError: 1', |
| 2971 |
f' +------------------------------------', |
| 2972 |
f' +---------------- 3 ----------------', |
| 2973 |
f' | ValueError: 2', |
| 2974 |
f' +------------------------------------', |
| 2975 |
f''] |
| 2976 |
|
| 2977 |
self.assertEqual(formatted, expected) |
| 2978 |
|
| 2979 |
def test_comparison(self): |
| 2980 |
try: |
| 2981 |
raise self.eg_info[1] |
| 2982 |
except ExceptionGroup: |
| 2983 |
exc_info = sys.exc_info() |
| 2984 |
for _ in range(5): |
| 2985 |
try: |
| 2986 |
raise exc_info[1] |
| 2987 |
except: |
| 2988 |
exc_info = sys.exc_info() |
| 2989 |
exc = traceback.TracebackException(*exc_info) |
| 2990 |
exc2 = traceback.TracebackException(*exc_info) |
| 2991 |
exc3 = traceback.TracebackException(*exc_info, limit=300) |
| 2992 |
ne = traceback.TracebackException(*exc_info, limit=3) |
| 2993 |
self.assertIsNot(exc, exc2) |
| 2994 |
self.assertEqual(exc, exc2) |
| 2995 |
self.assertEqual(exc, exc3) |
| 2996 |
self.assertNotEqual(exc, ne) |
| 2997 |
self.assertNotEqual(exc, object()) |
| 2998 |
self.assertEqual(exc, ALWAYS_EQ) |
| 2999 |
|
| 3000 |
|
| 3001 |
class MiscTest(unittest.TestCase): |
| 3002 |
|
| 3003 |
def test_all(self): |
| 3004 |
expected = set() |
| 3005 |
denylist = {'print_list'} |
| 3006 |
for name in dir(traceback): |
| 3007 |
if name.startswith('_') or name in denylist: |
| 3008 |
continue |
| 3009 |
module_object = getattr(traceback, name) |
| 3010 |
if getattr(module_object, '__module__', None) == 'traceback': |
| 3011 |
expected.add(name) |
| 3012 |
self.assertCountEqual(traceback.__all__, expected) |
| 3013 |
|
| 3014 |
|
| 3015 |
if __name__ == "__main__": |
| 3016 |
unittest.main() |