blob: bc5f83a5d2dc89522212fa661070438e902e4672 [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)
Pablo Galindo Salgadoc72311d2021-11-25 01:01:40 +0000229 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)
Pablo Galindo Salgadoc72311d2021-11-25 01:01:40 +0000236 check("[a b c d e f]", 1, 2)
Pablo Galindo Salgadoc5214122021-12-07 15:23:33 +0000237 check("for x yfff:", 1, 7)
Ammar Askar025eb982018-09-24 17:12:49 -0400238
239 # Errors thrown by compile.c
240 check('class foo:return 1', 1, 11)
241 check('def f():\n continue', 2, 3)
242 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100243 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400244
245 # Errors thrown by tokenizer.c
246 check('(0x+1)', 1, 3)
247 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700248 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400249 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700250 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200251 check('\u03b1 = 0xI', 1, 6)
252 check(b'\xce\xb1 = 0xI', 1, 6)
253 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
254 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100255 check(b"""if 1:
256 def foo():
257 '''
258
259 def bar():
260 pass
261
262 def baz():
263 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300264 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100265 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
266 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700267 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700268 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Ammar Askar025eb982018-09-24 17:12:49 -0400269
270 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200271 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400272 check('def f():\n from _ import *', 1, 1)
273 check('def f(x, x):\n pass', 1, 1)
274 check('def f(x):\n nonlocal x', 2, 3)
275 check('def f(x):\n x = 1\n global x', 3, 3)
276 check('nonlocal x', 1, 1)
277 check('def f():\n global x\n nonlocal x', 2, 3)
278
Ammar Askar025eb982018-09-24 17:12:49 -0400279 # Errors thrown by future.c
280 check('from __future__ import doesnt_exist', 1, 1)
281 check('from __future__ import braces', 1, 1)
282 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100283 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300284 check('def f():\n x, y: int', 2, 3)
285 check('[*x for x in xs]', 1, 2)
286 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300287 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100288 check('(yield i) = 2', 1, 2)
289 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200290
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000291 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000292 def testSettingException(self):
293 # test that setting an exception at the C level works even if the
294 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000295
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000296 class BadException(Exception):
297 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000298 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000299
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000300 class InvalidException:
301 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000302
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000303 def test_capi1():
304 import _testcapi
305 try:
306 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000307 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000308 exc, err, tb = sys.exc_info()
309 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000310 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000311 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000312 else:
313 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000314
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000315 def test_capi2():
316 import _testcapi
317 try:
318 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000319 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000320 exc, err, tb = sys.exc_info()
321 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000322 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000323 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000324 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000325 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000326 else:
327 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000328
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000329 def test_capi3():
330 import _testcapi
331 self.assertRaises(SystemError, _testcapi.raise_exception,
332 InvalidException, 1)
333
334 if not sys.platform.startswith('java'):
335 test_capi1()
336 test_capi2()
337 test_capi3()
338
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339 def test_WindowsError(self):
340 try:
341 WindowsError
342 except NameError:
343 pass
344 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200345 self.assertIs(WindowsError, OSError)
346 self.assertEqual(str(OSError(1001)), "1001")
347 self.assertEqual(str(OSError(1001, "message")),
348 "[Errno 1001] message")
349 # POSIX errno (9 aka EBADF) is untranslated
350 w = OSError(9, 'foo', 'bar')
351 self.assertEqual(w.errno, 9)
352 self.assertEqual(w.winerror, None)
353 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
354 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
355 w = OSError(0, 'foo', 'bar', 3)
356 self.assertEqual(w.errno, 2)
357 self.assertEqual(w.winerror, 3)
358 self.assertEqual(w.strerror, 'foo')
359 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000360 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100361 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200362 # Unknown win error becomes EINVAL (22)
363 w = OSError(0, 'foo', None, 1001)
364 self.assertEqual(w.errno, 22)
365 self.assertEqual(w.winerror, 1001)
366 self.assertEqual(w.strerror, 'foo')
367 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000368 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100369 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200370 # Non-numeric "errno"
371 w = OSError('bar', 'foo')
372 self.assertEqual(w.errno, 'bar')
373 self.assertEqual(w.winerror, None)
374 self.assertEqual(w.strerror, 'foo')
375 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000376 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000377
Victor Stinnerd223fa62015-04-02 14:17:38 +0200378 @unittest.skipUnless(sys.platform == 'win32',
379 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300380 def test_windows_message(self):
381 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200382 ctypes = import_module('ctypes')
383 # this error code has no message, Python formats it as hexadecimal
384 code = 3765269347
385 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
386 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300387
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000388 def testAttributes(self):
389 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000390
391 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000392 (BaseException, (), {'args' : ()}),
393 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000394 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000395 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000396 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000397 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000398 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000399 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200400 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000401 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000402 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200403 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000404 {'args' : ('foo', 'bar'),
405 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000406 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200407 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000408 {'args' : ('foo', 'bar'),
409 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000410 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800411 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
412 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200413 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000414 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000415 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
416 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200417 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000418 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000419 'strerror' : 'strErrorStr',
420 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000421 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000422 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100423 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000424 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000425 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000426 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100427 'filename' : None, 'lineno' : None, 'offset' : None,
428 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000429 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100430 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000431 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000432 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100433 'offsetStr', 'textStr',
434 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000435 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100436 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
437 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000438 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100439 'textStr', 'endLinenoStr', 'endOffsetStr',
440 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000441 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000442 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100443 'textStr', 'endLinenoStr', 'endOffsetStr',
444 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000445 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100446 'filename' : None, 'lineno' : None, 'offset' : None,
447 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000448 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000449 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
450 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000451 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000452 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000453 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000454 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000455 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000456 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000457 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000458 'ordinal not in range'),
459 'encoding' : 'ascii', 'object' : b'\xff',
460 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000461 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
462 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000463 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000464 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000465 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000467 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000468 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000469 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000470 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100471 (NaiveException, ('foo',),
472 {'args': ('foo',), 'x': 'foo'}),
473 (SlottedNaiveException, ('foo',),
474 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000475 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000476 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200477 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000478 exceptionList.append(
479 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000480 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200481 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000482 'errno' : 1,
483 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000484 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000485 except NameError:
486 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000487
Guido van Rossumebe3e162007-05-17 18:20:34 +0000488 for exc, args, expected in exceptionList:
489 try:
490 e = exc(*args)
491 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000492 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100493 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000494 else:
495 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100496 if not type(e).__name__.endswith('NaiveException'):
497 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000498 # Verify no ref leaks in Exc_str()
499 s = str(e)
500 for checkArgName in expected:
501 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000502 self.assertEqual(repr(value),
503 repr(expected[checkArgName]),
504 '%r.%s == %r, expected %r' % (
505 e, checkArgName,
506 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000507
Guido van Rossumebe3e162007-05-17 18:20:34 +0000508 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000509 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000510 for protocol in range(p.HIGHEST_PROTOCOL + 1):
511 s = p.dumps(e, protocol)
512 new = p.loads(s)
513 for checkArgName in expected:
514 got = repr(getattr(new, checkArgName))
515 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000516 self.assertEqual(got, want,
517 'pickled "%r", attribute "%s' %
518 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000519
Collin Winter828f04a2007-08-31 00:04:24 +0000520 def testWithTraceback(self):
521 try:
522 raise IndexError(4)
523 except:
524 tb = sys.exc_info()[2]
525
526 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000527 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000528 self.assertEqual(e.__traceback__, tb)
529
530 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000531 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000532 self.assertEqual(e.__traceback__, tb)
533
534 class MyException(Exception):
535 pass
536
537 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000538 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000539 self.assertEqual(e.__traceback__, tb)
540
541 def testInvalidTraceback(self):
542 try:
543 Exception().__traceback__ = 5
544 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000545 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000546 else:
547 self.fail("No exception raised")
548
Georg Brandlab6f2f62009-03-31 04:16:10 +0000549 def testInvalidAttrs(self):
550 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
551 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
552 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
553 self.assertRaises(TypeError, delattr, Exception(), '__context__')
554
Collin Winter828f04a2007-08-31 00:04:24 +0000555 def testNoneClearsTracebackAttr(self):
556 try:
557 raise IndexError(4)
558 except:
559 tb = sys.exc_info()[2]
560
561 e = Exception()
562 e.__traceback__ = tb
563 e.__traceback__ = None
564 self.assertEqual(e.__traceback__, None)
565
566 def testChainingAttrs(self):
567 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000568 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700569 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000570
571 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000572 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700573 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000574
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200575 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000576 pass
577
578 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000579 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700580 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000581
582 def testChainingDescriptors(self):
583 try:
584 raise Exception()
585 except Exception as exc:
586 e = exc
587
588 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700589 self.assertIsNone(e.__cause__)
590 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000591
592 e.__context__ = NameError()
593 e.__cause__ = None
594 self.assertIsInstance(e.__context__, NameError)
595 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700596 self.assertTrue(e.__suppress_context__)
597 e.__suppress_context__ = False
598 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000599
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000600 def testKeywordArgs(self):
601 # test that builtin exception don't take keyword args,
602 # but user-defined subclasses can if they want
603 self.assertRaises(TypeError, BaseException, a=1)
604
605 class DerivedException(BaseException):
606 def __init__(self, fancy_arg):
607 BaseException.__init__(self)
608 self.fancy_arg = fancy_arg
609
610 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000611 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000612
Brett Cannon31f59292011-02-21 19:29:56 +0000613 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614 def testInfiniteRecursion(self):
615 def f():
616 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400617 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000618
619 def g():
620 try:
621 return g()
622 except ValueError:
623 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400624 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000625
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000626 def test_str(self):
627 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000628 self.assertTrue(str(Exception))
629 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000630 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000631
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000632 def testExceptionCleanupNames(self):
633 # Make sure the local variable bound to the exception instance by
634 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000635 try:
636 raise Exception()
637 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000638 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000639 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000640 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000641
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000642 def testExceptionCleanupState(self):
643 # Make sure exception state is cleaned up as soon as the except
644 # block is left. See #2507
645
646 class MyException(Exception):
647 def __init__(self, obj):
648 self.obj = obj
649 class MyObj:
650 pass
651
652 def inner_raising_func():
653 # Create some references in exception value and traceback
654 local_ref = obj
655 raise MyException(obj)
656
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000657 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000658 obj = MyObj()
659 wr = weakref.ref(obj)
660 try:
661 inner_raising_func()
662 except MyException as e:
663 pass
664 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300665 gc_collect() # For PyPy or other GCs.
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000666 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300667 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000668
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000669 # Qualified "except" without "as"
670 obj = MyObj()
671 wr = weakref.ref(obj)
672 try:
673 inner_raising_func()
674 except MyException:
675 pass
676 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300677 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000678 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300679 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000680
681 # Bare "except"
682 obj = MyObj()
683 wr = weakref.ref(obj)
684 try:
685 inner_raising_func()
686 except:
687 pass
688 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300689 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000690 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300691 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000692
693 # "except" with premature block leave
694 obj = MyObj()
695 wr = weakref.ref(obj)
696 for i in [0]:
697 try:
698 inner_raising_func()
699 except:
700 break
701 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300702 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000703 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300704 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000705
706 # "except" block raising another exception
707 obj = MyObj()
708 wr = weakref.ref(obj)
709 try:
710 try:
711 inner_raising_func()
712 except:
713 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000714 except KeyError as e:
715 # We want to test that the except block above got rid of
716 # the exception raised in inner_raising_func(), but it
717 # also ends up in the __context__ of the KeyError, so we
718 # must clear the latter manually for our test to succeed.
719 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000720 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300721 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000722 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800723 # guarantee no ref cycles on CPython (don't gc_collect)
724 if check_impl_detail(cpython=False):
725 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300726 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000727
728 # Some complicated construct
729 obj = MyObj()
730 wr = weakref.ref(obj)
731 try:
732 inner_raising_func()
733 except MyException:
734 try:
735 try:
736 raise
737 finally:
738 raise
739 except MyException:
740 pass
741 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800742 if check_impl_detail(cpython=False):
743 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000744 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300745 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000746
747 # Inside an exception-silencing "with" block
748 class Context:
749 def __enter__(self):
750 return self
751 def __exit__ (self, exc_type, exc_value, exc_tb):
752 return True
753 obj = MyObj()
754 wr = weakref.ref(obj)
755 with Context():
756 inner_raising_func()
757 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800758 if check_impl_detail(cpython=False):
759 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000760 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300761 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000762
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000763 def test_exception_target_in_nested_scope(self):
764 # issue 4617: This used to raise a SyntaxError
765 # "can not delete variable 'e' referenced in nested scope"
766 def print_error():
767 e
768 try:
769 something
770 except Exception as e:
771 print_error()
772 # implicit "del e" here
773
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000774 def test_generator_leaking(self):
775 # Test that generator exception state doesn't leak into the calling
776 # frame
777 def yield_raise():
778 try:
779 raise KeyError("caught")
780 except KeyError:
781 yield sys.exc_info()[0]
782 yield sys.exc_info()[0]
783 yield sys.exc_info()[0]
784 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000785 self.assertEqual(next(g), KeyError)
786 self.assertEqual(sys.exc_info()[0], None)
787 self.assertEqual(next(g), KeyError)
788 self.assertEqual(sys.exc_info()[0], None)
789 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000790
791 # Same test, but inside an exception handler
792 try:
793 raise TypeError("foo")
794 except TypeError:
795 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000796 self.assertEqual(next(g), KeyError)
797 self.assertEqual(sys.exc_info()[0], TypeError)
798 self.assertEqual(next(g), KeyError)
799 self.assertEqual(sys.exc_info()[0], TypeError)
800 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000801 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000802 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000803
Benjamin Peterson83195c32011-07-03 13:44:00 -0500804 def test_generator_leaking2(self):
805 # See issue 12475.
806 def g():
807 yield
808 try:
809 raise RuntimeError
810 except RuntimeError:
811 it = g()
812 next(it)
813 try:
814 next(it)
815 except StopIteration:
816 pass
817 self.assertEqual(sys.exc_info(), (None, None, None))
818
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100819 def test_generator_leaking3(self):
820 # See issue #23353. When gen.throw() is called, the caller's
821 # exception state should be save and restored.
822 def g():
823 try:
824 yield
825 except ZeroDivisionError:
826 yield sys.exc_info()[1]
827 it = g()
828 next(it)
829 try:
830 1/0
831 except ZeroDivisionError as e:
832 self.assertIs(sys.exc_info()[1], e)
833 gen_exc = it.throw(e)
834 self.assertIs(sys.exc_info()[1], e)
835 self.assertIs(gen_exc, e)
836 self.assertEqual(sys.exc_info(), (None, None, None))
837
838 def test_generator_leaking4(self):
839 # See issue #23353. When an exception is raised by a generator,
840 # the caller's exception state should still be restored.
841 def g():
842 try:
843 1/0
844 except ZeroDivisionError:
845 yield sys.exc_info()[0]
846 raise
847 it = g()
848 try:
849 raise TypeError
850 except TypeError:
851 # The caller's exception state (TypeError) is temporarily
852 # saved in the generator.
853 tp = next(it)
854 self.assertIs(tp, ZeroDivisionError)
855 try:
856 next(it)
857 # We can't check it immediately, but while next() returns
858 # with an exception, it shouldn't have restored the old
859 # exception state (TypeError).
860 except ZeroDivisionError as e:
861 self.assertIs(sys.exc_info()[1], e)
862 # We used to find TypeError here.
863 self.assertEqual(sys.exc_info(), (None, None, None))
864
Benjamin Petersonac913412011-07-03 16:25:11 -0500865 def test_generator_doesnt_retain_old_exc(self):
866 def g():
867 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
868 yield
869 self.assertEqual(sys.exc_info(), (None, None, None))
870 it = g()
871 try:
872 raise RuntimeError
873 except RuntimeError:
874 next(it)
875 self.assertRaises(StopIteration, next, it)
876
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000877 def test_generator_finalizing_and_exc_info(self):
878 # See #7173
879 def simple_gen():
880 yield 1
881 def run_gen():
882 gen = simple_gen()
883 try:
884 raise RuntimeError
885 except RuntimeError:
886 return next(gen)
887 run_gen()
888 gc_collect()
889 self.assertEqual(sys.exc_info(), (None, None, None))
890
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200891 def _check_generator_cleanup_exc_state(self, testfunc):
892 # Issue #12791: exception state is cleaned up as soon as a generator
893 # is closed (reference cycles are broken).
894 class MyException(Exception):
895 def __init__(self, obj):
896 self.obj = obj
897 class MyObj:
898 pass
899
900 def raising_gen():
901 try:
902 raise MyException(obj)
903 except MyException:
904 yield
905
906 obj = MyObj()
907 wr = weakref.ref(obj)
908 g = raising_gen()
909 next(g)
910 testfunc(g)
911 g = obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300912 gc_collect() # For PyPy or other GCs.
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200913 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300914 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200915
916 def test_generator_throw_cleanup_exc_state(self):
917 def do_throw(g):
918 try:
919 g.throw(RuntimeError())
920 except RuntimeError:
921 pass
922 self._check_generator_cleanup_exc_state(do_throw)
923
924 def test_generator_close_cleanup_exc_state(self):
925 def do_close(g):
926 g.close()
927 self._check_generator_cleanup_exc_state(do_close)
928
929 def test_generator_del_cleanup_exc_state(self):
930 def do_del(g):
931 g = None
932 self._check_generator_cleanup_exc_state(do_del)
933
934 def test_generator_next_cleanup_exc_state(self):
935 def do_next(g):
936 try:
937 next(g)
938 except StopIteration:
939 pass
940 else:
941 self.fail("should have raised StopIteration")
942 self._check_generator_cleanup_exc_state(do_next)
943
944 def test_generator_send_cleanup_exc_state(self):
945 def do_send(g):
946 try:
947 g.send(None)
948 except StopIteration:
949 pass
950 else:
951 self.fail("should have raised StopIteration")
952 self._check_generator_cleanup_exc_state(do_send)
953
Benjamin Peterson27d63672008-06-15 20:09:12 +0000954 def test_3114(self):
955 # Bug #3114: in its destructor, MyObject retrieves a pointer to
956 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000957 class MyObject:
958 def __del__(self):
959 nonlocal e
960 e = sys.exc_info()
961 e = ()
962 try:
963 raise Exception(MyObject())
964 except:
965 pass
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300966 gc_collect() # For PyPy or other GCs.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000967 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000968
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -0700969 def test_raise_does_not_create_context_chain_cycle(self):
970 class A(Exception):
971 pass
972 class B(Exception):
973 pass
974 class C(Exception):
975 pass
976
977 # Create a context chain:
978 # C -> B -> A
979 # Then raise A in context of C.
980 try:
981 try:
982 raise A
983 except A as a_:
984 a = a_
985 try:
986 raise B
987 except B as b_:
988 b = b_
989 try:
990 raise C
991 except C as c_:
992 c = c_
993 self.assertIsInstance(a, A)
994 self.assertIsInstance(b, B)
995 self.assertIsInstance(c, C)
996 self.assertIsNone(a.__context__)
997 self.assertIs(b.__context__, a)
998 self.assertIs(c.__context__, b)
999 raise a
1000 except A as e:
1001 exc = e
1002
1003 # Expect A -> C -> B, without cycle
1004 self.assertIs(exc, a)
1005 self.assertIs(a.__context__, c)
1006 self.assertIs(c.__context__, b)
1007 self.assertIsNone(b.__context__)
1008
1009 def test_no_hang_on_context_chain_cycle1(self):
1010 # See issue 25782. Cycle in context chain.
1011
1012 def cycle():
1013 try:
1014 raise ValueError(1)
1015 except ValueError as ex:
1016 ex.__context__ = ex
1017 raise TypeError(2)
1018
1019 try:
1020 cycle()
1021 except Exception as e:
1022 exc = e
1023
1024 self.assertIsInstance(exc, TypeError)
1025 self.assertIsInstance(exc.__context__, ValueError)
1026 self.assertIs(exc.__context__.__context__, exc.__context__)
1027
Miss Islington (bot)19604092021-08-16 02:01:14 -07001028 @unittest.skip("See issue 44895")
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -07001029 def test_no_hang_on_context_chain_cycle2(self):
1030 # See issue 25782. Cycle at head of context chain.
1031
1032 class A(Exception):
1033 pass
1034 class B(Exception):
1035 pass
1036 class C(Exception):
1037 pass
1038
1039 # Context cycle:
1040 # +-----------+
1041 # V |
1042 # C --> B --> A
1043 with self.assertRaises(C) as cm:
1044 try:
1045 raise A()
1046 except A as _a:
1047 a = _a
1048 try:
1049 raise B()
1050 except B as _b:
1051 b = _b
1052 try:
1053 raise C()
1054 except C as _c:
1055 c = _c
1056 a.__context__ = c
1057 raise c
1058
1059 self.assertIs(cm.exception, c)
1060 # Verify the expected context chain cycle
1061 self.assertIs(c.__context__, b)
1062 self.assertIs(b.__context__, a)
1063 self.assertIs(a.__context__, c)
1064
1065 def test_no_hang_on_context_chain_cycle3(self):
1066 # See issue 25782. Longer context chain with cycle.
1067
1068 class A(Exception):
1069 pass
1070 class B(Exception):
1071 pass
1072 class C(Exception):
1073 pass
1074 class D(Exception):
1075 pass
1076 class E(Exception):
1077 pass
1078
1079 # Context cycle:
1080 # +-----------+
1081 # V |
1082 # E --> D --> C --> B --> A
1083 with self.assertRaises(E) as cm:
1084 try:
1085 raise A()
1086 except A as _a:
1087 a = _a
1088 try:
1089 raise B()
1090 except B as _b:
1091 b = _b
1092 try:
1093 raise C()
1094 except C as _c:
1095 c = _c
1096 a.__context__ = c
1097 try:
1098 raise D()
1099 except D as _d:
1100 d = _d
1101 e = E()
1102 raise e
1103
1104 self.assertIs(cm.exception, e)
1105 # Verify the expected context chain cycle
1106 self.assertIs(e.__context__, d)
1107 self.assertIs(d.__context__, c)
1108 self.assertIs(c.__context__, b)
1109 self.assertIs(b.__context__, a)
1110 self.assertIs(a.__context__, c)
1111
Benjamin Peterson24dfb052014-04-02 12:05:35 -04001112 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +00001113 # See issue 7309. This was a crasher.
1114
1115 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
1116 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
1117 u.end = 2
1118 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
1119 u.end = 5
1120 u.reason = 0x345345345345345345
1121 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
1122 u.encoding = 4000
1123 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
1124 u.start = 1000
1125 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
1126
1127 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
1128 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
1129 u.end = 2
1130 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
1131 u.end = 5
1132 u.reason = 0x345345345345345345
1133 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
1134 u.encoding = 4000
1135 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
1136 u.start = 1000
1137 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
1138
1139 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
1140 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
1141 u.end = 2
1142 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
1143 u.end = 5
1144 u.reason = 0x345345345345345345
1145 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
1146 u.start = 1000
1147 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +00001148
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001149 def test_unicode_errors_no_object(self):
1150 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -04001151 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001152 for klass in klasses:
1153 self.assertEqual(str(klass.__new__(klass)), "")
1154
Brett Cannon31f59292011-02-21 19:29:56 +00001155 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001156 def test_badisinstance(self):
1157 # Bug #2542: if issubclass(e, MyException) raises an exception,
1158 # it should be ignored
1159 class Meta(type):
1160 def __subclasscheck__(cls, subclass):
1161 raise ValueError()
1162 class MyException(Exception, metaclass=Meta):
1163 pass
1164
Martin Panter3263f682016-02-28 03:16:11 +00001165 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001166 try:
1167 raise KeyError()
1168 except MyException as e:
1169 self.fail("exception should not be a MyException")
1170 except KeyError:
1171 pass
1172 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001173 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001174 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001175 self.fail("Should have raised KeyError")
1176
1177 def g():
1178 try:
1179 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001180 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001181 return sys.exc_info()
1182 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001183 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001184 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001185
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001186
1187 @cpython_only
Benjamin Petersonef36dfe2021-08-13 02:45:13 -07001188 def test_trashcan_recursion(self):
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001189 # See bpo-33930
1190
1191 def foo():
1192 o = object()
1193 for x in range(1_000_000):
1194 # Create a big chain of method objects that will trigger
1195 # a deep chain of calls when they need to be destructed.
1196 o = o.__dir__
1197
1198 foo()
1199 support.gc_collect()
1200
xdegaye56d1f5c2017-10-26 15:09:06 +02001201 @cpython_only
1202 def test_recursion_normalizing_exception(self):
1203 # Issue #22898.
1204 # Test that a RecursionError is raised when tstate->recursion_depth is
1205 # equal to recursion_limit in PyErr_NormalizeException() and check
1206 # that a ResourceWarning is printed.
1207 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001208 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001209 # singleton was being used in that case, that held traceback data and
1210 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1211 # finalization of these locals.
1212 code = """if 1:
1213 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001214 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001215
1216 class MyException(Exception): pass
1217
1218 def setrecursionlimit(depth):
1219 while 1:
1220 try:
1221 sys.setrecursionlimit(depth)
1222 return depth
1223 except RecursionError:
1224 # sys.setrecursionlimit() raises a RecursionError if
1225 # the new recursion limit is too low (issue #25274).
1226 depth += 1
1227
1228 def recurse(cnt):
1229 cnt -= 1
1230 if cnt:
1231 recurse(cnt)
1232 else:
1233 generator.throw(MyException)
1234
1235 def gen():
1236 f = open(%a, mode='rb', buffering=0)
1237 yield
1238
1239 generator = gen()
1240 next(generator)
1241 recursionlimit = sys.getrecursionlimit()
1242 depth = get_recursion_depth()
1243 try:
1244 # Upon the last recursive invocation of recurse(),
1245 # tstate->recursion_depth is equal to (recursion_limit - 1)
1246 # and is equal to recursion_limit when _gen_throw() calls
1247 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001248 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001249 finally:
1250 sys.setrecursionlimit(recursionlimit)
1251 print('Done.')
1252 """ % __file__
1253 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1254 # Check that the program does not fail with SIGABRT.
1255 self.assertEqual(rc, 1)
1256 self.assertIn(b'RecursionError', err)
1257 self.assertIn(b'ResourceWarning', err)
1258 self.assertIn(b'Done.', out)
1259
1260 @cpython_only
1261 def test_recursion_normalizing_infinite_exception(self):
1262 # Issue #30697. Test that a RecursionError is raised when
1263 # PyErr_NormalizeException() maximum recursion depth has been
1264 # exceeded.
1265 code = """if 1:
1266 import _testcapi
1267 try:
1268 raise _testcapi.RecursingInfinitelyError
1269 finally:
1270 print('Done.')
1271 """
1272 rc, out, err = script_helper.assert_python_failure("-c", code)
1273 self.assertEqual(rc, 1)
1274 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1275 b'while normalizing an exception', err)
1276 self.assertIn(b'Done.', out)
1277
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001278
1279 def test_recursion_in_except_handler(self):
1280
1281 def set_relative_recursion_limit(n):
1282 depth = 1
1283 while True:
1284 try:
1285 sys.setrecursionlimit(depth)
1286 except RecursionError:
1287 depth += 1
1288 else:
1289 break
1290 sys.setrecursionlimit(depth+n)
1291
1292 def recurse_in_except():
1293 try:
1294 1/0
1295 except:
1296 recurse_in_except()
1297
1298 def recurse_after_except():
1299 try:
1300 1/0
1301 except:
1302 pass
1303 recurse_after_except()
1304
1305 def recurse_in_body_and_except():
1306 try:
1307 recurse_in_body_and_except()
1308 except:
1309 recurse_in_body_and_except()
1310
1311 recursionlimit = sys.getrecursionlimit()
1312 try:
1313 set_relative_recursion_limit(10)
1314 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1315 with self.subTest(func=func):
1316 try:
1317 func()
1318 except RecursionError:
1319 pass
1320 else:
1321 self.fail("Should have raised a RecursionError")
1322 finally:
1323 sys.setrecursionlimit(recursionlimit)
1324
1325
xdegaye56d1f5c2017-10-26 15:09:06 +02001326 @cpython_only
1327 def test_recursion_normalizing_with_no_memory(self):
1328 # Issue #30697. Test that in the abort that occurs when there is no
1329 # memory left and the size of the Python frames stack is greater than
1330 # the size of the list of preallocated MemoryError instances, the
1331 # Fatal Python error message mentions MemoryError.
1332 code = """if 1:
1333 import _testcapi
1334 class C(): pass
1335 def recurse(cnt):
1336 cnt -= 1
1337 if cnt:
1338 recurse(cnt)
1339 else:
1340 _testcapi.set_nomemory(0)
1341 C()
1342 recurse(16)
1343 """
1344 with SuppressCrashReport():
1345 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001346 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1347 b'Cannot recover from MemoryErrors while '
1348 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001349
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001350 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001351 def test_MemoryError(self):
1352 # PyErr_NoMemory always raises the same exception instance.
1353 # Check that the traceback is not doubled.
1354 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001355 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001356 def raiseMemError():
1357 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001358 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001359 except MemoryError as e:
1360 tb = e.__traceback__
1361 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001362 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001363 return traceback.format_tb(tb)
1364
1365 tb1 = raiseMemError()
1366 tb2 = raiseMemError()
1367 self.assertEqual(tb1, tb2)
1368
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001369 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001370 def test_exception_with_doc(self):
1371 import _testcapi
1372 doc2 = "This is a test docstring."
1373 doc4 = "This is another test docstring."
1374
1375 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1376 "error1")
1377
1378 # test basic usage of PyErr_NewException
1379 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1380 self.assertIs(type(error1), type)
1381 self.assertTrue(issubclass(error1, Exception))
1382 self.assertIsNone(error1.__doc__)
1383
1384 # test with given docstring
1385 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1386 self.assertEqual(error2.__doc__, doc2)
1387
1388 # test with explicit base (without docstring)
1389 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1390 base=error2)
1391 self.assertTrue(issubclass(error3, error2))
1392
1393 # test with explicit base tuple
1394 class C(object):
1395 pass
1396 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1397 (error3, C))
1398 self.assertTrue(issubclass(error4, error3))
1399 self.assertTrue(issubclass(error4, C))
1400 self.assertEqual(error4.__doc__, doc4)
1401
1402 # test with explicit dictionary
1403 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1404 error4, {'a': 1})
1405 self.assertTrue(issubclass(error5, error4))
1406 self.assertEqual(error5.a, 1)
1407 self.assertEqual(error5.__doc__, "")
1408
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001409 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001410 def test_memory_error_cleanup(self):
1411 # Issue #5437: preallocated MemoryError instances should not keep
1412 # traceback objects alive.
1413 from _testcapi import raise_memoryerror
1414 class C:
1415 pass
1416 wr = None
1417 def inner():
1418 nonlocal wr
1419 c = C()
1420 wr = weakref.ref(c)
1421 raise_memoryerror()
1422 # We cannot use assertRaises since it manually deletes the traceback
1423 try:
1424 inner()
1425 except MemoryError as e:
1426 self.assertNotEqual(wr(), None)
1427 else:
1428 self.fail("MemoryError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001429 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001430 self.assertEqual(wr(), None)
1431
Brett Cannon31f59292011-02-21 19:29:56 +00001432 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001433 def test_recursion_error_cleanup(self):
1434 # Same test as above, but with "recursion exceeded" errors
1435 class C:
1436 pass
1437 wr = None
1438 def inner():
1439 nonlocal wr
1440 c = C()
1441 wr = weakref.ref(c)
1442 inner()
1443 # We cannot use assertRaises since it manually deletes the traceback
1444 try:
1445 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001446 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001447 self.assertNotEqual(wr(), None)
1448 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001449 self.fail("RecursionError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001450 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001451 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001452
Antoine Pitroua7622852011-09-01 21:37:43 +02001453 def test_errno_ENOTDIR(self):
1454 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1455 with self.assertRaises(OSError) as cm:
1456 os.listdir(__file__)
1457 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1458
Martin Panter3263f682016-02-28 03:16:11 +00001459 def test_unraisable(self):
1460 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1461 class BrokenDel:
1462 def __del__(self):
1463 exc = ValueError("del is broken")
1464 # The following line is included in the traceback report:
1465 raise exc
1466
Victor Stinnere4d300e2019-05-22 23:44:02 +02001467 obj = BrokenDel()
1468 with support.catch_unraisable_exception() as cm:
1469 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001470
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001471 gc_collect() # For PyPy or other GCs.
Victor Stinnere4d300e2019-05-22 23:44:02 +02001472 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1473 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001474
1475 def test_unhandled(self):
1476 # Check for sensible reporting of unhandled exceptions
1477 for exc_type in (ValueError, BrokenStrException):
1478 with self.subTest(exc_type):
1479 try:
1480 exc = exc_type("test message")
1481 # The following line is included in the traceback report:
1482 raise exc
1483 except exc_type:
1484 with captured_stderr() as stderr:
1485 sys.__excepthook__(*sys.exc_info())
1486 report = stderr.getvalue()
1487 self.assertIn("test_exceptions.py", report)
1488 self.assertIn("raise exc", report)
1489 self.assertIn(exc_type.__name__, report)
1490 if exc_type is BrokenStrException:
1491 self.assertIn("<exception str() failed>", report)
1492 else:
1493 self.assertIn("test message", report)
1494 self.assertTrue(report.endswith("\n"))
1495
xdegaye66caacf2017-10-23 18:08:41 +02001496 @cpython_only
1497 def test_memory_error_in_PyErr_PrintEx(self):
1498 code = """if 1:
1499 import _testcapi
1500 class C(): pass
1501 _testcapi.set_nomemory(0, %d)
1502 C()
1503 """
1504
1505 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1506 # Span a large range of tests as the CPython code always evolves with
1507 # changes that add or remove memory allocations.
1508 for i in range(1, 20):
1509 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1510 self.assertIn(rc, (1, 120))
1511 self.assertIn(b'MemoryError', err)
1512
Mark Shannonae3087c2017-10-22 22:41:51 +01001513 def test_yield_in_nested_try_excepts(self):
1514 #Issue #25612
1515 class MainError(Exception):
1516 pass
1517
1518 class SubError(Exception):
1519 pass
1520
1521 def main():
1522 try:
1523 raise MainError()
1524 except MainError:
1525 try:
1526 yield
1527 except SubError:
1528 pass
1529 raise
1530
1531 coro = main()
1532 coro.send(None)
1533 with self.assertRaises(MainError):
1534 coro.throw(SubError())
1535
1536 def test_generator_doesnt_retain_old_exc2(self):
1537 #Issue 28884#msg282532
1538 def g():
1539 try:
1540 raise ValueError
1541 except ValueError:
1542 yield 1
1543 self.assertEqual(sys.exc_info(), (None, None, None))
1544 yield 2
1545
1546 gen = g()
1547
1548 try:
1549 raise IndexError
1550 except IndexError:
1551 self.assertEqual(next(gen), 1)
1552 self.assertEqual(next(gen), 2)
1553
1554 def test_raise_in_generator(self):
1555 #Issue 25612#msg304117
1556 def g():
1557 yield 1
1558 raise
1559 yield 2
1560
1561 with self.assertRaises(ZeroDivisionError):
1562 i = g()
1563 try:
1564 1/0
1565 except:
1566 next(i)
1567 next(i)
1568
Zackery Spytzce6a0702019-08-25 03:44:09 -06001569 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1570 def test_assert_shadowing(self):
1571 # Shadowing AssertionError would cause the assert statement to
1572 # misbehave.
1573 global AssertionError
1574 AssertionError = TypeError
1575 try:
1576 assert False, 'hello'
1577 except BaseException as e:
1578 del AssertionError
1579 self.assertIsInstance(e, AssertionError)
1580 self.assertEqual(str(e), 'hello')
1581 else:
1582 del AssertionError
1583 self.fail('Expected exception')
1584
Pablo Galindo9b648a92020-09-01 19:39:46 +01001585 def test_memory_error_subclasses(self):
1586 # bpo-41654: MemoryError instances use a freelist of objects that are
1587 # linked using the 'dict' attribute when they are inactive/dead.
1588 # Subclasses of MemoryError should not participate in the freelist
1589 # schema. This test creates a MemoryError object and keeps it alive
1590 # (therefore advancing the freelist) and then it creates and destroys a
1591 # subclass object. Finally, it checks that creating a new MemoryError
1592 # succeeds, proving that the freelist is not corrupted.
1593
1594 class TestException(MemoryError):
1595 pass
1596
1597 try:
1598 raise MemoryError
1599 except MemoryError as exc:
1600 inst = exc
1601
1602 try:
1603 raise TestException
1604 except Exception:
1605 pass
1606
1607 for _ in range(10):
1608 try:
1609 raise MemoryError
1610 except MemoryError as exc:
1611 pass
1612
1613 gc_collect()
1614
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001615global_for_suggestions = None
1616
1617class NameErrorTests(unittest.TestCase):
1618 def test_name_error_has_name(self):
1619 try:
1620 bluch
1621 except NameError as exc:
1622 self.assertEqual("bluch", exc.name)
1623
1624 def test_name_error_suggestions(self):
1625 def Substitution():
1626 noise = more_noise = a = bc = None
1627 blech = None
1628 print(bluch)
1629
1630 def Elimination():
1631 noise = more_noise = a = bc = None
1632 blch = None
1633 print(bluch)
1634
1635 def Addition():
1636 noise = more_noise = a = bc = None
1637 bluchin = None
1638 print(bluch)
1639
1640 def SubstitutionOverElimination():
1641 blach = None
1642 bluc = None
1643 print(bluch)
1644
1645 def SubstitutionOverAddition():
1646 blach = None
1647 bluchi = None
1648 print(bluch)
1649
1650 def EliminationOverAddition():
1651 blucha = None
1652 bluc = None
1653 print(bluch)
1654
Pablo Galindo7a041162021-04-19 23:35:53 +01001655 for func, suggestion in [(Substitution, "'blech'?"),
1656 (Elimination, "'blch'?"),
1657 (Addition, "'bluchin'?"),
1658 (EliminationOverAddition, "'blucha'?"),
1659 (SubstitutionOverElimination, "'blach'?"),
1660 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001661 err = None
1662 try:
1663 func()
1664 except NameError as exc:
1665 with support.captured_stderr() as err:
1666 sys.__excepthook__(*sys.exc_info())
1667 self.assertIn(suggestion, err.getvalue())
1668
1669 def test_name_error_suggestions_from_globals(self):
1670 def func():
1671 print(global_for_suggestio)
1672 try:
1673 func()
1674 except NameError as exc:
1675 with support.captured_stderr() as err:
1676 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001677 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001678
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001679 def test_name_error_suggestions_from_builtins(self):
1680 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001681 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001682 try:
1683 func()
1684 except NameError as exc:
1685 with support.captured_stderr() as err:
1686 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001687 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001688
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001689 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1690 def f():
1691 somethingverywronghehehehehehe = None
1692 print(somethingverywronghe)
1693
1694 try:
1695 f()
1696 except NameError as exc:
1697 with support.captured_stderr() as err:
1698 sys.__excepthook__(*sys.exc_info())
1699
1700 self.assertNotIn("somethingverywronghehe", err.getvalue())
1701
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001702 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1703 vvv = mom = w = id = pytho = None
1704
1705 with self.subTest(name="b"):
1706 try:
1707 b
1708 except NameError as exc:
1709 with support.captured_stderr() as err:
1710 sys.__excepthook__(*sys.exc_info())
1711 self.assertNotIn("you mean", err.getvalue())
1712 self.assertNotIn("vvv", err.getvalue())
1713 self.assertNotIn("mom", err.getvalue())
1714 self.assertNotIn("'id'", err.getvalue())
1715 self.assertNotIn("'w'", err.getvalue())
1716 self.assertNotIn("'pytho'", err.getvalue())
1717
1718 with self.subTest(name="v"):
1719 try:
1720 v
1721 except NameError as exc:
1722 with support.captured_stderr() as err:
1723 sys.__excepthook__(*sys.exc_info())
1724 self.assertNotIn("you mean", err.getvalue())
1725 self.assertNotIn("vvv", err.getvalue())
1726 self.assertNotIn("mom", err.getvalue())
1727 self.assertNotIn("'id'", err.getvalue())
1728 self.assertNotIn("'w'", err.getvalue())
1729 self.assertNotIn("'pytho'", err.getvalue())
1730
1731 with self.subTest(name="m"):
1732 try:
1733 m
1734 except NameError as exc:
1735 with support.captured_stderr() as err:
1736 sys.__excepthook__(*sys.exc_info())
1737 self.assertNotIn("you mean", err.getvalue())
1738 self.assertNotIn("vvv", err.getvalue())
1739 self.assertNotIn("mom", err.getvalue())
1740 self.assertNotIn("'id'", err.getvalue())
1741 self.assertNotIn("'w'", err.getvalue())
1742 self.assertNotIn("'pytho'", err.getvalue())
1743
1744 with self.subTest(name="py"):
1745 try:
1746 py
1747 except NameError as exc:
1748 with support.captured_stderr() as err:
1749 sys.__excepthook__(*sys.exc_info())
1750 self.assertNotIn("you mean", err.getvalue())
1751 self.assertNotIn("vvv", err.getvalue())
1752 self.assertNotIn("mom", err.getvalue())
1753 self.assertNotIn("'id'", err.getvalue())
1754 self.assertNotIn("'w'", err.getvalue())
1755 self.assertNotIn("'pytho'", err.getvalue())
1756
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001757 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001758 def f():
1759 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001760 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1761 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1762 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1763 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1764 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1765 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1766 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1767 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1768 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1769 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1770 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1771 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1772 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1773 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1774 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1775 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1776 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1777 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1778 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1779 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1780 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1781 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1782 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1783 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1784 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1785 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1786 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1787 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1788 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1789 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1790 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1791 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1792 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1793 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1794 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1795 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1796 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1797 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1798 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1799 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1800 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1801 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1802 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1803 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1804 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1805 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1806 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1807 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1808 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1809 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1810 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1811 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1812 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1813 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1814 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1815 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1816 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1817 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1818 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1819 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1820 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1821 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1822 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1823 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1824 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1825 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1826 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1827 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1828 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1829 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1830 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1831 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1832 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1833 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1834 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1835 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1836 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1837 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1838 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1839 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1840 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001841 print(a0)
1842
1843 try:
1844 f()
1845 except NameError as exc:
1846 with support.captured_stderr() as err:
1847 sys.__excepthook__(*sys.exc_info())
1848
Miss Islington (bot)d55bf812021-10-07 05:11:38 -07001849 self.assertNotRegex(err.getvalue(), r"NameError.*a1")
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001850
1851 def test_name_error_with_custom_exceptions(self):
1852 def f():
1853 blech = None
1854 raise NameError()
1855
1856 try:
1857 f()
1858 except NameError as exc:
1859 with support.captured_stderr() as err:
1860 sys.__excepthook__(*sys.exc_info())
1861
1862 self.assertNotIn("blech", err.getvalue())
1863
1864 def f():
1865 blech = None
1866 raise NameError
1867
1868 try:
1869 f()
1870 except NameError as exc:
1871 with support.captured_stderr() as err:
1872 sys.__excepthook__(*sys.exc_info())
1873
1874 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001875
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001876 def test_unbound_local_error_doesn_not_match(self):
1877 def foo():
1878 something = 3
1879 print(somethong)
1880 somethong = 3
1881
1882 try:
1883 foo()
1884 except UnboundLocalError as exc:
1885 with support.captured_stderr() as err:
1886 sys.__excepthook__(*sys.exc_info())
1887
1888 self.assertNotIn("something", err.getvalue())
1889
Łukasz Langa8eabe602021-11-18 01:28:04 +01001890 def test_issue45826(self):
1891 # regression test for bpo-45826
1892 def f():
1893 with self.assertRaisesRegex(NameError, 'aaa'):
1894 aab
1895
1896 try:
1897 f()
1898 except self.failureException:
1899 with support.captured_stderr() as err:
1900 sys.__excepthook__(*sys.exc_info())
1901
1902 self.assertIn("aab", err.getvalue())
1903
1904 def test_issue45826_focused(self):
1905 def f():
1906 try:
1907 nonsense
1908 except BaseException as E:
1909 E.with_traceback(None)
1910 raise ZeroDivisionError()
1911
1912 try:
1913 f()
1914 except ZeroDivisionError:
1915 with support.captured_stderr() as err:
1916 sys.__excepthook__(*sys.exc_info())
1917
1918 self.assertIn("nonsense", err.getvalue())
1919 self.assertIn("ZeroDivisionError", err.getvalue())
1920
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001921
Pablo Galindo37494b42021-04-14 02:36:07 +01001922class AttributeErrorTests(unittest.TestCase):
1923 def test_attributes(self):
1924 # Setting 'attr' should not be a problem.
1925 exc = AttributeError('Ouch!')
1926 self.assertIsNone(exc.name)
1927 self.assertIsNone(exc.obj)
1928
1929 sentinel = object()
1930 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1931 self.assertEqual(exc.name, 'carry')
1932 self.assertIs(exc.obj, sentinel)
1933
1934 def test_getattr_has_name_and_obj(self):
1935 class A:
1936 blech = None
1937
1938 obj = A()
1939 try:
1940 obj.bluch
1941 except AttributeError as exc:
1942 self.assertEqual("bluch", exc.name)
1943 self.assertEqual(obj, exc.obj)
1944
1945 def test_getattr_has_name_and_obj_for_method(self):
1946 class A:
1947 def blech(self):
1948 return
1949
1950 obj = A()
1951 try:
1952 obj.bluch()
1953 except AttributeError as exc:
1954 self.assertEqual("bluch", exc.name)
1955 self.assertEqual(obj, exc.obj)
1956
1957 def test_getattr_suggestions(self):
1958 class Substitution:
1959 noise = more_noise = a = bc = None
1960 blech = None
1961
1962 class Elimination:
1963 noise = more_noise = a = bc = None
1964 blch = None
1965
1966 class Addition:
1967 noise = more_noise = a = bc = None
1968 bluchin = None
1969
1970 class SubstitutionOverElimination:
1971 blach = None
1972 bluc = None
1973
1974 class SubstitutionOverAddition:
1975 blach = None
1976 bluchi = None
1977
1978 class EliminationOverAddition:
1979 blucha = None
1980 bluc = None
1981
Pablo Galindo7a041162021-04-19 23:35:53 +01001982 for cls, suggestion in [(Substitution, "'blech'?"),
1983 (Elimination, "'blch'?"),
1984 (Addition, "'bluchin'?"),
1985 (EliminationOverAddition, "'bluc'?"),
1986 (SubstitutionOverElimination, "'blach'?"),
1987 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001988 try:
1989 cls().bluch
1990 except AttributeError as exc:
1991 with support.captured_stderr() as err:
1992 sys.__excepthook__(*sys.exc_info())
1993
1994 self.assertIn(suggestion, err.getvalue())
1995
1996 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1997 class A:
1998 blech = None
1999
2000 try:
2001 A().somethingverywrong
2002 except AttributeError as exc:
2003 with support.captured_stderr() as err:
2004 sys.__excepthook__(*sys.exc_info())
2005
2006 self.assertNotIn("blech", err.getvalue())
2007
Dennis Sweeney284c52d2021-04-26 20:22:27 -04002008 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
2009 class MyClass:
2010 vvv = mom = w = id = pytho = None
2011
2012 with self.subTest(name="b"):
2013 try:
2014 MyClass.b
2015 except AttributeError as exc:
2016 with support.captured_stderr() as err:
2017 sys.__excepthook__(*sys.exc_info())
2018 self.assertNotIn("you mean", err.getvalue())
2019 self.assertNotIn("vvv", err.getvalue())
2020 self.assertNotIn("mom", err.getvalue())
2021 self.assertNotIn("'id'", err.getvalue())
2022 self.assertNotIn("'w'", err.getvalue())
2023 self.assertNotIn("'pytho'", err.getvalue())
2024
2025 with self.subTest(name="v"):
2026 try:
2027 MyClass.v
2028 except AttributeError as exc:
2029 with support.captured_stderr() as err:
2030 sys.__excepthook__(*sys.exc_info())
2031 self.assertNotIn("you mean", err.getvalue())
2032 self.assertNotIn("vvv", err.getvalue())
2033 self.assertNotIn("mom", err.getvalue())
2034 self.assertNotIn("'id'", err.getvalue())
2035 self.assertNotIn("'w'", err.getvalue())
2036 self.assertNotIn("'pytho'", err.getvalue())
2037
2038 with self.subTest(name="m"):
2039 try:
2040 MyClass.m
2041 except AttributeError as exc:
2042 with support.captured_stderr() as err:
2043 sys.__excepthook__(*sys.exc_info())
2044 self.assertNotIn("you mean", err.getvalue())
2045 self.assertNotIn("vvv", err.getvalue())
2046 self.assertNotIn("mom", err.getvalue())
2047 self.assertNotIn("'id'", err.getvalue())
2048 self.assertNotIn("'w'", err.getvalue())
2049 self.assertNotIn("'pytho'", err.getvalue())
2050
2051 with self.subTest(name="py"):
2052 try:
2053 MyClass.py
2054 except AttributeError as exc:
2055 with support.captured_stderr() as err:
2056 sys.__excepthook__(*sys.exc_info())
2057 self.assertNotIn("you mean", err.getvalue())
2058 self.assertNotIn("vvv", err.getvalue())
2059 self.assertNotIn("mom", err.getvalue())
2060 self.assertNotIn("'id'", err.getvalue())
2061 self.assertNotIn("'w'", err.getvalue())
2062 self.assertNotIn("'pytho'", err.getvalue())
2063
2064
Pablo Galindo37494b42021-04-14 02:36:07 +01002065 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
2066 class A:
2067 blech = None
2068 # A class with a very big __dict__ will not be consider
2069 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04002070 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01002071 setattr(A, f"index_{index}", None)
2072
2073 try:
2074 A().bluch
2075 except AttributeError as exc:
2076 with support.captured_stderr() as err:
2077 sys.__excepthook__(*sys.exc_info())
2078
2079 self.assertNotIn("blech", err.getvalue())
2080
2081 def test_getattr_suggestions_no_args(self):
2082 class A:
2083 blech = None
2084 def __getattr__(self, attr):
2085 raise AttributeError()
2086
2087 try:
2088 A().bluch
2089 except AttributeError as exc:
2090 with support.captured_stderr() as err:
2091 sys.__excepthook__(*sys.exc_info())
2092
2093 self.assertIn("blech", err.getvalue())
2094
2095 class A:
2096 blech = None
2097 def __getattr__(self, attr):
2098 raise AttributeError
2099
2100 try:
2101 A().bluch
2102 except AttributeError as exc:
2103 with support.captured_stderr() as err:
2104 sys.__excepthook__(*sys.exc_info())
2105
2106 self.assertIn("blech", err.getvalue())
2107
2108 def test_getattr_suggestions_invalid_args(self):
2109 class NonStringifyClass:
2110 __str__ = None
2111 __repr__ = None
2112
2113 class A:
2114 blech = None
2115 def __getattr__(self, attr):
2116 raise AttributeError(NonStringifyClass())
2117
2118 class B:
2119 blech = None
2120 def __getattr__(self, attr):
2121 raise AttributeError("Error", 23)
2122
2123 class C:
2124 blech = None
2125 def __getattr__(self, attr):
2126 raise AttributeError(23)
2127
2128 for cls in [A, B, C]:
2129 try:
2130 cls().bluch
2131 except AttributeError as exc:
2132 with support.captured_stderr() as err:
2133 sys.__excepthook__(*sys.exc_info())
2134
2135 self.assertIn("blech", err.getvalue())
2136
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07002137 def test_getattr_suggestions_for_same_name(self):
2138 class A:
2139 def __dir__(self):
2140 return ['blech']
2141 try:
2142 A().blech
2143 except AttributeError as exc:
2144 with support.captured_stderr() as err:
2145 sys.__excepthook__(*sys.exc_info())
2146
2147 self.assertNotIn("Did you mean", err.getvalue())
2148
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01002149 def test_attribute_error_with_failing_dict(self):
2150 class T:
2151 bluch = 1
2152 def __dir__(self):
2153 raise AttributeError("oh no!")
2154
2155 try:
2156 T().blich
2157 except AttributeError as exc:
2158 with support.captured_stderr() as err:
2159 sys.__excepthook__(*sys.exc_info())
2160
2161 self.assertNotIn("blech", err.getvalue())
2162 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01002163
Pablo Galindo0b1c1692021-04-17 23:28:45 +01002164 def test_attribute_error_with_bad_name(self):
2165 try:
2166 raise AttributeError(name=12, obj=23)
2167 except AttributeError as exc:
2168 with support.captured_stderr() as err:
2169 sys.__excepthook__(*sys.exc_info())
2170
2171 self.assertNotIn("?", err.getvalue())
2172
2173
Brett Cannon79ec55e2012-04-12 20:24:54 -04002174class ImportErrorTests(unittest.TestCase):
2175
2176 def test_attributes(self):
2177 # Setting 'name' and 'path' should not be a problem.
2178 exc = ImportError('test')
2179 self.assertIsNone(exc.name)
2180 self.assertIsNone(exc.path)
2181
2182 exc = ImportError('test', name='somemodule')
2183 self.assertEqual(exc.name, 'somemodule')
2184 self.assertIsNone(exc.path)
2185
2186 exc = ImportError('test', path='somepath')
2187 self.assertEqual(exc.path, 'somepath')
2188 self.assertIsNone(exc.name)
2189
2190 exc = ImportError('test', path='somepath', name='somename')
2191 self.assertEqual(exc.name, 'somename')
2192 self.assertEqual(exc.path, 'somepath')
2193
Michael Seifert64c8f702017-04-09 09:47:12 +02002194 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002195 with self.assertRaisesRegex(TypeError, msg):
2196 ImportError('test', invalid='keyword')
2197
2198 with self.assertRaisesRegex(TypeError, msg):
2199 ImportError('test', name='name', invalid='keyword')
2200
2201 with self.assertRaisesRegex(TypeError, msg):
2202 ImportError('test', path='path', invalid='keyword')
2203
2204 with self.assertRaisesRegex(TypeError, msg):
2205 ImportError(invalid='keyword')
2206
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002207 with self.assertRaisesRegex(TypeError, msg):
2208 ImportError('test', invalid='keyword', another=True)
2209
Serhiy Storchakae9e44482016-09-28 07:53:32 +03002210 def test_reset_attributes(self):
2211 exc = ImportError('test', name='name', path='path')
2212 self.assertEqual(exc.args, ('test',))
2213 self.assertEqual(exc.msg, 'test')
2214 self.assertEqual(exc.name, 'name')
2215 self.assertEqual(exc.path, 'path')
2216
2217 # Reset not specified attributes
2218 exc.__init__()
2219 self.assertEqual(exc.args, ())
2220 self.assertEqual(exc.msg, None)
2221 self.assertEqual(exc.name, None)
2222 self.assertEqual(exc.path, None)
2223
Brett Cannon07c6e712012-08-24 13:05:09 -04002224 def test_non_str_argument(self):
2225 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002226 with check_warnings(('', BytesWarning), quiet=True):
2227 arg = b'abc'
2228 exc = ImportError(arg)
2229 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002230
Serhiy Storchakab7853962017-04-08 09:55:07 +03002231 def test_copy_pickle(self):
2232 for kwargs in (dict(),
2233 dict(name='somename'),
2234 dict(path='somepath'),
2235 dict(name='somename', path='somepath')):
2236 orig = ImportError('test', **kwargs)
2237 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2238 exc = pickle.loads(pickle.dumps(orig, proto))
2239 self.assertEqual(exc.args, ('test',))
2240 self.assertEqual(exc.msg, 'test')
2241 self.assertEqual(exc.name, orig.name)
2242 self.assertEqual(exc.path, orig.path)
2243 for c in copy.copy, copy.deepcopy:
2244 exc = c(orig)
2245 self.assertEqual(exc.args, ('test',))
2246 self.assertEqual(exc.msg, 'test')
2247 self.assertEqual(exc.name, orig.name)
2248 self.assertEqual(exc.path, orig.path)
2249
Pablo Galindoa77aac42021-04-23 14:27:05 +01002250class SyntaxErrorTests(unittest.TestCase):
2251 def test_range_of_offsets(self):
2252 cases = [
2253 # Basic range from 2->7
2254 (("bad.py", 1, 2, "abcdefg", 1, 7),
2255 dedent(
2256 """
2257 File "bad.py", line 1
2258 abcdefg
2259 ^^^^^
2260 SyntaxError: bad bad
2261 """)),
2262 # end_offset = start_offset + 1
2263 (("bad.py", 1, 2, "abcdefg", 1, 3),
2264 dedent(
2265 """
2266 File "bad.py", line 1
2267 abcdefg
2268 ^
2269 SyntaxError: bad bad
2270 """)),
2271 # Negative end offset
2272 (("bad.py", 1, 2, "abcdefg", 1, -2),
2273 dedent(
2274 """
2275 File "bad.py", line 1
2276 abcdefg
2277 ^
2278 SyntaxError: bad bad
2279 """)),
2280 # end offset before starting offset
2281 (("bad.py", 1, 4, "abcdefg", 1, 2),
2282 dedent(
2283 """
2284 File "bad.py", line 1
2285 abcdefg
2286 ^
2287 SyntaxError: bad bad
2288 """)),
2289 # Both offsets negative
2290 (("bad.py", 1, -4, "abcdefg", 1, -2),
2291 dedent(
2292 """
2293 File "bad.py", line 1
2294 abcdefg
2295 SyntaxError: bad bad
2296 """)),
2297 # Both offsets negative and the end more negative
2298 (("bad.py", 1, -4, "abcdefg", 1, -5),
2299 dedent(
2300 """
2301 File "bad.py", line 1
2302 abcdefg
2303 SyntaxError: bad bad
2304 """)),
2305 # Both offsets 0
2306 (("bad.py", 1, 0, "abcdefg", 1, 0),
2307 dedent(
2308 """
2309 File "bad.py", line 1
2310 abcdefg
2311 SyntaxError: bad bad
2312 """)),
2313 # Start offset 0 and end offset not 0
2314 (("bad.py", 1, 0, "abcdefg", 1, 5),
2315 dedent(
2316 """
2317 File "bad.py", line 1
2318 abcdefg
2319 SyntaxError: bad bad
2320 """)),
Christian Clausscfca4a62021-10-07 17:49:47 +02002321 # End offset pass the source length
Pablo Galindoa77aac42021-04-23 14:27:05 +01002322 (("bad.py", 1, 2, "abcdefg", 1, 100),
2323 dedent(
2324 """
2325 File "bad.py", line 1
2326 abcdefg
2327 ^^^^^^
2328 SyntaxError: bad bad
2329 """)),
2330 ]
2331 for args, expected in cases:
2332 with self.subTest(args=args):
2333 try:
2334 raise SyntaxError("bad bad", args)
2335 except SyntaxError as exc:
2336 with support.captured_stderr() as err:
2337 sys.__excepthook__(*sys.exc_info())
Miss Islington (bot)c800e392021-09-21 15:38:59 -07002338 self.assertIn(expected, err.getvalue())
Pablo Galindoa77aac42021-04-23 14:27:05 +01002339 the_exception = exc
2340
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002341 def test_encodings(self):
2342 source = (
2343 '# -*- coding: cp437 -*-\n'
2344 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2345 )
2346 try:
2347 with open(TESTFN, 'w', encoding='cp437') as testfile:
2348 testfile.write(source)
2349 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2350 err = err.decode('utf-8').splitlines()
2351
2352 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2353 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2354 finally:
2355 unlink(TESTFN)
2356
Łukasz Langa904af3d2021-11-20 16:34:56 +01002357 # Check backwards tokenizer errors
2358 source = '# -*- coding: ascii -*-\n\n(\n'
2359 try:
2360 with open(TESTFN, 'w', encoding='ascii') as testfile:
2361 testfile.write(source)
2362 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2363 err = err.decode('utf-8').splitlines()
2364
2365 self.assertEqual(err[-3], ' (')
2366 self.assertEqual(err[-2], ' ^')
2367 finally:
2368 unlink(TESTFN)
2369
Pablo Galindoa77aac42021-04-23 14:27:05 +01002370 def test_attributes_new_constructor(self):
2371 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2372 the_exception = SyntaxError("bad bad", args)
2373 filename, lineno, offset, error, end_lineno, end_offset = args
2374 self.assertEqual(filename, the_exception.filename)
2375 self.assertEqual(lineno, the_exception.lineno)
2376 self.assertEqual(end_lineno, the_exception.end_lineno)
2377 self.assertEqual(offset, the_exception.offset)
2378 self.assertEqual(end_offset, the_exception.end_offset)
2379 self.assertEqual(error, the_exception.text)
2380 self.assertEqual("bad bad", the_exception.msg)
2381
2382 def test_attributes_old_constructor(self):
2383 args = ("bad.py", 1, 2, "abcdefg")
2384 the_exception = SyntaxError("bad bad", args)
2385 filename, lineno, offset, error = args
2386 self.assertEqual(filename, the_exception.filename)
2387 self.assertEqual(lineno, the_exception.lineno)
2388 self.assertEqual(None, the_exception.end_lineno)
2389 self.assertEqual(offset, the_exception.offset)
2390 self.assertEqual(None, the_exception.end_offset)
2391 self.assertEqual(error, the_exception.text)
2392 self.assertEqual("bad bad", the_exception.msg)
2393
2394 def test_incorrect_constructor(self):
2395 args = ("bad.py", 1, 2)
2396 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2397
2398 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2399 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2400
2401 args = ("bad.py", 1, 2, "abcdefg", 1)
2402 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2403
Brett Cannon79ec55e2012-04-12 20:24:54 -04002404
Mark Shannonbf353f32020-12-17 13:55:28 +00002405class PEP626Tests(unittest.TestCase):
2406
Mark Shannon0b6b2862021-06-24 13:09:14 +01002407 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002408 try:
2409 f()
2410 except Exception as ex:
2411 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002412 else:
2413 self.fail("No exception raised")
2414 lines = []
2415 t = t.tb_next # Skip this function
2416 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002417 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002418 lines.append(
2419 None if frame.f_lineno is None else
2420 frame.f_lineno-frame.f_code.co_firstlineno
2421 )
2422 t = t.tb_next
2423 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002424
2425 def test_lineno_after_raise_simple(self):
2426 def simple():
2427 1/0
2428 pass
2429 self.lineno_after_raise(simple, 1)
2430
2431 def test_lineno_after_raise_in_except(self):
2432 def in_except():
2433 try:
2434 1/0
2435 except:
2436 1/0
2437 pass
2438 self.lineno_after_raise(in_except, 4)
2439
2440 def test_lineno_after_other_except(self):
2441 def other_except():
2442 try:
2443 1/0
2444 except TypeError as ex:
2445 pass
2446 self.lineno_after_raise(other_except, 3)
2447
2448 def test_lineno_in_named_except(self):
2449 def in_named_except():
2450 try:
2451 1/0
2452 except Exception as ex:
2453 1/0
2454 pass
2455 self.lineno_after_raise(in_named_except, 4)
2456
2457 def test_lineno_in_try(self):
2458 def in_try():
2459 try:
2460 1/0
2461 finally:
2462 pass
2463 self.lineno_after_raise(in_try, 4)
2464
2465 def test_lineno_in_finally_normal(self):
2466 def in_finally_normal():
2467 try:
2468 pass
2469 finally:
2470 1/0
2471 pass
2472 self.lineno_after_raise(in_finally_normal, 4)
2473
2474 def test_lineno_in_finally_except(self):
2475 def in_finally_except():
2476 try:
2477 1/0
2478 finally:
2479 1/0
2480 pass
2481 self.lineno_after_raise(in_finally_except, 4)
2482
2483 def test_lineno_after_with(self):
2484 class Noop:
2485 def __enter__(self):
2486 return self
2487 def __exit__(self, *args):
2488 pass
2489 def after_with():
2490 with Noop():
2491 1/0
2492 pass
2493 self.lineno_after_raise(after_with, 2)
2494
Mark Shannon088a15c2021-04-29 19:28:50 +01002495 def test_missing_lineno_shows_as_none(self):
2496 def f():
2497 1/0
2498 self.lineno_after_raise(f, 1)
2499 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2500 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002501
Mark Shannon0b6b2862021-06-24 13:09:14 +01002502 def test_lineno_after_raise_in_with_exit(self):
2503 class ExitFails:
2504 def __enter__(self):
2505 return self
2506 def __exit__(self, *args):
2507 raise ValueError
2508
2509 def after_with():
2510 with ExitFails():
2511 1/0
2512 self.lineno_after_raise(after_with, 1, 1)
2513
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002514if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002515 unittest.main()