blob: cc0640dda09802ee6fbd1993d6b3cb4b2231d39e [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
Miss Islington (bot)438817f2021-12-11 17:24:12 -0800271 check('x = [(yield i) for i in range(3)]', 1, 7)
272 check('def f():\n from _ import *', 2, 17)
273 check('def f(x, x):\n pass', 1, 10)
274 check('{i for i in range(5) if (j := 0) for j in range(5)}', 1, 38)
Ammar Askar025eb982018-09-24 17:12:49 -0400275 check('def f(x):\n nonlocal x', 2, 3)
276 check('def f(x):\n x = 1\n global x', 3, 3)
277 check('nonlocal x', 1, 1)
278 check('def f():\n global x\n nonlocal x', 2, 3)
279
Ammar Askar025eb982018-09-24 17:12:49 -0400280 # Errors thrown by future.c
281 check('from __future__ import doesnt_exist', 1, 1)
282 check('from __future__ import braces', 1, 1)
283 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100284 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300285 check('def f():\n x, y: int', 2, 3)
286 check('[*x for x in xs]', 1, 2)
287 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300288 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100289 check('(yield i) = 2', 1, 2)
290 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200291
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000292 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000293 def testSettingException(self):
294 # test that setting an exception at the C level works even if the
295 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000296
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000297 class BadException(Exception):
298 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000299 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000300
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000301 class InvalidException:
302 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000303
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000304 def test_capi1():
305 import _testcapi
306 try:
307 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000308 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000309 exc, err, tb = sys.exc_info()
310 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000311 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000312 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000313 else:
314 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000315
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000316 def test_capi2():
317 import _testcapi
318 try:
319 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000320 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000321 exc, err, tb = sys.exc_info()
322 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000323 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000324 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000325 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000326 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000327 else:
328 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000329
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000330 def test_capi3():
331 import _testcapi
332 self.assertRaises(SystemError, _testcapi.raise_exception,
333 InvalidException, 1)
334
335 if not sys.platform.startswith('java'):
336 test_capi1()
337 test_capi2()
338 test_capi3()
339
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 def test_WindowsError(self):
341 try:
342 WindowsError
343 except NameError:
344 pass
345 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200346 self.assertIs(WindowsError, OSError)
347 self.assertEqual(str(OSError(1001)), "1001")
348 self.assertEqual(str(OSError(1001, "message")),
349 "[Errno 1001] message")
350 # POSIX errno (9 aka EBADF) is untranslated
351 w = OSError(9, 'foo', 'bar')
352 self.assertEqual(w.errno, 9)
353 self.assertEqual(w.winerror, None)
354 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
355 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
356 w = OSError(0, 'foo', 'bar', 3)
357 self.assertEqual(w.errno, 2)
358 self.assertEqual(w.winerror, 3)
359 self.assertEqual(w.strerror, 'foo')
360 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000361 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100362 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200363 # Unknown win error becomes EINVAL (22)
364 w = OSError(0, 'foo', None, 1001)
365 self.assertEqual(w.errno, 22)
366 self.assertEqual(w.winerror, 1001)
367 self.assertEqual(w.strerror, 'foo')
368 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000369 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100370 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200371 # Non-numeric "errno"
372 w = OSError('bar', 'foo')
373 self.assertEqual(w.errno, 'bar')
374 self.assertEqual(w.winerror, None)
375 self.assertEqual(w.strerror, 'foo')
376 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000377 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378
Victor Stinnerd223fa62015-04-02 14:17:38 +0200379 @unittest.skipUnless(sys.platform == 'win32',
380 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300381 def test_windows_message(self):
382 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200383 ctypes = import_module('ctypes')
384 # this error code has no message, Python formats it as hexadecimal
385 code = 3765269347
386 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
387 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300388
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000389 def testAttributes(self):
390 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000391
392 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000393 (BaseException, (), {'args' : ()}),
394 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000395 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000396 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000397 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000398 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000399 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000400 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200401 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000402 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000403 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200404 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000405 {'args' : ('foo', 'bar'),
406 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000407 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200408 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000409 {'args' : ('foo', 'bar'),
410 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000411 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800412 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
413 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200414 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000415 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000416 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
417 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200418 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000419 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000420 'strerror' : 'strErrorStr',
421 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000422 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000423 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100424 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000425 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000426 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000427 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100428 'filename' : None, 'lineno' : None, 'offset' : None,
429 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000430 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100431 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000432 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000433 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100434 'offsetStr', 'textStr',
435 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000436 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100437 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
438 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000439 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100440 'textStr', 'endLinenoStr', 'endOffsetStr',
441 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000442 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000443 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100444 'textStr', 'endLinenoStr', 'endOffsetStr',
445 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000446 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100447 'filename' : None, 'lineno' : None, 'offset' : None,
448 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000449 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000450 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
451 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000452 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000454 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000455 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000456 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000457 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000458 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000459 'ordinal not in range'),
460 'encoding' : 'ascii', 'object' : b'\xff',
461 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000462 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
463 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000464 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000466 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000467 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000468 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000469 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000470 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000471 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100472 (NaiveException, ('foo',),
473 {'args': ('foo',), 'x': 'foo'}),
474 (SlottedNaiveException, ('foo',),
475 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000476 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000477 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200478 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000479 exceptionList.append(
480 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000481 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200482 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000483 'errno' : 1,
484 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000485 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000486 except NameError:
487 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000488
Guido van Rossumebe3e162007-05-17 18:20:34 +0000489 for exc, args, expected in exceptionList:
490 try:
491 e = exc(*args)
492 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000493 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100494 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000495 else:
496 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100497 if not type(e).__name__.endswith('NaiveException'):
498 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000499 # Verify no ref leaks in Exc_str()
500 s = str(e)
501 for checkArgName in expected:
502 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000503 self.assertEqual(repr(value),
504 repr(expected[checkArgName]),
505 '%r.%s == %r, expected %r' % (
506 e, checkArgName,
507 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000508
Guido van Rossumebe3e162007-05-17 18:20:34 +0000509 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000510 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000511 for protocol in range(p.HIGHEST_PROTOCOL + 1):
512 s = p.dumps(e, protocol)
513 new = p.loads(s)
514 for checkArgName in expected:
515 got = repr(getattr(new, checkArgName))
516 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000517 self.assertEqual(got, want,
518 'pickled "%r", attribute "%s' %
519 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000520
Collin Winter828f04a2007-08-31 00:04:24 +0000521 def testWithTraceback(self):
522 try:
523 raise IndexError(4)
524 except:
525 tb = sys.exc_info()[2]
526
527 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000528 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000529 self.assertEqual(e.__traceback__, tb)
530
531 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000532 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000533 self.assertEqual(e.__traceback__, tb)
534
535 class MyException(Exception):
536 pass
537
538 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000539 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000540 self.assertEqual(e.__traceback__, tb)
541
542 def testInvalidTraceback(self):
543 try:
544 Exception().__traceback__ = 5
545 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000546 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000547 else:
548 self.fail("No exception raised")
549
Georg Brandlab6f2f62009-03-31 04:16:10 +0000550 def testInvalidAttrs(self):
551 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
552 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
553 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
554 self.assertRaises(TypeError, delattr, Exception(), '__context__')
555
Collin Winter828f04a2007-08-31 00:04:24 +0000556 def testNoneClearsTracebackAttr(self):
557 try:
558 raise IndexError(4)
559 except:
560 tb = sys.exc_info()[2]
561
562 e = Exception()
563 e.__traceback__ = tb
564 e.__traceback__ = None
565 self.assertEqual(e.__traceback__, None)
566
567 def testChainingAttrs(self):
568 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000569 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700570 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000571
572 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000573 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700574 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000575
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200576 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000577 pass
578
579 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000580 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700581 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000582
583 def testChainingDescriptors(self):
584 try:
585 raise Exception()
586 except Exception as exc:
587 e = exc
588
589 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700590 self.assertIsNone(e.__cause__)
591 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000592
593 e.__context__ = NameError()
594 e.__cause__ = None
595 self.assertIsInstance(e.__context__, NameError)
596 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700597 self.assertTrue(e.__suppress_context__)
598 e.__suppress_context__ = False
599 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000600
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000601 def testKeywordArgs(self):
602 # test that builtin exception don't take keyword args,
603 # but user-defined subclasses can if they want
604 self.assertRaises(TypeError, BaseException, a=1)
605
606 class DerivedException(BaseException):
607 def __init__(self, fancy_arg):
608 BaseException.__init__(self)
609 self.fancy_arg = fancy_arg
610
611 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000612 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000613
Brett Cannon31f59292011-02-21 19:29:56 +0000614 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000615 def testInfiniteRecursion(self):
616 def f():
617 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400618 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619
620 def g():
621 try:
622 return g()
623 except ValueError:
624 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400625 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000626
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000627 def test_str(self):
628 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000629 self.assertTrue(str(Exception))
630 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000631 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000632
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000633 def testExceptionCleanupNames(self):
634 # Make sure the local variable bound to the exception instance by
635 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000636 try:
637 raise Exception()
638 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000639 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000640 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000641 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000642
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000643 def testExceptionCleanupState(self):
644 # Make sure exception state is cleaned up as soon as the except
645 # block is left. See #2507
646
647 class MyException(Exception):
648 def __init__(self, obj):
649 self.obj = obj
650 class MyObj:
651 pass
652
653 def inner_raising_func():
654 # Create some references in exception value and traceback
655 local_ref = obj
656 raise MyException(obj)
657
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000658 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000659 obj = MyObj()
660 wr = weakref.ref(obj)
661 try:
662 inner_raising_func()
663 except MyException as e:
664 pass
665 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300666 gc_collect() # For PyPy or other GCs.
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000667 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300668 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000669
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000670 # Qualified "except" without "as"
671 obj = MyObj()
672 wr = weakref.ref(obj)
673 try:
674 inner_raising_func()
675 except MyException:
676 pass
677 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300678 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000679 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300680 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000681
682 # Bare "except"
683 obj = MyObj()
684 wr = weakref.ref(obj)
685 try:
686 inner_raising_func()
687 except:
688 pass
689 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300690 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000691 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300692 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000693
694 # "except" with premature block leave
695 obj = MyObj()
696 wr = weakref.ref(obj)
697 for i in [0]:
698 try:
699 inner_raising_func()
700 except:
701 break
702 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300703 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000704 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300705 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000706
707 # "except" block raising another exception
708 obj = MyObj()
709 wr = weakref.ref(obj)
710 try:
711 try:
712 inner_raising_func()
713 except:
714 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000715 except KeyError as e:
716 # We want to test that the except block above got rid of
717 # the exception raised in inner_raising_func(), but it
718 # also ends up in the __context__ of the KeyError, so we
719 # must clear the latter manually for our test to succeed.
720 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000721 obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300722 gc_collect() # For PyPy or other GCs.
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000723 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800724 # guarantee no ref cycles on CPython (don't gc_collect)
725 if check_impl_detail(cpython=False):
726 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300727 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000728
729 # Some complicated construct
730 obj = MyObj()
731 wr = weakref.ref(obj)
732 try:
733 inner_raising_func()
734 except MyException:
735 try:
736 try:
737 raise
738 finally:
739 raise
740 except MyException:
741 pass
742 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800743 if check_impl_detail(cpython=False):
744 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000745 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300746 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000747
748 # Inside an exception-silencing "with" block
749 class Context:
750 def __enter__(self):
751 return self
752 def __exit__ (self, exc_type, exc_value, exc_tb):
753 return True
754 obj = MyObj()
755 wr = weakref.ref(obj)
756 with Context():
757 inner_raising_func()
758 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800759 if check_impl_detail(cpython=False):
760 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000761 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300762 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000763
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000764 def test_exception_target_in_nested_scope(self):
765 # issue 4617: This used to raise a SyntaxError
766 # "can not delete variable 'e' referenced in nested scope"
767 def print_error():
768 e
769 try:
770 something
771 except Exception as e:
772 print_error()
773 # implicit "del e" here
774
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000775 def test_generator_leaking(self):
776 # Test that generator exception state doesn't leak into the calling
777 # frame
778 def yield_raise():
779 try:
780 raise KeyError("caught")
781 except KeyError:
782 yield sys.exc_info()[0]
783 yield sys.exc_info()[0]
784 yield sys.exc_info()[0]
785 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000786 self.assertEqual(next(g), KeyError)
787 self.assertEqual(sys.exc_info()[0], None)
788 self.assertEqual(next(g), KeyError)
789 self.assertEqual(sys.exc_info()[0], None)
790 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000791
792 # Same test, but inside an exception handler
793 try:
794 raise TypeError("foo")
795 except TypeError:
796 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000797 self.assertEqual(next(g), KeyError)
798 self.assertEqual(sys.exc_info()[0], TypeError)
799 self.assertEqual(next(g), KeyError)
800 self.assertEqual(sys.exc_info()[0], TypeError)
801 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000802 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000803 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000804
Benjamin Peterson83195c32011-07-03 13:44:00 -0500805 def test_generator_leaking2(self):
806 # See issue 12475.
807 def g():
808 yield
809 try:
810 raise RuntimeError
811 except RuntimeError:
812 it = g()
813 next(it)
814 try:
815 next(it)
816 except StopIteration:
817 pass
818 self.assertEqual(sys.exc_info(), (None, None, None))
819
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100820 def test_generator_leaking3(self):
821 # See issue #23353. When gen.throw() is called, the caller's
822 # exception state should be save and restored.
823 def g():
824 try:
825 yield
826 except ZeroDivisionError:
827 yield sys.exc_info()[1]
828 it = g()
829 next(it)
830 try:
831 1/0
832 except ZeroDivisionError as e:
833 self.assertIs(sys.exc_info()[1], e)
834 gen_exc = it.throw(e)
835 self.assertIs(sys.exc_info()[1], e)
836 self.assertIs(gen_exc, e)
837 self.assertEqual(sys.exc_info(), (None, None, None))
838
839 def test_generator_leaking4(self):
840 # See issue #23353. When an exception is raised by a generator,
841 # the caller's exception state should still be restored.
842 def g():
843 try:
844 1/0
845 except ZeroDivisionError:
846 yield sys.exc_info()[0]
847 raise
848 it = g()
849 try:
850 raise TypeError
851 except TypeError:
852 # The caller's exception state (TypeError) is temporarily
853 # saved in the generator.
854 tp = next(it)
855 self.assertIs(tp, ZeroDivisionError)
856 try:
857 next(it)
858 # We can't check it immediately, but while next() returns
859 # with an exception, it shouldn't have restored the old
860 # exception state (TypeError).
861 except ZeroDivisionError as e:
862 self.assertIs(sys.exc_info()[1], e)
863 # We used to find TypeError here.
864 self.assertEqual(sys.exc_info(), (None, None, None))
865
Benjamin Petersonac913412011-07-03 16:25:11 -0500866 def test_generator_doesnt_retain_old_exc(self):
867 def g():
868 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
869 yield
870 self.assertEqual(sys.exc_info(), (None, None, None))
871 it = g()
872 try:
873 raise RuntimeError
874 except RuntimeError:
875 next(it)
876 self.assertRaises(StopIteration, next, it)
877
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000878 def test_generator_finalizing_and_exc_info(self):
879 # See #7173
880 def simple_gen():
881 yield 1
882 def run_gen():
883 gen = simple_gen()
884 try:
885 raise RuntimeError
886 except RuntimeError:
887 return next(gen)
888 run_gen()
889 gc_collect()
890 self.assertEqual(sys.exc_info(), (None, None, None))
891
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200892 def _check_generator_cleanup_exc_state(self, testfunc):
893 # Issue #12791: exception state is cleaned up as soon as a generator
894 # is closed (reference cycles are broken).
895 class MyException(Exception):
896 def __init__(self, obj):
897 self.obj = obj
898 class MyObj:
899 pass
900
901 def raising_gen():
902 try:
903 raise MyException(obj)
904 except MyException:
905 yield
906
907 obj = MyObj()
908 wr = weakref.ref(obj)
909 g = raising_gen()
910 next(g)
911 testfunc(g)
912 g = obj = None
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300913 gc_collect() # For PyPy or other GCs.
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200914 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300915 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200916
917 def test_generator_throw_cleanup_exc_state(self):
918 def do_throw(g):
919 try:
920 g.throw(RuntimeError())
921 except RuntimeError:
922 pass
923 self._check_generator_cleanup_exc_state(do_throw)
924
925 def test_generator_close_cleanup_exc_state(self):
926 def do_close(g):
927 g.close()
928 self._check_generator_cleanup_exc_state(do_close)
929
930 def test_generator_del_cleanup_exc_state(self):
931 def do_del(g):
932 g = None
933 self._check_generator_cleanup_exc_state(do_del)
934
935 def test_generator_next_cleanup_exc_state(self):
936 def do_next(g):
937 try:
938 next(g)
939 except StopIteration:
940 pass
941 else:
942 self.fail("should have raised StopIteration")
943 self._check_generator_cleanup_exc_state(do_next)
944
945 def test_generator_send_cleanup_exc_state(self):
946 def do_send(g):
947 try:
948 g.send(None)
949 except StopIteration:
950 pass
951 else:
952 self.fail("should have raised StopIteration")
953 self._check_generator_cleanup_exc_state(do_send)
954
Benjamin Peterson27d63672008-06-15 20:09:12 +0000955 def test_3114(self):
956 # Bug #3114: in its destructor, MyObject retrieves a pointer to
957 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000958 class MyObject:
959 def __del__(self):
960 nonlocal e
961 e = sys.exc_info()
962 e = ()
963 try:
964 raise Exception(MyObject())
965 except:
966 pass
Serhiy Storchaka462c1f02021-09-08 18:08:57 +0300967 gc_collect() # For PyPy or other GCs.
Ezio Melottib3aedd42010-11-20 19:04:17 +0000968 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000969
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -0700970 def test_raise_does_not_create_context_chain_cycle(self):
971 class A(Exception):
972 pass
973 class B(Exception):
974 pass
975 class C(Exception):
976 pass
977
978 # Create a context chain:
979 # C -> B -> A
980 # Then raise A in context of C.
981 try:
982 try:
983 raise A
984 except A as a_:
985 a = a_
986 try:
987 raise B
988 except B as b_:
989 b = b_
990 try:
991 raise C
992 except C as c_:
993 c = c_
994 self.assertIsInstance(a, A)
995 self.assertIsInstance(b, B)
996 self.assertIsInstance(c, C)
997 self.assertIsNone(a.__context__)
998 self.assertIs(b.__context__, a)
999 self.assertIs(c.__context__, b)
1000 raise a
1001 except A as e:
1002 exc = e
1003
1004 # Expect A -> C -> B, without cycle
1005 self.assertIs(exc, a)
1006 self.assertIs(a.__context__, c)
1007 self.assertIs(c.__context__, b)
1008 self.assertIsNone(b.__context__)
1009
1010 def test_no_hang_on_context_chain_cycle1(self):
1011 # See issue 25782. Cycle in context chain.
1012
1013 def cycle():
1014 try:
1015 raise ValueError(1)
1016 except ValueError as ex:
1017 ex.__context__ = ex
1018 raise TypeError(2)
1019
1020 try:
1021 cycle()
1022 except Exception as e:
1023 exc = e
1024
1025 self.assertIsInstance(exc, TypeError)
1026 self.assertIsInstance(exc.__context__, ValueError)
1027 self.assertIs(exc.__context__.__context__, exc.__context__)
1028
Miss Islington (bot)19604092021-08-16 02:01:14 -07001029 @unittest.skip("See issue 44895")
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -07001030 def test_no_hang_on_context_chain_cycle2(self):
1031 # See issue 25782. Cycle at head of context chain.
1032
1033 class A(Exception):
1034 pass
1035 class B(Exception):
1036 pass
1037 class C(Exception):
1038 pass
1039
1040 # Context cycle:
1041 # +-----------+
1042 # V |
1043 # C --> B --> A
1044 with self.assertRaises(C) as cm:
1045 try:
1046 raise A()
1047 except A as _a:
1048 a = _a
1049 try:
1050 raise B()
1051 except B as _b:
1052 b = _b
1053 try:
1054 raise C()
1055 except C as _c:
1056 c = _c
1057 a.__context__ = c
1058 raise c
1059
1060 self.assertIs(cm.exception, c)
1061 # Verify the expected context chain cycle
1062 self.assertIs(c.__context__, b)
1063 self.assertIs(b.__context__, a)
1064 self.assertIs(a.__context__, c)
1065
1066 def test_no_hang_on_context_chain_cycle3(self):
1067 # See issue 25782. Longer context chain with cycle.
1068
1069 class A(Exception):
1070 pass
1071 class B(Exception):
1072 pass
1073 class C(Exception):
1074 pass
1075 class D(Exception):
1076 pass
1077 class E(Exception):
1078 pass
1079
1080 # Context cycle:
1081 # +-----------+
1082 # V |
1083 # E --> D --> C --> B --> A
1084 with self.assertRaises(E) as cm:
1085 try:
1086 raise A()
1087 except A as _a:
1088 a = _a
1089 try:
1090 raise B()
1091 except B as _b:
1092 b = _b
1093 try:
1094 raise C()
1095 except C as _c:
1096 c = _c
1097 a.__context__ = c
1098 try:
1099 raise D()
1100 except D as _d:
1101 d = _d
1102 e = E()
1103 raise e
1104
1105 self.assertIs(cm.exception, e)
1106 # Verify the expected context chain cycle
1107 self.assertIs(e.__context__, d)
1108 self.assertIs(d.__context__, c)
1109 self.assertIs(c.__context__, b)
1110 self.assertIs(b.__context__, a)
1111 self.assertIs(a.__context__, c)
1112
Benjamin Peterson24dfb052014-04-02 12:05:35 -04001113 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +00001114 # See issue 7309. This was a crasher.
1115
1116 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
1117 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
1118 u.end = 2
1119 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
1120 u.end = 5
1121 u.reason = 0x345345345345345345
1122 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
1123 u.encoding = 4000
1124 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
1125 u.start = 1000
1126 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
1127
1128 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
1129 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
1130 u.end = 2
1131 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
1132 u.end = 5
1133 u.reason = 0x345345345345345345
1134 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
1135 u.encoding = 4000
1136 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
1137 u.start = 1000
1138 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
1139
1140 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
1141 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
1142 u.end = 2
1143 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
1144 u.end = 5
1145 u.reason = 0x345345345345345345
1146 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
1147 u.start = 1000
1148 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +00001149
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001150 def test_unicode_errors_no_object(self):
1151 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -04001152 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001153 for klass in klasses:
1154 self.assertEqual(str(klass.__new__(klass)), "")
1155
Brett Cannon31f59292011-02-21 19:29:56 +00001156 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001157 def test_badisinstance(self):
1158 # Bug #2542: if issubclass(e, MyException) raises an exception,
1159 # it should be ignored
1160 class Meta(type):
1161 def __subclasscheck__(cls, subclass):
1162 raise ValueError()
1163 class MyException(Exception, metaclass=Meta):
1164 pass
1165
Martin Panter3263f682016-02-28 03:16:11 +00001166 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001167 try:
1168 raise KeyError()
1169 except MyException as e:
1170 self.fail("exception should not be a MyException")
1171 except KeyError:
1172 pass
1173 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001174 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001175 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001176 self.fail("Should have raised KeyError")
1177
1178 def g():
1179 try:
1180 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001181 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001182 return sys.exc_info()
1183 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001184 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001185 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001186
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001187
1188 @cpython_only
Benjamin Petersonef36dfe2021-08-13 02:45:13 -07001189 def test_trashcan_recursion(self):
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001190 # See bpo-33930
1191
1192 def foo():
1193 o = object()
1194 for x in range(1_000_000):
1195 # Create a big chain of method objects that will trigger
1196 # a deep chain of calls when they need to be destructed.
1197 o = o.__dir__
1198
1199 foo()
1200 support.gc_collect()
1201
xdegaye56d1f5c2017-10-26 15:09:06 +02001202 @cpython_only
1203 def test_recursion_normalizing_exception(self):
1204 # Issue #22898.
1205 # Test that a RecursionError is raised when tstate->recursion_depth is
1206 # equal to recursion_limit in PyErr_NormalizeException() and check
1207 # that a ResourceWarning is printed.
1208 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001209 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001210 # singleton was being used in that case, that held traceback data and
1211 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1212 # finalization of these locals.
1213 code = """if 1:
1214 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001215 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001216
1217 class MyException(Exception): pass
1218
1219 def setrecursionlimit(depth):
1220 while 1:
1221 try:
1222 sys.setrecursionlimit(depth)
1223 return depth
1224 except RecursionError:
1225 # sys.setrecursionlimit() raises a RecursionError if
1226 # the new recursion limit is too low (issue #25274).
1227 depth += 1
1228
1229 def recurse(cnt):
1230 cnt -= 1
1231 if cnt:
1232 recurse(cnt)
1233 else:
1234 generator.throw(MyException)
1235
1236 def gen():
1237 f = open(%a, mode='rb', buffering=0)
1238 yield
1239
1240 generator = gen()
1241 next(generator)
1242 recursionlimit = sys.getrecursionlimit()
1243 depth = get_recursion_depth()
1244 try:
1245 # Upon the last recursive invocation of recurse(),
1246 # tstate->recursion_depth is equal to (recursion_limit - 1)
1247 # and is equal to recursion_limit when _gen_throw() calls
1248 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001249 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001250 finally:
1251 sys.setrecursionlimit(recursionlimit)
1252 print('Done.')
1253 """ % __file__
1254 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1255 # Check that the program does not fail with SIGABRT.
1256 self.assertEqual(rc, 1)
1257 self.assertIn(b'RecursionError', err)
1258 self.assertIn(b'ResourceWarning', err)
1259 self.assertIn(b'Done.', out)
1260
1261 @cpython_only
1262 def test_recursion_normalizing_infinite_exception(self):
1263 # Issue #30697. Test that a RecursionError is raised when
1264 # PyErr_NormalizeException() maximum recursion depth has been
1265 # exceeded.
1266 code = """if 1:
1267 import _testcapi
1268 try:
1269 raise _testcapi.RecursingInfinitelyError
1270 finally:
1271 print('Done.')
1272 """
1273 rc, out, err = script_helper.assert_python_failure("-c", code)
1274 self.assertEqual(rc, 1)
1275 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1276 b'while normalizing an exception', err)
1277 self.assertIn(b'Done.', out)
1278
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001279
1280 def test_recursion_in_except_handler(self):
1281
1282 def set_relative_recursion_limit(n):
1283 depth = 1
1284 while True:
1285 try:
1286 sys.setrecursionlimit(depth)
1287 except RecursionError:
1288 depth += 1
1289 else:
1290 break
1291 sys.setrecursionlimit(depth+n)
1292
1293 def recurse_in_except():
1294 try:
1295 1/0
1296 except:
1297 recurse_in_except()
1298
1299 def recurse_after_except():
1300 try:
1301 1/0
1302 except:
1303 pass
1304 recurse_after_except()
1305
1306 def recurse_in_body_and_except():
1307 try:
1308 recurse_in_body_and_except()
1309 except:
1310 recurse_in_body_and_except()
1311
1312 recursionlimit = sys.getrecursionlimit()
1313 try:
1314 set_relative_recursion_limit(10)
1315 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1316 with self.subTest(func=func):
1317 try:
1318 func()
1319 except RecursionError:
1320 pass
1321 else:
1322 self.fail("Should have raised a RecursionError")
1323 finally:
1324 sys.setrecursionlimit(recursionlimit)
1325
1326
xdegaye56d1f5c2017-10-26 15:09:06 +02001327 @cpython_only
1328 def test_recursion_normalizing_with_no_memory(self):
1329 # Issue #30697. Test that in the abort that occurs when there is no
1330 # memory left and the size of the Python frames stack is greater than
1331 # the size of the list of preallocated MemoryError instances, the
1332 # Fatal Python error message mentions MemoryError.
1333 code = """if 1:
1334 import _testcapi
1335 class C(): pass
1336 def recurse(cnt):
1337 cnt -= 1
1338 if cnt:
1339 recurse(cnt)
1340 else:
1341 _testcapi.set_nomemory(0)
1342 C()
1343 recurse(16)
1344 """
1345 with SuppressCrashReport():
1346 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001347 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1348 b'Cannot recover from MemoryErrors while '
1349 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001350
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001351 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001352 def test_MemoryError(self):
1353 # PyErr_NoMemory always raises the same exception instance.
1354 # Check that the traceback is not doubled.
1355 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001356 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001357 def raiseMemError():
1358 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001359 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001360 except MemoryError as e:
1361 tb = e.__traceback__
1362 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001363 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001364 return traceback.format_tb(tb)
1365
1366 tb1 = raiseMemError()
1367 tb2 = raiseMemError()
1368 self.assertEqual(tb1, tb2)
1369
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001370 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001371 def test_exception_with_doc(self):
1372 import _testcapi
1373 doc2 = "This is a test docstring."
1374 doc4 = "This is another test docstring."
1375
1376 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1377 "error1")
1378
1379 # test basic usage of PyErr_NewException
1380 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1381 self.assertIs(type(error1), type)
1382 self.assertTrue(issubclass(error1, Exception))
1383 self.assertIsNone(error1.__doc__)
1384
1385 # test with given docstring
1386 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1387 self.assertEqual(error2.__doc__, doc2)
1388
1389 # test with explicit base (without docstring)
1390 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1391 base=error2)
1392 self.assertTrue(issubclass(error3, error2))
1393
1394 # test with explicit base tuple
1395 class C(object):
1396 pass
1397 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1398 (error3, C))
1399 self.assertTrue(issubclass(error4, error3))
1400 self.assertTrue(issubclass(error4, C))
1401 self.assertEqual(error4.__doc__, doc4)
1402
1403 # test with explicit dictionary
1404 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1405 error4, {'a': 1})
1406 self.assertTrue(issubclass(error5, error4))
1407 self.assertEqual(error5.a, 1)
1408 self.assertEqual(error5.__doc__, "")
1409
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001410 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001411 def test_memory_error_cleanup(self):
1412 # Issue #5437: preallocated MemoryError instances should not keep
1413 # traceback objects alive.
1414 from _testcapi import raise_memoryerror
1415 class C:
1416 pass
1417 wr = None
1418 def inner():
1419 nonlocal wr
1420 c = C()
1421 wr = weakref.ref(c)
1422 raise_memoryerror()
1423 # We cannot use assertRaises since it manually deletes the traceback
1424 try:
1425 inner()
1426 except MemoryError as e:
1427 self.assertNotEqual(wr(), None)
1428 else:
1429 self.fail("MemoryError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001430 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001431 self.assertEqual(wr(), None)
1432
Brett Cannon31f59292011-02-21 19:29:56 +00001433 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001434 def test_recursion_error_cleanup(self):
1435 # Same test as above, but with "recursion exceeded" errors
1436 class C:
1437 pass
1438 wr = None
1439 def inner():
1440 nonlocal wr
1441 c = C()
1442 wr = weakref.ref(c)
1443 inner()
1444 # We cannot use assertRaises since it manually deletes the traceback
1445 try:
1446 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001447 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001448 self.assertNotEqual(wr(), None)
1449 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001450 self.fail("RecursionError not raised")
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001451 gc_collect() # For PyPy or other GCs.
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001452 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001453
Antoine Pitroua7622852011-09-01 21:37:43 +02001454 def test_errno_ENOTDIR(self):
1455 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1456 with self.assertRaises(OSError) as cm:
1457 os.listdir(__file__)
1458 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1459
Martin Panter3263f682016-02-28 03:16:11 +00001460 def test_unraisable(self):
1461 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1462 class BrokenDel:
1463 def __del__(self):
1464 exc = ValueError("del is broken")
1465 # The following line is included in the traceback report:
1466 raise exc
1467
Victor Stinnere4d300e2019-05-22 23:44:02 +02001468 obj = BrokenDel()
1469 with support.catch_unraisable_exception() as cm:
1470 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001471
Serhiy Storchaka462c1f02021-09-08 18:08:57 +03001472 gc_collect() # For PyPy or other GCs.
Victor Stinnere4d300e2019-05-22 23:44:02 +02001473 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1474 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001475
1476 def test_unhandled(self):
1477 # Check for sensible reporting of unhandled exceptions
1478 for exc_type in (ValueError, BrokenStrException):
1479 with self.subTest(exc_type):
1480 try:
1481 exc = exc_type("test message")
1482 # The following line is included in the traceback report:
1483 raise exc
1484 except exc_type:
1485 with captured_stderr() as stderr:
1486 sys.__excepthook__(*sys.exc_info())
1487 report = stderr.getvalue()
1488 self.assertIn("test_exceptions.py", report)
1489 self.assertIn("raise exc", report)
1490 self.assertIn(exc_type.__name__, report)
1491 if exc_type is BrokenStrException:
1492 self.assertIn("<exception str() failed>", report)
1493 else:
1494 self.assertIn("test message", report)
1495 self.assertTrue(report.endswith("\n"))
1496
xdegaye66caacf2017-10-23 18:08:41 +02001497 @cpython_only
1498 def test_memory_error_in_PyErr_PrintEx(self):
1499 code = """if 1:
1500 import _testcapi
1501 class C(): pass
1502 _testcapi.set_nomemory(0, %d)
1503 C()
1504 """
1505
1506 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1507 # Span a large range of tests as the CPython code always evolves with
1508 # changes that add or remove memory allocations.
1509 for i in range(1, 20):
1510 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1511 self.assertIn(rc, (1, 120))
1512 self.assertIn(b'MemoryError', err)
1513
Mark Shannonae3087c2017-10-22 22:41:51 +01001514 def test_yield_in_nested_try_excepts(self):
1515 #Issue #25612
1516 class MainError(Exception):
1517 pass
1518
1519 class SubError(Exception):
1520 pass
1521
1522 def main():
1523 try:
1524 raise MainError()
1525 except MainError:
1526 try:
1527 yield
1528 except SubError:
1529 pass
1530 raise
1531
1532 coro = main()
1533 coro.send(None)
1534 with self.assertRaises(MainError):
1535 coro.throw(SubError())
1536
1537 def test_generator_doesnt_retain_old_exc2(self):
1538 #Issue 28884#msg282532
1539 def g():
1540 try:
1541 raise ValueError
1542 except ValueError:
1543 yield 1
1544 self.assertEqual(sys.exc_info(), (None, None, None))
1545 yield 2
1546
1547 gen = g()
1548
1549 try:
1550 raise IndexError
1551 except IndexError:
1552 self.assertEqual(next(gen), 1)
1553 self.assertEqual(next(gen), 2)
1554
1555 def test_raise_in_generator(self):
1556 #Issue 25612#msg304117
1557 def g():
1558 yield 1
1559 raise
1560 yield 2
1561
1562 with self.assertRaises(ZeroDivisionError):
1563 i = g()
1564 try:
1565 1/0
1566 except:
1567 next(i)
1568 next(i)
1569
Zackery Spytzce6a0702019-08-25 03:44:09 -06001570 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1571 def test_assert_shadowing(self):
1572 # Shadowing AssertionError would cause the assert statement to
1573 # misbehave.
1574 global AssertionError
1575 AssertionError = TypeError
1576 try:
1577 assert False, 'hello'
1578 except BaseException as e:
1579 del AssertionError
1580 self.assertIsInstance(e, AssertionError)
1581 self.assertEqual(str(e), 'hello')
1582 else:
1583 del AssertionError
1584 self.fail('Expected exception')
1585
Pablo Galindo9b648a92020-09-01 19:39:46 +01001586 def test_memory_error_subclasses(self):
1587 # bpo-41654: MemoryError instances use a freelist of objects that are
1588 # linked using the 'dict' attribute when they are inactive/dead.
1589 # Subclasses of MemoryError should not participate in the freelist
1590 # schema. This test creates a MemoryError object and keeps it alive
1591 # (therefore advancing the freelist) and then it creates and destroys a
1592 # subclass object. Finally, it checks that creating a new MemoryError
1593 # succeeds, proving that the freelist is not corrupted.
1594
1595 class TestException(MemoryError):
1596 pass
1597
1598 try:
1599 raise MemoryError
1600 except MemoryError as exc:
1601 inst = exc
1602
1603 try:
1604 raise TestException
1605 except Exception:
1606 pass
1607
1608 for _ in range(10):
1609 try:
1610 raise MemoryError
1611 except MemoryError as exc:
1612 pass
1613
1614 gc_collect()
1615
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001616global_for_suggestions = None
1617
1618class NameErrorTests(unittest.TestCase):
1619 def test_name_error_has_name(self):
1620 try:
1621 bluch
1622 except NameError as exc:
1623 self.assertEqual("bluch", exc.name)
1624
1625 def test_name_error_suggestions(self):
1626 def Substitution():
1627 noise = more_noise = a = bc = None
1628 blech = None
1629 print(bluch)
1630
1631 def Elimination():
1632 noise = more_noise = a = bc = None
1633 blch = None
1634 print(bluch)
1635
1636 def Addition():
1637 noise = more_noise = a = bc = None
1638 bluchin = None
1639 print(bluch)
1640
1641 def SubstitutionOverElimination():
1642 blach = None
1643 bluc = None
1644 print(bluch)
1645
1646 def SubstitutionOverAddition():
1647 blach = None
1648 bluchi = None
1649 print(bluch)
1650
1651 def EliminationOverAddition():
1652 blucha = None
1653 bluc = None
1654 print(bluch)
1655
Pablo Galindo7a041162021-04-19 23:35:53 +01001656 for func, suggestion in [(Substitution, "'blech'?"),
1657 (Elimination, "'blch'?"),
1658 (Addition, "'bluchin'?"),
1659 (EliminationOverAddition, "'blucha'?"),
1660 (SubstitutionOverElimination, "'blach'?"),
1661 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001662 err = None
1663 try:
1664 func()
1665 except NameError as exc:
1666 with support.captured_stderr() as err:
1667 sys.__excepthook__(*sys.exc_info())
1668 self.assertIn(suggestion, err.getvalue())
1669
1670 def test_name_error_suggestions_from_globals(self):
1671 def func():
1672 print(global_for_suggestio)
1673 try:
1674 func()
1675 except NameError as exc:
1676 with support.captured_stderr() as err:
1677 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001678 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001679
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001680 def test_name_error_suggestions_from_builtins(self):
1681 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001682 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001683 try:
1684 func()
1685 except NameError as exc:
1686 with support.captured_stderr() as err:
1687 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001688 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001689
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001690 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1691 def f():
1692 somethingverywronghehehehehehe = None
1693 print(somethingverywronghe)
1694
1695 try:
1696 f()
1697 except NameError as exc:
1698 with support.captured_stderr() as err:
1699 sys.__excepthook__(*sys.exc_info())
1700
1701 self.assertNotIn("somethingverywronghehe", err.getvalue())
1702
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001703 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1704 vvv = mom = w = id = pytho = None
1705
1706 with self.subTest(name="b"):
1707 try:
1708 b
1709 except NameError as exc:
1710 with support.captured_stderr() as err:
1711 sys.__excepthook__(*sys.exc_info())
1712 self.assertNotIn("you mean", err.getvalue())
1713 self.assertNotIn("vvv", err.getvalue())
1714 self.assertNotIn("mom", err.getvalue())
1715 self.assertNotIn("'id'", err.getvalue())
1716 self.assertNotIn("'w'", err.getvalue())
1717 self.assertNotIn("'pytho'", err.getvalue())
1718
1719 with self.subTest(name="v"):
1720 try:
1721 v
1722 except NameError as exc:
1723 with support.captured_stderr() as err:
1724 sys.__excepthook__(*sys.exc_info())
1725 self.assertNotIn("you mean", err.getvalue())
1726 self.assertNotIn("vvv", err.getvalue())
1727 self.assertNotIn("mom", err.getvalue())
1728 self.assertNotIn("'id'", err.getvalue())
1729 self.assertNotIn("'w'", err.getvalue())
1730 self.assertNotIn("'pytho'", err.getvalue())
1731
1732 with self.subTest(name="m"):
1733 try:
1734 m
1735 except NameError as exc:
1736 with support.captured_stderr() as err:
1737 sys.__excepthook__(*sys.exc_info())
1738 self.assertNotIn("you mean", err.getvalue())
1739 self.assertNotIn("vvv", err.getvalue())
1740 self.assertNotIn("mom", err.getvalue())
1741 self.assertNotIn("'id'", err.getvalue())
1742 self.assertNotIn("'w'", err.getvalue())
1743 self.assertNotIn("'pytho'", err.getvalue())
1744
1745 with self.subTest(name="py"):
1746 try:
1747 py
1748 except NameError as exc:
1749 with support.captured_stderr() as err:
1750 sys.__excepthook__(*sys.exc_info())
1751 self.assertNotIn("you mean", err.getvalue())
1752 self.assertNotIn("vvv", err.getvalue())
1753 self.assertNotIn("mom", err.getvalue())
1754 self.assertNotIn("'id'", err.getvalue())
1755 self.assertNotIn("'w'", err.getvalue())
1756 self.assertNotIn("'pytho'", err.getvalue())
1757
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001758 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001759 def f():
1760 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001761 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1762 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1763 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1764 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1765 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1766 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1767 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1768 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1769 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1770 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1771 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1772 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1773 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1774 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1775 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1776 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1777 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1778 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1779 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1780 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1781 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1782 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1783 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1784 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1785 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1786 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1787 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1788 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1789 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1790 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1791 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1792 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1793 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1794 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1795 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1796 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1797 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1798 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1799 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1800 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1801 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1802 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1803 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1804 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1805 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1806 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1807 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1808 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1809 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1810 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1811 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1812 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1813 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1814 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1815 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1816 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1817 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1818 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1819 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1820 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1821 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1822 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1823 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1824 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1825 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1826 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1827 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1828 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1829 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1830 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1831 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1832 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1833 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1834 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1835 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1836 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1837 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1838 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1839 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1840 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1841 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001842 print(a0)
1843
1844 try:
1845 f()
1846 except NameError as exc:
1847 with support.captured_stderr() as err:
1848 sys.__excepthook__(*sys.exc_info())
1849
Miss Islington (bot)d55bf812021-10-07 05:11:38 -07001850 self.assertNotRegex(err.getvalue(), r"NameError.*a1")
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001851
1852 def test_name_error_with_custom_exceptions(self):
1853 def f():
1854 blech = None
1855 raise NameError()
1856
1857 try:
1858 f()
1859 except NameError as exc:
1860 with support.captured_stderr() as err:
1861 sys.__excepthook__(*sys.exc_info())
1862
1863 self.assertNotIn("blech", err.getvalue())
1864
1865 def f():
1866 blech = None
1867 raise NameError
1868
1869 try:
1870 f()
1871 except NameError as exc:
1872 with support.captured_stderr() as err:
1873 sys.__excepthook__(*sys.exc_info())
1874
1875 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001876
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001877 def test_unbound_local_error_doesn_not_match(self):
1878 def foo():
1879 something = 3
1880 print(somethong)
1881 somethong = 3
1882
1883 try:
1884 foo()
1885 except UnboundLocalError as exc:
1886 with support.captured_stderr() as err:
1887 sys.__excepthook__(*sys.exc_info())
1888
1889 self.assertNotIn("something", err.getvalue())
1890
Łukasz Langa8eabe602021-11-18 01:28:04 +01001891 def test_issue45826(self):
1892 # regression test for bpo-45826
1893 def f():
1894 with self.assertRaisesRegex(NameError, 'aaa'):
1895 aab
1896
1897 try:
1898 f()
1899 except self.failureException:
1900 with support.captured_stderr() as err:
1901 sys.__excepthook__(*sys.exc_info())
1902
1903 self.assertIn("aab", err.getvalue())
1904
1905 def test_issue45826_focused(self):
1906 def f():
1907 try:
1908 nonsense
1909 except BaseException as E:
1910 E.with_traceback(None)
1911 raise ZeroDivisionError()
1912
1913 try:
1914 f()
1915 except ZeroDivisionError:
1916 with support.captured_stderr() as err:
1917 sys.__excepthook__(*sys.exc_info())
1918
1919 self.assertIn("nonsense", err.getvalue())
1920 self.assertIn("ZeroDivisionError", err.getvalue())
1921
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001922
Pablo Galindo37494b42021-04-14 02:36:07 +01001923class AttributeErrorTests(unittest.TestCase):
1924 def test_attributes(self):
1925 # Setting 'attr' should not be a problem.
1926 exc = AttributeError('Ouch!')
1927 self.assertIsNone(exc.name)
1928 self.assertIsNone(exc.obj)
1929
1930 sentinel = object()
1931 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1932 self.assertEqual(exc.name, 'carry')
1933 self.assertIs(exc.obj, sentinel)
1934
1935 def test_getattr_has_name_and_obj(self):
1936 class A:
1937 blech = None
1938
1939 obj = A()
1940 try:
1941 obj.bluch
1942 except AttributeError as exc:
1943 self.assertEqual("bluch", exc.name)
1944 self.assertEqual(obj, exc.obj)
1945
1946 def test_getattr_has_name_and_obj_for_method(self):
1947 class A:
1948 def blech(self):
1949 return
1950
1951 obj = A()
1952 try:
1953 obj.bluch()
1954 except AttributeError as exc:
1955 self.assertEqual("bluch", exc.name)
1956 self.assertEqual(obj, exc.obj)
1957
1958 def test_getattr_suggestions(self):
1959 class Substitution:
1960 noise = more_noise = a = bc = None
1961 blech = None
1962
1963 class Elimination:
1964 noise = more_noise = a = bc = None
1965 blch = None
1966
1967 class Addition:
1968 noise = more_noise = a = bc = None
1969 bluchin = None
1970
1971 class SubstitutionOverElimination:
1972 blach = None
1973 bluc = None
1974
1975 class SubstitutionOverAddition:
1976 blach = None
1977 bluchi = None
1978
1979 class EliminationOverAddition:
1980 blucha = None
1981 bluc = None
1982
Pablo Galindo7a041162021-04-19 23:35:53 +01001983 for cls, suggestion in [(Substitution, "'blech'?"),
1984 (Elimination, "'blch'?"),
1985 (Addition, "'bluchin'?"),
1986 (EliminationOverAddition, "'bluc'?"),
1987 (SubstitutionOverElimination, "'blach'?"),
1988 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001989 try:
1990 cls().bluch
1991 except AttributeError as exc:
1992 with support.captured_stderr() as err:
1993 sys.__excepthook__(*sys.exc_info())
1994
1995 self.assertIn(suggestion, err.getvalue())
1996
1997 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1998 class A:
1999 blech = None
2000
2001 try:
2002 A().somethingverywrong
2003 except AttributeError as exc:
2004 with support.captured_stderr() as err:
2005 sys.__excepthook__(*sys.exc_info())
2006
2007 self.assertNotIn("blech", err.getvalue())
2008
Dennis Sweeney284c52d2021-04-26 20:22:27 -04002009 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
2010 class MyClass:
2011 vvv = mom = w = id = pytho = None
2012
2013 with self.subTest(name="b"):
2014 try:
2015 MyClass.b
2016 except AttributeError as exc:
2017 with support.captured_stderr() as err:
2018 sys.__excepthook__(*sys.exc_info())
2019 self.assertNotIn("you mean", err.getvalue())
2020 self.assertNotIn("vvv", err.getvalue())
2021 self.assertNotIn("mom", err.getvalue())
2022 self.assertNotIn("'id'", err.getvalue())
2023 self.assertNotIn("'w'", err.getvalue())
2024 self.assertNotIn("'pytho'", err.getvalue())
2025
2026 with self.subTest(name="v"):
2027 try:
2028 MyClass.v
2029 except AttributeError as exc:
2030 with support.captured_stderr() as err:
2031 sys.__excepthook__(*sys.exc_info())
2032 self.assertNotIn("you mean", err.getvalue())
2033 self.assertNotIn("vvv", err.getvalue())
2034 self.assertNotIn("mom", err.getvalue())
2035 self.assertNotIn("'id'", err.getvalue())
2036 self.assertNotIn("'w'", err.getvalue())
2037 self.assertNotIn("'pytho'", err.getvalue())
2038
2039 with self.subTest(name="m"):
2040 try:
2041 MyClass.m
2042 except AttributeError as exc:
2043 with support.captured_stderr() as err:
2044 sys.__excepthook__(*sys.exc_info())
2045 self.assertNotIn("you mean", err.getvalue())
2046 self.assertNotIn("vvv", err.getvalue())
2047 self.assertNotIn("mom", err.getvalue())
2048 self.assertNotIn("'id'", err.getvalue())
2049 self.assertNotIn("'w'", err.getvalue())
2050 self.assertNotIn("'pytho'", err.getvalue())
2051
2052 with self.subTest(name="py"):
2053 try:
2054 MyClass.py
2055 except AttributeError as exc:
2056 with support.captured_stderr() as err:
2057 sys.__excepthook__(*sys.exc_info())
2058 self.assertNotIn("you mean", err.getvalue())
2059 self.assertNotIn("vvv", err.getvalue())
2060 self.assertNotIn("mom", err.getvalue())
2061 self.assertNotIn("'id'", err.getvalue())
2062 self.assertNotIn("'w'", err.getvalue())
2063 self.assertNotIn("'pytho'", err.getvalue())
2064
2065
Pablo Galindo37494b42021-04-14 02:36:07 +01002066 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
2067 class A:
2068 blech = None
2069 # A class with a very big __dict__ will not be consider
2070 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04002071 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01002072 setattr(A, f"index_{index}", None)
2073
2074 try:
2075 A().bluch
2076 except AttributeError as exc:
2077 with support.captured_stderr() as err:
2078 sys.__excepthook__(*sys.exc_info())
2079
2080 self.assertNotIn("blech", err.getvalue())
2081
2082 def test_getattr_suggestions_no_args(self):
2083 class A:
2084 blech = None
2085 def __getattr__(self, attr):
2086 raise AttributeError()
2087
2088 try:
2089 A().bluch
2090 except AttributeError as exc:
2091 with support.captured_stderr() as err:
2092 sys.__excepthook__(*sys.exc_info())
2093
2094 self.assertIn("blech", err.getvalue())
2095
2096 class A:
2097 blech = None
2098 def __getattr__(self, attr):
2099 raise AttributeError
2100
2101 try:
2102 A().bluch
2103 except AttributeError as exc:
2104 with support.captured_stderr() as err:
2105 sys.__excepthook__(*sys.exc_info())
2106
2107 self.assertIn("blech", err.getvalue())
2108
2109 def test_getattr_suggestions_invalid_args(self):
2110 class NonStringifyClass:
2111 __str__ = None
2112 __repr__ = None
2113
2114 class A:
2115 blech = None
2116 def __getattr__(self, attr):
2117 raise AttributeError(NonStringifyClass())
2118
2119 class B:
2120 blech = None
2121 def __getattr__(self, attr):
2122 raise AttributeError("Error", 23)
2123
2124 class C:
2125 blech = None
2126 def __getattr__(self, attr):
2127 raise AttributeError(23)
2128
2129 for cls in [A, B, C]:
2130 try:
2131 cls().bluch
2132 except AttributeError as exc:
2133 with support.captured_stderr() as err:
2134 sys.__excepthook__(*sys.exc_info())
2135
2136 self.assertIn("blech", err.getvalue())
2137
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07002138 def test_getattr_suggestions_for_same_name(self):
2139 class A:
2140 def __dir__(self):
2141 return ['blech']
2142 try:
2143 A().blech
2144 except AttributeError as exc:
2145 with support.captured_stderr() as err:
2146 sys.__excepthook__(*sys.exc_info())
2147
2148 self.assertNotIn("Did you mean", err.getvalue())
2149
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01002150 def test_attribute_error_with_failing_dict(self):
2151 class T:
2152 bluch = 1
2153 def __dir__(self):
2154 raise AttributeError("oh no!")
2155
2156 try:
2157 T().blich
2158 except AttributeError as exc:
2159 with support.captured_stderr() as err:
2160 sys.__excepthook__(*sys.exc_info())
2161
2162 self.assertNotIn("blech", err.getvalue())
2163 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01002164
Pablo Galindo0b1c1692021-04-17 23:28:45 +01002165 def test_attribute_error_with_bad_name(self):
2166 try:
2167 raise AttributeError(name=12, obj=23)
2168 except AttributeError as exc:
2169 with support.captured_stderr() as err:
2170 sys.__excepthook__(*sys.exc_info())
2171
2172 self.assertNotIn("?", err.getvalue())
2173
2174
Brett Cannon79ec55e2012-04-12 20:24:54 -04002175class ImportErrorTests(unittest.TestCase):
2176
2177 def test_attributes(self):
2178 # Setting 'name' and 'path' should not be a problem.
2179 exc = ImportError('test')
2180 self.assertIsNone(exc.name)
2181 self.assertIsNone(exc.path)
2182
2183 exc = ImportError('test', name='somemodule')
2184 self.assertEqual(exc.name, 'somemodule')
2185 self.assertIsNone(exc.path)
2186
2187 exc = ImportError('test', path='somepath')
2188 self.assertEqual(exc.path, 'somepath')
2189 self.assertIsNone(exc.name)
2190
2191 exc = ImportError('test', path='somepath', name='somename')
2192 self.assertEqual(exc.name, 'somename')
2193 self.assertEqual(exc.path, 'somepath')
2194
Michael Seifert64c8f702017-04-09 09:47:12 +02002195 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002196 with self.assertRaisesRegex(TypeError, msg):
2197 ImportError('test', invalid='keyword')
2198
2199 with self.assertRaisesRegex(TypeError, msg):
2200 ImportError('test', name='name', invalid='keyword')
2201
2202 with self.assertRaisesRegex(TypeError, msg):
2203 ImportError('test', path='path', invalid='keyword')
2204
2205 with self.assertRaisesRegex(TypeError, msg):
2206 ImportError(invalid='keyword')
2207
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002208 with self.assertRaisesRegex(TypeError, msg):
2209 ImportError('test', invalid='keyword', another=True)
2210
Serhiy Storchakae9e44482016-09-28 07:53:32 +03002211 def test_reset_attributes(self):
2212 exc = ImportError('test', name='name', path='path')
2213 self.assertEqual(exc.args, ('test',))
2214 self.assertEqual(exc.msg, 'test')
2215 self.assertEqual(exc.name, 'name')
2216 self.assertEqual(exc.path, 'path')
2217
2218 # Reset not specified attributes
2219 exc.__init__()
2220 self.assertEqual(exc.args, ())
2221 self.assertEqual(exc.msg, None)
2222 self.assertEqual(exc.name, None)
2223 self.assertEqual(exc.path, None)
2224
Brett Cannon07c6e712012-08-24 13:05:09 -04002225 def test_non_str_argument(self):
2226 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002227 with check_warnings(('', BytesWarning), quiet=True):
2228 arg = b'abc'
2229 exc = ImportError(arg)
2230 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002231
Serhiy Storchakab7853962017-04-08 09:55:07 +03002232 def test_copy_pickle(self):
2233 for kwargs in (dict(),
2234 dict(name='somename'),
2235 dict(path='somepath'),
2236 dict(name='somename', path='somepath')):
2237 orig = ImportError('test', **kwargs)
2238 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2239 exc = pickle.loads(pickle.dumps(orig, proto))
2240 self.assertEqual(exc.args, ('test',))
2241 self.assertEqual(exc.msg, 'test')
2242 self.assertEqual(exc.name, orig.name)
2243 self.assertEqual(exc.path, orig.path)
2244 for c in copy.copy, copy.deepcopy:
2245 exc = c(orig)
2246 self.assertEqual(exc.args, ('test',))
2247 self.assertEqual(exc.msg, 'test')
2248 self.assertEqual(exc.name, orig.name)
2249 self.assertEqual(exc.path, orig.path)
2250
Pablo Galindoa77aac42021-04-23 14:27:05 +01002251class SyntaxErrorTests(unittest.TestCase):
2252 def test_range_of_offsets(self):
2253 cases = [
2254 # Basic range from 2->7
2255 (("bad.py", 1, 2, "abcdefg", 1, 7),
2256 dedent(
2257 """
2258 File "bad.py", line 1
2259 abcdefg
2260 ^^^^^
2261 SyntaxError: bad bad
2262 """)),
2263 # end_offset = start_offset + 1
2264 (("bad.py", 1, 2, "abcdefg", 1, 3),
2265 dedent(
2266 """
2267 File "bad.py", line 1
2268 abcdefg
2269 ^
2270 SyntaxError: bad bad
2271 """)),
2272 # Negative end offset
2273 (("bad.py", 1, 2, "abcdefg", 1, -2),
2274 dedent(
2275 """
2276 File "bad.py", line 1
2277 abcdefg
2278 ^
2279 SyntaxError: bad bad
2280 """)),
2281 # end offset before starting offset
2282 (("bad.py", 1, 4, "abcdefg", 1, 2),
2283 dedent(
2284 """
2285 File "bad.py", line 1
2286 abcdefg
2287 ^
2288 SyntaxError: bad bad
2289 """)),
2290 # Both offsets negative
2291 (("bad.py", 1, -4, "abcdefg", 1, -2),
2292 dedent(
2293 """
2294 File "bad.py", line 1
2295 abcdefg
2296 SyntaxError: bad bad
2297 """)),
2298 # Both offsets negative and the end more negative
2299 (("bad.py", 1, -4, "abcdefg", 1, -5),
2300 dedent(
2301 """
2302 File "bad.py", line 1
2303 abcdefg
2304 SyntaxError: bad bad
2305 """)),
2306 # Both offsets 0
2307 (("bad.py", 1, 0, "abcdefg", 1, 0),
2308 dedent(
2309 """
2310 File "bad.py", line 1
2311 abcdefg
2312 SyntaxError: bad bad
2313 """)),
2314 # Start offset 0 and end offset not 0
2315 (("bad.py", 1, 0, "abcdefg", 1, 5),
2316 dedent(
2317 """
2318 File "bad.py", line 1
2319 abcdefg
2320 SyntaxError: bad bad
2321 """)),
Christian Clausscfca4a62021-10-07 17:49:47 +02002322 # End offset pass the source length
Pablo Galindoa77aac42021-04-23 14:27:05 +01002323 (("bad.py", 1, 2, "abcdefg", 1, 100),
2324 dedent(
2325 """
2326 File "bad.py", line 1
2327 abcdefg
2328 ^^^^^^
2329 SyntaxError: bad bad
2330 """)),
2331 ]
2332 for args, expected in cases:
2333 with self.subTest(args=args):
2334 try:
2335 raise SyntaxError("bad bad", args)
2336 except SyntaxError as exc:
2337 with support.captured_stderr() as err:
2338 sys.__excepthook__(*sys.exc_info())
Miss Islington (bot)c800e392021-09-21 15:38:59 -07002339 self.assertIn(expected, err.getvalue())
Pablo Galindoa77aac42021-04-23 14:27:05 +01002340 the_exception = exc
2341
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002342 def test_encodings(self):
2343 source = (
2344 '# -*- coding: cp437 -*-\n'
2345 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2346 )
2347 try:
2348 with open(TESTFN, 'w', encoding='cp437') as testfile:
2349 testfile.write(source)
2350 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2351 err = err.decode('utf-8').splitlines()
2352
2353 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2354 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2355 finally:
2356 unlink(TESTFN)
2357
Łukasz Langa904af3d2021-11-20 16:34:56 +01002358 # Check backwards tokenizer errors
2359 source = '# -*- coding: ascii -*-\n\n(\n'
2360 try:
2361 with open(TESTFN, 'w', encoding='ascii') as testfile:
2362 testfile.write(source)
2363 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2364 err = err.decode('utf-8').splitlines()
2365
2366 self.assertEqual(err[-3], ' (')
2367 self.assertEqual(err[-2], ' ^')
2368 finally:
2369 unlink(TESTFN)
2370
Miss Islington (bot)94483f12021-12-12 08:52:49 -08002371 def test_non_utf8(self):
2372 # Check non utf-8 characters
2373 try:
2374 with open(TESTFN, 'bw') as testfile:
2375 testfile.write(b"\x89")
2376 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2377 err = err.decode('utf-8').splitlines()
2378
2379 self.assertIn("SyntaxError: Non-UTF-8 code starting with '\\x89' in file", err[-1])
2380 finally:
2381 unlink(TESTFN)
2382
Pablo Galindoa77aac42021-04-23 14:27:05 +01002383 def test_attributes_new_constructor(self):
2384 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2385 the_exception = SyntaxError("bad bad", args)
2386 filename, lineno, offset, error, end_lineno, end_offset = args
2387 self.assertEqual(filename, the_exception.filename)
2388 self.assertEqual(lineno, the_exception.lineno)
2389 self.assertEqual(end_lineno, the_exception.end_lineno)
2390 self.assertEqual(offset, the_exception.offset)
2391 self.assertEqual(end_offset, the_exception.end_offset)
2392 self.assertEqual(error, the_exception.text)
2393 self.assertEqual("bad bad", the_exception.msg)
2394
2395 def test_attributes_old_constructor(self):
2396 args = ("bad.py", 1, 2, "abcdefg")
2397 the_exception = SyntaxError("bad bad", args)
2398 filename, lineno, offset, error = args
2399 self.assertEqual(filename, the_exception.filename)
2400 self.assertEqual(lineno, the_exception.lineno)
2401 self.assertEqual(None, the_exception.end_lineno)
2402 self.assertEqual(offset, the_exception.offset)
2403 self.assertEqual(None, the_exception.end_offset)
2404 self.assertEqual(error, the_exception.text)
2405 self.assertEqual("bad bad", the_exception.msg)
2406
2407 def test_incorrect_constructor(self):
2408 args = ("bad.py", 1, 2)
2409 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2410
2411 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2412 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2413
2414 args = ("bad.py", 1, 2, "abcdefg", 1)
2415 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2416
Brett Cannon79ec55e2012-04-12 20:24:54 -04002417
Mark Shannonbf353f32020-12-17 13:55:28 +00002418class PEP626Tests(unittest.TestCase):
2419
Mark Shannon0b6b2862021-06-24 13:09:14 +01002420 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002421 try:
2422 f()
2423 except Exception as ex:
2424 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002425 else:
2426 self.fail("No exception raised")
2427 lines = []
2428 t = t.tb_next # Skip this function
2429 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002430 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002431 lines.append(
2432 None if frame.f_lineno is None else
2433 frame.f_lineno-frame.f_code.co_firstlineno
2434 )
2435 t = t.tb_next
2436 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002437
2438 def test_lineno_after_raise_simple(self):
2439 def simple():
2440 1/0
2441 pass
2442 self.lineno_after_raise(simple, 1)
2443
2444 def test_lineno_after_raise_in_except(self):
2445 def in_except():
2446 try:
2447 1/0
2448 except:
2449 1/0
2450 pass
2451 self.lineno_after_raise(in_except, 4)
2452
2453 def test_lineno_after_other_except(self):
2454 def other_except():
2455 try:
2456 1/0
2457 except TypeError as ex:
2458 pass
2459 self.lineno_after_raise(other_except, 3)
2460
2461 def test_lineno_in_named_except(self):
2462 def in_named_except():
2463 try:
2464 1/0
2465 except Exception as ex:
2466 1/0
2467 pass
2468 self.lineno_after_raise(in_named_except, 4)
2469
2470 def test_lineno_in_try(self):
2471 def in_try():
2472 try:
2473 1/0
2474 finally:
2475 pass
2476 self.lineno_after_raise(in_try, 4)
2477
2478 def test_lineno_in_finally_normal(self):
2479 def in_finally_normal():
2480 try:
2481 pass
2482 finally:
2483 1/0
2484 pass
2485 self.lineno_after_raise(in_finally_normal, 4)
2486
2487 def test_lineno_in_finally_except(self):
2488 def in_finally_except():
2489 try:
2490 1/0
2491 finally:
2492 1/0
2493 pass
2494 self.lineno_after_raise(in_finally_except, 4)
2495
2496 def test_lineno_after_with(self):
2497 class Noop:
2498 def __enter__(self):
2499 return self
2500 def __exit__(self, *args):
2501 pass
2502 def after_with():
2503 with Noop():
2504 1/0
2505 pass
2506 self.lineno_after_raise(after_with, 2)
2507
Mark Shannon088a15c2021-04-29 19:28:50 +01002508 def test_missing_lineno_shows_as_none(self):
2509 def f():
2510 1/0
2511 self.lineno_after_raise(f, 1)
2512 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2513 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002514
Mark Shannon0b6b2862021-06-24 13:09:14 +01002515 def test_lineno_after_raise_in_with_exit(self):
2516 class ExitFails:
2517 def __enter__(self):
2518 return self
2519 def __exit__(self, *args):
2520 raise ValueError
2521
2522 def after_with():
2523 with ExitFails():
2524 1/0
2525 self.lineno_after_raise(after_with, 1, 1)
2526
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002527if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002528 unittest.main()