| 1 |
# encoding: utf-8 |
| 2 |
"""Tests for IPython.core.ultratb""" |
| 3 |
import io |
| 4 |
import os.path |
| 5 |
import platform |
| 6 |
import re |
| 7 |
import sys |
| 8 |
import traceback |
| 9 |
import unittest |
| 10 |
from textwrap import dedent |
| 11 |
|
| 12 |
from tempfile import TemporaryDirectory |
| 13 |
|
| 14 |
from IPython.core.ultratb import VerboseTB, FormattedTB |
| 15 |
from IPython.testing import tools as tt |
| 16 |
from IPython.testing.decorators import onlyif_unicode_paths, skip_without |
| 17 |
from IPython.utils.syspathcontext import prepended_to_syspath |
| 18 |
|
| 19 |
file_1 = """1 |
| 20 |
2 |
| 21 |
3 |
| 22 |
def f(): |
| 23 |
1/0 |
| 24 |
""" |
| 25 |
|
| 26 |
file_2 = """def f(): |
| 27 |
1/0 |
| 28 |
""" |
| 29 |
|
| 30 |
|
| 31 |
def recursionlimit(frames): |
| 32 |
""" |
| 33 |
decorator to set the recursion limit temporarily |
| 34 |
""" |
| 35 |
|
| 36 |
def inner(test_function): |
| 37 |
def wrapper(*args, **kwargs): |
| 38 |
rl = sys.getrecursionlimit() |
| 39 |
sys.setrecursionlimit(frames) |
| 40 |
try: |
| 41 |
return test_function(*args, **kwargs) |
| 42 |
finally: |
| 43 |
sys.setrecursionlimit(rl) |
| 44 |
|
| 45 |
return wrapper |
| 46 |
|
| 47 |
return inner |
| 48 |
|
| 49 |
|
| 50 |
class ChangedPyFileTest(unittest.TestCase): |
| 51 |
def test_changing_py_file(self): |
| 52 |
"""Traceback produced if the line where the error occurred is missing? |
| 53 |
|
| 54 |
https://github.com/ipython/ipython/issues/1456 |
| 55 |
""" |
| 56 |
with TemporaryDirectory() as td: |
| 57 |
fname = os.path.join(td, "foo_1456.py") |
| 58 |
with open(fname, "w", encoding="utf-8") as f: |
| 59 |
f.write(file_1) |
| 60 |
|
| 61 |
with prepended_to_syspath(td): |
| 62 |
ip.run_cell("import foo_1456") |
| 63 |
|
| 64 |
with tt.AssertPrints("ZeroDivisionError"): |
| 65 |
ip.run_cell("foo_1456.f()") |
| 66 |
|
| 67 |
# Make the file shorter, so the line of the error is missing. |
| 68 |
with open(fname, "w", encoding="utf-8") as f: |
| 69 |
f.write(file_2) |
| 70 |
|
| 71 |
# For some reason, this was failing on the *second* call after |
| 72 |
# changing the file, so we call f() twice. |
| 73 |
with tt.AssertNotPrints("Internal Python error", channel="stderr"): |
| 74 |
with tt.AssertPrints("ZeroDivisionError"): |
| 75 |
ip.run_cell("foo_1456.f()") |
| 76 |
with tt.AssertPrints("ZeroDivisionError"): |
| 77 |
ip.run_cell("foo_1456.f()") |
| 78 |
|
| 79 |
|
| 80 |
iso_8859_5_file = '''# coding: iso-8859-5 |
| 81 |
|
| 82 |
def fail(): |
| 83 |
"""дбИЖ""" |
| 84 |
1/0 # дбИЖ |
| 85 |
''' |
| 86 |
|
| 87 |
|
| 88 |
class NonAsciiTest(unittest.TestCase): |
| 89 |
@onlyif_unicode_paths |
| 90 |
def test_nonascii_path(self): |
| 91 |
# Non-ascii directory name as well. |
| 92 |
with TemporaryDirectory(suffix="é") as td: |
| 93 |
fname = os.path.join(td, "fooé.py") |
| 94 |
with open(fname, "w", encoding="utf-8") as f: |
| 95 |
f.write(file_1) |
| 96 |
|
| 97 |
with prepended_to_syspath(td): |
| 98 |
ip.run_cell("import fooé") |
| 99 |
|
| 100 |
with tt.AssertPrints("ZeroDivisionError"): |
| 101 |
ip.run_cell("fooé.f()") |
| 102 |
|
| 103 |
def test_iso8859_5(self): |
| 104 |
with TemporaryDirectory() as td: |
| 105 |
fname = os.path.join(td, "dfghjkl.py") |
| 106 |
|
| 107 |
with io.open(fname, "w", encoding="iso-8859-5") as f: |
| 108 |
f.write(iso_8859_5_file) |
| 109 |
|
| 110 |
with prepended_to_syspath(td): |
| 111 |
ip.run_cell("from dfghjkl import fail") |
| 112 |
|
| 113 |
with tt.AssertPrints("ZeroDivisionError"): |
| 114 |
with tt.AssertPrints("дбИЖ", suppress=False): |
| 115 |
ip.run_cell("fail()") |
| 116 |
|
| 117 |
def test_nonascii_msg(self): |
| 118 |
cell = "raise Exception('é')" |
| 119 |
expected = "Exception('é')" |
| 120 |
ip.run_cell("%xmode plain") |
| 121 |
with tt.AssertPrints(expected): |
| 122 |
ip.run_cell(cell) |
| 123 |
|
| 124 |
ip.run_cell("%xmode verbose") |
| 125 |
with tt.AssertPrints(expected): |
| 126 |
ip.run_cell(cell) |
| 127 |
|
| 128 |
ip.run_cell("%xmode context") |
| 129 |
with tt.AssertPrints(expected): |
| 130 |
ip.run_cell(cell) |
| 131 |
|
| 132 |
ip.run_cell("%xmode minimal") |
| 133 |
with tt.AssertPrints("Exception: é"): |
| 134 |
ip.run_cell(cell) |
| 135 |
|
| 136 |
# Put this back into Context mode for later tests. |
| 137 |
ip.run_cell("%xmode context") |
| 138 |
|
| 139 |
|
| 140 |
class NestedGenExprTestCase(unittest.TestCase): |
| 141 |
""" |
| 142 |
Regression test for the following issues: |
| 143 |
https://github.com/ipython/ipython/issues/8293 |
| 144 |
https://github.com/ipython/ipython/issues/8205 |
| 145 |
""" |
| 146 |
|
| 147 |
def test_nested_genexpr(self): |
| 148 |
code = dedent( |
| 149 |
"""\ |
| 150 |
class SpecificException(Exception): |
| 151 |
pass |
| 152 |
|
| 153 |
def foo_8293(x): |
| 154 |
raise SpecificException("Success!") |
| 155 |
|
| 156 |
sum(sum(foo_8293(x) for _ in [0]) for x in [0]) |
| 157 |
""" |
| 158 |
) |
| 159 |
with tt.AssertPrints("SpecificException: Success!", suppress=False): |
| 160 |
ip.run_cell(code) |
| 161 |
|
| 162 |
|
| 163 |
indentationerror_file = """if True: |
| 164 |
zoom() |
| 165 |
""" |
| 166 |
|
| 167 |
|
| 168 |
class IndentationErrorTest(unittest.TestCase): |
| 169 |
def test_indentationerror_shows_line(self): |
| 170 |
# See issue gh-2398 |
| 171 |
with tt.AssertPrints("IndentationError"): |
| 172 |
with tt.AssertPrints("zoom()", suppress=False): |
| 173 |
ip.run_cell(indentationerror_file) |
| 174 |
|
| 175 |
with TemporaryDirectory() as td: |
| 176 |
fname = os.path.join(td, "foo_2398.py") |
| 177 |
with open(fname, "w", encoding="utf-8") as f: |
| 178 |
f.write(indentationerror_file) |
| 179 |
|
| 180 |
with tt.AssertPrints("IndentationError"): |
| 181 |
with tt.AssertPrints("zoom()", suppress=False): |
| 182 |
ip.run_line_magic("run", fname) |
| 183 |
|
| 184 |
|
| 185 |
@skip_without("pandas") |
| 186 |
def test_dynamic_code(): |
| 187 |
code = """ |
| 188 |
import pandas |
| 189 |
df = pandas.DataFrame([]) |
| 190 |
|
| 191 |
# Important: only fails inside of an "exec" call: |
| 192 |
exec("df.foobarbaz()") |
| 193 |
""" |
| 194 |
|
| 195 |
with tt.AssertPrints("Could not get source"): |
| 196 |
ip.run_cell(code) |
| 197 |
|
| 198 |
|
| 199 |
se_file_1 = """1 |
| 200 |
2 |
| 201 |
7/ |
| 202 |
""" |
| 203 |
|
| 204 |
se_file_2 = """7/ |
| 205 |
""" |
| 206 |
|
| 207 |
|
| 208 |
class SyntaxErrorTest(unittest.TestCase): |
| 209 |
def test_syntaxerror_no_stacktrace_at_compile_time(self): |
| 210 |
syntax_error_at_compile_time = """ |
| 211 |
def foo_syntax_error_test(): |
| 212 |
.. |
| 213 |
""" |
| 214 |
with tt.AssertPrints("SyntaxError"): |
| 215 |
ip.run_cell(syntax_error_at_compile_time) |
| 216 |
|
| 217 |
with tt.AssertNotPrints("foo_syntax_error_test()"): |
| 218 |
ip.run_cell(syntax_error_at_compile_time) |
| 219 |
|
| 220 |
def test_syntaxerror_stacktrace_when_running_compiled_code(self): |
| 221 |
syntax_error_at_runtime = """ |
| 222 |
def foo_syntax_error_test_2(): |
| 223 |
eval("..") |
| 224 |
|
| 225 |
def bar_syntax_error_test_2(): |
| 226 |
foo_syntax_error_test_2() |
| 227 |
|
| 228 |
bar_syntax_error_test_2() |
| 229 |
""" |
| 230 |
with tt.AssertPrints("SyntaxError"): |
| 231 |
ip.run_cell(syntax_error_at_runtime) |
| 232 |
# Assert syntax error during runtime generate stacktrace |
| 233 |
with tt.AssertPrints( |
| 234 |
["foo_syntax_error_test_2()", "bar_syntax_error_test_2()"] |
| 235 |
): |
| 236 |
ip.run_cell(syntax_error_at_runtime) |
| 237 |
del ip.user_ns["bar_syntax_error_test_2"] |
| 238 |
del ip.user_ns["foo_syntax_error_test_2"] |
| 239 |
|
| 240 |
def test_changing_py_file(self): |
| 241 |
with TemporaryDirectory() as td: |
| 242 |
fname = os.path.join(td, "foo_test_changing_py_file.py") |
| 243 |
with open(fname, "w", encoding="utf-8") as f: |
| 244 |
f.write(se_file_1) |
| 245 |
|
| 246 |
with tt.AssertPrints(["7/", "SyntaxError"]): |
| 247 |
ip.run_line_magic("run", fname) |
| 248 |
|
| 249 |
# Modify the file |
| 250 |
with open(fname, "w", encoding="utf-8") as f: |
| 251 |
f.write(se_file_2) |
| 252 |
|
| 253 |
# The SyntaxError should point to the correct line |
| 254 |
with tt.AssertPrints(["7/", "SyntaxError"]): |
| 255 |
ip.run_line_magic("run", fname) |
| 256 |
|
| 257 |
def test_non_syntaxerror(self): |
| 258 |
# SyntaxTB may be called with an error other than a SyntaxError |
| 259 |
# See e.g. gh-4361 |
| 260 |
try: |
| 261 |
raise ValueError("QWERTY") |
| 262 |
except ValueError: |
| 263 |
with tt.AssertPrints("QWERTY"): |
| 264 |
ip.showsyntaxerror() |
| 265 |
|
| 266 |
|
| 267 |
import sys |
| 268 |
|
| 269 |
if platform.python_implementation() != "PyPy": |
| 270 |
""" |
| 271 |
New 3.9 Pgen Parser does not raise Memory error, except on failed malloc. |
| 272 |
""" |
| 273 |
|
| 274 |
class MemoryErrorTest(unittest.TestCase): |
| 275 |
def test_memoryerror(self): |
| 276 |
memoryerror_code = "(" * 200 + ")" * 200 |
| 277 |
ip.run_cell(memoryerror_code) |
| 278 |
|
| 279 |
|
| 280 |
class Python3ChainedExceptionsTest(unittest.TestCase): |
| 281 |
DIRECT_CAUSE_ERROR_CODE = """ |
| 282 |
try: |
| 283 |
x = 1 + 2 |
| 284 |
print(not_defined_here) |
| 285 |
except Exception as e: |
| 286 |
x += 55 |
| 287 |
x - 1 |
| 288 |
y = {} |
| 289 |
raise KeyError('uh') from e |
| 290 |
""" |
| 291 |
|
| 292 |
EXCEPTION_DURING_HANDLING_CODE = """ |
| 293 |
try: |
| 294 |
x = 1 + 2 |
| 295 |
print(not_defined_here) |
| 296 |
except Exception as e: |
| 297 |
x += 55 |
| 298 |
x - 1 |
| 299 |
y = {} |
| 300 |
raise KeyError('uh') |
| 301 |
""" |
| 302 |
|
| 303 |
SUPPRESS_CHAINING_CODE = """ |
| 304 |
try: |
| 305 |
1/0 |
| 306 |
except Exception: |
| 307 |
raise ValueError("Yikes") from None |
| 308 |
""" |
| 309 |
|
| 310 |
SYS_EXIT_WITH_CONTEXT_CODE = """ |
| 311 |
try: |
| 312 |
1/0 |
| 313 |
except Exception as e: |
| 314 |
raise SystemExit(1) |
| 315 |
""" |
| 316 |
|
| 317 |
def test_direct_cause_error(self): |
| 318 |
with tt.AssertPrints(["KeyError", "NameError", "direct cause"]): |
| 319 |
ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE) |
| 320 |
|
| 321 |
def test_exception_during_handling_error(self): |
| 322 |
with tt.AssertPrints(["KeyError", "NameError", "During handling"]): |
| 323 |
ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE) |
| 324 |
|
| 325 |
def test_sysexit_while_handling_error(self): |
| 326 |
with tt.AssertPrints(["SystemExit", "to see the full traceback"]): |
| 327 |
with tt.AssertNotPrints(["another exception"], suppress=False): |
| 328 |
ip.run_cell(self.SYS_EXIT_WITH_CONTEXT_CODE) |
| 329 |
|
| 330 |
def test_suppress_exception_chaining(self): |
| 331 |
with ( |
| 332 |
tt.AssertNotPrints("ZeroDivisionError"), |
| 333 |
tt.AssertPrints("ValueError", suppress=False), |
| 334 |
): |
| 335 |
ip.run_cell(self.SUPPRESS_CHAINING_CODE) |
| 336 |
|
| 337 |
def test_plain_direct_cause_error(self): |
| 338 |
with tt.AssertPrints(["KeyError", "NameError", "direct cause"]): |
| 339 |
ip.run_cell("%xmode Plain") |
| 340 |
ip.run_cell(self.DIRECT_CAUSE_ERROR_CODE) |
| 341 |
ip.run_cell("%xmode Verbose") |
| 342 |
|
| 343 |
def test_plain_exception_during_handling_error(self): |
| 344 |
with tt.AssertPrints(["KeyError", "NameError", "During handling"]): |
| 345 |
ip.run_cell("%xmode Plain") |
| 346 |
ip.run_cell(self.EXCEPTION_DURING_HANDLING_CODE) |
| 347 |
ip.run_cell("%xmode Verbose") |
| 348 |
|
| 349 |
def test_plain_suppress_exception_chaining(self): |
| 350 |
with ( |
| 351 |
tt.AssertNotPrints("ZeroDivisionError"), |
| 352 |
tt.AssertPrints("ValueError", suppress=False), |
| 353 |
): |
| 354 |
ip.run_cell("%xmode Plain") |
| 355 |
ip.run_cell(self.SUPPRESS_CHAINING_CODE) |
| 356 |
ip.run_cell("%xmode Verbose") |
| 357 |
|
| 358 |
|
| 359 |
class RecursionTest(unittest.TestCase): |
| 360 |
DEFINITIONS = """ |
| 361 |
def non_recurs(): |
| 362 |
1/0 |
| 363 |
|
| 364 |
def r1(): |
| 365 |
r1() |
| 366 |
|
| 367 |
def r3a(): |
| 368 |
r3b() |
| 369 |
|
| 370 |
def r3b(): |
| 371 |
r3c() |
| 372 |
|
| 373 |
def r3c(): |
| 374 |
r3a() |
| 375 |
|
| 376 |
def r3o1(): |
| 377 |
r3a() |
| 378 |
|
| 379 |
def r3o2(): |
| 380 |
r3o1() |
| 381 |
""" |
| 382 |
|
| 383 |
def setUp(self): |
| 384 |
ip.run_cell(self.DEFINITIONS) |
| 385 |
|
| 386 |
def test_no_recursion(self): |
| 387 |
with tt.AssertNotPrints("skipping similar frames"): |
| 388 |
ip.run_cell("non_recurs()") |
| 389 |
|
| 390 |
@recursionlimit(200) |
| 391 |
def test_recursion_one_frame(self): |
| 392 |
with tt.AssertPrints( |
| 393 |
re.compile( |
| 394 |
r"\[\.\.\. skipping similar frames: r1 at line 5 \(\d{2,3} times\)\]" |
| 395 |
) |
| 396 |
): |
| 397 |
ip.run_cell("r1()") |
| 398 |
|
| 399 |
@recursionlimit(160) |
| 400 |
def test_recursion_three_frames(self): |
| 401 |
with ( |
| 402 |
tt.AssertPrints("[... skipping similar frames: "), |
| 403 |
tt.AssertPrints( |
| 404 |
re.compile(r"r3a at line 8 \(\d{2} times\)"), suppress=False |
| 405 |
), |
| 406 |
tt.AssertPrints( |
| 407 |
re.compile(r"r3b at line 11 \(\d{2} times\)"), suppress=False |
| 408 |
), |
| 409 |
tt.AssertPrints( |
| 410 |
re.compile(r"r3c at line 14 \(\d{2} times\)"), suppress=False |
| 411 |
), |
| 412 |
): |
| 413 |
ip.run_cell("r3o2()") |
| 414 |
|
| 415 |
|
| 416 |
class PEP678NotesReportingTest(unittest.TestCase): |
| 417 |
ERROR_WITH_NOTE = """ |
| 418 |
try: |
| 419 |
raise AssertionError("Message") |
| 420 |
except Exception as e: |
| 421 |
try: |
| 422 |
e.add_note("This is a PEP-678 note.") |
| 423 |
except AttributeError: # Python <= 3.10 |
| 424 |
e.__notes__ = ("This is a PEP-678 note.",) |
| 425 |
raise |
| 426 |
""" |
| 427 |
|
| 428 |
def test_verbose_reports_notes(self): |
| 429 |
with tt.AssertPrints(["AssertionError", "Message", "This is a PEP-678 note."]): |
| 430 |
ip.run_cell(self.ERROR_WITH_NOTE) |
| 431 |
|
| 432 |
def test_plain_reports_notes(self): |
| 433 |
with tt.AssertPrints(["AssertionError", "Message", "This is a PEP-678 note."]): |
| 434 |
ip.run_cell("%xmode Plain") |
| 435 |
ip.run_cell(self.ERROR_WITH_NOTE) |
| 436 |
ip.run_cell("%xmode Verbose") |
| 437 |
|
| 438 |
|
| 439 |
class ExceptionMessagePreferenceTest(unittest.TestCase): |
| 440 |
""" |
| 441 |
Test that exception string representation is preferred over .msg attribute |
| 442 |
for non-SyntaxError exceptions in %xmode plain. |
| 443 |
""" |
| 444 |
|
| 445 |
def test_jsondecodeerror_message(self): |
| 446 |
cell = "import json;json.loads('{\"a\": }')" |
| 447 |
if platform.python_implementation() == "PyPy": |
| 448 |
expected = "JSONDecodeError: Unexpected '}': line 1 column 7 (char 6)" |
| 449 |
else: |
| 450 |
expected = "JSONDecodeError: Expecting value: line 1 column 7 (char 6)" |
| 451 |
ip.run_cell("%xmode plain") |
| 452 |
with tt.AssertPrints(expected): |
| 453 |
ip.run_cell(cell) |
| 454 |
ip.run_cell("%xmode context") |
| 455 |
|
| 456 |
|
| 457 |
# ---------------------------------------------------------------------------- |
| 458 |
|
| 459 |
|
| 460 |
# module testing (minimal) |
| 461 |
def test_handlers(): |
| 462 |
def spam(c, d_e): |
| 463 |
(d, e) = d_e |
| 464 |
x = c + d |
| 465 |
y = c * d |
| 466 |
foo(x, y) |
| 467 |
|
| 468 |
def foo(a, b, bar=1): |
| 469 |
eggs(a, b + bar) |
| 470 |
|
| 471 |
def eggs(f, g, z=globals()): |
| 472 |
h = f + g |
| 473 |
i = f - g |
| 474 |
return h / i |
| 475 |
|
| 476 |
buff = io.StringIO() |
| 477 |
|
| 478 |
buff.write("") |
| 479 |
buff.write("*** Before ***") |
| 480 |
try: |
| 481 |
buff.write(spam(1, (2, 3))) |
| 482 |
except: |
| 483 |
traceback.print_exc(file=buff) |
| 484 |
|
| 485 |
handler = FormattedTB(ostream=buff) |
| 486 |
buff.write("*** FormattedTB ***") |
| 487 |
try: |
| 488 |
buff.write(spam(1, (2, 3))) |
| 489 |
except: |
| 490 |
handler(*sys.exc_info()) |
| 491 |
buff.write("") |
| 492 |
|
| 493 |
handler = VerboseTB(ostream=buff) |
| 494 |
buff.write("*** VerboseTB ***") |
| 495 |
try: |
| 496 |
buff.write(spam(1, (2, 3))) |
| 497 |
except: |
| 498 |
handler(*sys.exc_info()) |
| 499 |
buff.write("") |
| 500 |
|
| 501 |
|
| 502 |
def testSyntaxError(): |
| 503 |
cell = "raise SyntaxError()" |
| 504 |
expected = "SyntaxError\n" |
| 505 |
with tt.AssertPrints(expected): |
| 506 |
ip.run_cell(cell) |