| 1 |
# Python test set -- part 5, built-in exceptions |
| 2 |
|
| 3 |
import copy |
| 4 |
import os |
| 5 |
import sys |
| 6 |
import unittest |
| 7 |
import pickle |
| 8 |
import weakref |
| 9 |
import errno |
| 10 |
from codecs import BOM_UTF8 |
| 11 |
from itertools import product |
| 12 |
from textwrap import dedent |
| 13 |
|
| 14 |
from test.support import (captured_stderr, check_impl_detail, |
| 15 |
cpython_only, gc_collect, |
| 16 |
no_tracing, script_helper, |
| 17 |
SuppressCrashReport, |
| 18 |
force_not_colorized) |
| 19 |
from test.support.import_helper import import_module |
| 20 |
from test.support.os_helper import TESTFN, unlink |
| 21 |
from test.support.warnings_helper import check_warnings |
| 22 |
from test import support |
| 23 |
|
| 24 |
try: |
| 25 |
import _testcapi |
| 26 |
from _testcapi import INT_MAX |
| 27 |
except ImportError: |
| 28 |
_testcapi = None |
| 29 |
INT_MAX = 2**31 - 1 |
| 30 |
|
| 31 |
|
| 32 |
class NaiveException(Exception): |
| 33 |
def __init__(self, x): |
| 34 |
self.x = x |
| 35 |
|
| 36 |
class SlottedNaiveException(Exception): |
| 37 |
__slots__ = ('x',) |
| 38 |
def __init__(self, x): |
| 39 |
self.x = x |
| 40 |
|
| 41 |
class BrokenStrException(Exception): |
| 42 |
def __str__(self): |
| 43 |
raise Exception("str() is broken") |
| 44 |
|
| 45 |
# XXX This is not really enough, each *operation* should be tested! |
| 46 |
|
| 47 |
|
| 48 |
class ExceptionTests(unittest.TestCase): |
| 49 |
|
| 50 |
def raise_catch(self, exc, excname): |
| 51 |
with self.subTest(exc=exc, excname=excname): |
| 52 |
try: |
| 53 |
raise exc("spam") |
| 54 |
except exc as err: |
| 55 |
buf1 = str(err) |
| 56 |
try: |
| 57 |
raise exc("spam") |
| 58 |
except exc as err: |
| 59 |
buf2 = str(err) |
| 60 |
self.assertEqual(buf1, buf2) |
| 61 |
self.assertEqual(exc.__name__, excname) |
| 62 |
|
| 63 |
def testRaising(self): |
| 64 |
self.raise_catch(AttributeError, "AttributeError") |
| 65 |
self.assertRaises(AttributeError, getattr, sys, "undefined_attribute") |
| 66 |
|
| 67 |
self.raise_catch(EOFError, "EOFError") |
| 68 |
fp = open(TESTFN, 'w', encoding="utf-8") |
| 69 |
fp.close() |
| 70 |
fp = open(TESTFN, 'r', encoding="utf-8") |
| 71 |
savestdin = sys.stdin |
| 72 |
try: |
| 73 |
try: |
| 74 |
import marshal |
| 75 |
marshal.loads(b'') |
| 76 |
except EOFError: |
| 77 |
pass |
| 78 |
finally: |
| 79 |
sys.stdin = savestdin |
| 80 |
fp.close() |
| 81 |
unlink(TESTFN) |
| 82 |
|
| 83 |
self.raise_catch(OSError, "OSError") |
| 84 |
self.assertRaises(OSError, open, 'this file does not exist', 'r') |
| 85 |
|
| 86 |
self.raise_catch(ImportError, "ImportError") |
| 87 |
self.assertRaises(ImportError, __import__, "undefined_module") |
| 88 |
|
| 89 |
self.raise_catch(IndexError, "IndexError") |
| 90 |
x = [] |
| 91 |
self.assertRaises(IndexError, x.__getitem__, 10) |
| 92 |
|
| 93 |
self.raise_catch(KeyError, "KeyError") |
| 94 |
x = {} |
| 95 |
self.assertRaises(KeyError, x.__getitem__, 'key') |
| 96 |
|
| 97 |
self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt") |
| 98 |
|
| 99 |
self.raise_catch(MemoryError, "MemoryError") |
| 100 |
|
| 101 |
self.raise_catch(NameError, "NameError") |
| 102 |
try: x = undefined_variable |
| 103 |
except NameError: pass |
| 104 |
|
| 105 |
self.raise_catch(OverflowError, "OverflowError") |
| 106 |
x = 1 |
| 107 |
for dummy in range(128): |
| 108 |
x += x # this simply shouldn't blow up |
| 109 |
|
| 110 |
self.raise_catch(RuntimeError, "RuntimeError") |
| 111 |
self.raise_catch(RecursionError, "RecursionError") |
| 112 |
|
| 113 |
self.raise_catch(SyntaxError, "SyntaxError") |
| 114 |
try: exec('/\n') |
| 115 |
except SyntaxError: pass |
| 116 |
|
| 117 |
self.raise_catch(IndentationError, "IndentationError") |
| 118 |
|
| 119 |
self.raise_catch(TabError, "TabError") |
| 120 |
try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", |
| 121 |
'<string>', 'exec') |
| 122 |
except TabError: pass |
| 123 |
else: self.fail("TabError not raised") |
| 124 |
|
| 125 |
self.raise_catch(SystemError, "SystemError") |
| 126 |
|
| 127 |
self.raise_catch(SystemExit, "SystemExit") |
| 128 |
self.assertRaises(SystemExit, sys.exit, 0) |
| 129 |
|
| 130 |
self.raise_catch(TypeError, "TypeError") |
| 131 |
try: [] + () |
| 132 |
except TypeError: pass |
| 133 |
|
| 134 |
self.raise_catch(ValueError, "ValueError") |
| 135 |
self.assertRaises(ValueError, chr, 17<<16) |
| 136 |
|
| 137 |
self.raise_catch(ZeroDivisionError, "ZeroDivisionError") |
| 138 |
try: x = 1/0 |
| 139 |
except ZeroDivisionError: pass |
| 140 |
|
| 141 |
self.raise_catch(Exception, "Exception") |
| 142 |
try: x = 1/0 |
| 143 |
except Exception as e: pass |
| 144 |
|
| 145 |
self.raise_catch(StopAsyncIteration, "StopAsyncIteration") |
| 146 |
|
| 147 |
def testSyntaxErrorMessage(self): |
| 148 |
# make sure the right exception message is raised for each of |
| 149 |
# these code fragments |
| 150 |
|
| 151 |
def ckmsg(src, msg): |
| 152 |
with self.subTest(src=src, msg=msg): |
| 153 |
try: |
| 154 |
compile(src, '<fragment>', 'exec') |
| 155 |
except SyntaxError as e: |
| 156 |
if e.msg != msg: |
| 157 |
self.fail("expected %s, got %s" % (msg, e.msg)) |
| 158 |
else: |
| 159 |
self.fail("failed to get expected SyntaxError") |
| 160 |
|
| 161 |
s = '''if 1: |
| 162 |
try: |
| 163 |
continue |
| 164 |
except: |
| 165 |
pass''' |
| 166 |
|
| 167 |
ckmsg(s, "'continue' not properly in loop") |
| 168 |
ckmsg("continue\n", "'continue' not properly in loop") |
| 169 |
ckmsg("f'{6 0}'", "invalid syntax. Perhaps you forgot a comma?") |
| 170 |
|
| 171 |
def testSyntaxErrorMissingParens(self): |
| 172 |
def ckmsg(src, msg, exception=SyntaxError): |
| 173 |
try: |
| 174 |
compile(src, '<fragment>', 'exec') |
| 175 |
except exception as e: |
| 176 |
if e.msg != msg: |
| 177 |
self.fail("expected %s, got %s" % (msg, e.msg)) |
| 178 |
else: |
| 179 |
self.fail("failed to get expected SyntaxError") |
| 180 |
|
| 181 |
s = '''print "old style"''' |
| 182 |
ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?") |
| 183 |
|
| 184 |
s = '''print "old style",''' |
| 185 |
ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?") |
| 186 |
|
| 187 |
s = 'print f(a+b,c)' |
| 188 |
ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?") |
| 189 |
|
| 190 |
s = '''exec "old style"''' |
| 191 |
ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?") |
| 192 |
|
| 193 |
s = 'exec f(a+b,c)' |
| 194 |
ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?") |
| 195 |
|
| 196 |
# Check that we don't incorrectly identify '(...)' as an expression to the right |
| 197 |
# of 'print' |
| 198 |
|
| 199 |
s = 'print (a+b,c) $ 42' |
| 200 |
ckmsg(s, "invalid syntax") |
| 201 |
|
| 202 |
s = 'exec (a+b,c) $ 42' |
| 203 |
ckmsg(s, "invalid syntax") |
| 204 |
|
| 205 |
# should not apply to subclasses, see issue #31161 |
| 206 |
s = '''if True:\nprint "No indent"''' |
| 207 |
ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError) |
| 208 |
|
| 209 |
s = '''if True:\n print()\n\texec "mixed tabs and spaces"''' |
| 210 |
ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError) |
| 211 |
|
| 212 |
def check(self, src, lineno, offset, end_lineno=None, end_offset=None, encoding='utf-8'): |
| 213 |
with self.subTest(source=src, lineno=lineno, offset=offset): |
| 214 |
with self.assertRaises(SyntaxError) as cm: |
| 215 |
compile(src, '<fragment>', 'exec') |
| 216 |
self.assertEqual(cm.exception.lineno, lineno) |
| 217 |
self.assertEqual(cm.exception.offset, offset) |
| 218 |
if end_lineno is not None: |
| 219 |
self.assertEqual(cm.exception.end_lineno, end_lineno) |
| 220 |
if end_offset is not None: |
| 221 |
self.assertEqual(cm.exception.end_offset, end_offset) |
| 222 |
|
| 223 |
if cm.exception.text is not None: |
| 224 |
if not isinstance(src, str): |
| 225 |
src = src.decode(encoding, 'replace') |
| 226 |
line = src.split('\n')[lineno-1] |
| 227 |
if lineno == 1: |
| 228 |
line = line.removeprefix('\ufeff') |
| 229 |
self.assertIn(line, cm.exception.text) |
| 230 |
|
| 231 |
def test_error_offset_continuation_characters(self): |
| 232 |
check = self.check |
| 233 |
check('"\\\n"(1 for c in I,\\\n\\', 2, 2) |
| 234 |
|
| 235 |
def testSyntaxErrorOffset(self): |
| 236 |
check = self.check |
| 237 |
check('def fact(x):\n\treturn x!\n', 2, 10) |
| 238 |
check('1 +\n', 1, 4) |
| 239 |
check('def spam():\n print(1)\n print(2)', 3, 10) |
| 240 |
check('Python = "Python" +', 1, 20) |
| 241 |
check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20) |
| 242 |
check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +', |
| 243 |
2, 19, encoding='cp1251') |
| 244 |
check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 12) |
| 245 |
check(b'\n\n\nPython = "\xcf\xb3\xf2\xee\xed" +', 4, 12) |
| 246 |
check(b'\xef\xbb\xbfPython = "\xcf\xb3\xf2\xee\xed" +', 1, 12) |
| 247 |
check('x = "a', 1, 5) |
| 248 |
check('lambda x: x = 2', 1, 1) |
| 249 |
check('f{a + b + c}', 1, 2) |
| 250 |
check('[file for str(file) in []\n]', 1, 11) |
| 251 |
check('a = « hello » « world »', 1, 5) |
| 252 |
check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5) |
| 253 |
check('[file for\n str(file) in []]', 2, 2) |
| 254 |
check("ages = {'Alice'=22, 'Bob'=23}", 1, 9) |
| 255 |
check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19) |
| 256 |
check("[a b c d e f]", 1, 2) |
| 257 |
check("for x yfff:", 1, 7) |
| 258 |
check("f(a for a in b, c)", 1, 3, 1, 15) |
| 259 |
check("f(a for a in b if a, c)", 1, 3, 1, 20) |
| 260 |
check("f(a, b for b in c)", 1, 6, 1, 18) |
| 261 |
check("f(a, b for b in c, d)", 1, 6, 1, 18) |
| 262 |
|
| 263 |
# Errors thrown by compile.c |
| 264 |
check('class foo:return 1', 1, 11) |
| 265 |
check('def f():\n continue', 2, 3) |
| 266 |
check('def f():\n break', 2, 3) |
| 267 |
check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1) |
| 268 |
check('try:\n pass\nexcept*:\n pass', 3, 8) |
| 269 |
check('try:\n pass\nexcept*:\n pass\nexcept* ValueError:\n pass', 3, 8) |
| 270 |
|
| 271 |
# Errors thrown by the tokenizer |
| 272 |
check('(0x+1)', 1, 3) |
| 273 |
check('x = 0xI', 1, 6) |
| 274 |
check('0010 + 2', 1, 1) |
| 275 |
check('x = 32e-+4', 1, 8) |
| 276 |
check('x = 0o9', 1, 7) |
| 277 |
check('\u03b1 = 0xI', 1, 6) |
| 278 |
check(b'\xce\xb1 = 0xI', 1, 6) |
| 279 |
check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6, |
| 280 |
encoding='iso8859-7') |
| 281 |
check(b"""if 1: |
| 282 |
def foo(): |
| 283 |
''' |
| 284 |
|
| 285 |
def bar(): |
| 286 |
pass |
| 287 |
|
| 288 |
def baz(): |
| 289 |
'''quux''' |
| 290 |
""", 9, 24) |
| 291 |
check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4) |
| 292 |
check("(1+)", 1, 4) |
| 293 |
check("[interesting\nfoo()\n", 1, 1) |
| 294 |
check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 1, 0) |
| 295 |
check("""f''' |
| 296 |
{ |
| 297 |
(123_a) |
| 298 |
}'''""", 3, 17) |
| 299 |
check("""f''' |
| 300 |
{ |
| 301 |
f\"\"\" |
| 302 |
{ |
| 303 |
(123_a) |
| 304 |
} |
| 305 |
\"\"\" |
| 306 |
}'''""", 5, 17) |
| 307 |
check('''f""" |
| 308 |
|
| 309 |
|
| 310 |
{ |
| 311 |
6 |
| 312 |
0="""''', 5, 13) |
| 313 |
check('b"fooжжж"'.encode(), 1, 1, 1, 10) |
| 314 |
|
| 315 |
# Errors thrown by symtable.c |
| 316 |
check('x = [(yield i) for i in range(3)]', 1, 7) |
| 317 |
check('def f():\n from _ import *', 2, 17) |
| 318 |
check('def f(x, x):\n pass', 1, 10) |
| 319 |
check('{i for i in range(5) if (j := 0) for j in range(5)}', 1, 38) |
| 320 |
check('def f(x):\n nonlocal x', 2, 3) |
| 321 |
check('def f(x):\n x = 1\n global x', 3, 3) |
| 322 |
check('nonlocal x', 1, 1) |
| 323 |
check('def f():\n global x\n nonlocal x', 2, 3) |
| 324 |
|
| 325 |
# Errors thrown by future.c |
| 326 |
check('from __future__ import doesnt_exist', 1, 24) |
| 327 |
check('from __future__ import braces', 1, 24) |
| 328 |
check('x=1\nfrom __future__ import division', 2, 1) |
| 329 |
check('foo(1=2)', 1, 5) |
| 330 |
check('def f():\n x, y: int', 2, 3) |
| 331 |
check('[*x for x in xs]', 1, 2) |
| 332 |
check('foo(x for x in range(10), 100)', 1, 5) |
| 333 |
check('for 1 in []: pass', 1, 5) |
| 334 |
check('(yield i) = 2', 1, 2) |
| 335 |
check('def f(*):\n pass', 1, 7) |
| 336 |
|
| 337 |
@unittest.skipIf(INT_MAX >= sys.maxsize, "Downcasting to int is safe for col_offset") |
| 338 |
@support.requires_resource('cpu') |
| 339 |
@support.bigmemtest(INT_MAX, memuse=2, dry_run=False) |
| 340 |
def testMemoryErrorBigSource(self, size): |
| 341 |
src = b"if True:\n%*s" % (size, b"pass") |
| 342 |
with self.assertRaisesRegex(OverflowError, "Parser column offset overflow"): |
| 343 |
compile(src, '<fragment>', 'exec') |
| 344 |
|
| 345 |
@cpython_only |
| 346 |
def testSettingException(self): |
| 347 |
# test that setting an exception at the C level works even if the |
| 348 |
# exception object can't be constructed. |
| 349 |
|
| 350 |
class BadException(Exception): |
| 351 |
def __init__(self_): |
| 352 |
raise RuntimeError("can't instantiate BadException") |
| 353 |
|
| 354 |
class InvalidException: |
| 355 |
pass |
| 356 |
|
| 357 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 358 |
def test_capi1(): |
| 359 |
try: |
| 360 |
_testcapi.raise_exception(BadException, 1) |
| 361 |
except TypeError as err: |
| 362 |
co = err.__traceback__.tb_frame.f_code |
| 363 |
self.assertEqual(co.co_name, "test_capi1") |
| 364 |
self.assertEndsWith(co.co_filename, 'test_exceptions.py') |
| 365 |
else: |
| 366 |
self.fail("Expected exception") |
| 367 |
|
| 368 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 369 |
def test_capi2(): |
| 370 |
try: |
| 371 |
_testcapi.raise_exception(BadException, 0) |
| 372 |
except RuntimeError as err: |
| 373 |
tb = err.__traceback__.tb_next |
| 374 |
co = tb.tb_frame.f_code |
| 375 |
self.assertEqual(co.co_name, "__init__") |
| 376 |
self.assertEndsWith(co.co_filename, 'test_exceptions.py') |
| 377 |
co2 = tb.tb_frame.f_back.f_code |
| 378 |
self.assertEqual(co2.co_name, "test_capi2") |
| 379 |
else: |
| 380 |
self.fail("Expected exception") |
| 381 |
|
| 382 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 383 |
def test_capi3(): |
| 384 |
self.assertRaises(SystemError, _testcapi.raise_exception, |
| 385 |
InvalidException, 1) |
| 386 |
|
| 387 |
test_capi1() |
| 388 |
test_capi2() |
| 389 |
test_capi3() |
| 390 |
|
| 391 |
def test_WindowsError(self): |
| 392 |
try: |
| 393 |
WindowsError |
| 394 |
except NameError: |
| 395 |
pass |
| 396 |
else: |
| 397 |
self.assertIs(WindowsError, OSError) |
| 398 |
self.assertEqual(str(OSError(1001)), "1001") |
| 399 |
self.assertEqual(str(OSError(1001, "message")), |
| 400 |
"[Errno 1001] message") |
| 401 |
# POSIX errno (9 aka EBADF) is untranslated |
| 402 |
w = OSError(9, 'foo', 'bar') |
| 403 |
self.assertEqual(w.errno, 9) |
| 404 |
self.assertEqual(w.winerror, None) |
| 405 |
self.assertEqual(str(w), "[Errno 9] foo: 'bar'") |
| 406 |
# ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2) |
| 407 |
w = OSError(0, 'foo', 'bar', 3) |
| 408 |
self.assertEqual(w.errno, 2) |
| 409 |
self.assertEqual(w.winerror, 3) |
| 410 |
self.assertEqual(w.strerror, 'foo') |
| 411 |
self.assertEqual(w.filename, 'bar') |
| 412 |
self.assertEqual(w.filename2, None) |
| 413 |
self.assertEqual(str(w), "[WinError 3] foo: 'bar'") |
| 414 |
# Unknown win error becomes EINVAL (22) |
| 415 |
w = OSError(0, 'foo', None, 1001) |
| 416 |
self.assertEqual(w.errno, 22) |
| 417 |
self.assertEqual(w.winerror, 1001) |
| 418 |
self.assertEqual(w.strerror, 'foo') |
| 419 |
self.assertEqual(w.filename, None) |
| 420 |
self.assertEqual(w.filename2, None) |
| 421 |
self.assertEqual(str(w), "[WinError 1001] foo") |
| 422 |
# Non-numeric "errno" |
| 423 |
w = OSError('bar', 'foo') |
| 424 |
self.assertEqual(w.errno, 'bar') |
| 425 |
self.assertEqual(w.winerror, None) |
| 426 |
self.assertEqual(w.strerror, 'foo') |
| 427 |
self.assertEqual(w.filename, None) |
| 428 |
self.assertEqual(w.filename2, None) |
| 429 |
|
| 430 |
@unittest.skipUnless(sys.platform == 'win32', |
| 431 |
'test specific to Windows') |
| 432 |
def test_windows_message(self): |
| 433 |
"""Should fill in unknown error code in Windows error message""" |
| 434 |
ctypes = import_module('ctypes') |
| 435 |
# this error code has no message, Python formats it as hexadecimal |
| 436 |
code = 3765269347 |
| 437 |
with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code): |
| 438 |
ctypes.pythonapi.PyErr_SetFromWindowsErr(code) |
| 439 |
|
| 440 |
def testAttributes(self): |
| 441 |
# test that exception attributes are happy |
| 442 |
|
| 443 |
exceptionList = [ |
| 444 |
(BaseException, (), {}, {'args' : ()}), |
| 445 |
(BaseException, (1, ), {}, {'args' : (1,)}), |
| 446 |
(BaseException, ('foo',), {}, |
| 447 |
{'args' : ('foo',)}), |
| 448 |
(BaseException, ('foo', 1), {}, |
| 449 |
{'args' : ('foo', 1)}), |
| 450 |
(SystemExit, ('foo',), {}, |
| 451 |
{'args' : ('foo',), 'code' : 'foo'}), |
| 452 |
(OSError, ('foo',), {}, |
| 453 |
{'args' : ('foo',), 'filename' : None, 'filename2' : None, |
| 454 |
'errno' : None, 'strerror' : None}), |
| 455 |
(OSError, ('foo', 'bar'), {}, |
| 456 |
{'args' : ('foo', 'bar'), |
| 457 |
'filename' : None, 'filename2' : None, |
| 458 |
'errno' : 'foo', 'strerror' : 'bar'}), |
| 459 |
(OSError, ('foo', 'bar', 'baz'), {}, |
| 460 |
{'args' : ('foo', 'bar'), |
| 461 |
'filename' : 'baz', 'filename2' : None, |
| 462 |
'errno' : 'foo', 'strerror' : 'bar'}), |
| 463 |
(OSError, ('foo', 'bar', 'baz', None, 'quux'), {}, |
| 464 |
{'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}), |
| 465 |
(OSError, ('errnoStr', 'strErrorStr', 'filenameStr'), {}, |
| 466 |
{'args' : ('errnoStr', 'strErrorStr'), |
| 467 |
'strerror' : 'strErrorStr', 'errno' : 'errnoStr', |
| 468 |
'filename' : 'filenameStr'}), |
| 469 |
(OSError, (1, 'strErrorStr', 'filenameStr'), {}, |
| 470 |
{'args' : (1, 'strErrorStr'), 'errno' : 1, |
| 471 |
'strerror' : 'strErrorStr', |
| 472 |
'filename' : 'filenameStr', 'filename2' : None}), |
| 473 |
(SyntaxError, (), {}, {'msg' : None, 'text' : None, |
| 474 |
'filename' : None, 'lineno' : None, 'offset' : None, |
| 475 |
'end_offset': None, 'print_file_and_line' : None}), |
| 476 |
(SyntaxError, ('msgStr',), {}, |
| 477 |
{'args' : ('msgStr',), 'text' : None, |
| 478 |
'print_file_and_line' : None, 'msg' : 'msgStr', |
| 479 |
'filename' : None, 'lineno' : None, 'offset' : None, |
| 480 |
'end_offset': None}), |
| 481 |
(SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr', |
| 482 |
'textStr', 'endLinenoStr', 'endOffsetStr')), {}, |
| 483 |
{'offset' : 'offsetStr', 'text' : 'textStr', |
| 484 |
'args' : ('msgStr', ('filenameStr', 'linenoStr', |
| 485 |
'offsetStr', 'textStr', |
| 486 |
'endLinenoStr', 'endOffsetStr')), |
| 487 |
'print_file_and_line' : None, 'msg' : 'msgStr', |
| 488 |
'filename' : 'filenameStr', 'lineno' : 'linenoStr', |
| 489 |
'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}), |
| 490 |
(SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
| 491 |
'textStr', 'endLinenoStr', 'endOffsetStr', |
| 492 |
'print_file_and_lineStr'), {}, |
| 493 |
{'text' : None, |
| 494 |
'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr', |
| 495 |
'textStr', 'endLinenoStr', 'endOffsetStr', |
| 496 |
'print_file_and_lineStr'), |
| 497 |
'print_file_and_line' : None, 'msg' : 'msgStr', |
| 498 |
'filename' : None, 'lineno' : None, 'offset' : None, |
| 499 |
'end_lineno': None, 'end_offset': None}), |
| 500 |
(UnicodeError, (), {}, {'args' : (),}), |
| 501 |
(UnicodeEncodeError, ('ascii', 'a', 0, 1, |
| 502 |
'ordinal not in range'), {}, |
| 503 |
{'args' : ('ascii', 'a', 0, 1, |
| 504 |
'ordinal not in range'), |
| 505 |
'encoding' : 'ascii', 'object' : 'a', |
| 506 |
'start' : 0, 'reason' : 'ordinal not in range'}), |
| 507 |
(UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1, |
| 508 |
'ordinal not in range'), {}, |
| 509 |
{'args' : ('ascii', bytearray(b'\xff'), 0, 1, |
| 510 |
'ordinal not in range'), |
| 511 |
'encoding' : 'ascii', 'object' : b'\xff', |
| 512 |
'start' : 0, 'reason' : 'ordinal not in range'}), |
| 513 |
(UnicodeDecodeError, ('ascii', b'\xff', 0, 1, |
| 514 |
'ordinal not in range'), {}, |
| 515 |
{'args' : ('ascii', b'\xff', 0, 1, |
| 516 |
'ordinal not in range'), |
| 517 |
'encoding' : 'ascii', 'object' : b'\xff', |
| 518 |
'start' : 0, 'reason' : 'ordinal not in range'}), |
| 519 |
(UnicodeTranslateError, ("\u3042", 0, 1, "ouch"), {}, |
| 520 |
{'args' : ('\u3042', 0, 1, 'ouch'), |
| 521 |
'object' : '\u3042', 'reason' : 'ouch', |
| 522 |
'start' : 0, 'end' : 1}), |
| 523 |
(NaiveException, ('foo',), {}, |
| 524 |
{'args': ('foo',), 'x': 'foo'}), |
| 525 |
(SlottedNaiveException, ('foo',), {}, |
| 526 |
{'args': ('foo',), 'x': 'foo'}), |
| 527 |
(AttributeError, ('foo',), dict(name='name', obj='obj'), |
| 528 |
dict(args=('foo',), name='name', obj='obj')), |
| 529 |
] |
| 530 |
try: |
| 531 |
# More tests are in test_WindowsError |
| 532 |
exceptionList.append( |
| 533 |
(WindowsError, (1, 'strErrorStr', 'filenameStr'), {}, |
| 534 |
{'args' : (1, 'strErrorStr'), |
| 535 |
'strerror' : 'strErrorStr', 'winerror' : None, |
| 536 |
'errno' : 1, |
| 537 |
'filename' : 'filenameStr', 'filename2' : None}) |
| 538 |
) |
| 539 |
except NameError: |
| 540 |
pass |
| 541 |
|
| 542 |
for exc, args, kwargs, expected in exceptionList: |
| 543 |
try: |
| 544 |
e = exc(*args, **kwargs) |
| 545 |
except: |
| 546 |
print(f"\nexc={exc!r}, args={args!r}", file=sys.stderr) |
| 547 |
# raise |
| 548 |
else: |
| 549 |
# Verify module name |
| 550 |
if not type(e).__name__.endswith('NaiveException'): |
| 551 |
self.assertEqual(type(e).__module__, 'builtins') |
| 552 |
# Verify no ref leaks in Exc_str() |
| 553 |
s = str(e) |
| 554 |
for checkArgName in expected: |
| 555 |
value = getattr(e, checkArgName) |
| 556 |
self.assertEqual(repr(value), |
| 557 |
repr(expected[checkArgName]), |
| 558 |
'%r.%s == %r, expected %r' % ( |
| 559 |
e, checkArgName, |
| 560 |
value, expected[checkArgName])) |
| 561 |
|
| 562 |
# test for pickling support |
| 563 |
for p in [pickle]: |
| 564 |
for protocol in range(p.HIGHEST_PROTOCOL + 1): |
| 565 |
s = p.dumps(e, protocol) |
| 566 |
new = p.loads(s) |
| 567 |
for checkArgName in expected: |
| 568 |
got = repr(getattr(new, checkArgName)) |
| 569 |
if exc == AttributeError and checkArgName == 'obj': |
| 570 |
# See GH-103352, we're not pickling |
| 571 |
# obj at this point. So verify it's None. |
| 572 |
want = repr(None) |
| 573 |
else: |
| 574 |
want = repr(expected[checkArgName]) |
| 575 |
self.assertEqual(got, want, |
| 576 |
'pickled "%r", attribute "%s' % |
| 577 |
(e, checkArgName)) |
| 578 |
|
| 579 |
def test_setstate(self): |
| 580 |
e = Exception(42) |
| 581 |
e.blah = 53 |
| 582 |
self.assertEqual(e.args, (42,)) |
| 583 |
self.assertEqual(e.blah, 53) |
| 584 |
self.assertRaises(AttributeError, getattr, e, 'a') |
| 585 |
self.assertRaises(AttributeError, getattr, e, 'b') |
| 586 |
e.__setstate__({'a': 1 , 'b': 2}) |
| 587 |
self.assertEqual(e.args, (42,)) |
| 588 |
self.assertEqual(e.blah, 53) |
| 589 |
self.assertEqual(e.a, 1) |
| 590 |
self.assertEqual(e.b, 2) |
| 591 |
e.__setstate__({'a': 11, 'args': (1,2,3), 'blah': 35}) |
| 592 |
self.assertEqual(e.args, (1,2,3)) |
| 593 |
self.assertEqual(e.blah, 35) |
| 594 |
self.assertEqual(e.a, 11) |
| 595 |
self.assertEqual(e.b, 2) |
| 596 |
|
| 597 |
def test_invalid_setstate(self): |
| 598 |
e = Exception(42) |
| 599 |
with self.assertRaisesRegex(TypeError, "state is not a dictionary"): |
| 600 |
e.__setstate__(42) |
| 601 |
|
| 602 |
def test_notes(self): |
| 603 |
for e in [BaseException(1), Exception(2), ValueError(3)]: |
| 604 |
with self.subTest(e=e): |
| 605 |
self.assertNotHasAttr(e, '__notes__') |
| 606 |
e.add_note("My Note") |
| 607 |
self.assertEqual(e.__notes__, ["My Note"]) |
| 608 |
|
| 609 |
with self.assertRaises(TypeError): |
| 610 |
e.add_note(42) |
| 611 |
self.assertEqual(e.__notes__, ["My Note"]) |
| 612 |
|
| 613 |
e.add_note("Your Note") |
| 614 |
self.assertEqual(e.__notes__, ["My Note", "Your Note"]) |
| 615 |
|
| 616 |
del e.__notes__ |
| 617 |
self.assertNotHasAttr(e, '__notes__') |
| 618 |
|
| 619 |
e.add_note("Our Note") |
| 620 |
self.assertEqual(e.__notes__, ["Our Note"]) |
| 621 |
|
| 622 |
e.__notes__ = 42 |
| 623 |
self.assertEqual(e.__notes__, 42) |
| 624 |
|
| 625 |
with self.assertRaises(TypeError): |
| 626 |
e.add_note("will not work") |
| 627 |
self.assertEqual(e.__notes__, 42) |
| 628 |
|
| 629 |
def testWithTraceback(self): |
| 630 |
try: |
| 631 |
raise IndexError(4) |
| 632 |
except Exception as e: |
| 633 |
tb = e.__traceback__ |
| 634 |
|
| 635 |
e = BaseException().with_traceback(tb) |
| 636 |
self.assertIsInstance(e, BaseException) |
| 637 |
self.assertEqual(e.__traceback__, tb) |
| 638 |
|
| 639 |
e = IndexError(5).with_traceback(tb) |
| 640 |
self.assertIsInstance(e, IndexError) |
| 641 |
self.assertEqual(e.__traceback__, tb) |
| 642 |
|
| 643 |
class MyException(Exception): |
| 644 |
pass |
| 645 |
|
| 646 |
e = MyException().with_traceback(tb) |
| 647 |
self.assertIsInstance(e, MyException) |
| 648 |
self.assertEqual(e.__traceback__, tb) |
| 649 |
|
| 650 |
def testInvalidTraceback(self): |
| 651 |
try: |
| 652 |
Exception().__traceback__ = 5 |
| 653 |
except TypeError as e: |
| 654 |
self.assertIn("__traceback__ must be a traceback", str(e)) |
| 655 |
else: |
| 656 |
self.fail("No exception raised") |
| 657 |
|
| 658 |
def test_invalid_setattr(self): |
| 659 |
TE = TypeError |
| 660 |
exc = Exception() |
| 661 |
msg = "'int' object is not iterable" |
| 662 |
self.assertRaisesRegex(TE, msg, setattr, exc, 'args', 1) |
| 663 |
msg = "__traceback__ must be a traceback or None" |
| 664 |
self.assertRaisesRegex(TE, msg, setattr, exc, '__traceback__', 1) |
| 665 |
msg = "exception cause must be None or derive from BaseException" |
| 666 |
self.assertRaisesRegex(TE, msg, setattr, exc, '__cause__', 1) |
| 667 |
msg = "exception context must be None or derive from BaseException" |
| 668 |
self.assertRaisesRegex(TE, msg, setattr, exc, '__context__', 1) |
| 669 |
|
| 670 |
def test_invalid_delattr(self): |
| 671 |
TE = TypeError |
| 672 |
try: |
| 673 |
raise IndexError(4) |
| 674 |
except Exception as e: |
| 675 |
exc = e |
| 676 |
|
| 677 |
msg = "may not be deleted" |
| 678 |
self.assertRaisesRegex(TE, msg, delattr, exc, 'args') |
| 679 |
self.assertRaisesRegex(TE, msg, delattr, exc, '__traceback__') |
| 680 |
self.assertRaisesRegex(TE, msg, delattr, exc, '__cause__') |
| 681 |
self.assertRaisesRegex(TE, msg, delattr, exc, '__context__') |
| 682 |
|
| 683 |
def testNoneClearsTracebackAttr(self): |
| 684 |
try: |
| 685 |
raise IndexError(4) |
| 686 |
except Exception as e: |
| 687 |
tb = e.__traceback__ |
| 688 |
|
| 689 |
e = Exception() |
| 690 |
e.__traceback__ = tb |
| 691 |
e.__traceback__ = None |
| 692 |
self.assertEqual(e.__traceback__, None) |
| 693 |
|
| 694 |
def testChainingAttrs(self): |
| 695 |
e = Exception() |
| 696 |
self.assertIsNone(e.__context__) |
| 697 |
self.assertIsNone(e.__cause__) |
| 698 |
|
| 699 |
e = TypeError() |
| 700 |
self.assertIsNone(e.__context__) |
| 701 |
self.assertIsNone(e.__cause__) |
| 702 |
|
| 703 |
class MyException(OSError): |
| 704 |
pass |
| 705 |
|
| 706 |
e = MyException() |
| 707 |
self.assertIsNone(e.__context__) |
| 708 |
self.assertIsNone(e.__cause__) |
| 709 |
|
| 710 |
def testChainingDescriptors(self): |
| 711 |
try: |
| 712 |
raise Exception() |
| 713 |
except Exception as exc: |
| 714 |
e = exc |
| 715 |
|
| 716 |
self.assertIsNone(e.__context__) |
| 717 |
self.assertIsNone(e.__cause__) |
| 718 |
self.assertFalse(e.__suppress_context__) |
| 719 |
|
| 720 |
e.__context__ = NameError() |
| 721 |
e.__cause__ = None |
| 722 |
self.assertIsInstance(e.__context__, NameError) |
| 723 |
self.assertIsNone(e.__cause__) |
| 724 |
self.assertTrue(e.__suppress_context__) |
| 725 |
e.__suppress_context__ = False |
| 726 |
self.assertFalse(e.__suppress_context__) |
| 727 |
|
| 728 |
def testKeywordArgs(self): |
| 729 |
# test that builtin exception don't take keyword args, |
| 730 |
# but user-defined subclasses can if they want |
| 731 |
self.assertRaises(TypeError, BaseException, a=1) |
| 732 |
|
| 733 |
class DerivedException(BaseException): |
| 734 |
def __init__(self, fancy_arg): |
| 735 |
BaseException.__init__(self) |
| 736 |
self.fancy_arg = fancy_arg |
| 737 |
|
| 738 |
x = DerivedException(fancy_arg=42) |
| 739 |
self.assertEqual(x.fancy_arg, 42) |
| 740 |
|
| 741 |
@no_tracing |
| 742 |
def testInfiniteRecursion(self): |
| 743 |
def f(): |
| 744 |
return f() |
| 745 |
self.assertRaises(RecursionError, f) |
| 746 |
|
| 747 |
def g(): |
| 748 |
try: |
| 749 |
return g() |
| 750 |
except ValueError: |
| 751 |
return -1 |
| 752 |
self.assertRaises(RecursionError, g) |
| 753 |
|
| 754 |
def test_str(self): |
| 755 |
# Make sure both instances and classes have a str representation. |
| 756 |
self.assertTrue(str(Exception)) |
| 757 |
self.assertTrue(str(Exception('a'))) |
| 758 |
self.assertTrue(str(Exception('a', 'b'))) |
| 759 |
|
| 760 |
def test_exception_cleanup_names(self): |
| 761 |
# Make sure the local variable bound to the exception instance by |
| 762 |
# an "except" statement is only visible inside the except block. |
| 763 |
try: |
| 764 |
raise Exception() |
| 765 |
except Exception as e: |
| 766 |
self.assertIsInstance(e, Exception) |
| 767 |
self.assertNotIn('e', locals()) |
| 768 |
with self.assertRaises(UnboundLocalError): |
| 769 |
e |
| 770 |
|
| 771 |
def test_exception_cleanup_names2(self): |
| 772 |
# Make sure the cleanup doesn't break if the variable is explicitly deleted. |
| 773 |
try: |
| 774 |
raise Exception() |
| 775 |
except Exception as e: |
| 776 |
self.assertIsInstance(e, Exception) |
| 777 |
del e |
| 778 |
self.assertNotIn('e', locals()) |
| 779 |
with self.assertRaises(UnboundLocalError): |
| 780 |
e |
| 781 |
|
| 782 |
def testExceptionCleanupState(self): |
| 783 |
# Make sure exception state is cleaned up as soon as the except |
| 784 |
# block is left. See #2507 |
| 785 |
|
| 786 |
class MyException(Exception): |
| 787 |
def __init__(self, obj): |
| 788 |
self.obj = obj |
| 789 |
class MyObj: |
| 790 |
pass |
| 791 |
|
| 792 |
def inner_raising_func(): |
| 793 |
# Create some references in exception value and traceback |
| 794 |
local_ref = obj |
| 795 |
raise MyException(obj) |
| 796 |
|
| 797 |
# Qualified "except" with "as" |
| 798 |
obj = MyObj() |
| 799 |
wr = weakref.ref(obj) |
| 800 |
try: |
| 801 |
inner_raising_func() |
| 802 |
except MyException as e: |
| 803 |
pass |
| 804 |
obj = None |
| 805 |
gc_collect() # For PyPy or other GCs. |
| 806 |
obj = wr() |
| 807 |
self.assertIsNone(obj) |
| 808 |
|
| 809 |
# Qualified "except" without "as" |
| 810 |
obj = MyObj() |
| 811 |
wr = weakref.ref(obj) |
| 812 |
try: |
| 813 |
inner_raising_func() |
| 814 |
except MyException: |
| 815 |
pass |
| 816 |
obj = None |
| 817 |
gc_collect() # For PyPy or other GCs. |
| 818 |
obj = wr() |
| 819 |
self.assertIsNone(obj) |
| 820 |
|
| 821 |
# Bare "except" |
| 822 |
obj = MyObj() |
| 823 |
wr = weakref.ref(obj) |
| 824 |
try: |
| 825 |
inner_raising_func() |
| 826 |
except: |
| 827 |
pass |
| 828 |
obj = None |
| 829 |
gc_collect() # For PyPy or other GCs. |
| 830 |
obj = wr() |
| 831 |
self.assertIsNone(obj) |
| 832 |
|
| 833 |
# "except" with premature block leave |
| 834 |
obj = MyObj() |
| 835 |
wr = weakref.ref(obj) |
| 836 |
for i in [0]: |
| 837 |
try: |
| 838 |
inner_raising_func() |
| 839 |
except: |
| 840 |
break |
| 841 |
obj = None |
| 842 |
gc_collect() # For PyPy or other GCs. |
| 843 |
obj = wr() |
| 844 |
self.assertIsNone(obj) |
| 845 |
|
| 846 |
# "except" block raising another exception |
| 847 |
obj = MyObj() |
| 848 |
wr = weakref.ref(obj) |
| 849 |
try: |
| 850 |
try: |
| 851 |
inner_raising_func() |
| 852 |
except: |
| 853 |
raise KeyError |
| 854 |
except KeyError as e: |
| 855 |
# We want to test that the except block above got rid of |
| 856 |
# the exception raised in inner_raising_func(), but it |
| 857 |
# also ends up in the __context__ of the KeyError, so we |
| 858 |
# must clear the latter manually for our test to succeed. |
| 859 |
e.__context__ = None |
| 860 |
obj = None |
| 861 |
gc_collect() # For PyPy or other GCs. |
| 862 |
obj = wr() |
| 863 |
# guarantee no ref cycles on CPython (don't gc_collect) |
| 864 |
if check_impl_detail(cpython=False): |
| 865 |
gc_collect() |
| 866 |
self.assertIsNone(obj) |
| 867 |
|
| 868 |
# Some complicated construct |
| 869 |
obj = MyObj() |
| 870 |
wr = weakref.ref(obj) |
| 871 |
try: |
| 872 |
inner_raising_func() |
| 873 |
except MyException: |
| 874 |
try: |
| 875 |
try: |
| 876 |
raise |
| 877 |
finally: |
| 878 |
raise |
| 879 |
except MyException: |
| 880 |
pass |
| 881 |
obj = None |
| 882 |
if check_impl_detail(cpython=False): |
| 883 |
gc_collect() |
| 884 |
obj = wr() |
| 885 |
self.assertIsNone(obj) |
| 886 |
|
| 887 |
# Inside an exception-silencing "with" block |
| 888 |
class Context: |
| 889 |
def __enter__(self): |
| 890 |
return self |
| 891 |
def __exit__ (self, exc_type, exc_value, exc_tb): |
| 892 |
return True |
| 893 |
obj = MyObj() |
| 894 |
wr = weakref.ref(obj) |
| 895 |
with Context(): |
| 896 |
inner_raising_func() |
| 897 |
obj = None |
| 898 |
if check_impl_detail(cpython=False): |
| 899 |
gc_collect() |
| 900 |
obj = wr() |
| 901 |
self.assertIsNone(obj) |
| 902 |
|
| 903 |
def test_exception_target_in_nested_scope(self): |
| 904 |
# issue 4617: This used to raise a SyntaxError |
| 905 |
# "can not delete variable 'e' referenced in nested scope" |
| 906 |
def print_error(): |
| 907 |
e |
| 908 |
try: |
| 909 |
something |
| 910 |
except Exception as e: |
| 911 |
print_error() |
| 912 |
# implicit "del e" here |
| 913 |
|
| 914 |
def test_generator_leaking(self): |
| 915 |
# Test that generator exception state doesn't leak into the calling |
| 916 |
# frame |
| 917 |
def yield_raise(): |
| 918 |
try: |
| 919 |
raise KeyError("caught") |
| 920 |
except KeyError: |
| 921 |
yield sys.exception() |
| 922 |
yield sys.exception() |
| 923 |
yield sys.exception() |
| 924 |
g = yield_raise() |
| 925 |
self.assertIsInstance(next(g), KeyError) |
| 926 |
self.assertIsNone(sys.exception()) |
| 927 |
self.assertIsInstance(next(g), KeyError) |
| 928 |
self.assertIsNone(sys.exception()) |
| 929 |
self.assertIsNone(next(g)) |
| 930 |
|
| 931 |
# Same test, but inside an exception handler |
| 932 |
try: |
| 933 |
raise TypeError("foo") |
| 934 |
except TypeError: |
| 935 |
g = yield_raise() |
| 936 |
self.assertIsInstance(next(g), KeyError) |
| 937 |
self.assertIsInstance(sys.exception(), TypeError) |
| 938 |
self.assertIsInstance(next(g), KeyError) |
| 939 |
self.assertIsInstance(sys.exception(), TypeError) |
| 940 |
self.assertIsInstance(next(g), TypeError) |
| 941 |
del g |
| 942 |
self.assertIsInstance(sys.exception(), TypeError) |
| 943 |
|
| 944 |
def test_generator_leaking2(self): |
| 945 |
# See issue 12475. |
| 946 |
def g(): |
| 947 |
yield |
| 948 |
try: |
| 949 |
raise RuntimeError |
| 950 |
except RuntimeError: |
| 951 |
it = g() |
| 952 |
next(it) |
| 953 |
try: |
| 954 |
next(it) |
| 955 |
except StopIteration: |
| 956 |
pass |
| 957 |
self.assertIsNone(sys.exception()) |
| 958 |
|
| 959 |
def test_generator_leaking3(self): |
| 960 |
# See issue #23353. When gen.throw() is called, the caller's |
| 961 |
# exception state should be save and restored. |
| 962 |
def g(): |
| 963 |
try: |
| 964 |
yield |
| 965 |
except ZeroDivisionError: |
| 966 |
yield sys.exception() |
| 967 |
it = g() |
| 968 |
next(it) |
| 969 |
try: |
| 970 |
1/0 |
| 971 |
except ZeroDivisionError as e: |
| 972 |
self.assertIs(sys.exception(), e) |
| 973 |
gen_exc = it.throw(e) |
| 974 |
self.assertIs(sys.exception(), e) |
| 975 |
self.assertIs(gen_exc, e) |
| 976 |
self.assertIsNone(sys.exception()) |
| 977 |
|
| 978 |
def test_generator_leaking4(self): |
| 979 |
# See issue #23353. When an exception is raised by a generator, |
| 980 |
# the caller's exception state should still be restored. |
| 981 |
def g(): |
| 982 |
try: |
| 983 |
1/0 |
| 984 |
except ZeroDivisionError: |
| 985 |
yield sys.exception() |
| 986 |
raise |
| 987 |
it = g() |
| 988 |
try: |
| 989 |
raise TypeError |
| 990 |
except TypeError: |
| 991 |
# The caller's exception state (TypeError) is temporarily |
| 992 |
# saved in the generator. |
| 993 |
tp = type(next(it)) |
| 994 |
self.assertIs(tp, ZeroDivisionError) |
| 995 |
try: |
| 996 |
next(it) |
| 997 |
# We can't check it immediately, but while next() returns |
| 998 |
# with an exception, it shouldn't have restored the old |
| 999 |
# exception state (TypeError). |
| 1000 |
except ZeroDivisionError as e: |
| 1001 |
self.assertIs(sys.exception(), e) |
| 1002 |
# We used to find TypeError here. |
| 1003 |
self.assertIsNone(sys.exception()) |
| 1004 |
|
| 1005 |
def test_generator_doesnt_retain_old_exc(self): |
| 1006 |
def g(): |
| 1007 |
self.assertIsInstance(sys.exception(), RuntimeError) |
| 1008 |
yield |
| 1009 |
self.assertIsNone(sys.exception()) |
| 1010 |
it = g() |
| 1011 |
try: |
| 1012 |
raise RuntimeError |
| 1013 |
except RuntimeError: |
| 1014 |
next(it) |
| 1015 |
self.assertRaises(StopIteration, next, it) |
| 1016 |
|
| 1017 |
def test_generator_finalizing_and_sys_exception(self): |
| 1018 |
# See #7173 |
| 1019 |
def simple_gen(): |
| 1020 |
yield 1 |
| 1021 |
def run_gen(): |
| 1022 |
gen = simple_gen() |
| 1023 |
try: |
| 1024 |
raise RuntimeError |
| 1025 |
except RuntimeError: |
| 1026 |
return next(gen) |
| 1027 |
run_gen() |
| 1028 |
gc_collect() |
| 1029 |
self.assertIsNone(sys.exception()) |
| 1030 |
|
| 1031 |
def _check_generator_cleanup_exc_state(self, testfunc): |
| 1032 |
# Issue #12791: exception state is cleaned up as soon as a generator |
| 1033 |
# is closed (reference cycles are broken). |
| 1034 |
class MyException(Exception): |
| 1035 |
def __init__(self, obj): |
| 1036 |
self.obj = obj |
| 1037 |
class MyObj: |
| 1038 |
pass |
| 1039 |
|
| 1040 |
def raising_gen(): |
| 1041 |
try: |
| 1042 |
raise MyException(obj) |
| 1043 |
except MyException: |
| 1044 |
yield |
| 1045 |
|
| 1046 |
obj = MyObj() |
| 1047 |
wr = weakref.ref(obj) |
| 1048 |
g = raising_gen() |
| 1049 |
next(g) |
| 1050 |
testfunc(g) |
| 1051 |
g = obj = None |
| 1052 |
gc_collect() # For PyPy or other GCs. |
| 1053 |
obj = wr() |
| 1054 |
self.assertIsNone(obj) |
| 1055 |
|
| 1056 |
def test_generator_throw_cleanup_exc_state(self): |
| 1057 |
def do_throw(g): |
| 1058 |
try: |
| 1059 |
g.throw(RuntimeError()) |
| 1060 |
except RuntimeError: |
| 1061 |
pass |
| 1062 |
self._check_generator_cleanup_exc_state(do_throw) |
| 1063 |
|
| 1064 |
def test_generator_close_cleanup_exc_state(self): |
| 1065 |
def do_close(g): |
| 1066 |
g.close() |
| 1067 |
self._check_generator_cleanup_exc_state(do_close) |
| 1068 |
|
| 1069 |
def test_generator_del_cleanup_exc_state(self): |
| 1070 |
def do_del(g): |
| 1071 |
g = None |
| 1072 |
self._check_generator_cleanup_exc_state(do_del) |
| 1073 |
|
| 1074 |
def test_generator_next_cleanup_exc_state(self): |
| 1075 |
def do_next(g): |
| 1076 |
try: |
| 1077 |
next(g) |
| 1078 |
except StopIteration: |
| 1079 |
pass |
| 1080 |
else: |
| 1081 |
self.fail("should have raised StopIteration") |
| 1082 |
self._check_generator_cleanup_exc_state(do_next) |
| 1083 |
|
| 1084 |
def test_generator_send_cleanup_exc_state(self): |
| 1085 |
def do_send(g): |
| 1086 |
try: |
| 1087 |
g.send(None) |
| 1088 |
except StopIteration: |
| 1089 |
pass |
| 1090 |
else: |
| 1091 |
self.fail("should have raised StopIteration") |
| 1092 |
self._check_generator_cleanup_exc_state(do_send) |
| 1093 |
|
| 1094 |
def test_3114(self): |
| 1095 |
# Bug #3114: in its destructor, MyObject retrieves a pointer to |
| 1096 |
# obsolete and/or deallocated objects. |
| 1097 |
class MyObject: |
| 1098 |
def __del__(self): |
| 1099 |
nonlocal e |
| 1100 |
e = sys.exception() |
| 1101 |
e = () |
| 1102 |
try: |
| 1103 |
raise Exception(MyObject()) |
| 1104 |
except: |
| 1105 |
pass |
| 1106 |
gc_collect() # For PyPy or other GCs. |
| 1107 |
self.assertIsNone(e) |
| 1108 |
|
| 1109 |
def test_raise_does_not_create_context_chain_cycle(self): |
| 1110 |
class A(Exception): |
| 1111 |
pass |
| 1112 |
class B(Exception): |
| 1113 |
pass |
| 1114 |
class C(Exception): |
| 1115 |
pass |
| 1116 |
|
| 1117 |
# Create a context chain: |
| 1118 |
# C -> B -> A |
| 1119 |
# Then raise A in context of C. |
| 1120 |
try: |
| 1121 |
try: |
| 1122 |
raise A |
| 1123 |
except A as a_: |
| 1124 |
a = a_ |
| 1125 |
try: |
| 1126 |
raise B |
| 1127 |
except B as b_: |
| 1128 |
b = b_ |
| 1129 |
try: |
| 1130 |
raise C |
| 1131 |
except C as c_: |
| 1132 |
c = c_ |
| 1133 |
self.assertIsInstance(a, A) |
| 1134 |
self.assertIsInstance(b, B) |
| 1135 |
self.assertIsInstance(c, C) |
| 1136 |
self.assertIsNone(a.__context__) |
| 1137 |
self.assertIs(b.__context__, a) |
| 1138 |
self.assertIs(c.__context__, b) |
| 1139 |
raise a |
| 1140 |
except A as e: |
| 1141 |
exc = e |
| 1142 |
|
| 1143 |
# Expect A -> C -> B, without cycle |
| 1144 |
self.assertIs(exc, a) |
| 1145 |
self.assertIs(a.__context__, c) |
| 1146 |
self.assertIs(c.__context__, b) |
| 1147 |
self.assertIsNone(b.__context__) |
| 1148 |
|
| 1149 |
def test_no_hang_on_context_chain_cycle1(self): |
| 1150 |
# See issue 25782. Cycle in context chain. |
| 1151 |
|
| 1152 |
def cycle(): |
| 1153 |
try: |
| 1154 |
raise ValueError(1) |
| 1155 |
except ValueError as ex: |
| 1156 |
ex.__context__ = ex |
| 1157 |
raise TypeError(2) |
| 1158 |
|
| 1159 |
try: |
| 1160 |
cycle() |
| 1161 |
except Exception as e: |
| 1162 |
exc = e |
| 1163 |
|
| 1164 |
self.assertIsInstance(exc, TypeError) |
| 1165 |
self.assertIsInstance(exc.__context__, ValueError) |
| 1166 |
self.assertIs(exc.__context__.__context__, exc.__context__) |
| 1167 |
|
| 1168 |
def test_no_hang_on_context_chain_cycle2(self): |
| 1169 |
# See issue 25782. Cycle at head of context chain. |
| 1170 |
|
| 1171 |
class A(Exception): |
| 1172 |
pass |
| 1173 |
class B(Exception): |
| 1174 |
pass |
| 1175 |
class C(Exception): |
| 1176 |
pass |
| 1177 |
|
| 1178 |
# Context cycle: |
| 1179 |
# +-----------+ |
| 1180 |
# V | |
| 1181 |
# C --> B --> A |
| 1182 |
with self.assertRaises(C) as cm: |
| 1183 |
try: |
| 1184 |
raise A() |
| 1185 |
except A as _a: |
| 1186 |
a = _a |
| 1187 |
try: |
| 1188 |
raise B() |
| 1189 |
except B as _b: |
| 1190 |
b = _b |
| 1191 |
try: |
| 1192 |
raise C() |
| 1193 |
except C as _c: |
| 1194 |
c = _c |
| 1195 |
a.__context__ = c |
| 1196 |
raise c |
| 1197 |
|
| 1198 |
self.assertIs(cm.exception, c) |
| 1199 |
# Verify the expected context chain cycle |
| 1200 |
self.assertIs(c.__context__, b) |
| 1201 |
self.assertIs(b.__context__, a) |
| 1202 |
self.assertIs(a.__context__, c) |
| 1203 |
|
| 1204 |
def test_no_hang_on_context_chain_cycle3(self): |
| 1205 |
# See issue 25782. Longer context chain with cycle. |
| 1206 |
|
| 1207 |
class A(Exception): |
| 1208 |
pass |
| 1209 |
class B(Exception): |
| 1210 |
pass |
| 1211 |
class C(Exception): |
| 1212 |
pass |
| 1213 |
class D(Exception): |
| 1214 |
pass |
| 1215 |
class E(Exception): |
| 1216 |
pass |
| 1217 |
|
| 1218 |
# Context cycle: |
| 1219 |
# +-----------+ |
| 1220 |
# V | |
| 1221 |
# E --> D --> C --> B --> A |
| 1222 |
with self.assertRaises(E) as cm: |
| 1223 |
try: |
| 1224 |
raise A() |
| 1225 |
except A as _a: |
| 1226 |
a = _a |
| 1227 |
try: |
| 1228 |
raise B() |
| 1229 |
except B as _b: |
| 1230 |
b = _b |
| 1231 |
try: |
| 1232 |
raise C() |
| 1233 |
except C as _c: |
| 1234 |
c = _c |
| 1235 |
a.__context__ = c |
| 1236 |
try: |
| 1237 |
raise D() |
| 1238 |
except D as _d: |
| 1239 |
d = _d |
| 1240 |
e = E() |
| 1241 |
raise e |
| 1242 |
|
| 1243 |
self.assertIs(cm.exception, e) |
| 1244 |
# Verify the expected context chain cycle |
| 1245 |
self.assertIs(e.__context__, d) |
| 1246 |
self.assertIs(d.__context__, c) |
| 1247 |
self.assertIs(c.__context__, b) |
| 1248 |
self.assertIs(b.__context__, a) |
| 1249 |
self.assertIs(a.__context__, c) |
| 1250 |
|
| 1251 |
def test_context_of_exception_in_try_and_finally(self): |
| 1252 |
try: |
| 1253 |
try: |
| 1254 |
te = TypeError(1) |
| 1255 |
raise te |
| 1256 |
finally: |
| 1257 |
ve = ValueError(2) |
| 1258 |
raise ve |
| 1259 |
except Exception as e: |
| 1260 |
exc = e |
| 1261 |
|
| 1262 |
self.assertIs(exc, ve) |
| 1263 |
self.assertIs(exc.__context__, te) |
| 1264 |
|
| 1265 |
def test_context_of_exception_in_except_and_finally(self): |
| 1266 |
try: |
| 1267 |
try: |
| 1268 |
te = TypeError(1) |
| 1269 |
raise te |
| 1270 |
except: |
| 1271 |
ve = ValueError(2) |
| 1272 |
raise ve |
| 1273 |
finally: |
| 1274 |
oe = OSError(3) |
| 1275 |
raise oe |
| 1276 |
except Exception as e: |
| 1277 |
exc = e |
| 1278 |
|
| 1279 |
self.assertIs(exc, oe) |
| 1280 |
self.assertIs(exc.__context__, ve) |
| 1281 |
self.assertIs(exc.__context__.__context__, te) |
| 1282 |
|
| 1283 |
def test_context_of_exception_in_else_and_finally(self): |
| 1284 |
try: |
| 1285 |
try: |
| 1286 |
pass |
| 1287 |
except: |
| 1288 |
pass |
| 1289 |
else: |
| 1290 |
ve = ValueError(1) |
| 1291 |
raise ve |
| 1292 |
finally: |
| 1293 |
oe = OSError(2) |
| 1294 |
raise oe |
| 1295 |
except Exception as e: |
| 1296 |
exc = e |
| 1297 |
|
| 1298 |
self.assertIs(exc, oe) |
| 1299 |
self.assertIs(exc.__context__, ve) |
| 1300 |
|
| 1301 |
def test_unicode_change_attributes(self): |
| 1302 |
# See issue 7309. This was a crasher. |
| 1303 |
|
| 1304 |
u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo') |
| 1305 |
self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo") |
| 1306 |
u.end = 2 |
| 1307 |
self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo") |
| 1308 |
u.end = 5 |
| 1309 |
u.reason = 0x345345345345345345 |
| 1310 |
self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997") |
| 1311 |
u.encoding = 4000 |
| 1312 |
self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997") |
| 1313 |
u.start = 1000 |
| 1314 |
self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997") |
| 1315 |
|
| 1316 |
u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo') |
| 1317 |
self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo") |
| 1318 |
u.end = 2 |
| 1319 |
self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo") |
| 1320 |
u.end = 5 |
| 1321 |
u.reason = 0x345345345345345345 |
| 1322 |
self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997") |
| 1323 |
u.encoding = 4000 |
| 1324 |
self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997") |
| 1325 |
u.start = 1000 |
| 1326 |
self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997") |
| 1327 |
|
| 1328 |
u = UnicodeTranslateError('xxxx', 1, 5, 'foo') |
| 1329 |
self.assertEqual(str(u), "can't translate characters in position 1-4: foo") |
| 1330 |
u.end = 2 |
| 1331 |
self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo") |
| 1332 |
u.end = 5 |
| 1333 |
u.reason = 0x345345345345345345 |
| 1334 |
self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997") |
| 1335 |
u.start = 1000 |
| 1336 |
self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997") |
| 1337 |
|
| 1338 |
def test_unicode_errors_no_object(self): |
| 1339 |
# See issue #21134. |
| 1340 |
klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError |
| 1341 |
for klass in klasses: |
| 1342 |
self.assertEqual(str(klass.__new__(klass)), "") |
| 1343 |
|
| 1344 |
def test_unicode_error_str_does_not_crash(self): |
| 1345 |
# Test that str(UnicodeError(...)) does not crash. |
| 1346 |
# See https://github.com/python/cpython/issues/123378. |
| 1347 |
|
| 1348 |
for start, end, objlen in product( |
| 1349 |
range(-5, 5), |
| 1350 |
range(-5, 5), |
| 1351 |
range(7), |
| 1352 |
): |
| 1353 |
obj = 'a' * objlen |
| 1354 |
with self.subTest('encode', objlen=objlen, start=start, end=end): |
| 1355 |
exc = UnicodeEncodeError('utf-8', obj, start, end, '') |
| 1356 |
self.assertIsInstance(str(exc), str) |
| 1357 |
|
| 1358 |
with self.subTest('translate', objlen=objlen, start=start, end=end): |
| 1359 |
exc = UnicodeTranslateError(obj, start, end, '') |
| 1360 |
self.assertIsInstance(str(exc), str) |
| 1361 |
|
| 1362 |
encoded = obj.encode() |
| 1363 |
with self.subTest('decode', objlen=objlen, start=start, end=end): |
| 1364 |
exc = UnicodeDecodeError('utf-8', encoded, start, end, '') |
| 1365 |
self.assertIsInstance(str(exc), str) |
| 1366 |
|
| 1367 |
def test_unicode_error_evil_str_set_none_object(self): |
| 1368 |
def side_effect(exc): |
| 1369 |
exc.object = None |
| 1370 |
self.do_test_unicode_error_mutate(side_effect) |
| 1371 |
|
| 1372 |
def test_unicode_error_evil_str_del_self_object(self): |
| 1373 |
def side_effect(exc): |
| 1374 |
del exc.object |
| 1375 |
self.do_test_unicode_error_mutate(side_effect) |
| 1376 |
|
| 1377 |
def do_test_unicode_error_mutate(self, side_effect): |
| 1378 |
# Test that str(UnicodeError(...)) does not crash when |
| 1379 |
# side-effects mutate the underlying 'object' attribute. |
| 1380 |
# See https://github.com/python/cpython/issues/128974. |
| 1381 |
|
| 1382 |
class Evil(str): |
| 1383 |
def __str__(self): |
| 1384 |
side_effect(exc) |
| 1385 |
return self |
| 1386 |
|
| 1387 |
for reason, encoding in [ |
| 1388 |
("reason", Evil("utf-8")), |
| 1389 |
(Evil("reason"), "utf-8"), |
| 1390 |
(Evil("reason"), Evil("utf-8")), |
| 1391 |
]: |
| 1392 |
with self.subTest(encoding=encoding, reason=reason): |
| 1393 |
with self.subTest(UnicodeEncodeError): |
| 1394 |
exc = UnicodeEncodeError(encoding, "x", 0, 1, reason) |
| 1395 |
self.assertRaises(TypeError, str, exc) |
| 1396 |
with self.subTest(UnicodeDecodeError): |
| 1397 |
exc = UnicodeDecodeError(encoding, b"x", 0, 1, reason) |
| 1398 |
self.assertRaises(TypeError, str, exc) |
| 1399 |
|
| 1400 |
with self.subTest(UnicodeTranslateError): |
| 1401 |
exc = UnicodeTranslateError("x", 0, 1, Evil("reason")) |
| 1402 |
self.assertRaises(TypeError, str, exc) |
| 1403 |
|
| 1404 |
@no_tracing |
| 1405 |
def test_badisinstance(self): |
| 1406 |
# Bug #2542: if issubclass(e, MyException) raises an exception, |
| 1407 |
# it should be ignored |
| 1408 |
class Meta(type): |
| 1409 |
def __subclasscheck__(cls, subclass): |
| 1410 |
raise ValueError() |
| 1411 |
class MyException(Exception, metaclass=Meta): |
| 1412 |
pass |
| 1413 |
|
| 1414 |
with captured_stderr() as stderr: |
| 1415 |
try: |
| 1416 |
raise KeyError() |
| 1417 |
except MyException as e: |
| 1418 |
self.fail("exception should not be a MyException") |
| 1419 |
except KeyError: |
| 1420 |
pass |
| 1421 |
except: |
| 1422 |
self.fail("Should have raised KeyError") |
| 1423 |
else: |
| 1424 |
self.fail("Should have raised KeyError") |
| 1425 |
|
| 1426 |
def g(): |
| 1427 |
try: |
| 1428 |
return g() |
| 1429 |
except RecursionError as e: |
| 1430 |
return e |
| 1431 |
exc = g() |
| 1432 |
self.assertIsInstance(exc, RecursionError, type(exc)) |
| 1433 |
self.assertIn("maximum recursion depth exceeded", str(exc)) |
| 1434 |
|
| 1435 |
@support.skip_wasi_stack_overflow() |
| 1436 |
@support.skip_emscripten_stack_overflow() |
| 1437 |
@cpython_only |
| 1438 |
@support.requires_resource('cpu') |
| 1439 |
def test_trashcan_recursion(self): |
| 1440 |
# See bpo-33930 |
| 1441 |
|
| 1442 |
def foo(): |
| 1443 |
o = object() |
| 1444 |
for x in range(1_000_000): |
| 1445 |
# Create a big chain of method objects that will trigger |
| 1446 |
# a deep chain of calls when they need to be destructed. |
| 1447 |
o = o.__dir__ |
| 1448 |
|
| 1449 |
foo() |
| 1450 |
support.gc_collect() |
| 1451 |
|
| 1452 |
@support.skip_emscripten_stack_overflow() |
| 1453 |
@cpython_only |
| 1454 |
def test_recursion_normalizing_exception(self): |
| 1455 |
import_module("_testinternalcapi") |
| 1456 |
# Issue #22898. |
| 1457 |
# Test that a RecursionError is raised when tstate->recursion_depth is |
| 1458 |
# equal to recursion_limit in PyErr_NormalizeException() and check |
| 1459 |
# that a ResourceWarning is printed. |
| 1460 |
# Prior to #22898, the recursivity of PyErr_NormalizeException() was |
| 1461 |
# controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst |
| 1462 |
# singleton was being used in that case, that held traceback data and |
| 1463 |
# locals indefinitely and would cause a segfault in _PyExc_Fini() upon |
| 1464 |
# finalization of these locals. |
| 1465 |
code = """if 1: |
| 1466 |
import sys |
| 1467 |
from _testinternalcapi import get_recursion_depth |
| 1468 |
from test import support |
| 1469 |
|
| 1470 |
class MyException(Exception): pass |
| 1471 |
|
| 1472 |
def setrecursionlimit(depth): |
| 1473 |
while 1: |
| 1474 |
try: |
| 1475 |
sys.setrecursionlimit(depth) |
| 1476 |
return depth |
| 1477 |
except RecursionError: |
| 1478 |
# sys.setrecursionlimit() raises a RecursionError if |
| 1479 |
# the new recursion limit is too low (issue #25274). |
| 1480 |
depth += 1 |
| 1481 |
|
| 1482 |
def recurse(cnt): |
| 1483 |
cnt -= 1 |
| 1484 |
if cnt: |
| 1485 |
recurse(cnt) |
| 1486 |
else: |
| 1487 |
generator.throw(MyException) |
| 1488 |
|
| 1489 |
def gen(): |
| 1490 |
f = open(%a, mode='rb', buffering=0) |
| 1491 |
yield |
| 1492 |
|
| 1493 |
generator = gen() |
| 1494 |
next(generator) |
| 1495 |
recursionlimit = sys.getrecursionlimit() |
| 1496 |
try: |
| 1497 |
recurse(support.exceeds_recursion_limit()) |
| 1498 |
finally: |
| 1499 |
sys.setrecursionlimit(recursionlimit) |
| 1500 |
print('Done.') |
| 1501 |
""" % __file__ |
| 1502 |
rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code) |
| 1503 |
# Check that the program does not fail with SIGABRT. |
| 1504 |
self.assertEqual(rc, 1) |
| 1505 |
self.assertIn(b'RecursionError', err) |
| 1506 |
self.assertIn(b'ResourceWarning', err) |
| 1507 |
self.assertIn(b'Done.', out) |
| 1508 |
|
| 1509 |
@cpython_only |
| 1510 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1511 |
@force_not_colorized |
| 1512 |
def test_recursion_normalizing_infinite_exception(self): |
| 1513 |
# Issue #30697. Test that a RecursionError is raised when |
| 1514 |
# maximum recursion depth has been exceeded when creating |
| 1515 |
# an exception |
| 1516 |
code = """if 1: |
| 1517 |
import _testcapi |
| 1518 |
try: |
| 1519 |
raise _testcapi.RecursingInfinitelyError |
| 1520 |
finally: |
| 1521 |
print('Done.') |
| 1522 |
""" |
| 1523 |
rc, out, err = script_helper.assert_python_failure("-c", code) |
| 1524 |
self.assertEqual(rc, 1) |
| 1525 |
expected = b'RecursionError' |
| 1526 |
self.assertTrue(expected in err, msg=f"{expected!r} not found in {err[:3_000]!r}... (truncated)") |
| 1527 |
self.assertIn(b'Done.', out) |
| 1528 |
|
| 1529 |
|
| 1530 |
@support.skip_emscripten_stack_overflow() |
| 1531 |
def test_recursion_in_except_handler(self): |
| 1532 |
|
| 1533 |
def set_relative_recursion_limit(n): |
| 1534 |
depth = 1 |
| 1535 |
while True: |
| 1536 |
try: |
| 1537 |
sys.setrecursionlimit(depth) |
| 1538 |
except RecursionError: |
| 1539 |
depth += 1 |
| 1540 |
else: |
| 1541 |
break |
| 1542 |
sys.setrecursionlimit(depth+n) |
| 1543 |
|
| 1544 |
def recurse_in_except(): |
| 1545 |
try: |
| 1546 |
1/0 |
| 1547 |
except: |
| 1548 |
recurse_in_except() |
| 1549 |
|
| 1550 |
def recurse_after_except(): |
| 1551 |
try: |
| 1552 |
1/0 |
| 1553 |
except: |
| 1554 |
pass |
| 1555 |
recurse_after_except() |
| 1556 |
|
| 1557 |
def recurse_in_body_and_except(): |
| 1558 |
try: |
| 1559 |
recurse_in_body_and_except() |
| 1560 |
except: |
| 1561 |
recurse_in_body_and_except() |
| 1562 |
|
| 1563 |
recursionlimit = sys.getrecursionlimit() |
| 1564 |
try: |
| 1565 |
set_relative_recursion_limit(10) |
| 1566 |
for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except): |
| 1567 |
with self.subTest(func=func): |
| 1568 |
try: |
| 1569 |
func() |
| 1570 |
except RecursionError: |
| 1571 |
pass |
| 1572 |
else: |
| 1573 |
self.fail("Should have raised a RecursionError") |
| 1574 |
finally: |
| 1575 |
sys.setrecursionlimit(recursionlimit) |
| 1576 |
|
| 1577 |
|
| 1578 |
@cpython_only |
| 1579 |
# Python built with Py_TRACE_REFS fail with a fatal error in |
| 1580 |
# _PyRefchain_Trace() on memory allocation error. |
| 1581 |
@unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') |
| 1582 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1583 |
def test_recursion_normalizing_with_no_memory(self): |
| 1584 |
# Issue #30697. Test that in the abort that occurs when there is no |
| 1585 |
# memory left and the size of the Python frames stack is greater than |
| 1586 |
# the size of the list of preallocated MemoryError instances, the |
| 1587 |
# Fatal Python error message mentions MemoryError. |
| 1588 |
code = """if 1: |
| 1589 |
import _testcapi |
| 1590 |
class C(): pass |
| 1591 |
def recurse(cnt): |
| 1592 |
cnt -= 1 |
| 1593 |
if cnt: |
| 1594 |
recurse(cnt) |
| 1595 |
else: |
| 1596 |
_testcapi.set_nomemory(0) |
| 1597 |
C() |
| 1598 |
recurse(16) |
| 1599 |
""" |
| 1600 |
with SuppressCrashReport(): |
| 1601 |
rc, out, err = script_helper.assert_python_failure("-c", code) |
| 1602 |
self.assertIn(b'MemoryError', err) |
| 1603 |
|
| 1604 |
@cpython_only |
| 1605 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1606 |
def test_MemoryError(self): |
| 1607 |
# PyErr_NoMemory always raises the same exception instance. |
| 1608 |
# Check that the traceback is not doubled. |
| 1609 |
import traceback |
| 1610 |
from _testcapi import raise_memoryerror |
| 1611 |
def raiseMemError(): |
| 1612 |
try: |
| 1613 |
raise_memoryerror() |
| 1614 |
except MemoryError as e: |
| 1615 |
tb = e.__traceback__ |
| 1616 |
else: |
| 1617 |
self.fail("Should have raised a MemoryError") |
| 1618 |
return traceback.format_tb(tb) |
| 1619 |
|
| 1620 |
tb1 = raiseMemError() |
| 1621 |
tb2 = raiseMemError() |
| 1622 |
self.assertEqual(tb1, tb2) |
| 1623 |
|
| 1624 |
@cpython_only |
| 1625 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1626 |
def test_exception_with_doc(self): |
| 1627 |
doc2 = "This is a test docstring." |
| 1628 |
doc4 = "This is another test docstring." |
| 1629 |
|
| 1630 |
self.assertRaises(SystemError, _testcapi.make_exception_with_doc, |
| 1631 |
"error1") |
| 1632 |
|
| 1633 |
# test basic usage of PyErr_NewException |
| 1634 |
error1 = _testcapi.make_exception_with_doc("_testcapi.error1") |
| 1635 |
self.assertIs(type(error1), type) |
| 1636 |
self.assertIsSubclass(error1, Exception) |
| 1637 |
self.assertIsNone(error1.__doc__) |
| 1638 |
|
| 1639 |
# test with given docstring |
| 1640 |
error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2) |
| 1641 |
self.assertEqual(error2.__doc__, doc2) |
| 1642 |
|
| 1643 |
# test with explicit base (without docstring) |
| 1644 |
error3 = _testcapi.make_exception_with_doc("_testcapi.error3", |
| 1645 |
base=error2) |
| 1646 |
self.assertIsSubclass(error3, error2) |
| 1647 |
|
| 1648 |
# test with explicit base tuple |
| 1649 |
class C(object): |
| 1650 |
pass |
| 1651 |
error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4, |
| 1652 |
(error3, C)) |
| 1653 |
self.assertIsSubclass(error4, error3) |
| 1654 |
self.assertIsSubclass(error4, C) |
| 1655 |
self.assertEqual(error4.__doc__, doc4) |
| 1656 |
|
| 1657 |
# test with explicit dictionary |
| 1658 |
error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "", |
| 1659 |
error4, {'a': 1}) |
| 1660 |
self.assertIsSubclass(error5, error4) |
| 1661 |
self.assertEqual(error5.a, 1) |
| 1662 |
self.assertEqual(error5.__doc__, "") |
| 1663 |
|
| 1664 |
@cpython_only |
| 1665 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1666 |
def test_memory_error_cleanup(self): |
| 1667 |
# Issue #5437: preallocated MemoryError instances should not keep |
| 1668 |
# traceback objects alive. |
| 1669 |
from _testcapi import raise_memoryerror |
| 1670 |
class C: |
| 1671 |
pass |
| 1672 |
wr = None |
| 1673 |
def inner(): |
| 1674 |
nonlocal wr |
| 1675 |
c = C() |
| 1676 |
wr = weakref.ref(c) |
| 1677 |
raise_memoryerror() |
| 1678 |
# We cannot use assertRaises since it manually deletes the traceback |
| 1679 |
try: |
| 1680 |
inner() |
| 1681 |
except MemoryError as e: |
| 1682 |
self.assertNotEqual(wr(), None) |
| 1683 |
else: |
| 1684 |
self.fail("MemoryError not raised") |
| 1685 |
gc_collect() # For PyPy or other GCs. |
| 1686 |
self.assertEqual(wr(), None) |
| 1687 |
|
| 1688 |
@no_tracing |
| 1689 |
def test_recursion_error_cleanup(self): |
| 1690 |
# Same test as above, but with "recursion exceeded" errors |
| 1691 |
class C: |
| 1692 |
pass |
| 1693 |
wr = None |
| 1694 |
def inner(): |
| 1695 |
nonlocal wr |
| 1696 |
c = C() |
| 1697 |
wr = weakref.ref(c) |
| 1698 |
inner() |
| 1699 |
# We cannot use assertRaises since it manually deletes the traceback |
| 1700 |
try: |
| 1701 |
inner() |
| 1702 |
except RecursionError as e: |
| 1703 |
self.assertNotEqual(wr(), None) |
| 1704 |
else: |
| 1705 |
self.fail("RecursionError not raised") |
| 1706 |
gc_collect() # For PyPy or other GCs. |
| 1707 |
self.assertEqual(wr(), None) |
| 1708 |
|
| 1709 |
def test_errno_ENOTDIR(self): |
| 1710 |
# Issue #12802: "not a directory" errors are ENOTDIR even on Windows |
| 1711 |
with self.assertRaises(OSError) as cm: |
| 1712 |
os.listdir(__file__) |
| 1713 |
self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception) |
| 1714 |
|
| 1715 |
def test_unraisable(self): |
| 1716 |
# Issue #22836: PyErr_WriteUnraisable() should give sensible reports |
| 1717 |
class BrokenDel: |
| 1718 |
def __del__(self): |
| 1719 |
exc = ValueError("del is broken") |
| 1720 |
# The following line is included in the traceback report: |
| 1721 |
raise exc |
| 1722 |
|
| 1723 |
obj = BrokenDel() |
| 1724 |
with support.catch_unraisable_exception() as cm: |
| 1725 |
obj_repr = repr(type(obj).__del__) |
| 1726 |
del obj |
| 1727 |
|
| 1728 |
gc_collect() # For PyPy or other GCs. |
| 1729 |
self.assertEqual(cm.unraisable.err_msg, |
| 1730 |
f"Exception ignored while calling " |
| 1731 |
f"deallocator {obj_repr}") |
| 1732 |
self.assertIsNotNone(cm.unraisable.exc_traceback) |
| 1733 |
|
| 1734 |
def test_unhandled(self): |
| 1735 |
# Check for sensible reporting of unhandled exceptions |
| 1736 |
for exc_type in (ValueError, BrokenStrException): |
| 1737 |
with self.subTest(exc_type): |
| 1738 |
try: |
| 1739 |
exc = exc_type("test message") |
| 1740 |
# The following line is included in the traceback report: |
| 1741 |
raise exc |
| 1742 |
except exc_type: |
| 1743 |
with captured_stderr() as stderr: |
| 1744 |
sys.__excepthook__(*sys.exc_info()) |
| 1745 |
report = stderr.getvalue() |
| 1746 |
self.assertIn("test_exceptions.py", report) |
| 1747 |
self.assertIn("raise exc", report) |
| 1748 |
self.assertIn(exc_type.__name__, report) |
| 1749 |
if exc_type is BrokenStrException: |
| 1750 |
self.assertIn("<exception str() failed>", report) |
| 1751 |
else: |
| 1752 |
self.assertIn("test message", report) |
| 1753 |
self.assertEndsWith(report, "\n") |
| 1754 |
|
| 1755 |
@cpython_only |
| 1756 |
# Python built with Py_TRACE_REFS fail with a fatal error in |
| 1757 |
# _PyRefchain_Trace() on memory allocation error. |
| 1758 |
@unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') |
| 1759 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1760 |
def test_memory_error_in_PyErr_PrintEx(self): |
| 1761 |
code = """if 1: |
| 1762 |
import _testcapi |
| 1763 |
class C(): pass |
| 1764 |
_testcapi.set_nomemory(0, %d) |
| 1765 |
C() |
| 1766 |
""" |
| 1767 |
|
| 1768 |
# Issue #30817: Abort in PyErr_PrintEx() when no memory. |
| 1769 |
# Span a large range of tests as the CPython code always evolves with |
| 1770 |
# changes that add or remove memory allocations. |
| 1771 |
for i in range(1, 20): |
| 1772 |
rc, out, err = script_helper.assert_python_failure("-c", code % i) |
| 1773 |
self.assertIn(rc, (1, 120)) |
| 1774 |
self.assertIn(b'MemoryError', err) |
| 1775 |
|
| 1776 |
def test_yield_in_nested_try_excepts(self): |
| 1777 |
#Issue #25612 |
| 1778 |
class MainError(Exception): |
| 1779 |
pass |
| 1780 |
|
| 1781 |
class SubError(Exception): |
| 1782 |
pass |
| 1783 |
|
| 1784 |
def main(): |
| 1785 |
try: |
| 1786 |
raise MainError() |
| 1787 |
except MainError: |
| 1788 |
try: |
| 1789 |
yield |
| 1790 |
except SubError: |
| 1791 |
pass |
| 1792 |
raise |
| 1793 |
|
| 1794 |
coro = main() |
| 1795 |
coro.send(None) |
| 1796 |
with self.assertRaises(MainError): |
| 1797 |
coro.throw(SubError()) |
| 1798 |
|
| 1799 |
def test_generator_doesnt_retain_old_exc2(self): |
| 1800 |
#Issue 28884#msg282532 |
| 1801 |
def g(): |
| 1802 |
try: |
| 1803 |
raise ValueError |
| 1804 |
except ValueError: |
| 1805 |
yield 1 |
| 1806 |
self.assertIsNone(sys.exception()) |
| 1807 |
yield 2 |
| 1808 |
|
| 1809 |
gen = g() |
| 1810 |
|
| 1811 |
try: |
| 1812 |
raise IndexError |
| 1813 |
except IndexError: |
| 1814 |
self.assertEqual(next(gen), 1) |
| 1815 |
self.assertEqual(next(gen), 2) |
| 1816 |
|
| 1817 |
def test_raise_in_generator(self): |
| 1818 |
#Issue 25612#msg304117 |
| 1819 |
def g(): |
| 1820 |
yield 1 |
| 1821 |
raise |
| 1822 |
yield 2 |
| 1823 |
|
| 1824 |
with self.assertRaises(ZeroDivisionError): |
| 1825 |
i = g() |
| 1826 |
try: |
| 1827 |
1/0 |
| 1828 |
except: |
| 1829 |
next(i) |
| 1830 |
next(i) |
| 1831 |
|
| 1832 |
@unittest.skipUnless(__debug__, "Won't work if __debug__ is False") |
| 1833 |
def test_assert_shadowing(self): |
| 1834 |
# Shadowing AssertionError would cause the assert statement to |
| 1835 |
# misbehave. |
| 1836 |
global AssertionError |
| 1837 |
AssertionError = TypeError |
| 1838 |
try: |
| 1839 |
assert False, 'hello' |
| 1840 |
except BaseException as e: |
| 1841 |
del AssertionError |
| 1842 |
self.assertIsInstance(e, AssertionError) |
| 1843 |
self.assertEqual(str(e), 'hello') |
| 1844 |
else: |
| 1845 |
del AssertionError |
| 1846 |
self.fail('Expected exception') |
| 1847 |
|
| 1848 |
def test_memory_error_subclasses(self): |
| 1849 |
# bpo-41654: MemoryError instances use a freelist of objects that are |
| 1850 |
# linked using the 'dict' attribute when they are inactive/dead. |
| 1851 |
# Subclasses of MemoryError should not participate in the freelist |
| 1852 |
# schema. This test creates a MemoryError object and keeps it alive |
| 1853 |
# (therefore advancing the freelist) and then it creates and destroys a |
| 1854 |
# subclass object. Finally, it checks that creating a new MemoryError |
| 1855 |
# succeeds, proving that the freelist is not corrupted. |
| 1856 |
|
| 1857 |
class TestException(MemoryError): |
| 1858 |
pass |
| 1859 |
|
| 1860 |
try: |
| 1861 |
raise MemoryError |
| 1862 |
except MemoryError as exc: |
| 1863 |
inst = exc |
| 1864 |
|
| 1865 |
try: |
| 1866 |
raise TestException |
| 1867 |
except Exception: |
| 1868 |
pass |
| 1869 |
|
| 1870 |
for _ in range(10): |
| 1871 |
try: |
| 1872 |
raise MemoryError |
| 1873 |
except MemoryError as exc: |
| 1874 |
pass |
| 1875 |
|
| 1876 |
gc_collect() |
| 1877 |
|
| 1878 |
@unittest.skipIf(_testcapi is None, "requires _testcapi") |
| 1879 |
def test_memory_error_in_subinterp(self): |
| 1880 |
# gh-109894: subinterpreters shouldn't count on last resort memory error |
| 1881 |
# when MemoryError is raised through PyErr_NoMemory() call, |
| 1882 |
# and should preallocate memory errors as does the main interpreter. |
| 1883 |
# interp.static_objects.last_resort_memory_error.args |
| 1884 |
# should be initialized to empty tuple to avoid crash on attempt to print it. |
| 1885 |
code = f"""if 1: |
| 1886 |
import _testcapi |
| 1887 |
_testcapi.run_in_subinterp(\"[0]*{sys.maxsize}\") |
| 1888 |
exit(0) |
| 1889 |
""" |
| 1890 |
rc, _, err = script_helper.assert_python_ok("-c", code) |
| 1891 |
self.assertIn(b'MemoryError', err) |
| 1892 |
|
| 1893 |
def test_keyerror_context(self): |
| 1894 |
# Make sure that _PyErr_SetKeyError() chains exceptions |
| 1895 |
try: |
| 1896 |
err1 = None |
| 1897 |
err2 = None |
| 1898 |
try: |
| 1899 |
d = {} |
| 1900 |
try: |
| 1901 |
raise ValueError("bug") |
| 1902 |
except Exception as exc: |
| 1903 |
err1 = exc |
| 1904 |
d[1] |
| 1905 |
except Exception as exc: |
| 1906 |
err2 = exc |
| 1907 |
|
| 1908 |
self.assertIsInstance(err1, ValueError) |
| 1909 |
self.assertIsInstance(err2, KeyError) |
| 1910 |
self.assertEqual(err2.__context__, err1) |
| 1911 |
finally: |
| 1912 |
# Break any potential reference cycle |
| 1913 |
exc1 = None |
| 1914 |
exc2 = None |
| 1915 |
|
| 1916 |
|
| 1917 |
@cpython_only |
| 1918 |
# Python built with Py_TRACE_REFS fail with a fatal error in |
| 1919 |
# _PyRefchain_Trace() on memory allocation error. |
| 1920 |
@unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') |
| 1921 |
def test_exec_set_nomemory_hang(self): |
| 1922 |
import_module("_testcapi") |
| 1923 |
# gh-134163: A MemoryError inside code that was wrapped by a try/except |
| 1924 |
# block would lead to an infinite loop. |
| 1925 |
|
| 1926 |
# The frame_lasti needs to be greater than 257 to prevent |
| 1927 |
# PyLong_FromLong() from returning cached integers, which |
| 1928 |
# don't require a memory allocation. Prepend some dummy code |
| 1929 |
# to artificially increase the instruction index. |
| 1930 |
warmup_code = "a = list(range(0, 1))\n" * 60 |
| 1931 |
user_input = warmup_code + dedent(""" |
| 1932 |
try: |
| 1933 |
import _testcapi |
| 1934 |
_testcapi.set_nomemory(0) |
| 1935 |
b = list(range(1000, 2000)) |
| 1936 |
except Exception as e: |
| 1937 |
import traceback |
| 1938 |
traceback.print_exc() |
| 1939 |
""") |
| 1940 |
with SuppressCrashReport(): |
| 1941 |
with script_helper.spawn_python('-c', user_input) as p: |
| 1942 |
p.wait() |
| 1943 |
output = p.stdout.read() |
| 1944 |
|
| 1945 |
self.assertIn(p.returncode, (0, 1)) |
| 1946 |
self.assertGreater(len(output), 0) # At minimum, should not hang |
| 1947 |
self.assertIn(b"MemoryError", output) |
| 1948 |
|
| 1949 |
|
| 1950 |
class NameErrorTests(unittest.TestCase): |
| 1951 |
def test_name_error_has_name(self): |
| 1952 |
try: |
| 1953 |
bluch |
| 1954 |
except NameError as exc: |
| 1955 |
self.assertEqual("bluch", exc.name) |
| 1956 |
|
| 1957 |
def test_issue45826(self): |
| 1958 |
# regression test for bpo-45826 |
| 1959 |
def f(): |
| 1960 |
with self.assertRaisesRegex(NameError, 'aaa'): |
| 1961 |
aab |
| 1962 |
|
| 1963 |
try: |
| 1964 |
f() |
| 1965 |
except self.failureException: |
| 1966 |
with support.captured_stderr() as err: |
| 1967 |
sys.__excepthook__(*sys.exc_info()) |
| 1968 |
else: |
| 1969 |
self.fail("assertRaisesRegex should have failed.") |
| 1970 |
|
| 1971 |
self.assertIn("aab", err.getvalue()) |
| 1972 |
|
| 1973 |
def test_issue45826_focused(self): |
| 1974 |
def f(): |
| 1975 |
try: |
| 1976 |
nonsense |
| 1977 |
except BaseException as E: |
| 1978 |
E.with_traceback(None) |
| 1979 |
raise ZeroDivisionError() |
| 1980 |
|
| 1981 |
try: |
| 1982 |
f() |
| 1983 |
except ZeroDivisionError: |
| 1984 |
with support.captured_stderr() as err: |
| 1985 |
sys.__excepthook__(*sys.exc_info()) |
| 1986 |
|
| 1987 |
self.assertIn("nonsense", err.getvalue()) |
| 1988 |
self.assertIn("ZeroDivisionError", err.getvalue()) |
| 1989 |
|
| 1990 |
def test_gh_111654(self): |
| 1991 |
def f(): |
| 1992 |
class TestClass: |
| 1993 |
TestClass |
| 1994 |
|
| 1995 |
self.assertRaises(NameError, f) |
| 1996 |
|
| 1997 |
# Note: name suggestion tests live in `test_traceback`. |
| 1998 |
|
| 1999 |
|
| 2000 |
class AttributeErrorTests(unittest.TestCase): |
| 2001 |
def test_attributes(self): |
| 2002 |
# Setting 'attr' should not be a problem. |
| 2003 |
exc = AttributeError('Ouch!') |
| 2004 |
self.assertIsNone(exc.name) |
| 2005 |
self.assertIsNone(exc.obj) |
| 2006 |
|
| 2007 |
sentinel = object() |
| 2008 |
exc = AttributeError('Ouch', name='carry', obj=sentinel) |
| 2009 |
self.assertEqual(exc.name, 'carry') |
| 2010 |
self.assertIs(exc.obj, sentinel) |
| 2011 |
|
| 2012 |
def test_getattr_has_name_and_obj(self): |
| 2013 |
class A: |
| 2014 |
blech = None |
| 2015 |
|
| 2016 |
obj = A() |
| 2017 |
try: |
| 2018 |
obj.bluch |
| 2019 |
except AttributeError as exc: |
| 2020 |
self.assertEqual("bluch", exc.name) |
| 2021 |
self.assertEqual(obj, exc.obj) |
| 2022 |
try: |
| 2023 |
object.__getattribute__(obj, "bluch") |
| 2024 |
except AttributeError as exc: |
| 2025 |
self.assertEqual("bluch", exc.name) |
| 2026 |
self.assertEqual(obj, exc.obj) |
| 2027 |
|
| 2028 |
def test_getattr_has_name_and_obj_for_method(self): |
| 2029 |
class A: |
| 2030 |
def blech(self): |
| 2031 |
return |
| 2032 |
|
| 2033 |
obj = A() |
| 2034 |
try: |
| 2035 |
obj.bluch() |
| 2036 |
except AttributeError as exc: |
| 2037 |
self.assertEqual("bluch", exc.name) |
| 2038 |
self.assertEqual(obj, exc.obj) |
| 2039 |
|
| 2040 |
# Note: name suggestion tests live in `test_traceback`. |
| 2041 |
|
| 2042 |
|
| 2043 |
class ImportErrorTests(unittest.TestCase): |
| 2044 |
|
| 2045 |
def test_attributes(self): |
| 2046 |
# Setting 'name' and 'path' should not be a problem. |
| 2047 |
exc = ImportError('test') |
| 2048 |
self.assertIsNone(exc.name) |
| 2049 |
self.assertIsNone(exc.path) |
| 2050 |
|
| 2051 |
exc = ImportError('test', name='somemodule') |
| 2052 |
self.assertEqual(exc.name, 'somemodule') |
| 2053 |
self.assertIsNone(exc.path) |
| 2054 |
|
| 2055 |
exc = ImportError('test', path='somepath') |
| 2056 |
self.assertEqual(exc.path, 'somepath') |
| 2057 |
self.assertIsNone(exc.name) |
| 2058 |
|
| 2059 |
exc = ImportError('test', path='somepath', name='somename') |
| 2060 |
self.assertEqual(exc.name, 'somename') |
| 2061 |
self.assertEqual(exc.path, 'somepath') |
| 2062 |
|
| 2063 |
msg = r"ImportError\(\) got an unexpected keyword argument 'invalid'" |
| 2064 |
with self.assertRaisesRegex(TypeError, msg): |
| 2065 |
ImportError('test', invalid='keyword') |
| 2066 |
|
| 2067 |
with self.assertRaisesRegex(TypeError, msg): |
| 2068 |
ImportError('test', name='name', invalid='keyword') |
| 2069 |
|
| 2070 |
with self.assertRaisesRegex(TypeError, msg): |
| 2071 |
ImportError('test', path='path', invalid='keyword') |
| 2072 |
|
| 2073 |
with self.assertRaisesRegex(TypeError, msg): |
| 2074 |
ImportError(invalid='keyword') |
| 2075 |
|
| 2076 |
with self.assertRaisesRegex(TypeError, msg): |
| 2077 |
ImportError('test', invalid='keyword', another=True) |
| 2078 |
|
| 2079 |
def test_reset_attributes(self): |
| 2080 |
exc = ImportError('test', name='name', path='path') |
| 2081 |
self.assertEqual(exc.args, ('test',)) |
| 2082 |
self.assertEqual(exc.msg, 'test') |
| 2083 |
self.assertEqual(exc.name, 'name') |
| 2084 |
self.assertEqual(exc.path, 'path') |
| 2085 |
|
| 2086 |
# Reset not specified attributes |
| 2087 |
exc.__init__() |
| 2088 |
self.assertEqual(exc.args, ()) |
| 2089 |
self.assertEqual(exc.msg, None) |
| 2090 |
self.assertEqual(exc.name, None) |
| 2091 |
self.assertEqual(exc.path, None) |
| 2092 |
|
| 2093 |
def test_non_str_argument(self): |
| 2094 |
# Issue #15778 |
| 2095 |
with check_warnings(('', BytesWarning), quiet=True): |
| 2096 |
arg = b'abc' |
| 2097 |
exc = ImportError(arg) |
| 2098 |
self.assertEqual(str(arg), str(exc)) |
| 2099 |
|
| 2100 |
def test_copy_pickle(self): |
| 2101 |
for kwargs in (dict(), |
| 2102 |
dict(name='somename'), |
| 2103 |
dict(path='somepath'), |
| 2104 |
dict(name='somename', path='somepath')): |
| 2105 |
orig = ImportError('test', **kwargs) |
| 2106 |
for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
| 2107 |
exc = pickle.loads(pickle.dumps(orig, proto)) |
| 2108 |
self.assertEqual(exc.args, ('test',)) |
| 2109 |
self.assertEqual(exc.msg, 'test') |
| 2110 |
self.assertEqual(exc.name, orig.name) |
| 2111 |
self.assertEqual(exc.path, orig.path) |
| 2112 |
for c in copy.copy, copy.deepcopy: |
| 2113 |
exc = c(orig) |
| 2114 |
self.assertEqual(exc.args, ('test',)) |
| 2115 |
self.assertEqual(exc.msg, 'test') |
| 2116 |
self.assertEqual(exc.name, orig.name) |
| 2117 |
self.assertEqual(exc.path, orig.path) |
| 2118 |
|
| 2119 |
|
| 2120 |
def run_script(source): |
| 2121 |
if isinstance(source, str): |
| 2122 |
with open(TESTFN, 'w', encoding='utf-8') as testfile: |
| 2123 |
testfile.write(dedent(source)) |
| 2124 |
else: |
| 2125 |
with open(TESTFN, 'wb') as testfile: |
| 2126 |
testfile.write(source) |
| 2127 |
_rc, _out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN) |
| 2128 |
return err.decode('utf-8').splitlines() |
| 2129 |
|
| 2130 |
class AssertionErrorTests(unittest.TestCase): |
| 2131 |
def tearDown(self): |
| 2132 |
unlink(TESTFN) |
| 2133 |
|
| 2134 |
@force_not_colorized |
| 2135 |
def test_assertion_error_location(self): |
| 2136 |
cases = [ |
| 2137 |
('assert None', |
| 2138 |
[ |
| 2139 |
' assert None', |
| 2140 |
' ^^^^', |
| 2141 |
'AssertionError', |
| 2142 |
], |
| 2143 |
), |
| 2144 |
('assert 0', |
| 2145 |
[ |
| 2146 |
' assert 0', |
| 2147 |
' ^', |
| 2148 |
'AssertionError', |
| 2149 |
], |
| 2150 |
), |
| 2151 |
('assert 1 > 2', |
| 2152 |
[ |
| 2153 |
' assert 1 > 2', |
| 2154 |
' ^^^^^', |
| 2155 |
'AssertionError', |
| 2156 |
], |
| 2157 |
), |
| 2158 |
('assert 1 > 2 and 3 > 2', |
| 2159 |
[ |
| 2160 |
' assert 1 > 2 and 3 > 2', |
| 2161 |
' ^^^^^^^^^^^^^^^', |
| 2162 |
'AssertionError', |
| 2163 |
], |
| 2164 |
), |
| 2165 |
('assert 1 > 2, "messäge"', |
| 2166 |
[ |
| 2167 |
' assert 1 > 2, "messäge"', |
| 2168 |
' ^^^^^', |
| 2169 |
'AssertionError: messäge', |
| 2170 |
], |
| 2171 |
), |
| 2172 |
('assert 1 > 2, "messäge"'.encode(), |
| 2173 |
[ |
| 2174 |
' assert 1 > 2, "messäge"', |
| 2175 |
' ^^^^^', |
| 2176 |
'AssertionError: messäge', |
| 2177 |
], |
| 2178 |
), |
| 2179 |
('# coding: latin1\nassert 1 > 2, "messäge"'.encode('latin1'), |
| 2180 |
[ |
| 2181 |
' assert 1 > 2, "messäge"', |
| 2182 |
' ^^^^^', |
| 2183 |
'AssertionError: messäge', |
| 2184 |
], |
| 2185 |
), |
| 2186 |
(BOM_UTF8 + 'assert 1 > 2, "messäge"'.encode(), |
| 2187 |
[ |
| 2188 |
' assert 1 > 2, "messäge"', |
| 2189 |
' ^^^^^', |
| 2190 |
'AssertionError: messäge', |
| 2191 |
], |
| 2192 |
), |
| 2193 |
|
| 2194 |
# Multiline: |
| 2195 |
(""" |
| 2196 |
assert ( |
| 2197 |
1 > 2) |
| 2198 |
""", |
| 2199 |
[ |
| 2200 |
' 1 > 2)', |
| 2201 |
' ^^^^^', |
| 2202 |
'AssertionError', |
| 2203 |
], |
| 2204 |
), |
| 2205 |
(""" |
| 2206 |
assert ( |
| 2207 |
1 > 2), "Message" |
| 2208 |
""", |
| 2209 |
[ |
| 2210 |
' 1 > 2), "Message"', |
| 2211 |
' ^^^^^', |
| 2212 |
'AssertionError: Message', |
| 2213 |
], |
| 2214 |
), |
| 2215 |
(""" |
| 2216 |
assert ( |
| 2217 |
1 > 2), \\ |
| 2218 |
"Message" |
| 2219 |
""", |
| 2220 |
[ |
| 2221 |
' 1 > 2), \\', |
| 2222 |
' ^^^^^', |
| 2223 |
'AssertionError: Message', |
| 2224 |
], |
| 2225 |
), |
| 2226 |
] |
| 2227 |
for source, expected in cases: |
| 2228 |
with self.subTest(source=source): |
| 2229 |
result = run_script(source) |
| 2230 |
self.assertEqual(result[-3:], expected) |
| 2231 |
|
| 2232 |
@force_not_colorized |
| 2233 |
def test_multiline_not_highlighted(self): |
| 2234 |
cases = [ |
| 2235 |
(""" |
| 2236 |
assert ( |
| 2237 |
1 > 2 |
| 2238 |
) |
| 2239 |
""", |
| 2240 |
[ |
| 2241 |
' 1 > 2', |
| 2242 |
'AssertionError', |
| 2243 |
], |
| 2244 |
), |
| 2245 |
(""" |
| 2246 |
assert ( |
| 2247 |
1 < 2 and |
| 2248 |
3 > 4 |
| 2249 |
) |
| 2250 |
""", |
| 2251 |
[ |
| 2252 |
' 1 < 2 and', |
| 2253 |
' 3 > 4', |
| 2254 |
'AssertionError', |
| 2255 |
], |
| 2256 |
), |
| 2257 |
] |
| 2258 |
for source, expected in cases: |
| 2259 |
with self.subTest(source=source): |
| 2260 |
result = run_script(source) |
| 2261 |
self.assertEqual(result[-len(expected):], expected) |
| 2262 |
|
| 2263 |
|
| 2264 |
@support.force_not_colorized_test_class |
| 2265 |
class SyntaxErrorTests(unittest.TestCase): |
| 2266 |
maxDiff = None |
| 2267 |
|
| 2268 |
@force_not_colorized |
| 2269 |
def test_range_of_offsets(self): |
| 2270 |
cases = [ |
| 2271 |
# Basic range from 2->7 |
| 2272 |
(("bad.py", 1, 2, "abcdefg", 1, 7), |
| 2273 |
dedent( |
| 2274 |
""" |
| 2275 |
File "bad.py", line 1 |
| 2276 |
abcdefg |
| 2277 |
^^^^^ |
| 2278 |
SyntaxError: bad bad |
| 2279 |
""")), |
| 2280 |
# end_offset = start_offset + 1 |
| 2281 |
(("bad.py", 1, 2, "abcdefg", 1, 3), |
| 2282 |
dedent( |
| 2283 |
""" |
| 2284 |
File "bad.py", line 1 |
| 2285 |
abcdefg |
| 2286 |
^ |
| 2287 |
SyntaxError: bad bad |
| 2288 |
""")), |
| 2289 |
# Negative end offset |
| 2290 |
(("bad.py", 1, 2, "abcdefg", 1, -2), |
| 2291 |
dedent( |
| 2292 |
""" |
| 2293 |
File "bad.py", line 1 |
| 2294 |
abcdefg |
| 2295 |
^ |
| 2296 |
SyntaxError: bad bad |
| 2297 |
""")), |
| 2298 |
# end offset before starting offset |
| 2299 |
(("bad.py", 1, 4, "abcdefg", 1, 2), |
| 2300 |
dedent( |
| 2301 |
""" |
| 2302 |
File "bad.py", line 1 |
| 2303 |
abcdefg |
| 2304 |
^ |
| 2305 |
SyntaxError: bad bad |
| 2306 |
""")), |
| 2307 |
# Both offsets negative |
| 2308 |
(("bad.py", 1, -4, "abcdefg", 1, -2), |
| 2309 |
dedent( |
| 2310 |
""" |
| 2311 |
File "bad.py", line 1 |
| 2312 |
abcdefg |
| 2313 |
SyntaxError: bad bad |
| 2314 |
""")), |
| 2315 |
# Both offsets negative and the end more negative |
| 2316 |
(("bad.py", 1, -4, "abcdefg", 1, -5), |
| 2317 |
dedent( |
| 2318 |
""" |
| 2319 |
File "bad.py", line 1 |
| 2320 |
abcdefg |
| 2321 |
SyntaxError: bad bad |
| 2322 |
""")), |
| 2323 |
# Both offsets 0 |
| 2324 |
(("bad.py", 1, 0, "abcdefg", 1, 0), |
| 2325 |
dedent( |
| 2326 |
""" |
| 2327 |
File "bad.py", line 1 |
| 2328 |
abcdefg |
| 2329 |
SyntaxError: bad bad |
| 2330 |
""")), |
| 2331 |
# Start offset 0 and end offset not 0 |
| 2332 |
(("bad.py", 1, 0, "abcdefg", 1, 5), |
| 2333 |
dedent( |
| 2334 |
""" |
| 2335 |
File "bad.py", line 1 |
| 2336 |
abcdefg |
| 2337 |
SyntaxError: bad bad |
| 2338 |
""")), |
| 2339 |
# End offset pass the source length |
| 2340 |
(("bad.py", 1, 2, "abcdefg", 1, 100), |
| 2341 |
dedent( |
| 2342 |
""" |
| 2343 |
File "bad.py", line 1 |
| 2344 |
abcdefg |
| 2345 |
^^^^^^ |
| 2346 |
SyntaxError: bad bad |
| 2347 |
""")), |
| 2348 |
] |
| 2349 |
for args, expected in cases: |
| 2350 |
with self.subTest(args=args): |
| 2351 |
try: |
| 2352 |
raise SyntaxError("bad bad", args) |
| 2353 |
except SyntaxError as exc: |
| 2354 |
with support.captured_stderr() as err: |
| 2355 |
sys.__excepthook__(*sys.exc_info()) |
| 2356 |
self.assertIn(expected, err.getvalue()) |
| 2357 |
the_exception = exc |
| 2358 |
|
| 2359 |
@force_not_colorized |
| 2360 |
def test_subclass(self): |
| 2361 |
class MySyntaxError(SyntaxError): |
| 2362 |
pass |
| 2363 |
|
| 2364 |
try: |
| 2365 |
raise MySyntaxError("bad bad", ("bad.py", 1, 2, "abcdefg", 1, 7)) |
| 2366 |
except SyntaxError as exc: |
| 2367 |
with support.captured_stderr() as err: |
| 2368 |
sys.__excepthook__(*sys.exc_info()) |
| 2369 |
self.assertIn(""" |
| 2370 |
File "bad.py", line 1 |
| 2371 |
abcdefg |
| 2372 |
^^^^^ |
| 2373 |
""", err.getvalue()) |
| 2374 |
|
| 2375 |
def test_encodings(self): |
| 2376 |
self.addCleanup(unlink, TESTFN) |
| 2377 |
source = ( |
| 2378 |
'# -*- coding: cp437 -*-\n' |
| 2379 |
'"¢¢¢¢¢¢" + f(4, x for x in range(1))\n' |
| 2380 |
) |
| 2381 |
err = run_script(source.encode('cp437')) |
| 2382 |
self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))') |
| 2383 |
self.assertEqual(err[-2], ' ^^^') |
| 2384 |
|
| 2385 |
# Check backwards tokenizer errors |
| 2386 |
source = '# -*- coding: ascii -*-\n\n(\n' |
| 2387 |
err = run_script(source) |
| 2388 |
self.assertEqual(err[-3], ' (') |
| 2389 |
self.assertEqual(err[-2], ' ^') |
| 2390 |
|
| 2391 |
def test_non_utf8(self): |
| 2392 |
# Check non utf-8 characters |
| 2393 |
self.addCleanup(unlink, TESTFN) |
| 2394 |
err = run_script(b"\x89") |
| 2395 |
self.assertIn("SyntaxError: Non-UTF-8 code starting with '\\x89' in file", err[-1]) |
| 2396 |
|
| 2397 |
def test_string_source(self): |
| 2398 |
def try_compile(source): |
| 2399 |
with self.assertRaises(SyntaxError) as cm: |
| 2400 |
compile(source, '<string>', 'exec') |
| 2401 |
return cm.exception |
| 2402 |
|
| 2403 |
exc = try_compile('return "ä"') |
| 2404 |
self.assertEqual(str(exc), "'return' outside function (<string>, line 1)") |
| 2405 |
self.assertIsNone(exc.text) |
| 2406 |
self.assertEqual(exc.offset, 1) |
| 2407 |
self.assertEqual(exc.end_offset, 12) |
| 2408 |
|
| 2409 |
exc = try_compile('return "ä"'.encode()) |
| 2410 |
self.assertEqual(str(exc), "'return' outside function (<string>, line 1)") |
| 2411 |
self.assertIsNone(exc.text) |
| 2412 |
self.assertEqual(exc.offset, 1) |
| 2413 |
self.assertEqual(exc.end_offset, 12) |
| 2414 |
|
| 2415 |
exc = try_compile(BOM_UTF8 + 'return "ä"'.encode()) |
| 2416 |
self.assertEqual(str(exc), "'return' outside function (<string>, line 1)") |
| 2417 |
self.assertIsNone(exc.text) |
| 2418 |
self.assertEqual(exc.offset, 1) |
| 2419 |
self.assertEqual(exc.end_offset, 12) |
| 2420 |
|
| 2421 |
exc = try_compile('# coding: latin1\nreturn "ä"'.encode('latin1')) |
| 2422 |
self.assertEqual(str(exc), "'return' outside function (<string>, line 2)") |
| 2423 |
self.assertIsNone(exc.text) |
| 2424 |
self.assertEqual(exc.offset, 1) |
| 2425 |
self.assertEqual(exc.end_offset, 12) |
| 2426 |
|
| 2427 |
exc = try_compile('return "ä" #' + 'ä'*1000) |
| 2428 |
self.assertEqual(str(exc), "'return' outside function (<string>, line 1)") |
| 2429 |
self.assertIsNone(exc.text) |
| 2430 |
self.assertEqual(exc.offset, 1) |
| 2431 |
self.assertEqual(exc.end_offset, 12) |
| 2432 |
|
| 2433 |
exc = try_compile('return "ä" # ' + 'ä'*1000) |
| 2434 |
self.assertEqual(str(exc), "'return' outside function (<string>, line 1)") |
| 2435 |
self.assertIsNone(exc.text) |
| 2436 |
self.assertEqual(exc.offset, 1) |
| 2437 |
self.assertEqual(exc.end_offset, 12) |
| 2438 |
|
| 2439 |
def test_file_source(self): |
| 2440 |
self.addCleanup(unlink, TESTFN) |
| 2441 |
err = run_script('return "ä"') |
| 2442 |
self.assertEqual(err[-3:], [ |
| 2443 |
' return "ä"', |
| 2444 |
' ^^^^^^^^^^', |
| 2445 |
"SyntaxError: 'return' outside function"]) |
| 2446 |
|
| 2447 |
err = run_script('return "ä"'.encode()) |
| 2448 |
self.assertEqual(err[-3:], [ |
| 2449 |
' return "ä"', |
| 2450 |
' ^^^^^^^^^^', |
| 2451 |
"SyntaxError: 'return' outside function"]) |
| 2452 |
|
| 2453 |
err = run_script(BOM_UTF8 + 'return "ä"'.encode()) |
| 2454 |
self.assertEqual(err[-3:], [ |
| 2455 |
' return "ä"', |
| 2456 |
' ^^^^^^^^^^', |
| 2457 |
"SyntaxError: 'return' outside function"]) |
| 2458 |
|
| 2459 |
err = run_script('# coding: latin1\nreturn "ä"'.encode('latin1')) |
| 2460 |
self.assertEqual(err[-3:], [ |
| 2461 |
' return "ä"', |
| 2462 |
' ^^^^^^^^^^', |
| 2463 |
"SyntaxError: 'return' outside function"]) |
| 2464 |
|
| 2465 |
err = run_script('return "ä" #' + 'ä'*1000) |
| 2466 |
self.assertEqual(err[-2:], [ |
| 2467 |
' ^^^^^^^^^^^', |
| 2468 |
"SyntaxError: 'return' outside function"]) |
| 2469 |
self.assertEqual(err[-3][:100], ' return "ä" #' + 'ä'*84) |
| 2470 |
|
| 2471 |
err = run_script('return "ä" # ' + 'ä'*1000) |
| 2472 |
self.assertEqual(err[-2:], [ |
| 2473 |
' ^^^^^^^^^^^', |
| 2474 |
"SyntaxError: 'return' outside function"]) |
| 2475 |
self.assertEqual(err[-3][:100], ' return "ä" # ' + 'ä'*83) |
| 2476 |
|
| 2477 |
def test_attributes_new_constructor(self): |
| 2478 |
args = ("bad.py", 1, 2, "abcdefg", 1, 100) |
| 2479 |
the_exception = SyntaxError("bad bad", args) |
| 2480 |
filename, lineno, offset, error, end_lineno, end_offset = args |
| 2481 |
self.assertEqual(filename, the_exception.filename) |
| 2482 |
self.assertEqual(lineno, the_exception.lineno) |
| 2483 |
self.assertEqual(end_lineno, the_exception.end_lineno) |
| 2484 |
self.assertEqual(offset, the_exception.offset) |
| 2485 |
self.assertEqual(end_offset, the_exception.end_offset) |
| 2486 |
self.assertEqual(error, the_exception.text) |
| 2487 |
self.assertEqual("bad bad", the_exception.msg) |
| 2488 |
|
| 2489 |
def test_attributes_old_constructor(self): |
| 2490 |
args = ("bad.py", 1, 2, "abcdefg") |
| 2491 |
the_exception = SyntaxError("bad bad", args) |
| 2492 |
filename, lineno, offset, error = args |
| 2493 |
self.assertEqual(filename, the_exception.filename) |
| 2494 |
self.assertEqual(lineno, the_exception.lineno) |
| 2495 |
self.assertEqual(None, the_exception.end_lineno) |
| 2496 |
self.assertEqual(offset, the_exception.offset) |
| 2497 |
self.assertEqual(None, the_exception.end_offset) |
| 2498 |
self.assertEqual(error, the_exception.text) |
| 2499 |
self.assertEqual("bad bad", the_exception.msg) |
| 2500 |
|
| 2501 |
def test_incorrect_constructor(self): |
| 2502 |
args = ("bad.py", 1, 2) |
| 2503 |
self.assertRaises(TypeError, SyntaxError, "bad bad", args) |
| 2504 |
|
| 2505 |
args = ("bad.py", 1, 2, 4, 5, 6, 7, 8) |
| 2506 |
self.assertRaises(TypeError, SyntaxError, "bad bad", args) |
| 2507 |
|
| 2508 |
args = ("bad.py", 1, 2, "abcdefg", 1) |
| 2509 |
self.assertRaises(TypeError, SyntaxError, "bad bad", args) |
| 2510 |
|
| 2511 |
def test_syntax_error_memory_leak(self): |
| 2512 |
# gh-146250: memory leak with re-initialization of SyntaxError |
| 2513 |
e = SyntaxError("msg", ("file.py", 1, 2, "txt", 2, 3)) |
| 2514 |
e.__init__("new_msg", ("new_file.py", 2, 3, "new_txt", 3, 4)) |
| 2515 |
self.assertEqual(e.msg, "new_msg") |
| 2516 |
self.assertEqual(e.args, ("new_msg", ("new_file.py", 2, 3, "new_txt", 3, 4))) |
| 2517 |
self.assertEqual(e.filename, "new_file.py") |
| 2518 |
self.assertEqual(e.lineno, 2) |
| 2519 |
self.assertEqual(e.offset, 3) |
| 2520 |
self.assertEqual(e.text, "new_txt") |
| 2521 |
self.assertEqual(e.end_lineno, 3) |
| 2522 |
self.assertEqual(e.end_offset, 4) |
| 2523 |
|
| 2524 |
e = SyntaxError("msg", ("file.py", 1, 2, "txt", 2, 3)) |
| 2525 |
e.__init__("new_msg", ("new_file.py", 2, 3, "new_txt")) |
| 2526 |
self.assertEqual(e.msg, "new_msg") |
| 2527 |
self.assertEqual(e.args, ("new_msg", ("new_file.py", 2, 3, "new_txt"))) |
| 2528 |
self.assertEqual(e.filename, "new_file.py") |
| 2529 |
self.assertEqual(e.lineno, 2) |
| 2530 |
self.assertEqual(e.offset, 3) |
| 2531 |
self.assertEqual(e.text, "new_txt") |
| 2532 |
self.assertIsNone(e.end_lineno) |
| 2533 |
self.assertIsNone(e.end_offset) |
| 2534 |
|
| 2535 |
|
| 2536 |
class TestInvalidExceptionMatcher(unittest.TestCase): |
| 2537 |
def test_except_star_invalid_exception_type(self): |
| 2538 |
with self.assertRaises(TypeError): |
| 2539 |
try: |
| 2540 |
raise ValueError |
| 2541 |
except 42: |
| 2542 |
pass |
| 2543 |
|
| 2544 |
with self.assertRaises(TypeError): |
| 2545 |
try: |
| 2546 |
raise ValueError |
| 2547 |
except (ValueError, 42): |
| 2548 |
pass |
| 2549 |
|
| 2550 |
|
| 2551 |
class PEP626Tests(unittest.TestCase): |
| 2552 |
|
| 2553 |
def lineno_after_raise(self, f, *expected): |
| 2554 |
try: |
| 2555 |
f() |
| 2556 |
except Exception as ex: |
| 2557 |
t = ex.__traceback__ |
| 2558 |
else: |
| 2559 |
self.fail("No exception raised") |
| 2560 |
lines = [] |
| 2561 |
t = t.tb_next # Skip this function |
| 2562 |
while t: |
| 2563 |
frame = t.tb_frame |
| 2564 |
lines.append( |
| 2565 |
None if frame.f_lineno is None else |
| 2566 |
frame.f_lineno-frame.f_code.co_firstlineno |
| 2567 |
) |
| 2568 |
t = t.tb_next |
| 2569 |
self.assertEqual(tuple(lines), expected) |
| 2570 |
|
| 2571 |
def test_lineno_after_raise_simple(self): |
| 2572 |
def simple(): |
| 2573 |
1/0 |
| 2574 |
pass |
| 2575 |
self.lineno_after_raise(simple, 1) |
| 2576 |
|
| 2577 |
def test_lineno_after_raise_in_except(self): |
| 2578 |
def in_except(): |
| 2579 |
try: |
| 2580 |
1/0 |
| 2581 |
except: |
| 2582 |
1/0 |
| 2583 |
pass |
| 2584 |
self.lineno_after_raise(in_except, 4) |
| 2585 |
|
| 2586 |
def test_lineno_after_other_except(self): |
| 2587 |
def other_except(): |
| 2588 |
try: |
| 2589 |
1/0 |
| 2590 |
except TypeError as ex: |
| 2591 |
pass |
| 2592 |
self.lineno_after_raise(other_except, 3) |
| 2593 |
|
| 2594 |
def test_lineno_in_named_except(self): |
| 2595 |
def in_named_except(): |
| 2596 |
try: |
| 2597 |
1/0 |
| 2598 |
except Exception as ex: |
| 2599 |
1/0 |
| 2600 |
pass |
| 2601 |
self.lineno_after_raise(in_named_except, 4) |
| 2602 |
|
| 2603 |
def test_lineno_in_try(self): |
| 2604 |
def in_try(): |
| 2605 |
try: |
| 2606 |
1/0 |
| 2607 |
finally: |
| 2608 |
pass |
| 2609 |
self.lineno_after_raise(in_try, 4) |
| 2610 |
|
| 2611 |
def test_lineno_in_finally_normal(self): |
| 2612 |
def in_finally_normal(): |
| 2613 |
try: |
| 2614 |
pass |
| 2615 |
finally: |
| 2616 |
1/0 |
| 2617 |
pass |
| 2618 |
self.lineno_after_raise(in_finally_normal, 4) |
| 2619 |
|
| 2620 |
def test_lineno_in_finally_except(self): |
| 2621 |
def in_finally_except(): |
| 2622 |
try: |
| 2623 |
1/0 |
| 2624 |
finally: |
| 2625 |
1/0 |
| 2626 |
pass |
| 2627 |
self.lineno_after_raise(in_finally_except, 4) |
| 2628 |
|
| 2629 |
def test_lineno_after_with(self): |
| 2630 |
class Noop: |
| 2631 |
def __enter__(self): |
| 2632 |
return self |
| 2633 |
def __exit__(self, *args): |
| 2634 |
pass |
| 2635 |
def after_with(): |
| 2636 |
with Noop(): |
| 2637 |
1/0 |
| 2638 |
pass |
| 2639 |
self.lineno_after_raise(after_with, 2) |
| 2640 |
|
| 2641 |
def test_missing_lineno_shows_as_none(self): |
| 2642 |
def f(): |
| 2643 |
1/0 |
| 2644 |
self.lineno_after_raise(f, 1) |
| 2645 |
f.__code__ = f.__code__.replace(co_linetable=b'\xf8\xf8\xf8\xf9\xf8\xf8\xf8') |
| 2646 |
self.lineno_after_raise(f, None) |
| 2647 |
|
| 2648 |
def test_lineno_after_raise_in_with_exit(self): |
| 2649 |
class ExitFails: |
| 2650 |
def __enter__(self): |
| 2651 |
return self |
| 2652 |
def __exit__(self, *args): |
| 2653 |
raise ValueError |
| 2654 |
|
| 2655 |
def after_with(): |
| 2656 |
with ExitFails(): |
| 2657 |
1/0 |
| 2658 |
self.lineno_after_raise(after_with, 1, 1) |
| 2659 |
|
| 2660 |
if __name__ == '__main__': |
| 2661 |
unittest.main() |