blob: 04c883cf53ba314ac654ac8d8dce54de06d5b404 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Serhiy Storchakab7853962017-04-08 09:55:07 +03003import copy
Pablo Galindo9b648a92020-09-01 19:39:46 +01004import gc
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00005import os
6import sys
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00007import unittest
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00008import pickle
Barry Warsaw8d109cb2008-05-08 04:26:35 +00009import weakref
Antoine Pitroua7622852011-09-01 21:37:43 +020010import errno
Pablo Galindoa77aac42021-04-23 14:27:05 +010011from textwrap import dedent
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000012
Hai Shi46605972020-08-04 00:49:18 +080013from test.support import (captured_stderr, check_impl_detail,
14 cpython_only, gc_collect,
15 no_tracing, script_helper,
xdegaye56d1f5c2017-10-26 15:09:06 +020016 SuppressCrashReport)
Hai Shi46605972020-08-04 00:49:18 +080017from test.support.import_helper import import_module
18from test.support.os_helper import TESTFN, unlink
19from test.support.warnings_helper import check_warnings
Victor Stinnere4d300e2019-05-22 23:44:02 +020020from test import support
21
22
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010023class NaiveException(Exception):
24 def __init__(self, x):
25 self.x = x
26
27class SlottedNaiveException(Exception):
28 __slots__ = ('x',)
29 def __init__(self, x):
30 self.x = x
31
Martin Panter3263f682016-02-28 03:16:11 +000032class BrokenStrException(Exception):
33 def __str__(self):
34 raise Exception("str() is broken")
35
Guido van Rossum3bead091992-01-27 17:00:37 +000036# XXX This is not really enough, each *operation* should be tested!
37
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000038class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000039
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000040 def raise_catch(self, exc, excname):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +010041 with self.subTest(exc=exc, excname=excname):
42 try:
43 raise exc("spam")
44 except exc as err:
45 buf1 = str(err)
46 try:
47 raise exc("spam")
48 except exc as err:
49 buf2 = str(err)
50 self.assertEqual(buf1, buf2)
51 self.assertEqual(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000052
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000053 def testRaising(self):
54 self.raise_catch(AttributeError, "AttributeError")
55 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000056
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000057 self.raise_catch(EOFError, "EOFError")
Inada Naoki8bbfeb32021-04-02 12:53:46 +090058 fp = open(TESTFN, 'w', encoding="utf-8")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000059 fp.close()
Inada Naoki8bbfeb32021-04-02 12:53:46 +090060 fp = open(TESTFN, 'r', encoding="utf-8")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000061 savestdin = sys.stdin
62 try:
63 try:
64 import marshal
Antoine Pitrou4a90ef02012-03-03 02:35:32 +010065 marshal.loads(b'')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000066 except EOFError:
67 pass
68 finally:
69 sys.stdin = savestdin
70 fp.close()
71 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020073 self.raise_catch(OSError, "OSError")
74 self.assertRaises(OSError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000075
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000076 self.raise_catch(ImportError, "ImportError")
77 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000078
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000079 self.raise_catch(IndexError, "IndexError")
80 x = []
81 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000083 self.raise_catch(KeyError, "KeyError")
84 x = {}
85 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000086
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000087 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000089 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000090
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000091 self.raise_catch(NameError, "NameError")
92 try: x = undefined_variable
93 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000094
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000095 self.raise_catch(OverflowError, "OverflowError")
96 x = 1
97 for dummy in range(128):
98 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.raise_catch(RuntimeError, "RuntimeError")
Yury Selivanovf488fb42015-07-03 01:04:23 -0400101 self.raise_catch(RecursionError, "RecursionError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +0000104 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000105 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000106
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000107 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000108
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000109 self.raise_catch(TabError, "TabError")
Georg Brandle1b5ac62008-06-04 13:06:58 +0000110 try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
111 '<string>', 'exec')
112 except TabError: pass
113 else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000114
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000115 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000116
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000117 self.raise_catch(SystemExit, "SystemExit")
118 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000119
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000120 self.raise_catch(TypeError, "TypeError")
121 try: [] + ()
122 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000123
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000124 self.raise_catch(ValueError, "ValueError")
Guido van Rossume63bae62007-07-17 00:34:25 +0000125 self.assertRaises(ValueError, chr, 17<<16)
Guido van Rossum3bead091992-01-27 17:00:37 +0000126
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000127 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
128 try: x = 1/0
129 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000130
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000131 self.raise_catch(Exception, "Exception")
132 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000133 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000134
Yury Selivanovccc897f2015-07-03 01:16:04 -0400135 self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
136
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000137 def testSyntaxErrorMessage(self):
138 # make sure the right exception message is raised for each of
139 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000140
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000141 def ckmsg(src, msg):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100142 with self.subTest(src=src, msg=msg):
143 try:
144 compile(src, '<fragment>', 'exec')
145 except SyntaxError as e:
146 if e.msg != msg:
147 self.fail("expected %s, got %s" % (msg, e.msg))
148 else:
149 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000150
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000151 s = '''if 1:
152 try:
153 continue
154 except:
155 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000156
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000157 ckmsg(s, "'continue' not properly in loop")
158 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000159
Martijn Pieters772d8092017-08-22 21:16:23 +0100160 def testSyntaxErrorMissingParens(self):
161 def ckmsg(src, msg, exception=SyntaxError):
162 try:
163 compile(src, '<fragment>', 'exec')
164 except exception as e:
165 if e.msg != msg:
166 self.fail("expected %s, got %s" % (msg, e.msg))
167 else:
168 self.fail("failed to get expected SyntaxError")
169
170 s = '''print "old style"'''
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700171 ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
Martijn Pieters772d8092017-08-22 21:16:23 +0100172
173 s = '''print "old style",'''
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700174 ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
Martijn Pieters772d8092017-08-22 21:16:23 +0100175
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100176 s = 'print f(a+b,c)'
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700177 ckmsg(s, "Missing parentheses in call to 'print'. Did you mean print(...)?")
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100178
Martijn Pieters772d8092017-08-22 21:16:23 +0100179 s = '''exec "old style"'''
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700180 ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?")
Martijn Pieters772d8092017-08-22 21:16:23 +0100181
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100182 s = 'exec f(a+b,c)'
Miss Islington (bot)68e3dca2021-07-27 14:19:18 -0700183 ckmsg(s, "Missing parentheses in call to 'exec'. Did you mean exec(...)?")
Pablo Galindo Salgadob977f852021-07-27 18:52:32 +0100184
Miss Islington (bot)35035bc2021-07-31 18:31:44 -0700185 # Check that we don't incorrectly identify '(...)' as an expression to the right
186 # of 'print'
187
188 s = 'print (a+b,c) $ 42'
189 ckmsg(s, "invalid syntax")
190
191 s = 'exec (a+b,c) $ 42'
192 ckmsg(s, "invalid syntax")
193
Martijn Pieters772d8092017-08-22 21:16:23 +0100194 # should not apply to subclasses, see issue #31161
195 s = '''if True:\nprint "No indent"'''
Pablo Galindo56c95df2021-04-21 15:28:21 +0100196 ckmsg(s, "expected an indented block after 'if' statement on line 1", IndentationError)
Martijn Pieters772d8092017-08-22 21:16:23 +0100197
198 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
199 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
200
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300201 def check(self, src, lineno, offset, encoding='utf-8'):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100202 with self.subTest(source=src, lineno=lineno, offset=offset):
203 with self.assertRaises(SyntaxError) as cm:
204 compile(src, '<fragment>', 'exec')
205 self.assertEqual(cm.exception.lineno, lineno)
206 self.assertEqual(cm.exception.offset, offset)
207 if cm.exception.text is not None:
208 if not isinstance(src, str):
209 src = src.decode(encoding, 'replace')
210 line = src.split('\n')[lineno-1]
211 self.assertIn(line, cm.exception.text)
Łukasz Langa5c9cab52021-10-19 22:31:18 +0200212
213 def test_error_offset_continuation_characters(self):
214 check = self.check
215 check('"\\\n"(1 for c in I,\\\n\\', 2, 2)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200216
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300217 def testSyntaxErrorOffset(self):
218 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200219 check('def fact(x):\n\treturn x!\n', 2, 10)
220 check('1 +\n', 1, 4)
221 check('def spam():\n print(1)\n print(2)', 3, 10)
222 check('Python = "Python" +', 1, 20)
223 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200224 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
225 2, 19, encoding='cp1251')
226 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300227 check('x = "a', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400228 check('lambda x: x = 2', 1, 1)
Lysandros Nikolaou15acc4e2020-10-27 20:54:20 +0200229 check('f{a + b + c}', 1, 2)
Pablo Galindo Salgado4ce55a22021-10-08 00:50:10 +0100230 check('[file for str(file) in []\n])', 1, 11)
Miss Islington (bot)933b5b62021-06-08 04:46:56 -0700231 check('a = « hello » « world »', 1, 5)
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200232 check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
233 check('[file for\n str(file) in []]', 2, 2)
Miss Islington (bot)07dba472021-05-21 08:29:58 -0700234 check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700235 check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
Ammar Askar025eb982018-09-24 17:12:49 -0400236
237 # Errors thrown by compile.c
238 check('class foo:return 1', 1, 11)
239 check('def f():\n continue', 2, 3)
240 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100241 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400242
243 # Errors thrown by tokenizer.c
244 check('(0x+1)', 1, 3)
245 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700246 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400247 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700248 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200249 check('\u03b1 = 0xI', 1, 6)
250 check(b'\xce\xb1 = 0xI', 1, 6)
251 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
252 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100253 check(b"""if 1:
254 def foo():
255 '''
256
257 def bar():
258 pass
259
260 def baz():
261 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300262 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100263 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
264 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700265 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700266 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Ammar Askar025eb982018-09-24 17:12:49 -0400267
268 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200269 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400270 check('def f():\n from _ import *', 1, 1)
271 check('def f(x, x):\n pass', 1, 1)
272 check('def f(x):\n nonlocal x', 2, 3)
273 check('def f(x):\n x = 1\n global x', 3, 3)
274 check('nonlocal x', 1, 1)
275 check('def f():\n global x\n nonlocal x', 2, 3)
276
Ammar Askar025eb982018-09-24 17:12:49 -0400277 # Errors thrown by future.c
278 check('from __future__ import doesnt_exist', 1, 1)
279 check('from __future__ import braces', 1, 1)
280 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100281 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300282 check('def f():\n x, y: int', 2, 3)
283 check('[*x for x in xs]', 1, 2)
284 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300285 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100286 check('(yield i) = 2', 1, 2)
287 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200288
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000289 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000290 def testSettingException(self):
291 # test that setting an exception at the C level works even if the
292 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000293
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000294 class BadException(Exception):
295 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000296 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000297
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000298 class InvalidException:
299 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000300
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000301 def test_capi1():
302 import _testcapi
303 try:
304 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000305 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000306 exc, err, tb = sys.exc_info()
307 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000308 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000309 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000310 else:
311 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000312
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000313 def test_capi2():
314 import _testcapi
315 try:
316 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000317 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000318 exc, err, tb = sys.exc_info()
319 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000320 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000321 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000322 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000323 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000324 else:
325 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000326
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000327 def test_capi3():
328 import _testcapi
329 self.assertRaises(SystemError, _testcapi.raise_exception,
330 InvalidException, 1)
331
332 if not sys.platform.startswith('java'):
333 test_capi1()
334 test_capi2()
335 test_capi3()
336
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337 def test_WindowsError(self):
338 try:
339 WindowsError
340 except NameError:
341 pass
342 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200343 self.assertIs(WindowsError, OSError)
344 self.assertEqual(str(OSError(1001)), "1001")
345 self.assertEqual(str(OSError(1001, "message")),
346 "[Errno 1001] message")
347 # POSIX errno (9 aka EBADF) is untranslated
348 w = OSError(9, 'foo', 'bar')
349 self.assertEqual(w.errno, 9)
350 self.assertEqual(w.winerror, None)
351 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
352 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
353 w = OSError(0, 'foo', 'bar', 3)
354 self.assertEqual(w.errno, 2)
355 self.assertEqual(w.winerror, 3)
356 self.assertEqual(w.strerror, 'foo')
357 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000358 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100359 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200360 # Unknown win error becomes EINVAL (22)
361 w = OSError(0, 'foo', None, 1001)
362 self.assertEqual(w.errno, 22)
363 self.assertEqual(w.winerror, 1001)
364 self.assertEqual(w.strerror, 'foo')
365 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000366 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100367 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200368 # Non-numeric "errno"
369 w = OSError('bar', 'foo')
370 self.assertEqual(w.errno, 'bar')
371 self.assertEqual(w.winerror, None)
372 self.assertEqual(w.strerror, 'foo')
373 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000374 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000375
Victor Stinnerd223fa62015-04-02 14:17:38 +0200376 @unittest.skipUnless(sys.platform == 'win32',
377 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300378 def test_windows_message(self):
379 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200380 ctypes = import_module('ctypes')
381 # this error code has no message, Python formats it as hexadecimal
382 code = 3765269347
383 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
384 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300385
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000386 def testAttributes(self):
387 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000388
389 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000390 (BaseException, (), {'args' : ()}),
391 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000392 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000393 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000394 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000395 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000396 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000397 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200398 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000399 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000400 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200401 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000402 {'args' : ('foo', 'bar'),
403 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000404 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200405 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000406 {'args' : ('foo', 'bar'),
407 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000408 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800409 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
410 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200411 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000412 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000413 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
414 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200415 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000416 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000417 'strerror' : 'strErrorStr',
418 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000419 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000420 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100421 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000422 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000423 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000424 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100425 'filename' : None, 'lineno' : None, 'offset' : None,
426 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000427 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100428 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000429 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000430 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100431 'offsetStr', 'textStr',
432 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000433 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100434 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
435 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000436 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100437 'textStr', 'endLinenoStr', 'endOffsetStr',
438 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000439 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000440 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100441 'textStr', 'endLinenoStr', 'endOffsetStr',
442 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000443 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100444 'filename' : None, 'lineno' : None, 'offset' : None,
445 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000446 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000447 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
448 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000449 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000450 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000451 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000452 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000453 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000454 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000455 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000456 'ordinal not in range'),
457 'encoding' : 'ascii', 'object' : b'\xff',
458 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000459 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
460 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000461 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000463 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000465 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000466 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000467 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000468 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100469 (NaiveException, ('foo',),
470 {'args': ('foo',), 'x': 'foo'}),
471 (SlottedNaiveException, ('foo',),
472 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000473 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000474 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200475 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000476 exceptionList.append(
477 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000478 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200479 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000480 'errno' : 1,
481 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000482 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000483 except NameError:
484 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000485
Guido van Rossumebe3e162007-05-17 18:20:34 +0000486 for exc, args, expected in exceptionList:
487 try:
488 e = exc(*args)
489 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000490 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100491 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000492 else:
493 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100494 if not type(e).__name__.endswith('NaiveException'):
495 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000496 # Verify no ref leaks in Exc_str()
497 s = str(e)
498 for checkArgName in expected:
499 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000500 self.assertEqual(repr(value),
501 repr(expected[checkArgName]),
502 '%r.%s == %r, expected %r' % (
503 e, checkArgName,
504 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000505
Guido van Rossumebe3e162007-05-17 18:20:34 +0000506 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000507 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000508 for protocol in range(p.HIGHEST_PROTOCOL + 1):
509 s = p.dumps(e, protocol)
510 new = p.loads(s)
511 for checkArgName in expected:
512 got = repr(getattr(new, checkArgName))
513 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000514 self.assertEqual(got, want,
515 'pickled "%r", attribute "%s' %
516 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000517
Collin Winter828f04a2007-08-31 00:04:24 +0000518 def testWithTraceback(self):
519 try:
520 raise IndexError(4)
521 except:
522 tb = sys.exc_info()[2]
523
524 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000525 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000526 self.assertEqual(e.__traceback__, tb)
527
528 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000529 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000530 self.assertEqual(e.__traceback__, tb)
531
532 class MyException(Exception):
533 pass
534
535 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000536 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000537 self.assertEqual(e.__traceback__, tb)
538
539 def testInvalidTraceback(self):
540 try:
541 Exception().__traceback__ = 5
542 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000543 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000544 else:
545 self.fail("No exception raised")
546
Georg Brandlab6f2f62009-03-31 04:16:10 +0000547 def testInvalidAttrs(self):
548 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
549 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
550 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
551 self.assertRaises(TypeError, delattr, Exception(), '__context__')
552
Collin Winter828f04a2007-08-31 00:04:24 +0000553 def testNoneClearsTracebackAttr(self):
554 try:
555 raise IndexError(4)
556 except:
557 tb = sys.exc_info()[2]
558
559 e = Exception()
560 e.__traceback__ = tb
561 e.__traceback__ = None
562 self.assertEqual(e.__traceback__, None)
563
564 def testChainingAttrs(self):
565 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000566 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700567 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000568
569 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000570 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700571 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000572
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200573 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000574 pass
575
576 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000577 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700578 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000579
580 def testChainingDescriptors(self):
581 try:
582 raise Exception()
583 except Exception as exc:
584 e = exc
585
586 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700587 self.assertIsNone(e.__cause__)
588 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000589
590 e.__context__ = NameError()
591 e.__cause__ = None
592 self.assertIsInstance(e.__context__, NameError)
593 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700594 self.assertTrue(e.__suppress_context__)
595 e.__suppress_context__ = False
596 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000597
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000598 def testKeywordArgs(self):
599 # test that builtin exception don't take keyword args,
600 # but user-defined subclasses can if they want
601 self.assertRaises(TypeError, BaseException, a=1)
602
603 class DerivedException(BaseException):
604 def __init__(self, fancy_arg):
605 BaseException.__init__(self)
606 self.fancy_arg = fancy_arg
607
608 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000609 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000610
Brett Cannon31f59292011-02-21 19:29:56 +0000611 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612 def testInfiniteRecursion(self):
613 def f():
614 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400615 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000616
617 def g():
618 try:
619 return g()
620 except ValueError:
621 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400622 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000623
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000624 def test_str(self):
625 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000626 self.assertTrue(str(Exception))
627 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000628 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000629
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000630 def testExceptionCleanupNames(self):
631 # Make sure the local variable bound to the exception instance by
632 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000633 try:
634 raise Exception()
635 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000636 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000637 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000638 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000639
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000640 def testExceptionCleanupState(self):
641 # Make sure exception state is cleaned up as soon as the except
642 # block is left. See #2507
643
644 class MyException(Exception):
645 def __init__(self, obj):
646 self.obj = obj
647 class MyObj:
648 pass
649
650 def inner_raising_func():
651 # Create some references in exception value and traceback
652 local_ref = obj
653 raise MyException(obj)
654
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000655 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000656 obj = MyObj()
657 wr = weakref.ref(obj)
658 try:
659 inner_raising_func()
660 except MyException as e:
661 pass
662 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300663 gc_collect() # For PyPy or other GCs.
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000664 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300665 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000666
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000667 # Qualified "except" without "as"
668 obj = MyObj()
669 wr = weakref.ref(obj)
670 try:
671 inner_raising_func()
672 except MyException:
673 pass
674 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300675 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000676 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300677 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000678
679 # Bare "except"
680 obj = MyObj()
681 wr = weakref.ref(obj)
682 try:
683 inner_raising_func()
684 except:
685 pass
686 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300687 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000688 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300689 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000690
691 # "except" with premature block leave
692 obj = MyObj()
693 wr = weakref.ref(obj)
694 for i in [0]:
695 try:
696 inner_raising_func()
697 except:
698 break
699 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300700 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000701 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300702 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000703
704 # "except" block raising another exception
705 obj = MyObj()
706 wr = weakref.ref(obj)
707 try:
708 try:
709 inner_raising_func()
710 except:
711 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000712 except KeyError as e:
713 # We want to test that the except block above got rid of
714 # the exception raised in inner_raising_func(), but it
715 # also ends up in the __context__ of the KeyError, so we
716 # must clear the latter manually for our test to succeed.
717 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000718 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300719 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000720 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800721 # guarantee no ref cycles on CPython (don't gc_collect)
722 if check_impl_detail(cpython=False):
723 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300724 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000725
726 # Some complicated construct
727 obj = MyObj()
728 wr = weakref.ref(obj)
729 try:
730 inner_raising_func()
731 except MyException:
732 try:
733 try:
734 raise
735 finally:
736 raise
737 except MyException:
738 pass
739 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800740 if check_impl_detail(cpython=False):
741 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000742 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300743 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000744
745 # Inside an exception-silencing "with" block
746 class Context:
747 def __enter__(self):
748 return self
749 def __exit__ (self, exc_type, exc_value, exc_tb):
750 return True
751 obj = MyObj()
752 wr = weakref.ref(obj)
753 with Context():
754 inner_raising_func()
755 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800756 if check_impl_detail(cpython=False):
757 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000758 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300759 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000760
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000761 def test_exception_target_in_nested_scope(self):
762 # issue 4617: This used to raise a SyntaxError
763 # "can not delete variable 'e' referenced in nested scope"
764 def print_error():
765 e
766 try:
767 something
768 except Exception as e:
769 print_error()
770 # implicit "del e" here
771
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000772 def test_generator_leaking(self):
773 # Test that generator exception state doesn't leak into the calling
774 # frame
775 def yield_raise():
776 try:
777 raise KeyError("caught")
778 except KeyError:
779 yield sys.exc_info()[0]
780 yield sys.exc_info()[0]
781 yield sys.exc_info()[0]
782 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000783 self.assertEqual(next(g), KeyError)
784 self.assertEqual(sys.exc_info()[0], None)
785 self.assertEqual(next(g), KeyError)
786 self.assertEqual(sys.exc_info()[0], None)
787 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000788
789 # Same test, but inside an exception handler
790 try:
791 raise TypeError("foo")
792 except TypeError:
793 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000794 self.assertEqual(next(g), KeyError)
795 self.assertEqual(sys.exc_info()[0], TypeError)
796 self.assertEqual(next(g), KeyError)
797 self.assertEqual(sys.exc_info()[0], TypeError)
798 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000799 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000800 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000801
Benjamin Peterson83195c32011-07-03 13:44:00 -0500802 def test_generator_leaking2(self):
803 # See issue 12475.
804 def g():
805 yield
806 try:
807 raise RuntimeError
808 except RuntimeError:
809 it = g()
810 next(it)
811 try:
812 next(it)
813 except StopIteration:
814 pass
815 self.assertEqual(sys.exc_info(), (None, None, None))
816
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100817 def test_generator_leaking3(self):
818 # See issue #23353. When gen.throw() is called, the caller's
819 # exception state should be save and restored.
820 def g():
821 try:
822 yield
823 except ZeroDivisionError:
824 yield sys.exc_info()[1]
825 it = g()
826 next(it)
827 try:
828 1/0
829 except ZeroDivisionError as e:
830 self.assertIs(sys.exc_info()[1], e)
831 gen_exc = it.throw(e)
832 self.assertIs(sys.exc_info()[1], e)
833 self.assertIs(gen_exc, e)
834 self.assertEqual(sys.exc_info(), (None, None, None))
835
836 def test_generator_leaking4(self):
837 # See issue #23353. When an exception is raised by a generator,
838 # the caller's exception state should still be restored.
839 def g():
840 try:
841 1/0
842 except ZeroDivisionError:
843 yield sys.exc_info()[0]
844 raise
845 it = g()
846 try:
847 raise TypeError
848 except TypeError:
849 # The caller's exception state (TypeError) is temporarily
850 # saved in the generator.
851 tp = next(it)
852 self.assertIs(tp, ZeroDivisionError)
853 try:
854 next(it)
855 # We can't check it immediately, but while next() returns
856 # with an exception, it shouldn't have restored the old
857 # exception state (TypeError).
858 except ZeroDivisionError as e:
859 self.assertIs(sys.exc_info()[1], e)
860 # We used to find TypeError here.
861 self.assertEqual(sys.exc_info(), (None, None, None))
862
Benjamin Petersonac913412011-07-03 16:25:11 -0500863 def test_generator_doesnt_retain_old_exc(self):
864 def g():
865 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
866 yield
867 self.assertEqual(sys.exc_info(), (None, None, None))
868 it = g()
869 try:
870 raise RuntimeError
871 except RuntimeError:
872 next(it)
873 self.assertRaises(StopIteration, next, it)
874
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000875 def test_generator_finalizing_and_exc_info(self):
876 # See #7173
877 def simple_gen():
878 yield 1
879 def run_gen():
880 gen = simple_gen()
881 try:
882 raise RuntimeError
883 except RuntimeError:
884 return next(gen)
885 run_gen()
886 gc_collect()
887 self.assertEqual(sys.exc_info(), (None, None, None))
888
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200889 def _check_generator_cleanup_exc_state(self, testfunc):
890 # Issue #12791: exception state is cleaned up as soon as a generator
891 # is closed (reference cycles are broken).
892 class MyException(Exception):
893 def __init__(self, obj):
894 self.obj = obj
895 class MyObj:
896 pass
897
898 def raising_gen():
899 try:
900 raise MyException(obj)
901 except MyException:
902 yield
903
904 obj = MyObj()
905 wr = weakref.ref(obj)
906 g = raising_gen()
907 next(g)
908 testfunc(g)
909 g = obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300910 gc_collect() # For PyPy or other GCs.
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200911 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300912 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200913
914 def test_generator_throw_cleanup_exc_state(self):
915 def do_throw(g):
916 try:
917 g.throw(RuntimeError())
918 except RuntimeError:
919 pass
920 self._check_generator_cleanup_exc_state(do_throw)
921
922 def test_generator_close_cleanup_exc_state(self):
923 def do_close(g):
924 g.close()
925 self._check_generator_cleanup_exc_state(do_close)
926
927 def test_generator_del_cleanup_exc_state(self):
928 def do_del(g):
929 g = None
930 self._check_generator_cleanup_exc_state(do_del)
931
932 def test_generator_next_cleanup_exc_state(self):
933 def do_next(g):
934 try:
935 next(g)
936 except StopIteration:
937 pass
938 else:
939 self.fail("should have raised StopIteration")
940 self._check_generator_cleanup_exc_state(do_next)
941
942 def test_generator_send_cleanup_exc_state(self):
943 def do_send(g):
944 try:
945 g.send(None)
946 except StopIteration:
947 pass
948 else:
949 self.fail("should have raised StopIteration")
950 self._check_generator_cleanup_exc_state(do_send)
951
Benjamin Peterson27d63672008-06-15 20:09:12 +0000952 def test_3114(self):
953 # Bug #3114: in its destructor, MyObject retrieves a pointer to
954 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000955 class MyObject:
956 def __del__(self):
957 nonlocal e
958 e = sys.exc_info()
959 e = ()
960 try:
961 raise Exception(MyObject())
962 except:
963 pass
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300964 gc_collect() # For PyPy or other GCs.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000965 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000966
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -0700967 def test_raise_does_not_create_context_chain_cycle(self):
968 class A(Exception):
969 pass
970 class B(Exception):
971 pass
972 class C(Exception):
973 pass
974
975 # Create a context chain:
976 # C -> B -> A
977 # Then raise A in context of C.
978 try:
979 try:
980 raise A
981 except A as a_:
982 a = a_
983 try:
984 raise B
985 except B as b_:
986 b = b_
987 try:
988 raise C
989 except C as c_:
990 c = c_
991 self.assertIsInstance(a, A)
992 self.assertIsInstance(b, B)
993 self.assertIsInstance(c, C)
994 self.assertIsNone(a.__context__)
995 self.assertIs(b.__context__, a)
996 self.assertIs(c.__context__, b)
997 raise a
998 except A as e:
999 exc = e
1000
1001 # Expect A -> C -> B, without cycle
1002 self.assertIs(exc, a)
1003 self.assertIs(a.__context__, c)
1004 self.assertIs(c.__context__, b)
1005 self.assertIsNone(b.__context__)
1006
1007 def test_no_hang_on_context_chain_cycle1(self):
1008 # See issue 25782. Cycle in context chain.
1009
1010 def cycle():
1011 try:
1012 raise ValueError(1)
1013 except ValueError as ex:
1014 ex.__context__ = ex
1015 raise TypeError(2)
1016
1017 try:
1018 cycle()
1019 except Exception as e:
1020 exc = e
1021
1022 self.assertIsInstance(exc, TypeError)
1023 self.assertIsInstance(exc.__context__, ValueError)
1024 self.assertIs(exc.__context__.__context__, exc.__context__)
1025
Miss Islington (bot)19604092021-08-16 02:01:14 -07001026 @unittest.skip("See issue 44895")
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -07001027 def test_no_hang_on_context_chain_cycle2(self):
1028 # See issue 25782. Cycle at head of context chain.
1029
1030 class A(Exception):
1031 pass
1032 class B(Exception):
1033 pass
1034 class C(Exception):
1035 pass
1036
1037 # Context cycle:
1038 # +-----------+
1039 # V |
1040 # C --> B --> A
1041 with self.assertRaises(C) as cm:
1042 try:
1043 raise A()
1044 except A as _a:
1045 a = _a
1046 try:
1047 raise B()
1048 except B as _b:
1049 b = _b
1050 try:
1051 raise C()
1052 except C as _c:
1053 c = _c
1054 a.__context__ = c
1055 raise c
1056
1057 self.assertIs(cm.exception, c)
1058 # Verify the expected context chain cycle
1059 self.assertIs(c.__context__, b)
1060 self.assertIs(b.__context__, a)
1061 self.assertIs(a.__context__, c)
1062
1063 def test_no_hang_on_context_chain_cycle3(self):
1064 # See issue 25782. Longer context chain with cycle.
1065
1066 class A(Exception):
1067 pass
1068 class B(Exception):
1069 pass
1070 class C(Exception):
1071 pass
1072 class D(Exception):
1073 pass
1074 class E(Exception):
1075 pass
1076
1077 # Context cycle:
1078 # +-----------+
1079 # V |
1080 # E --> D --> C --> B --> A
1081 with self.assertRaises(E) as cm:
1082 try:
1083 raise A()
1084 except A as _a:
1085 a = _a
1086 try:
1087 raise B()
1088 except B as _b:
1089 b = _b
1090 try:
1091 raise C()
1092 except C as _c:
1093 c = _c
1094 a.__context__ = c
1095 try:
1096 raise D()
1097 except D as _d:
1098 d = _d
1099 e = E()
1100 raise e
1101
1102 self.assertIs(cm.exception, e)
1103 # Verify the expected context chain cycle
1104 self.assertIs(e.__context__, d)
1105 self.assertIs(d.__context__, c)
1106 self.assertIs(c.__context__, b)
1107 self.assertIs(b.__context__, a)
1108 self.assertIs(a.__context__, c)
1109
Benjamin Peterson24dfb052014-04-02 12:05:35 -04001110 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +00001111 # See issue 7309. This was a crasher.
1112
1113 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
1114 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
1115 u.end = 2
1116 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
1117 u.end = 5
1118 u.reason = 0x345345345345345345
1119 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
1120 u.encoding = 4000
1121 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
1122 u.start = 1000
1123 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
1124
1125 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
1126 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
1127 u.end = 2
1128 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
1129 u.end = 5
1130 u.reason = 0x345345345345345345
1131 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
1132 u.encoding = 4000
1133 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
1134 u.start = 1000
1135 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
1136
1137 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
1138 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
1139 u.end = 2
1140 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
1141 u.end = 5
1142 u.reason = 0x345345345345345345
1143 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
1144 u.start = 1000
1145 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +00001146
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001147 def test_unicode_errors_no_object(self):
1148 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -04001149 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001150 for klass in klasses:
1151 self.assertEqual(str(klass.__new__(klass)), "")
1152
Brett Cannon31f59292011-02-21 19:29:56 +00001153 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001154 def test_badisinstance(self):
1155 # Bug #2542: if issubclass(e, MyException) raises an exception,
1156 # it should be ignored
1157 class Meta(type):
1158 def __subclasscheck__(cls, subclass):
1159 raise ValueError()
1160 class MyException(Exception, metaclass=Meta):
1161 pass
1162
Martin Panter3263f682016-02-28 03:16:11 +00001163 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001164 try:
1165 raise KeyError()
1166 except MyException as e:
1167 self.fail("exception should not be a MyException")
1168 except KeyError:
1169 pass
1170 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001171 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001172 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001173 self.fail("Should have raised KeyError")
1174
1175 def g():
1176 try:
1177 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001178 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001179 return sys.exc_info()
1180 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001181 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001182 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001183
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001184
1185 @cpython_only
Benjamin Petersonef36dfe2021-08-13 02:45:13 -07001186 def test_trashcan_recursion(self):
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001187 # See bpo-33930
1188
1189 def foo():
1190 o = object()
1191 for x in range(1_000_000):
1192 # Create a big chain of method objects that will trigger
1193 # a deep chain of calls when they need to be destructed.
1194 o = o.__dir__
1195
1196 foo()
1197 support.gc_collect()
1198
xdegaye56d1f5c2017-10-26 15:09:06 +02001199 @cpython_only
1200 def test_recursion_normalizing_exception(self):
1201 # Issue #22898.
1202 # Test that a RecursionError is raised when tstate->recursion_depth is
1203 # equal to recursion_limit in PyErr_NormalizeException() and check
1204 # that a ResourceWarning is printed.
1205 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001206 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001207 # singleton was being used in that case, that held traceback data and
1208 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1209 # finalization of these locals.
1210 code = """if 1:
1211 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001212 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001213
1214 class MyException(Exception): pass
1215
1216 def setrecursionlimit(depth):
1217 while 1:
1218 try:
1219 sys.setrecursionlimit(depth)
1220 return depth
1221 except RecursionError:
1222 # sys.setrecursionlimit() raises a RecursionError if
1223 # the new recursion limit is too low (issue #25274).
1224 depth += 1
1225
1226 def recurse(cnt):
1227 cnt -= 1
1228 if cnt:
1229 recurse(cnt)
1230 else:
1231 generator.throw(MyException)
1232
1233 def gen():
1234 f = open(%a, mode='rb', buffering=0)
1235 yield
1236
1237 generator = gen()
1238 next(generator)
1239 recursionlimit = sys.getrecursionlimit()
1240 depth = get_recursion_depth()
1241 try:
1242 # Upon the last recursive invocation of recurse(),
1243 # tstate->recursion_depth is equal to (recursion_limit - 1)
1244 # and is equal to recursion_limit when _gen_throw() calls
1245 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001246 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001247 finally:
1248 sys.setrecursionlimit(recursionlimit)
1249 print('Done.')
1250 """ % __file__
1251 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1252 # Check that the program does not fail with SIGABRT.
1253 self.assertEqual(rc, 1)
1254 self.assertIn(b'RecursionError', err)
1255 self.assertIn(b'ResourceWarning', err)
1256 self.assertIn(b'Done.', out)
1257
1258 @cpython_only
1259 def test_recursion_normalizing_infinite_exception(self):
1260 # Issue #30697. Test that a RecursionError is raised when
1261 # PyErr_NormalizeException() maximum recursion depth has been
1262 # exceeded.
1263 code = """if 1:
1264 import _testcapi
1265 try:
1266 raise _testcapi.RecursingInfinitelyError
1267 finally:
1268 print('Done.')
1269 """
1270 rc, out, err = script_helper.assert_python_failure("-c", code)
1271 self.assertEqual(rc, 1)
1272 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1273 b'while normalizing an exception', err)
1274 self.assertIn(b'Done.', out)
1275
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001276
1277 def test_recursion_in_except_handler(self):
1278
1279 def set_relative_recursion_limit(n):
1280 depth = 1
1281 while True:
1282 try:
1283 sys.setrecursionlimit(depth)
1284 except RecursionError:
1285 depth += 1
1286 else:
1287 break
1288 sys.setrecursionlimit(depth+n)
1289
1290 def recurse_in_except():
1291 try:
1292 1/0
1293 except:
1294 recurse_in_except()
1295
1296 def recurse_after_except():
1297 try:
1298 1/0
1299 except:
1300 pass
1301 recurse_after_except()
1302
1303 def recurse_in_body_and_except():
1304 try:
1305 recurse_in_body_and_except()
1306 except:
1307 recurse_in_body_and_except()
1308
1309 recursionlimit = sys.getrecursionlimit()
1310 try:
1311 set_relative_recursion_limit(10)
1312 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1313 with self.subTest(func=func):
1314 try:
1315 func()
1316 except RecursionError:
1317 pass
1318 else:
1319 self.fail("Should have raised a RecursionError")
1320 finally:
1321 sys.setrecursionlimit(recursionlimit)
1322
1323
xdegaye56d1f5c2017-10-26 15:09:06 +02001324 @cpython_only
1325 def test_recursion_normalizing_with_no_memory(self):
1326 # Issue #30697. Test that in the abort that occurs when there is no
1327 # memory left and the size of the Python frames stack is greater than
1328 # the size of the list of preallocated MemoryError instances, the
1329 # Fatal Python error message mentions MemoryError.
1330 code = """if 1:
1331 import _testcapi
1332 class C(): pass
1333 def recurse(cnt):
1334 cnt -= 1
1335 if cnt:
1336 recurse(cnt)
1337 else:
1338 _testcapi.set_nomemory(0)
1339 C()
1340 recurse(16)
1341 """
1342 with SuppressCrashReport():
1343 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001344 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1345 b'Cannot recover from MemoryErrors while '
1346 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001347
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001348 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001349 def test_MemoryError(self):
1350 # PyErr_NoMemory always raises the same exception instance.
1351 # Check that the traceback is not doubled.
1352 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001353 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001354 def raiseMemError():
1355 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001356 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001357 except MemoryError as e:
1358 tb = e.__traceback__
1359 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001360 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001361 return traceback.format_tb(tb)
1362
1363 tb1 = raiseMemError()
1364 tb2 = raiseMemError()
1365 self.assertEqual(tb1, tb2)
1366
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001367 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001368 def test_exception_with_doc(self):
1369 import _testcapi
1370 doc2 = "This is a test docstring."
1371 doc4 = "This is another test docstring."
1372
1373 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1374 "error1")
1375
1376 # test basic usage of PyErr_NewException
1377 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1378 self.assertIs(type(error1), type)
1379 self.assertTrue(issubclass(error1, Exception))
1380 self.assertIsNone(error1.__doc__)
1381
1382 # test with given docstring
1383 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1384 self.assertEqual(error2.__doc__, doc2)
1385
1386 # test with explicit base (without docstring)
1387 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1388 base=error2)
1389 self.assertTrue(issubclass(error3, error2))
1390
1391 # test with explicit base tuple
1392 class C(object):
1393 pass
1394 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1395 (error3, C))
1396 self.assertTrue(issubclass(error4, error3))
1397 self.assertTrue(issubclass(error4, C))
1398 self.assertEqual(error4.__doc__, doc4)
1399
1400 # test with explicit dictionary
1401 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1402 error4, {'a': 1})
1403 self.assertTrue(issubclass(error5, error4))
1404 self.assertEqual(error5.a, 1)
1405 self.assertEqual(error5.__doc__, "")
1406
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001407 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001408 def test_memory_error_cleanup(self):
1409 # Issue #5437: preallocated MemoryError instances should not keep
1410 # traceback objects alive.
1411 from _testcapi import raise_memoryerror
1412 class C:
1413 pass
1414 wr = None
1415 def inner():
1416 nonlocal wr
1417 c = C()
1418 wr = weakref.ref(c)
1419 raise_memoryerror()
1420 # We cannot use assertRaises since it manually deletes the traceback
1421 try:
1422 inner()
1423 except MemoryError as e:
1424 self.assertNotEqual(wr(), None)
1425 else:
1426 self.fail("MemoryError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001427 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001428 self.assertEqual(wr(), None)
1429
Brett Cannon31f59292011-02-21 19:29:56 +00001430 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001431 def test_recursion_error_cleanup(self):
1432 # Same test as above, but with "recursion exceeded" errors
1433 class C:
1434 pass
1435 wr = None
1436 def inner():
1437 nonlocal wr
1438 c = C()
1439 wr = weakref.ref(c)
1440 inner()
1441 # We cannot use assertRaises since it manually deletes the traceback
1442 try:
1443 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001444 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001445 self.assertNotEqual(wr(), None)
1446 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001447 self.fail("RecursionError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001448 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001449 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001450
Antoine Pitroua7622852011-09-01 21:37:43 +02001451 def test_errno_ENOTDIR(self):
1452 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1453 with self.assertRaises(OSError) as cm:
1454 os.listdir(__file__)
1455 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1456
Martin Panter3263f682016-02-28 03:16:11 +00001457 def test_unraisable(self):
1458 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1459 class BrokenDel:
1460 def __del__(self):
1461 exc = ValueError("del is broken")
1462 # The following line is included in the traceback report:
1463 raise exc
1464
Victor Stinnere4d300e2019-05-22 23:44:02 +02001465 obj = BrokenDel()
1466 with support.catch_unraisable_exception() as cm:
1467 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001468
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001469 gc_collect() # For PyPy or other GCs.
Victor Stinnere4d300e2019-05-22 23:44:02 +02001470 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1471 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001472
1473 def test_unhandled(self):
1474 # Check for sensible reporting of unhandled exceptions
1475 for exc_type in (ValueError, BrokenStrException):
1476 with self.subTest(exc_type):
1477 try:
1478 exc = exc_type("test message")
1479 # The following line is included in the traceback report:
1480 raise exc
1481 except exc_type:
1482 with captured_stderr() as stderr:
1483 sys.__excepthook__(*sys.exc_info())
1484 report = stderr.getvalue()
1485 self.assertIn("test_exceptions.py", report)
1486 self.assertIn("raise exc", report)
1487 self.assertIn(exc_type.__name__, report)
1488 if exc_type is BrokenStrException:
1489 self.assertIn("<exception str() failed>", report)
1490 else:
1491 self.assertIn("test message", report)
1492 self.assertTrue(report.endswith("\n"))
1493
xdegaye66caacf2017-10-23 18:08:41 +02001494 @cpython_only
1495 def test_memory_error_in_PyErr_PrintEx(self):
1496 code = """if 1:
1497 import _testcapi
1498 class C(): pass
1499 _testcapi.set_nomemory(0, %d)
1500 C()
1501 """
1502
1503 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1504 # Span a large range of tests as the CPython code always evolves with
1505 # changes that add or remove memory allocations.
1506 for i in range(1, 20):
1507 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1508 self.assertIn(rc, (1, 120))
1509 self.assertIn(b'MemoryError', err)
1510
Mark Shannonae3087c2017-10-22 22:41:51 +01001511 def test_yield_in_nested_try_excepts(self):
1512 #Issue #25612
1513 class MainError(Exception):
1514 pass
1515
1516 class SubError(Exception):
1517 pass
1518
1519 def main():
1520 try:
1521 raise MainError()
1522 except MainError:
1523 try:
1524 yield
1525 except SubError:
1526 pass
1527 raise
1528
1529 coro = main()
1530 coro.send(None)
1531 with self.assertRaises(MainError):
1532 coro.throw(SubError())
1533
1534 def test_generator_doesnt_retain_old_exc2(self):
1535 #Issue 28884#msg282532
1536 def g():
1537 try:
1538 raise ValueError
1539 except ValueError:
1540 yield 1
1541 self.assertEqual(sys.exc_info(), (None, None, None))
1542 yield 2
1543
1544 gen = g()
1545
1546 try:
1547 raise IndexError
1548 except IndexError:
1549 self.assertEqual(next(gen), 1)
1550 self.assertEqual(next(gen), 2)
1551
1552 def test_raise_in_generator(self):
1553 #Issue 25612#msg304117
1554 def g():
1555 yield 1
1556 raise
1557 yield 2
1558
1559 with self.assertRaises(ZeroDivisionError):
1560 i = g()
1561 try:
1562 1/0
1563 except:
1564 next(i)
1565 next(i)
1566
Zackery Spytzce6a0702019-08-25 03:44:09 -06001567 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1568 def test_assert_shadowing(self):
1569 # Shadowing AssertionError would cause the assert statement to
1570 # misbehave.
1571 global AssertionError
1572 AssertionError = TypeError
1573 try:
1574 assert False, 'hello'
1575 except BaseException as e:
1576 del AssertionError
1577 self.assertIsInstance(e, AssertionError)
1578 self.assertEqual(str(e), 'hello')
1579 else:
1580 del AssertionError
1581 self.fail('Expected exception')
1582
Pablo Galindo9b648a92020-09-01 19:39:46 +01001583 def test_memory_error_subclasses(self):
1584 # bpo-41654: MemoryError instances use a freelist of objects that are
1585 # linked using the 'dict' attribute when they are inactive/dead.
1586 # Subclasses of MemoryError should not participate in the freelist
1587 # schema. This test creates a MemoryError object and keeps it alive
1588 # (therefore advancing the freelist) and then it creates and destroys a
1589 # subclass object. Finally, it checks that creating a new MemoryError
1590 # succeeds, proving that the freelist is not corrupted.
1591
1592 class TestException(MemoryError):
1593 pass
1594
1595 try:
1596 raise MemoryError
1597 except MemoryError as exc:
1598 inst = exc
1599
1600 try:
1601 raise TestException
1602 except Exception:
1603 pass
1604
1605 for _ in range(10):
1606 try:
1607 raise MemoryError
1608 except MemoryError as exc:
1609 pass
1610
1611 gc_collect()
1612
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001613global_for_suggestions = None
1614
1615class NameErrorTests(unittest.TestCase):
1616 def test_name_error_has_name(self):
1617 try:
1618 bluch
1619 except NameError as exc:
1620 self.assertEqual("bluch", exc.name)
1621
1622 def test_name_error_suggestions(self):
1623 def Substitution():
1624 noise = more_noise = a = bc = None
1625 blech = None
1626 print(bluch)
1627
1628 def Elimination():
1629 noise = more_noise = a = bc = None
1630 blch = None
1631 print(bluch)
1632
1633 def Addition():
1634 noise = more_noise = a = bc = None
1635 bluchin = None
1636 print(bluch)
1637
1638 def SubstitutionOverElimination():
1639 blach = None
1640 bluc = None
1641 print(bluch)
1642
1643 def SubstitutionOverAddition():
1644 blach = None
1645 bluchi = None
1646 print(bluch)
1647
1648 def EliminationOverAddition():
1649 blucha = None
1650 bluc = None
1651 print(bluch)
1652
Pablo Galindo7a041162021-04-19 23:35:53 +01001653 for func, suggestion in [(Substitution, "'blech'?"),
1654 (Elimination, "'blch'?"),
1655 (Addition, "'bluchin'?"),
1656 (EliminationOverAddition, "'blucha'?"),
1657 (SubstitutionOverElimination, "'blach'?"),
1658 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001659 err = None
1660 try:
1661 func()
1662 except NameError as exc:
1663 with support.captured_stderr() as err:
1664 sys.__excepthook__(*sys.exc_info())
1665 self.assertIn(suggestion, err.getvalue())
1666
1667 def test_name_error_suggestions_from_globals(self):
1668 def func():
1669 print(global_for_suggestio)
1670 try:
1671 func()
1672 except NameError as exc:
1673 with support.captured_stderr() as err:
1674 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001675 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001676
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001677 def test_name_error_suggestions_from_builtins(self):
1678 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001679 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001680 try:
1681 func()
1682 except NameError as exc:
1683 with support.captured_stderr() as err:
1684 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001685 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001686
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001687 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1688 def f():
1689 somethingverywronghehehehehehe = None
1690 print(somethingverywronghe)
1691
1692 try:
1693 f()
1694 except NameError as exc:
1695 with support.captured_stderr() as err:
1696 sys.__excepthook__(*sys.exc_info())
1697
1698 self.assertNotIn("somethingverywronghehe", err.getvalue())
1699
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001700 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1701 vvv = mom = w = id = pytho = None
1702
1703 with self.subTest(name="b"):
1704 try:
1705 b
1706 except NameError as exc:
1707 with support.captured_stderr() as err:
1708 sys.__excepthook__(*sys.exc_info())
1709 self.assertNotIn("you mean", err.getvalue())
1710 self.assertNotIn("vvv", err.getvalue())
1711 self.assertNotIn("mom", err.getvalue())
1712 self.assertNotIn("'id'", err.getvalue())
1713 self.assertNotIn("'w'", err.getvalue())
1714 self.assertNotIn("'pytho'", err.getvalue())
1715
1716 with self.subTest(name="v"):
1717 try:
1718 v
1719 except NameError as exc:
1720 with support.captured_stderr() as err:
1721 sys.__excepthook__(*sys.exc_info())
1722 self.assertNotIn("you mean", err.getvalue())
1723 self.assertNotIn("vvv", err.getvalue())
1724 self.assertNotIn("mom", err.getvalue())
1725 self.assertNotIn("'id'", err.getvalue())
1726 self.assertNotIn("'w'", err.getvalue())
1727 self.assertNotIn("'pytho'", err.getvalue())
1728
1729 with self.subTest(name="m"):
1730 try:
1731 m
1732 except NameError as exc:
1733 with support.captured_stderr() as err:
1734 sys.__excepthook__(*sys.exc_info())
1735 self.assertNotIn("you mean", err.getvalue())
1736 self.assertNotIn("vvv", err.getvalue())
1737 self.assertNotIn("mom", err.getvalue())
1738 self.assertNotIn("'id'", err.getvalue())
1739 self.assertNotIn("'w'", err.getvalue())
1740 self.assertNotIn("'pytho'", err.getvalue())
1741
1742 with self.subTest(name="py"):
1743 try:
1744 py
1745 except NameError as exc:
1746 with support.captured_stderr() as err:
1747 sys.__excepthook__(*sys.exc_info())
1748 self.assertNotIn("you mean", err.getvalue())
1749 self.assertNotIn("vvv", err.getvalue())
1750 self.assertNotIn("mom", err.getvalue())
1751 self.assertNotIn("'id'", err.getvalue())
1752 self.assertNotIn("'w'", err.getvalue())
1753 self.assertNotIn("'pytho'", err.getvalue())
1754
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001755 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001756 def f():
1757 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001758 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1759 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1760 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1761 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1762 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1763 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1764 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1765 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1766 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1767 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1768 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1769 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1770 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1771 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1772 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1773 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1774 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1775 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1776 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1777 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1778 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1779 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1780 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1781 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1782 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1783 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1784 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1785 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1786 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1787 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1788 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1789 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1790 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1791 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1792 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1793 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1794 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1795 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1796 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1797 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1798 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1799 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1800 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1801 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1802 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1803 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1804 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1805 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1806 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1807 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1808 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1809 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1810 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1811 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1812 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1813 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1814 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1815 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1816 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1817 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1818 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1819 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1820 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1821 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1822 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1823 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1824 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1825 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1826 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1827 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1828 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1829 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1830 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1831 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1832 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1833 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1834 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1835 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1836 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1837 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1838 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001839 print(a0)
1840
1841 try:
1842 f()
1843 except NameError as exc:
1844 with support.captured_stderr() as err:
1845 sys.__excepthook__(*sys.exc_info())
1846
Miss Islington (bot)d55bf812021-10-07 05:11:38 -07001847 self.assertNotRegex(err.getvalue(), r"NameError.*a1")
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001848
1849 def test_name_error_with_custom_exceptions(self):
1850 def f():
1851 blech = None
1852 raise NameError()
1853
1854 try:
1855 f()
1856 except NameError as exc:
1857 with support.captured_stderr() as err:
1858 sys.__excepthook__(*sys.exc_info())
1859
1860 self.assertNotIn("blech", err.getvalue())
1861
1862 def f():
1863 blech = None
1864 raise NameError
1865
1866 try:
1867 f()
1868 except NameError as exc:
1869 with support.captured_stderr() as err:
1870 sys.__excepthook__(*sys.exc_info())
1871
1872 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001873
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001874 def test_unbound_local_error_doesn_not_match(self):
1875 def foo():
1876 something = 3
1877 print(somethong)
1878 somethong = 3
1879
1880 try:
1881 foo()
1882 except UnboundLocalError as exc:
1883 with support.captured_stderr() as err:
1884 sys.__excepthook__(*sys.exc_info())
1885
1886 self.assertNotIn("something", err.getvalue())
1887
Łukasz Langa8eabe602021-11-18 01:28:04 +01001888 def test_issue45826(self):
1889 # regression test for bpo-45826
1890 def f():
1891 with self.assertRaisesRegex(NameError, 'aaa'):
1892 aab
1893
1894 try:
1895 f()
1896 except self.failureException:
1897 with support.captured_stderr() as err:
1898 sys.__excepthook__(*sys.exc_info())
1899
1900 self.assertIn("aab", err.getvalue())
1901
1902 def test_issue45826_focused(self):
1903 def f():
1904 try:
1905 nonsense
1906 except BaseException as E:
1907 E.with_traceback(None)
1908 raise ZeroDivisionError()
1909
1910 try:
1911 f()
1912 except ZeroDivisionError:
1913 with support.captured_stderr() as err:
1914 sys.__excepthook__(*sys.exc_info())
1915
1916 self.assertIn("nonsense", err.getvalue())
1917 self.assertIn("ZeroDivisionError", err.getvalue())
1918
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001919
Pablo Galindo37494b42021-04-14 02:36:07 +01001920class AttributeErrorTests(unittest.TestCase):
1921 def test_attributes(self):
1922 # Setting 'attr' should not be a problem.
1923 exc = AttributeError('Ouch!')
1924 self.assertIsNone(exc.name)
1925 self.assertIsNone(exc.obj)
1926
1927 sentinel = object()
1928 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1929 self.assertEqual(exc.name, 'carry')
1930 self.assertIs(exc.obj, sentinel)
1931
1932 def test_getattr_has_name_and_obj(self):
1933 class A:
1934 blech = None
1935
1936 obj = A()
1937 try:
1938 obj.bluch
1939 except AttributeError as exc:
1940 self.assertEqual("bluch", exc.name)
1941 self.assertEqual(obj, exc.obj)
1942
1943 def test_getattr_has_name_and_obj_for_method(self):
1944 class A:
1945 def blech(self):
1946 return
1947
1948 obj = A()
1949 try:
1950 obj.bluch()
1951 except AttributeError as exc:
1952 self.assertEqual("bluch", exc.name)
1953 self.assertEqual(obj, exc.obj)
1954
1955 def test_getattr_suggestions(self):
1956 class Substitution:
1957 noise = more_noise = a = bc = None
1958 blech = None
1959
1960 class Elimination:
1961 noise = more_noise = a = bc = None
1962 blch = None
1963
1964 class Addition:
1965 noise = more_noise = a = bc = None
1966 bluchin = None
1967
1968 class SubstitutionOverElimination:
1969 blach = None
1970 bluc = None
1971
1972 class SubstitutionOverAddition:
1973 blach = None
1974 bluchi = None
1975
1976 class EliminationOverAddition:
1977 blucha = None
1978 bluc = None
1979
Pablo Galindo7a041162021-04-19 23:35:53 +01001980 for cls, suggestion in [(Substitution, "'blech'?"),
1981 (Elimination, "'blch'?"),
1982 (Addition, "'bluchin'?"),
1983 (EliminationOverAddition, "'bluc'?"),
1984 (SubstitutionOverElimination, "'blach'?"),
1985 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001986 try:
1987 cls().bluch
1988 except AttributeError as exc:
1989 with support.captured_stderr() as err:
1990 sys.__excepthook__(*sys.exc_info())
1991
1992 self.assertIn(suggestion, err.getvalue())
1993
1994 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1995 class A:
1996 blech = None
1997
1998 try:
1999 A().somethingverywrong
2000 except AttributeError as exc:
2001 with support.captured_stderr() as err:
2002 sys.__excepthook__(*sys.exc_info())
2003
2004 self.assertNotIn("blech", err.getvalue())
2005
Dennis Sweeney284c52d2021-04-26 20:22:27 -04002006 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
2007 class MyClass:
2008 vvv = mom = w = id = pytho = None
2009
2010 with self.subTest(name="b"):
2011 try:
2012 MyClass.b
2013 except AttributeError as exc:
2014 with support.captured_stderr() as err:
2015 sys.__excepthook__(*sys.exc_info())
2016 self.assertNotIn("you mean", err.getvalue())
2017 self.assertNotIn("vvv", err.getvalue())
2018 self.assertNotIn("mom", err.getvalue())
2019 self.assertNotIn("'id'", err.getvalue())
2020 self.assertNotIn("'w'", err.getvalue())
2021 self.assertNotIn("'pytho'", err.getvalue())
2022
2023 with self.subTest(name="v"):
2024 try:
2025 MyClass.v
2026 except AttributeError as exc:
2027 with support.captured_stderr() as err:
2028 sys.__excepthook__(*sys.exc_info())
2029 self.assertNotIn("you mean", err.getvalue())
2030 self.assertNotIn("vvv", err.getvalue())
2031 self.assertNotIn("mom", err.getvalue())
2032 self.assertNotIn("'id'", err.getvalue())
2033 self.assertNotIn("'w'", err.getvalue())
2034 self.assertNotIn("'pytho'", err.getvalue())
2035
2036 with self.subTest(name="m"):
2037 try:
2038 MyClass.m
2039 except AttributeError as exc:
2040 with support.captured_stderr() as err:
2041 sys.__excepthook__(*sys.exc_info())
2042 self.assertNotIn("you mean", err.getvalue())
2043 self.assertNotIn("vvv", err.getvalue())
2044 self.assertNotIn("mom", err.getvalue())
2045 self.assertNotIn("'id'", err.getvalue())
2046 self.assertNotIn("'w'", err.getvalue())
2047 self.assertNotIn("'pytho'", err.getvalue())
2048
2049 with self.subTest(name="py"):
2050 try:
2051 MyClass.py
2052 except AttributeError as exc:
2053 with support.captured_stderr() as err:
2054 sys.__excepthook__(*sys.exc_info())
2055 self.assertNotIn("you mean", err.getvalue())
2056 self.assertNotIn("vvv", err.getvalue())
2057 self.assertNotIn("mom", err.getvalue())
2058 self.assertNotIn("'id'", err.getvalue())
2059 self.assertNotIn("'w'", err.getvalue())
2060 self.assertNotIn("'pytho'", err.getvalue())
2061
2062
Pablo Galindo37494b42021-04-14 02:36:07 +01002063 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
2064 class A:
2065 blech = None
2066 # A class with a very big __dict__ will not be consider
2067 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04002068 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01002069 setattr(A, f"index_{index}", None)
2070
2071 try:
2072 A().bluch
2073 except AttributeError as exc:
2074 with support.captured_stderr() as err:
2075 sys.__excepthook__(*sys.exc_info())
2076
2077 self.assertNotIn("blech", err.getvalue())
2078
2079 def test_getattr_suggestions_no_args(self):
2080 class A:
2081 blech = None
2082 def __getattr__(self, attr):
2083 raise AttributeError()
2084
2085 try:
2086 A().bluch
2087 except AttributeError as exc:
2088 with support.captured_stderr() as err:
2089 sys.__excepthook__(*sys.exc_info())
2090
2091 self.assertIn("blech", err.getvalue())
2092
2093 class A:
2094 blech = None
2095 def __getattr__(self, attr):
2096 raise AttributeError
2097
2098 try:
2099 A().bluch
2100 except AttributeError as exc:
2101 with support.captured_stderr() as err:
2102 sys.__excepthook__(*sys.exc_info())
2103
2104 self.assertIn("blech", err.getvalue())
2105
2106 def test_getattr_suggestions_invalid_args(self):
2107 class NonStringifyClass:
2108 __str__ = None
2109 __repr__ = None
2110
2111 class A:
2112 blech = None
2113 def __getattr__(self, attr):
2114 raise AttributeError(NonStringifyClass())
2115
2116 class B:
2117 blech = None
2118 def __getattr__(self, attr):
2119 raise AttributeError("Error", 23)
2120
2121 class C:
2122 blech = None
2123 def __getattr__(self, attr):
2124 raise AttributeError(23)
2125
2126 for cls in [A, B, C]:
2127 try:
2128 cls().bluch
2129 except AttributeError as exc:
2130 with support.captured_stderr() as err:
2131 sys.__excepthook__(*sys.exc_info())
2132
2133 self.assertIn("blech", err.getvalue())
2134
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07002135 def test_getattr_suggestions_for_same_name(self):
2136 class A:
2137 def __dir__(self):
2138 return ['blech']
2139 try:
2140 A().blech
2141 except AttributeError as exc:
2142 with support.captured_stderr() as err:
2143 sys.__excepthook__(*sys.exc_info())
2144
2145 self.assertNotIn("Did you mean", err.getvalue())
2146
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01002147 def test_attribute_error_with_failing_dict(self):
2148 class T:
2149 bluch = 1
2150 def __dir__(self):
2151 raise AttributeError("oh no!")
2152
2153 try:
2154 T().blich
2155 except AttributeError as exc:
2156 with support.captured_stderr() as err:
2157 sys.__excepthook__(*sys.exc_info())
2158
2159 self.assertNotIn("blech", err.getvalue())
2160 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01002161
Pablo Galindo0b1c1692021-04-17 23:28:45 +01002162 def test_attribute_error_with_bad_name(self):
2163 try:
2164 raise AttributeError(name=12, obj=23)
2165 except AttributeError as exc:
2166 with support.captured_stderr() as err:
2167 sys.__excepthook__(*sys.exc_info())
2168
2169 self.assertNotIn("?", err.getvalue())
2170
2171
Brett Cannon79ec55e2012-04-12 20:24:54 -04002172class ImportErrorTests(unittest.TestCase):
2173
2174 def test_attributes(self):
2175 # Setting 'name' and 'path' should not be a problem.
2176 exc = ImportError('test')
2177 self.assertIsNone(exc.name)
2178 self.assertIsNone(exc.path)
2179
2180 exc = ImportError('test', name='somemodule')
2181 self.assertEqual(exc.name, 'somemodule')
2182 self.assertIsNone(exc.path)
2183
2184 exc = ImportError('test', path='somepath')
2185 self.assertEqual(exc.path, 'somepath')
2186 self.assertIsNone(exc.name)
2187
2188 exc = ImportError('test', path='somepath', name='somename')
2189 self.assertEqual(exc.name, 'somename')
2190 self.assertEqual(exc.path, 'somepath')
2191
Michael Seifert64c8f702017-04-09 09:47:12 +02002192 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002193 with self.assertRaisesRegex(TypeError, msg):
2194 ImportError('test', invalid='keyword')
2195
2196 with self.assertRaisesRegex(TypeError, msg):
2197 ImportError('test', name='name', invalid='keyword')
2198
2199 with self.assertRaisesRegex(TypeError, msg):
2200 ImportError('test', path='path', invalid='keyword')
2201
2202 with self.assertRaisesRegex(TypeError, msg):
2203 ImportError(invalid='keyword')
2204
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002205 with self.assertRaisesRegex(TypeError, msg):
2206 ImportError('test', invalid='keyword', another=True)
2207
Serhiy Storchakae9e44482016-09-28 07:53:32 +03002208 def test_reset_attributes(self):
2209 exc = ImportError('test', name='name', path='path')
2210 self.assertEqual(exc.args, ('test',))
2211 self.assertEqual(exc.msg, 'test')
2212 self.assertEqual(exc.name, 'name')
2213 self.assertEqual(exc.path, 'path')
2214
2215 # Reset not specified attributes
2216 exc.__init__()
2217 self.assertEqual(exc.args, ())
2218 self.assertEqual(exc.msg, None)
2219 self.assertEqual(exc.name, None)
2220 self.assertEqual(exc.path, None)
2221
Brett Cannon07c6e712012-08-24 13:05:09 -04002222 def test_non_str_argument(self):
2223 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002224 with check_warnings(('', BytesWarning), quiet=True):
2225 arg = b'abc'
2226 exc = ImportError(arg)
2227 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002228
Serhiy Storchakab7853962017-04-08 09:55:07 +03002229 def test_copy_pickle(self):
2230 for kwargs in (dict(),
2231 dict(name='somename'),
2232 dict(path='somepath'),
2233 dict(name='somename', path='somepath')):
2234 orig = ImportError('test', **kwargs)
2235 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2236 exc = pickle.loads(pickle.dumps(orig, proto))
2237 self.assertEqual(exc.args, ('test',))
2238 self.assertEqual(exc.msg, 'test')
2239 self.assertEqual(exc.name, orig.name)
2240 self.assertEqual(exc.path, orig.path)
2241 for c in copy.copy, copy.deepcopy:
2242 exc = c(orig)
2243 self.assertEqual(exc.args, ('test',))
2244 self.assertEqual(exc.msg, 'test')
2245 self.assertEqual(exc.name, orig.name)
2246 self.assertEqual(exc.path, orig.path)
2247
Pablo Galindoa77aac42021-04-23 14:27:05 +01002248class SyntaxErrorTests(unittest.TestCase):
2249 def test_range_of_offsets(self):
2250 cases = [
2251 # Basic range from 2->7
2252 (("bad.py", 1, 2, "abcdefg", 1, 7),
2253 dedent(
2254 """
2255 File "bad.py", line 1
2256 abcdefg
2257 ^^^^^
2258 SyntaxError: bad bad
2259 """)),
2260 # end_offset = start_offset + 1
2261 (("bad.py", 1, 2, "abcdefg", 1, 3),
2262 dedent(
2263 """
2264 File "bad.py", line 1
2265 abcdefg
2266 ^
2267 SyntaxError: bad bad
2268 """)),
2269 # Negative end offset
2270 (("bad.py", 1, 2, "abcdefg", 1, -2),
2271 dedent(
2272 """
2273 File "bad.py", line 1
2274 abcdefg
2275 ^
2276 SyntaxError: bad bad
2277 """)),
2278 # end offset before starting offset
2279 (("bad.py", 1, 4, "abcdefg", 1, 2),
2280 dedent(
2281 """
2282 File "bad.py", line 1
2283 abcdefg
2284 ^
2285 SyntaxError: bad bad
2286 """)),
2287 # Both offsets negative
2288 (("bad.py", 1, -4, "abcdefg", 1, -2),
2289 dedent(
2290 """
2291 File "bad.py", line 1
2292 abcdefg
2293 SyntaxError: bad bad
2294 """)),
2295 # Both offsets negative and the end more negative
2296 (("bad.py", 1, -4, "abcdefg", 1, -5),
2297 dedent(
2298 """
2299 File "bad.py", line 1
2300 abcdefg
2301 SyntaxError: bad bad
2302 """)),
2303 # Both offsets 0
2304 (("bad.py", 1, 0, "abcdefg", 1, 0),
2305 dedent(
2306 """
2307 File "bad.py", line 1
2308 abcdefg
2309 SyntaxError: bad bad
2310 """)),
2311 # Start offset 0 and end offset not 0
2312 (("bad.py", 1, 0, "abcdefg", 1, 5),
2313 dedent(
2314 """
2315 File "bad.py", line 1
2316 abcdefg
2317 SyntaxError: bad bad
2318 """)),
Christian Clausscfca4a62021-10-07 17:49:47 +02002319 # End offset pass the source length
Pablo Galindoa77aac42021-04-23 14:27:05 +01002320 (("bad.py", 1, 2, "abcdefg", 1, 100),
2321 dedent(
2322 """
2323 File "bad.py", line 1
2324 abcdefg
2325 ^^^^^^
2326 SyntaxError: bad bad
2327 """)),
2328 ]
2329 for args, expected in cases:
2330 with self.subTest(args=args):
2331 try:
2332 raise SyntaxError("bad bad", args)
2333 except SyntaxError as exc:
2334 with support.captured_stderr() as err:
2335 sys.__excepthook__(*sys.exc_info())
Miss Islington (bot)c800e392021-09-21 15:38:59 -07002336 self.assertIn(expected, err.getvalue())
Pablo Galindoa77aac42021-04-23 14:27:05 +01002337 the_exception = exc
2338
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002339 def test_encodings(self):
2340 source = (
2341 '# -*- coding: cp437 -*-\n'
2342 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2343 )
2344 try:
2345 with open(TESTFN, 'w', encoding='cp437') as testfile:
2346 testfile.write(source)
2347 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2348 err = err.decode('utf-8').splitlines()
2349
2350 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2351 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2352 finally:
2353 unlink(TESTFN)
2354
Łukasz Langa904af3d2021-11-20 16:34:56 +01002355 # Check backwards tokenizer errors
2356 source = '# -*- coding: ascii -*-\n\n(\n'
2357 try:
2358 with open(TESTFN, 'w', encoding='ascii') as testfile:
2359 testfile.write(source)
2360 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2361 err = err.decode('utf-8').splitlines()
2362
2363 self.assertEqual(err[-3], ' (')
2364 self.assertEqual(err[-2], ' ^')
2365 finally:
2366 unlink(TESTFN)
2367
Pablo Galindoa77aac42021-04-23 14:27:05 +01002368 def test_attributes_new_constructor(self):
2369 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2370 the_exception = SyntaxError("bad bad", args)
2371 filename, lineno, offset, error, end_lineno, end_offset = args
2372 self.assertEqual(filename, the_exception.filename)
2373 self.assertEqual(lineno, the_exception.lineno)
2374 self.assertEqual(end_lineno, the_exception.end_lineno)
2375 self.assertEqual(offset, the_exception.offset)
2376 self.assertEqual(end_offset, the_exception.end_offset)
2377 self.assertEqual(error, the_exception.text)
2378 self.assertEqual("bad bad", the_exception.msg)
2379
2380 def test_attributes_old_constructor(self):
2381 args = ("bad.py", 1, 2, "abcdefg")
2382 the_exception = SyntaxError("bad bad", args)
2383 filename, lineno, offset, error = args
2384 self.assertEqual(filename, the_exception.filename)
2385 self.assertEqual(lineno, the_exception.lineno)
2386 self.assertEqual(None, the_exception.end_lineno)
2387 self.assertEqual(offset, the_exception.offset)
2388 self.assertEqual(None, the_exception.end_offset)
2389 self.assertEqual(error, the_exception.text)
2390 self.assertEqual("bad bad", the_exception.msg)
2391
2392 def test_incorrect_constructor(self):
2393 args = ("bad.py", 1, 2)
2394 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2395
2396 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2397 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2398
2399 args = ("bad.py", 1, 2, "abcdefg", 1)
2400 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2401
Brett Cannon79ec55e2012-04-12 20:24:54 -04002402
Mark Shannonbf353f32020-12-17 13:55:28 +00002403class PEP626Tests(unittest.TestCase):
2404
Mark Shannon0b6b2862021-06-24 13:09:14 +01002405 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002406 try:
2407 f()
2408 except Exception as ex:
2409 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002410 else:
2411 self.fail("No exception raised")
2412 lines = []
2413 t = t.tb_next # Skip this function
2414 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002415 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002416 lines.append(
2417 None if frame.f_lineno is None else
2418 frame.f_lineno-frame.f_code.co_firstlineno
2419 )
2420 t = t.tb_next
2421 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002422
2423 def test_lineno_after_raise_simple(self):
2424 def simple():
2425 1/0
2426 pass
2427 self.lineno_after_raise(simple, 1)
2428
2429 def test_lineno_after_raise_in_except(self):
2430 def in_except():
2431 try:
2432 1/0
2433 except:
2434 1/0
2435 pass
2436 self.lineno_after_raise(in_except, 4)
2437
2438 def test_lineno_after_other_except(self):
2439 def other_except():
2440 try:
2441 1/0
2442 except TypeError as ex:
2443 pass
2444 self.lineno_after_raise(other_except, 3)
2445
2446 def test_lineno_in_named_except(self):
2447 def in_named_except():
2448 try:
2449 1/0
2450 except Exception as ex:
2451 1/0
2452 pass
2453 self.lineno_after_raise(in_named_except, 4)
2454
2455 def test_lineno_in_try(self):
2456 def in_try():
2457 try:
2458 1/0
2459 finally:
2460 pass
2461 self.lineno_after_raise(in_try, 4)
2462
2463 def test_lineno_in_finally_normal(self):
2464 def in_finally_normal():
2465 try:
2466 pass
2467 finally:
2468 1/0
2469 pass
2470 self.lineno_after_raise(in_finally_normal, 4)
2471
2472 def test_lineno_in_finally_except(self):
2473 def in_finally_except():
2474 try:
2475 1/0
2476 finally:
2477 1/0
2478 pass
2479 self.lineno_after_raise(in_finally_except, 4)
2480
2481 def test_lineno_after_with(self):
2482 class Noop:
2483 def __enter__(self):
2484 return self
2485 def __exit__(self, *args):
2486 pass
2487 def after_with():
2488 with Noop():
2489 1/0
2490 pass
2491 self.lineno_after_raise(after_with, 2)
2492
Mark Shannon088a15c2021-04-29 19:28:50 +01002493 def test_missing_lineno_shows_as_none(self):
2494 def f():
2495 1/0
2496 self.lineno_after_raise(f, 1)
2497 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2498 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002499
Mark Shannon0b6b2862021-06-24 13:09:14 +01002500 def test_lineno_after_raise_in_with_exit(self):
2501 class ExitFails:
2502 def __enter__(self):
2503 return self
2504 def __exit__(self, *args):
2505 raise ValueError
2506
2507 def after_with():
2508 with ExitFails():
2509 1/0
2510 self.lineno_after_raise(after_with, 1, 1)
2511
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002512if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002513 unittest.main()