blob: 520deb301ecf8ab1ba42d29377f842d5416c4327 [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)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200212
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300213 def testSyntaxErrorOffset(self):
214 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200215 check('def fact(x):\n\treturn x!\n', 2, 10)
216 check('1 +\n', 1, 4)
217 check('def spam():\n print(1)\n print(2)', 3, 10)
218 check('Python = "Python" +', 1, 20)
219 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200220 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
221 2, 19, encoding='cp1251')
222 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300223 check('x = "a', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400224 check('lambda x: x = 2', 1, 1)
Lysandros Nikolaou15acc4e2020-10-27 20:54:20 +0200225 check('f{a + b + c}', 1, 2)
Miss Islington (bot)756b7b92021-05-03 18:06:45 -0700226 check('[file for str(file) in []\n])', 2, 2)
Miss Islington (bot)933b5b62021-06-08 04:46:56 -0700227 check('a = « hello » « world »', 1, 5)
Lysandros Nikolaoue5fe5092021-01-14 23:36:30 +0200228 check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5)
229 check('[file for\n str(file) in []]', 2, 2)
Miss Islington (bot)07dba472021-05-21 08:29:58 -0700230 check("ages = {'Alice'=22, 'Bob'=23}", 1, 16)
Miss Islington (bot)f807a4f2021-06-09 14:45:43 -0700231 check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19)
Ammar Askar025eb982018-09-24 17:12:49 -0400232
233 # Errors thrown by compile.c
234 check('class foo:return 1', 1, 11)
235 check('def f():\n continue', 2, 3)
236 check('def f():\n break', 2, 3)
Mark Shannon8d4b1842021-05-06 13:38:50 +0100237 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 3, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400238
239 # Errors thrown by tokenizer.c
240 check('(0x+1)', 1, 3)
241 check('x = 0xI', 1, 6)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700242 check('0010 + 2', 1, 1)
Ammar Askar025eb982018-09-24 17:12:49 -0400243 check('x = 32e-+4', 1, 8)
Miss Islington (bot)2a722d42021-07-09 17:47:33 -0700244 check('x = 0o9', 1, 7)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200245 check('\u03b1 = 0xI', 1, 6)
246 check(b'\xce\xb1 = 0xI', 1, 6)
247 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
248 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100249 check(b"""if 1:
250 def foo():
251 '''
252
253 def bar():
254 pass
255
256 def baz():
257 '''quux'''
Batuhan Taskayaa698d522021-01-21 00:38:47 +0300258 """, 9, 24)
Pablo Galindobcc30362020-05-14 21:11:48 +0100259 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
260 check("(1+)", 1, 4)
Miss Islington (bot)1afaaf52021-05-15 10:39:18 -0700261 check("[interesting\nfoo()\n", 1, 1)
Miss Islington (bot)133cddf2021-06-14 10:07:52 -0700262 check(b"\xef\xbb\xbf#coding: utf8\nprint('\xe6\x88\x91')\n", 0, -1)
Ammar Askar025eb982018-09-24 17:12:49 -0400263
264 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200265 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400266 check('def f():\n from _ import *', 1, 1)
267 check('def f(x, x):\n pass', 1, 1)
268 check('def f(x):\n nonlocal x', 2, 3)
269 check('def f(x):\n x = 1\n global x', 3, 3)
270 check('nonlocal x', 1, 1)
271 check('def f():\n global x\n nonlocal x', 2, 3)
272
Ammar Askar025eb982018-09-24 17:12:49 -0400273 # Errors thrown by future.c
274 check('from __future__ import doesnt_exist', 1, 1)
275 check('from __future__ import braces', 1, 1)
276 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100277 check('foo(1=2)', 1, 5)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300278 check('def f():\n x, y: int', 2, 3)
279 check('[*x for x in xs]', 1, 2)
280 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300281 check('for 1 in []: pass', 1, 5)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100282 check('(yield i) = 2', 1, 2)
283 check('def f(*):\n pass', 1, 7)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200284
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000285 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000286 def testSettingException(self):
287 # test that setting an exception at the C level works even if the
288 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000289
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000290 class BadException(Exception):
291 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000292 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000293
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000294 class InvalidException:
295 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000296
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000297 def test_capi1():
298 import _testcapi
299 try:
300 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000301 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000302 exc, err, tb = sys.exc_info()
303 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000304 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000305 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000306 else:
307 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000308
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000309 def test_capi2():
310 import _testcapi
311 try:
312 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000313 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000314 exc, err, tb = sys.exc_info()
315 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000316 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000317 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000318 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000319 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000320 else:
321 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000322
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000323 def test_capi3():
324 import _testcapi
325 self.assertRaises(SystemError, _testcapi.raise_exception,
326 InvalidException, 1)
327
328 if not sys.platform.startswith('java'):
329 test_capi1()
330 test_capi2()
331 test_capi3()
332
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 def test_WindowsError(self):
334 try:
335 WindowsError
336 except NameError:
337 pass
338 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200339 self.assertIs(WindowsError, OSError)
340 self.assertEqual(str(OSError(1001)), "1001")
341 self.assertEqual(str(OSError(1001, "message")),
342 "[Errno 1001] message")
343 # POSIX errno (9 aka EBADF) is untranslated
344 w = OSError(9, 'foo', 'bar')
345 self.assertEqual(w.errno, 9)
346 self.assertEqual(w.winerror, None)
347 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
348 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
349 w = OSError(0, 'foo', 'bar', 3)
350 self.assertEqual(w.errno, 2)
351 self.assertEqual(w.winerror, 3)
352 self.assertEqual(w.strerror, 'foo')
353 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000354 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100355 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200356 # Unknown win error becomes EINVAL (22)
357 w = OSError(0, 'foo', None, 1001)
358 self.assertEqual(w.errno, 22)
359 self.assertEqual(w.winerror, 1001)
360 self.assertEqual(w.strerror, 'foo')
361 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000362 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100363 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200364 # Non-numeric "errno"
365 w = OSError('bar', 'foo')
366 self.assertEqual(w.errno, 'bar')
367 self.assertEqual(w.winerror, None)
368 self.assertEqual(w.strerror, 'foo')
369 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000370 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000371
Victor Stinnerd223fa62015-04-02 14:17:38 +0200372 @unittest.skipUnless(sys.platform == 'win32',
373 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300374 def test_windows_message(self):
375 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200376 ctypes = import_module('ctypes')
377 # this error code has no message, Python formats it as hexadecimal
378 code = 3765269347
379 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
380 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300381
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000382 def testAttributes(self):
383 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000384
385 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000386 (BaseException, (), {'args' : ()}),
387 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000388 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000389 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000390 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000391 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000392 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000393 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200394 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000395 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000396 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200397 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000398 {'args' : ('foo', 'bar'),
399 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000400 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200401 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000402 {'args' : ('foo', 'bar'),
403 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000404 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800405 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
406 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200407 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000408 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000409 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
410 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200411 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000412 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000413 'strerror' : 'strErrorStr',
414 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000415 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000416 'filename' : None, 'lineno' : None, 'offset' : None,
Pablo Galindoa77aac42021-04-23 14:27:05 +0100417 'end_offset': None, 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000418 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000419 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000420 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100421 'filename' : None, 'lineno' : None, 'offset' : None,
422 'end_offset': None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000423 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100424 'textStr', 'endLinenoStr', 'endOffsetStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000425 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000426 'args' : ('msgStr', ('filenameStr', 'linenoStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100427 'offsetStr', 'textStr',
428 'endLinenoStr', 'endOffsetStr')),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000429 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100430 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
431 'end_lineno': 'endLinenoStr', 'end_offset': 'endOffsetStr'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000432 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100433 'textStr', 'endLinenoStr', 'endOffsetStr',
434 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000435 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000436 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100437 'textStr', 'endLinenoStr', 'endOffsetStr',
438 'print_file_and_lineStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000439 'print_file_and_line' : None, 'msg' : 'msgStr',
Pablo Galindoa77aac42021-04-23 14:27:05 +0100440 'filename' : None, 'lineno' : None, 'offset' : None,
441 'end_lineno': None, 'end_offset': None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000442 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000443 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
444 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000445 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000446 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000447 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000448 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000449 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000450 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000451 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000452 'ordinal not in range'),
453 'encoding' : 'ascii', 'object' : b'\xff',
454 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000455 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
456 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000457 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000459 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000460 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000461 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000462 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000463 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000464 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100465 (NaiveException, ('foo',),
466 {'args': ('foo',), 'x': 'foo'}),
467 (SlottedNaiveException, ('foo',),
468 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000469 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000470 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200471 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000472 exceptionList.append(
473 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000474 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200475 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000476 'errno' : 1,
477 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000478 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000479 except NameError:
480 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000481
Guido van Rossumebe3e162007-05-17 18:20:34 +0000482 for exc, args, expected in exceptionList:
483 try:
484 e = exc(*args)
485 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000486 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Pablo Galindoa77aac42021-04-23 14:27:05 +0100487 # raise
Guido van Rossumebe3e162007-05-17 18:20:34 +0000488 else:
489 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100490 if not type(e).__name__.endswith('NaiveException'):
491 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000492 # Verify no ref leaks in Exc_str()
493 s = str(e)
494 for checkArgName in expected:
495 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000496 self.assertEqual(repr(value),
497 repr(expected[checkArgName]),
498 '%r.%s == %r, expected %r' % (
499 e, checkArgName,
500 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000501
Guido van Rossumebe3e162007-05-17 18:20:34 +0000502 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000503 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000504 for protocol in range(p.HIGHEST_PROTOCOL + 1):
505 s = p.dumps(e, protocol)
506 new = p.loads(s)
507 for checkArgName in expected:
508 got = repr(getattr(new, checkArgName))
509 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000510 self.assertEqual(got, want,
511 'pickled "%r", attribute "%s' %
512 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000513
Collin Winter828f04a2007-08-31 00:04:24 +0000514 def testWithTraceback(self):
515 try:
516 raise IndexError(4)
517 except:
518 tb = sys.exc_info()[2]
519
520 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000521 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000522 self.assertEqual(e.__traceback__, tb)
523
524 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000525 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000526 self.assertEqual(e.__traceback__, tb)
527
528 class MyException(Exception):
529 pass
530
531 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000532 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000533 self.assertEqual(e.__traceback__, tb)
534
535 def testInvalidTraceback(self):
536 try:
537 Exception().__traceback__ = 5
538 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000539 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000540 else:
541 self.fail("No exception raised")
542
Georg Brandlab6f2f62009-03-31 04:16:10 +0000543 def testInvalidAttrs(self):
544 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
545 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
546 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
547 self.assertRaises(TypeError, delattr, Exception(), '__context__')
548
Collin Winter828f04a2007-08-31 00:04:24 +0000549 def testNoneClearsTracebackAttr(self):
550 try:
551 raise IndexError(4)
552 except:
553 tb = sys.exc_info()[2]
554
555 e = Exception()
556 e.__traceback__ = tb
557 e.__traceback__ = None
558 self.assertEqual(e.__traceback__, None)
559
560 def testChainingAttrs(self):
561 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000562 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700563 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000564
565 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000566 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700567 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000568
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200569 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000570 pass
571
572 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000573 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700574 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000575
576 def testChainingDescriptors(self):
577 try:
578 raise Exception()
579 except Exception as exc:
580 e = exc
581
582 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700583 self.assertIsNone(e.__cause__)
584 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000585
586 e.__context__ = NameError()
587 e.__cause__ = None
588 self.assertIsInstance(e.__context__, NameError)
589 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700590 self.assertTrue(e.__suppress_context__)
591 e.__suppress_context__ = False
592 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000593
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000594 def testKeywordArgs(self):
595 # test that builtin exception don't take keyword args,
596 # but user-defined subclasses can if they want
597 self.assertRaises(TypeError, BaseException, a=1)
598
599 class DerivedException(BaseException):
600 def __init__(self, fancy_arg):
601 BaseException.__init__(self)
602 self.fancy_arg = fancy_arg
603
604 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000605 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000606
Brett Cannon31f59292011-02-21 19:29:56 +0000607 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000608 def testInfiniteRecursion(self):
609 def f():
610 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400611 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000612
613 def g():
614 try:
615 return g()
616 except ValueError:
617 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400618 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000619
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000620 def test_str(self):
621 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000622 self.assertTrue(str(Exception))
623 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000624 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000625
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000626 def testExceptionCleanupNames(self):
627 # Make sure the local variable bound to the exception instance by
628 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000629 try:
630 raise Exception()
631 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000632 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000633 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000634 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000635
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000636 def testExceptionCleanupState(self):
637 # Make sure exception state is cleaned up as soon as the except
638 # block is left. See #2507
639
640 class MyException(Exception):
641 def __init__(self, obj):
642 self.obj = obj
643 class MyObj:
644 pass
645
646 def inner_raising_func():
647 # Create some references in exception value and traceback
648 local_ref = obj
649 raise MyException(obj)
650
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000651 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000652 obj = MyObj()
653 wr = weakref.ref(obj)
654 try:
655 inner_raising_func()
656 except MyException as e:
657 pass
658 obj = None
659 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300660 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000661
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000662 # Qualified "except" without "as"
663 obj = MyObj()
664 wr = weakref.ref(obj)
665 try:
666 inner_raising_func()
667 except MyException:
668 pass
669 obj = None
670 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300671 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000672
673 # Bare "except"
674 obj = MyObj()
675 wr = weakref.ref(obj)
676 try:
677 inner_raising_func()
678 except:
679 pass
680 obj = None
681 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300682 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000683
684 # "except" with premature block leave
685 obj = MyObj()
686 wr = weakref.ref(obj)
687 for i in [0]:
688 try:
689 inner_raising_func()
690 except:
691 break
692 obj = None
693 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300694 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000695
696 # "except" block raising another exception
697 obj = MyObj()
698 wr = weakref.ref(obj)
699 try:
700 try:
701 inner_raising_func()
702 except:
703 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000704 except KeyError as e:
705 # We want to test that the except block above got rid of
706 # the exception raised in inner_raising_func(), but it
707 # also ends up in the __context__ of the KeyError, so we
708 # must clear the latter manually for our test to succeed.
709 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000710 obj = None
711 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800712 # guarantee no ref cycles on CPython (don't gc_collect)
713 if check_impl_detail(cpython=False):
714 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300715 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000716
717 # Some complicated construct
718 obj = MyObj()
719 wr = weakref.ref(obj)
720 try:
721 inner_raising_func()
722 except MyException:
723 try:
724 try:
725 raise
726 finally:
727 raise
728 except MyException:
729 pass
730 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800731 if check_impl_detail(cpython=False):
732 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000733 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300734 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000735
736 # Inside an exception-silencing "with" block
737 class Context:
738 def __enter__(self):
739 return self
740 def __exit__ (self, exc_type, exc_value, exc_tb):
741 return True
742 obj = MyObj()
743 wr = weakref.ref(obj)
744 with Context():
745 inner_raising_func()
746 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800747 if check_impl_detail(cpython=False):
748 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000749 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300750 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000751
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000752 def test_exception_target_in_nested_scope(self):
753 # issue 4617: This used to raise a SyntaxError
754 # "can not delete variable 'e' referenced in nested scope"
755 def print_error():
756 e
757 try:
758 something
759 except Exception as e:
760 print_error()
761 # implicit "del e" here
762
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000763 def test_generator_leaking(self):
764 # Test that generator exception state doesn't leak into the calling
765 # frame
766 def yield_raise():
767 try:
768 raise KeyError("caught")
769 except KeyError:
770 yield sys.exc_info()[0]
771 yield sys.exc_info()[0]
772 yield sys.exc_info()[0]
773 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000774 self.assertEqual(next(g), KeyError)
775 self.assertEqual(sys.exc_info()[0], None)
776 self.assertEqual(next(g), KeyError)
777 self.assertEqual(sys.exc_info()[0], None)
778 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000779
780 # Same test, but inside an exception handler
781 try:
782 raise TypeError("foo")
783 except TypeError:
784 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000785 self.assertEqual(next(g), KeyError)
786 self.assertEqual(sys.exc_info()[0], TypeError)
787 self.assertEqual(next(g), KeyError)
788 self.assertEqual(sys.exc_info()[0], TypeError)
789 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000790 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000791 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000792
Benjamin Peterson83195c32011-07-03 13:44:00 -0500793 def test_generator_leaking2(self):
794 # See issue 12475.
795 def g():
796 yield
797 try:
798 raise RuntimeError
799 except RuntimeError:
800 it = g()
801 next(it)
802 try:
803 next(it)
804 except StopIteration:
805 pass
806 self.assertEqual(sys.exc_info(), (None, None, None))
807
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100808 def test_generator_leaking3(self):
809 # See issue #23353. When gen.throw() is called, the caller's
810 # exception state should be save and restored.
811 def g():
812 try:
813 yield
814 except ZeroDivisionError:
815 yield sys.exc_info()[1]
816 it = g()
817 next(it)
818 try:
819 1/0
820 except ZeroDivisionError as e:
821 self.assertIs(sys.exc_info()[1], e)
822 gen_exc = it.throw(e)
823 self.assertIs(sys.exc_info()[1], e)
824 self.assertIs(gen_exc, e)
825 self.assertEqual(sys.exc_info(), (None, None, None))
826
827 def test_generator_leaking4(self):
828 # See issue #23353. When an exception is raised by a generator,
829 # the caller's exception state should still be restored.
830 def g():
831 try:
832 1/0
833 except ZeroDivisionError:
834 yield sys.exc_info()[0]
835 raise
836 it = g()
837 try:
838 raise TypeError
839 except TypeError:
840 # The caller's exception state (TypeError) is temporarily
841 # saved in the generator.
842 tp = next(it)
843 self.assertIs(tp, ZeroDivisionError)
844 try:
845 next(it)
846 # We can't check it immediately, but while next() returns
847 # with an exception, it shouldn't have restored the old
848 # exception state (TypeError).
849 except ZeroDivisionError as e:
850 self.assertIs(sys.exc_info()[1], e)
851 # We used to find TypeError here.
852 self.assertEqual(sys.exc_info(), (None, None, None))
853
Benjamin Petersonac913412011-07-03 16:25:11 -0500854 def test_generator_doesnt_retain_old_exc(self):
855 def g():
856 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
857 yield
858 self.assertEqual(sys.exc_info(), (None, None, None))
859 it = g()
860 try:
861 raise RuntimeError
862 except RuntimeError:
863 next(it)
864 self.assertRaises(StopIteration, next, it)
865
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000866 def test_generator_finalizing_and_exc_info(self):
867 # See #7173
868 def simple_gen():
869 yield 1
870 def run_gen():
871 gen = simple_gen()
872 try:
873 raise RuntimeError
874 except RuntimeError:
875 return next(gen)
876 run_gen()
877 gc_collect()
878 self.assertEqual(sys.exc_info(), (None, None, None))
879
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200880 def _check_generator_cleanup_exc_state(self, testfunc):
881 # Issue #12791: exception state is cleaned up as soon as a generator
882 # is closed (reference cycles are broken).
883 class MyException(Exception):
884 def __init__(self, obj):
885 self.obj = obj
886 class MyObj:
887 pass
888
889 def raising_gen():
890 try:
891 raise MyException(obj)
892 except MyException:
893 yield
894
895 obj = MyObj()
896 wr = weakref.ref(obj)
897 g = raising_gen()
898 next(g)
899 testfunc(g)
900 g = obj = None
901 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300902 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200903
904 def test_generator_throw_cleanup_exc_state(self):
905 def do_throw(g):
906 try:
907 g.throw(RuntimeError())
908 except RuntimeError:
909 pass
910 self._check_generator_cleanup_exc_state(do_throw)
911
912 def test_generator_close_cleanup_exc_state(self):
913 def do_close(g):
914 g.close()
915 self._check_generator_cleanup_exc_state(do_close)
916
917 def test_generator_del_cleanup_exc_state(self):
918 def do_del(g):
919 g = None
920 self._check_generator_cleanup_exc_state(do_del)
921
922 def test_generator_next_cleanup_exc_state(self):
923 def do_next(g):
924 try:
925 next(g)
926 except StopIteration:
927 pass
928 else:
929 self.fail("should have raised StopIteration")
930 self._check_generator_cleanup_exc_state(do_next)
931
932 def test_generator_send_cleanup_exc_state(self):
933 def do_send(g):
934 try:
935 g.send(None)
936 except StopIteration:
937 pass
938 else:
939 self.fail("should have raised StopIteration")
940 self._check_generator_cleanup_exc_state(do_send)
941
Benjamin Peterson27d63672008-06-15 20:09:12 +0000942 def test_3114(self):
943 # Bug #3114: in its destructor, MyObject retrieves a pointer to
944 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000945 class MyObject:
946 def __del__(self):
947 nonlocal e
948 e = sys.exc_info()
949 e = ()
950 try:
951 raise Exception(MyObject())
952 except:
953 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000954 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000955
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -0700956 def test_raise_does_not_create_context_chain_cycle(self):
957 class A(Exception):
958 pass
959 class B(Exception):
960 pass
961 class C(Exception):
962 pass
963
964 # Create a context chain:
965 # C -> B -> A
966 # Then raise A in context of C.
967 try:
968 try:
969 raise A
970 except A as a_:
971 a = a_
972 try:
973 raise B
974 except B as b_:
975 b = b_
976 try:
977 raise C
978 except C as c_:
979 c = c_
980 self.assertIsInstance(a, A)
981 self.assertIsInstance(b, B)
982 self.assertIsInstance(c, C)
983 self.assertIsNone(a.__context__)
984 self.assertIs(b.__context__, a)
985 self.assertIs(c.__context__, b)
986 raise a
987 except A as e:
988 exc = e
989
990 # Expect A -> C -> B, without cycle
991 self.assertIs(exc, a)
992 self.assertIs(a.__context__, c)
993 self.assertIs(c.__context__, b)
994 self.assertIsNone(b.__context__)
995
996 def test_no_hang_on_context_chain_cycle1(self):
997 # See issue 25782. Cycle in context chain.
998
999 def cycle():
1000 try:
1001 raise ValueError(1)
1002 except ValueError as ex:
1003 ex.__context__ = ex
1004 raise TypeError(2)
1005
1006 try:
1007 cycle()
1008 except Exception as e:
1009 exc = e
1010
1011 self.assertIsInstance(exc, TypeError)
1012 self.assertIsInstance(exc.__context__, ValueError)
1013 self.assertIs(exc.__context__.__context__, exc.__context__)
1014
Miss Islington (bot)19604092021-08-16 02:01:14 -07001015 @unittest.skip("See issue 44895")
Miss Islington (bot)d86bbe32021-08-10 06:47:23 -07001016 def test_no_hang_on_context_chain_cycle2(self):
1017 # See issue 25782. Cycle at head of context chain.
1018
1019 class A(Exception):
1020 pass
1021 class B(Exception):
1022 pass
1023 class C(Exception):
1024 pass
1025
1026 # Context cycle:
1027 # +-----------+
1028 # V |
1029 # C --> B --> A
1030 with self.assertRaises(C) as cm:
1031 try:
1032 raise A()
1033 except A as _a:
1034 a = _a
1035 try:
1036 raise B()
1037 except B as _b:
1038 b = _b
1039 try:
1040 raise C()
1041 except C as _c:
1042 c = _c
1043 a.__context__ = c
1044 raise c
1045
1046 self.assertIs(cm.exception, c)
1047 # Verify the expected context chain cycle
1048 self.assertIs(c.__context__, b)
1049 self.assertIs(b.__context__, a)
1050 self.assertIs(a.__context__, c)
1051
1052 def test_no_hang_on_context_chain_cycle3(self):
1053 # See issue 25782. Longer context chain with cycle.
1054
1055 class A(Exception):
1056 pass
1057 class B(Exception):
1058 pass
1059 class C(Exception):
1060 pass
1061 class D(Exception):
1062 pass
1063 class E(Exception):
1064 pass
1065
1066 # Context cycle:
1067 # +-----------+
1068 # V |
1069 # E --> D --> C --> B --> A
1070 with self.assertRaises(E) as cm:
1071 try:
1072 raise A()
1073 except A as _a:
1074 a = _a
1075 try:
1076 raise B()
1077 except B as _b:
1078 b = _b
1079 try:
1080 raise C()
1081 except C as _c:
1082 c = _c
1083 a.__context__ = c
1084 try:
1085 raise D()
1086 except D as _d:
1087 d = _d
1088 e = E()
1089 raise e
1090
1091 self.assertIs(cm.exception, e)
1092 # Verify the expected context chain cycle
1093 self.assertIs(e.__context__, d)
1094 self.assertIs(d.__context__, c)
1095 self.assertIs(c.__context__, b)
1096 self.assertIs(b.__context__, a)
1097 self.assertIs(a.__context__, c)
1098
Benjamin Peterson24dfb052014-04-02 12:05:35 -04001099 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +00001100 # See issue 7309. This was a crasher.
1101
1102 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
1103 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
1104 u.end = 2
1105 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
1106 u.end = 5
1107 u.reason = 0x345345345345345345
1108 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
1109 u.encoding = 4000
1110 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
1111 u.start = 1000
1112 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
1113
1114 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
1115 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
1116 u.end = 2
1117 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
1118 u.end = 5
1119 u.reason = 0x345345345345345345
1120 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
1121 u.encoding = 4000
1122 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
1123 u.start = 1000
1124 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
1125
1126 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
1127 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
1128 u.end = 2
1129 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
1130 u.end = 5
1131 u.reason = 0x345345345345345345
1132 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
1133 u.start = 1000
1134 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +00001135
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001136 def test_unicode_errors_no_object(self):
1137 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -04001138 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -04001139 for klass in klasses:
1140 self.assertEqual(str(klass.__new__(klass)), "")
1141
Brett Cannon31f59292011-02-21 19:29:56 +00001142 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001143 def test_badisinstance(self):
1144 # Bug #2542: if issubclass(e, MyException) raises an exception,
1145 # it should be ignored
1146 class Meta(type):
1147 def __subclasscheck__(cls, subclass):
1148 raise ValueError()
1149 class MyException(Exception, metaclass=Meta):
1150 pass
1151
Martin Panter3263f682016-02-28 03:16:11 +00001152 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001153 try:
1154 raise KeyError()
1155 except MyException as e:
1156 self.fail("exception should not be a MyException")
1157 except KeyError:
1158 pass
1159 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001160 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001161 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001162 self.fail("Should have raised KeyError")
1163
1164 def g():
1165 try:
1166 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001167 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +00001168 return sys.exc_info()
1169 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +03001170 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001171 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001172
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001173
1174 @cpython_only
Benjamin Petersonef36dfe2021-08-13 02:45:13 -07001175 def test_trashcan_recursion(self):
Miss Islington (bot)d6d2d542021-08-11 01:32:44 -07001176 # See bpo-33930
1177
1178 def foo():
1179 o = object()
1180 for x in range(1_000_000):
1181 # Create a big chain of method objects that will trigger
1182 # a deep chain of calls when they need to be destructed.
1183 o = o.__dir__
1184
1185 foo()
1186 support.gc_collect()
1187
xdegaye56d1f5c2017-10-26 15:09:06 +02001188 @cpython_only
1189 def test_recursion_normalizing_exception(self):
1190 # Issue #22898.
1191 # Test that a RecursionError is raised when tstate->recursion_depth is
1192 # equal to recursion_limit in PyErr_NormalizeException() and check
1193 # that a ResourceWarning is printed.
1194 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001195 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001196 # singleton was being used in that case, that held traceback data and
1197 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1198 # finalization of these locals.
1199 code = """if 1:
1200 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001201 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001202
1203 class MyException(Exception): pass
1204
1205 def setrecursionlimit(depth):
1206 while 1:
1207 try:
1208 sys.setrecursionlimit(depth)
1209 return depth
1210 except RecursionError:
1211 # sys.setrecursionlimit() raises a RecursionError if
1212 # the new recursion limit is too low (issue #25274).
1213 depth += 1
1214
1215 def recurse(cnt):
1216 cnt -= 1
1217 if cnt:
1218 recurse(cnt)
1219 else:
1220 generator.throw(MyException)
1221
1222 def gen():
1223 f = open(%a, mode='rb', buffering=0)
1224 yield
1225
1226 generator = gen()
1227 next(generator)
1228 recursionlimit = sys.getrecursionlimit()
1229 depth = get_recursion_depth()
1230 try:
1231 # Upon the last recursive invocation of recurse(),
1232 # tstate->recursion_depth is equal to (recursion_limit - 1)
1233 # and is equal to recursion_limit when _gen_throw() calls
1234 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001235 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001236 finally:
1237 sys.setrecursionlimit(recursionlimit)
1238 print('Done.')
1239 """ % __file__
1240 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1241 # Check that the program does not fail with SIGABRT.
1242 self.assertEqual(rc, 1)
1243 self.assertIn(b'RecursionError', err)
1244 self.assertIn(b'ResourceWarning', err)
1245 self.assertIn(b'Done.', out)
1246
1247 @cpython_only
1248 def test_recursion_normalizing_infinite_exception(self):
1249 # Issue #30697. Test that a RecursionError is raised when
1250 # PyErr_NormalizeException() maximum recursion depth has been
1251 # exceeded.
1252 code = """if 1:
1253 import _testcapi
1254 try:
1255 raise _testcapi.RecursingInfinitelyError
1256 finally:
1257 print('Done.')
1258 """
1259 rc, out, err = script_helper.assert_python_failure("-c", code)
1260 self.assertEqual(rc, 1)
1261 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1262 b'while normalizing an exception', err)
1263 self.assertIn(b'Done.', out)
1264
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001265
1266 def test_recursion_in_except_handler(self):
1267
1268 def set_relative_recursion_limit(n):
1269 depth = 1
1270 while True:
1271 try:
1272 sys.setrecursionlimit(depth)
1273 except RecursionError:
1274 depth += 1
1275 else:
1276 break
1277 sys.setrecursionlimit(depth+n)
1278
1279 def recurse_in_except():
1280 try:
1281 1/0
1282 except:
1283 recurse_in_except()
1284
1285 def recurse_after_except():
1286 try:
1287 1/0
1288 except:
1289 pass
1290 recurse_after_except()
1291
1292 def recurse_in_body_and_except():
1293 try:
1294 recurse_in_body_and_except()
1295 except:
1296 recurse_in_body_and_except()
1297
1298 recursionlimit = sys.getrecursionlimit()
1299 try:
1300 set_relative_recursion_limit(10)
1301 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1302 with self.subTest(func=func):
1303 try:
1304 func()
1305 except RecursionError:
1306 pass
1307 else:
1308 self.fail("Should have raised a RecursionError")
1309 finally:
1310 sys.setrecursionlimit(recursionlimit)
1311
1312
xdegaye56d1f5c2017-10-26 15:09:06 +02001313 @cpython_only
1314 def test_recursion_normalizing_with_no_memory(self):
1315 # Issue #30697. Test that in the abort that occurs when there is no
1316 # memory left and the size of the Python frames stack is greater than
1317 # the size of the list of preallocated MemoryError instances, the
1318 # Fatal Python error message mentions MemoryError.
1319 code = """if 1:
1320 import _testcapi
1321 class C(): pass
1322 def recurse(cnt):
1323 cnt -= 1
1324 if cnt:
1325 recurse(cnt)
1326 else:
1327 _testcapi.set_nomemory(0)
1328 C()
1329 recurse(16)
1330 """
1331 with SuppressCrashReport():
1332 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001333 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1334 b'Cannot recover from MemoryErrors while '
1335 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001336
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001337 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001338 def test_MemoryError(self):
1339 # PyErr_NoMemory always raises the same exception instance.
1340 # Check that the traceback is not doubled.
1341 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001342 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001343 def raiseMemError():
1344 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001345 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001346 except MemoryError as e:
1347 tb = e.__traceback__
1348 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001349 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001350 return traceback.format_tb(tb)
1351
1352 tb1 = raiseMemError()
1353 tb2 = raiseMemError()
1354 self.assertEqual(tb1, tb2)
1355
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001356 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001357 def test_exception_with_doc(self):
1358 import _testcapi
1359 doc2 = "This is a test docstring."
1360 doc4 = "This is another test docstring."
1361
1362 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1363 "error1")
1364
1365 # test basic usage of PyErr_NewException
1366 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1367 self.assertIs(type(error1), type)
1368 self.assertTrue(issubclass(error1, Exception))
1369 self.assertIsNone(error1.__doc__)
1370
1371 # test with given docstring
1372 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1373 self.assertEqual(error2.__doc__, doc2)
1374
1375 # test with explicit base (without docstring)
1376 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1377 base=error2)
1378 self.assertTrue(issubclass(error3, error2))
1379
1380 # test with explicit base tuple
1381 class C(object):
1382 pass
1383 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1384 (error3, C))
1385 self.assertTrue(issubclass(error4, error3))
1386 self.assertTrue(issubclass(error4, C))
1387 self.assertEqual(error4.__doc__, doc4)
1388
1389 # test with explicit dictionary
1390 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1391 error4, {'a': 1})
1392 self.assertTrue(issubclass(error5, error4))
1393 self.assertEqual(error5.a, 1)
1394 self.assertEqual(error5.__doc__, "")
1395
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001396 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001397 def test_memory_error_cleanup(self):
1398 # Issue #5437: preallocated MemoryError instances should not keep
1399 # traceback objects alive.
1400 from _testcapi import raise_memoryerror
1401 class C:
1402 pass
1403 wr = None
1404 def inner():
1405 nonlocal wr
1406 c = C()
1407 wr = weakref.ref(c)
1408 raise_memoryerror()
1409 # We cannot use assertRaises since it manually deletes the traceback
1410 try:
1411 inner()
1412 except MemoryError as e:
1413 self.assertNotEqual(wr(), None)
1414 else:
1415 self.fail("MemoryError not raised")
1416 self.assertEqual(wr(), None)
1417
Brett Cannon31f59292011-02-21 19:29:56 +00001418 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001419 def test_recursion_error_cleanup(self):
1420 # Same test as above, but with "recursion exceeded" errors
1421 class C:
1422 pass
1423 wr = None
1424 def inner():
1425 nonlocal wr
1426 c = C()
1427 wr = weakref.ref(c)
1428 inner()
1429 # We cannot use assertRaises since it manually deletes the traceback
1430 try:
1431 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001432 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001433 self.assertNotEqual(wr(), None)
1434 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001435 self.fail("RecursionError not raised")
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001436 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001437
Antoine Pitroua7622852011-09-01 21:37:43 +02001438 def test_errno_ENOTDIR(self):
1439 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1440 with self.assertRaises(OSError) as cm:
1441 os.listdir(__file__)
1442 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1443
Martin Panter3263f682016-02-28 03:16:11 +00001444 def test_unraisable(self):
1445 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1446 class BrokenDel:
1447 def __del__(self):
1448 exc = ValueError("del is broken")
1449 # The following line is included in the traceback report:
1450 raise exc
1451
Victor Stinnere4d300e2019-05-22 23:44:02 +02001452 obj = BrokenDel()
1453 with support.catch_unraisable_exception() as cm:
1454 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001455
Victor Stinnere4d300e2019-05-22 23:44:02 +02001456 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1457 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001458
1459 def test_unhandled(self):
1460 # Check for sensible reporting of unhandled exceptions
1461 for exc_type in (ValueError, BrokenStrException):
1462 with self.subTest(exc_type):
1463 try:
1464 exc = exc_type("test message")
1465 # The following line is included in the traceback report:
1466 raise exc
1467 except exc_type:
1468 with captured_stderr() as stderr:
1469 sys.__excepthook__(*sys.exc_info())
1470 report = stderr.getvalue()
1471 self.assertIn("test_exceptions.py", report)
1472 self.assertIn("raise exc", report)
1473 self.assertIn(exc_type.__name__, report)
1474 if exc_type is BrokenStrException:
1475 self.assertIn("<exception str() failed>", report)
1476 else:
1477 self.assertIn("test message", report)
1478 self.assertTrue(report.endswith("\n"))
1479
xdegaye66caacf2017-10-23 18:08:41 +02001480 @cpython_only
1481 def test_memory_error_in_PyErr_PrintEx(self):
1482 code = """if 1:
1483 import _testcapi
1484 class C(): pass
1485 _testcapi.set_nomemory(0, %d)
1486 C()
1487 """
1488
1489 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1490 # Span a large range of tests as the CPython code always evolves with
1491 # changes that add or remove memory allocations.
1492 for i in range(1, 20):
1493 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1494 self.assertIn(rc, (1, 120))
1495 self.assertIn(b'MemoryError', err)
1496
Mark Shannonae3087c2017-10-22 22:41:51 +01001497 def test_yield_in_nested_try_excepts(self):
1498 #Issue #25612
1499 class MainError(Exception):
1500 pass
1501
1502 class SubError(Exception):
1503 pass
1504
1505 def main():
1506 try:
1507 raise MainError()
1508 except MainError:
1509 try:
1510 yield
1511 except SubError:
1512 pass
1513 raise
1514
1515 coro = main()
1516 coro.send(None)
1517 with self.assertRaises(MainError):
1518 coro.throw(SubError())
1519
1520 def test_generator_doesnt_retain_old_exc2(self):
1521 #Issue 28884#msg282532
1522 def g():
1523 try:
1524 raise ValueError
1525 except ValueError:
1526 yield 1
1527 self.assertEqual(sys.exc_info(), (None, None, None))
1528 yield 2
1529
1530 gen = g()
1531
1532 try:
1533 raise IndexError
1534 except IndexError:
1535 self.assertEqual(next(gen), 1)
1536 self.assertEqual(next(gen), 2)
1537
1538 def test_raise_in_generator(self):
1539 #Issue 25612#msg304117
1540 def g():
1541 yield 1
1542 raise
1543 yield 2
1544
1545 with self.assertRaises(ZeroDivisionError):
1546 i = g()
1547 try:
1548 1/0
1549 except:
1550 next(i)
1551 next(i)
1552
Zackery Spytzce6a0702019-08-25 03:44:09 -06001553 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1554 def test_assert_shadowing(self):
1555 # Shadowing AssertionError would cause the assert statement to
1556 # misbehave.
1557 global AssertionError
1558 AssertionError = TypeError
1559 try:
1560 assert False, 'hello'
1561 except BaseException as e:
1562 del AssertionError
1563 self.assertIsInstance(e, AssertionError)
1564 self.assertEqual(str(e), 'hello')
1565 else:
1566 del AssertionError
1567 self.fail('Expected exception')
1568
Pablo Galindo9b648a92020-09-01 19:39:46 +01001569 def test_memory_error_subclasses(self):
1570 # bpo-41654: MemoryError instances use a freelist of objects that are
1571 # linked using the 'dict' attribute when they are inactive/dead.
1572 # Subclasses of MemoryError should not participate in the freelist
1573 # schema. This test creates a MemoryError object and keeps it alive
1574 # (therefore advancing the freelist) and then it creates and destroys a
1575 # subclass object. Finally, it checks that creating a new MemoryError
1576 # succeeds, proving that the freelist is not corrupted.
1577
1578 class TestException(MemoryError):
1579 pass
1580
1581 try:
1582 raise MemoryError
1583 except MemoryError as exc:
1584 inst = exc
1585
1586 try:
1587 raise TestException
1588 except Exception:
1589 pass
1590
1591 for _ in range(10):
1592 try:
1593 raise MemoryError
1594 except MemoryError as exc:
1595 pass
1596
1597 gc_collect()
1598
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001599global_for_suggestions = None
1600
1601class NameErrorTests(unittest.TestCase):
1602 def test_name_error_has_name(self):
1603 try:
1604 bluch
1605 except NameError as exc:
1606 self.assertEqual("bluch", exc.name)
1607
1608 def test_name_error_suggestions(self):
1609 def Substitution():
1610 noise = more_noise = a = bc = None
1611 blech = None
1612 print(bluch)
1613
1614 def Elimination():
1615 noise = more_noise = a = bc = None
1616 blch = None
1617 print(bluch)
1618
1619 def Addition():
1620 noise = more_noise = a = bc = None
1621 bluchin = None
1622 print(bluch)
1623
1624 def SubstitutionOverElimination():
1625 blach = None
1626 bluc = None
1627 print(bluch)
1628
1629 def SubstitutionOverAddition():
1630 blach = None
1631 bluchi = None
1632 print(bluch)
1633
1634 def EliminationOverAddition():
1635 blucha = None
1636 bluc = None
1637 print(bluch)
1638
Pablo Galindo7a041162021-04-19 23:35:53 +01001639 for func, suggestion in [(Substitution, "'blech'?"),
1640 (Elimination, "'blch'?"),
1641 (Addition, "'bluchin'?"),
1642 (EliminationOverAddition, "'blucha'?"),
1643 (SubstitutionOverElimination, "'blach'?"),
1644 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001645 err = None
1646 try:
1647 func()
1648 except NameError as exc:
1649 with support.captured_stderr() as err:
1650 sys.__excepthook__(*sys.exc_info())
1651 self.assertIn(suggestion, err.getvalue())
1652
1653 def test_name_error_suggestions_from_globals(self):
1654 def func():
1655 print(global_for_suggestio)
1656 try:
1657 func()
1658 except NameError as exc:
1659 with support.captured_stderr() as err:
1660 sys.__excepthook__(*sys.exc_info())
Pablo Galindo7a041162021-04-19 23:35:53 +01001661 self.assertIn("'global_for_suggestions'?", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001662
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001663 def test_name_error_suggestions_from_builtins(self):
1664 def func():
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001665 print(ZeroDivisionErrrrr)
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001666 try:
1667 func()
1668 except NameError as exc:
1669 with support.captured_stderr() as err:
1670 sys.__excepthook__(*sys.exc_info())
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001671 self.assertIn("'ZeroDivisionError'?", err.getvalue())
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001672
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001673 def test_name_error_suggestions_do_not_trigger_for_long_names(self):
1674 def f():
1675 somethingverywronghehehehehehe = None
1676 print(somethingverywronghe)
1677
1678 try:
1679 f()
1680 except NameError as exc:
1681 with support.captured_stderr() as err:
1682 sys.__excepthook__(*sys.exc_info())
1683
1684 self.assertNotIn("somethingverywronghehe", err.getvalue())
1685
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001686 def test_name_error_bad_suggestions_do_not_trigger_for_small_names(self):
1687 vvv = mom = w = id = pytho = None
1688
1689 with self.subTest(name="b"):
1690 try:
1691 b
1692 except NameError as exc:
1693 with support.captured_stderr() as err:
1694 sys.__excepthook__(*sys.exc_info())
1695 self.assertNotIn("you mean", err.getvalue())
1696 self.assertNotIn("vvv", err.getvalue())
1697 self.assertNotIn("mom", err.getvalue())
1698 self.assertNotIn("'id'", err.getvalue())
1699 self.assertNotIn("'w'", err.getvalue())
1700 self.assertNotIn("'pytho'", err.getvalue())
1701
1702 with self.subTest(name="v"):
1703 try:
1704 v
1705 except NameError as exc:
1706 with support.captured_stderr() as err:
1707 sys.__excepthook__(*sys.exc_info())
1708 self.assertNotIn("you mean", err.getvalue())
1709 self.assertNotIn("vvv", err.getvalue())
1710 self.assertNotIn("mom", err.getvalue())
1711 self.assertNotIn("'id'", err.getvalue())
1712 self.assertNotIn("'w'", err.getvalue())
1713 self.assertNotIn("'pytho'", err.getvalue())
1714
1715 with self.subTest(name="m"):
1716 try:
1717 m
1718 except NameError as exc:
1719 with support.captured_stderr() as err:
1720 sys.__excepthook__(*sys.exc_info())
1721 self.assertNotIn("you mean", err.getvalue())
1722 self.assertNotIn("vvv", err.getvalue())
1723 self.assertNotIn("mom", err.getvalue())
1724 self.assertNotIn("'id'", err.getvalue())
1725 self.assertNotIn("'w'", err.getvalue())
1726 self.assertNotIn("'pytho'", err.getvalue())
1727
1728 with self.subTest(name="py"):
1729 try:
1730 py
1731 except NameError as exc:
1732 with support.captured_stderr() as err:
1733 sys.__excepthook__(*sys.exc_info())
1734 self.assertNotIn("you mean", err.getvalue())
1735 self.assertNotIn("vvv", err.getvalue())
1736 self.assertNotIn("mom", err.getvalue())
1737 self.assertNotIn("'id'", err.getvalue())
1738 self.assertNotIn("'w'", err.getvalue())
1739 self.assertNotIn("'pytho'", err.getvalue())
1740
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001741 def test_name_error_suggestions_do_not_trigger_for_too_many_locals(self):
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001742 def f():
1743 # Mutating locals() is unreliable, so we need to do it by hand
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04001744 a1 = a2 = a3 = a4 = a5 = a6 = a7 = a8 = a9 = a10 = \
1745 a11 = a12 = a13 = a14 = a15 = a16 = a17 = a18 = a19 = a20 = \
1746 a21 = a22 = a23 = a24 = a25 = a26 = a27 = a28 = a29 = a30 = \
1747 a31 = a32 = a33 = a34 = a35 = a36 = a37 = a38 = a39 = a40 = \
1748 a41 = a42 = a43 = a44 = a45 = a46 = a47 = a48 = a49 = a50 = \
1749 a51 = a52 = a53 = a54 = a55 = a56 = a57 = a58 = a59 = a60 = \
1750 a61 = a62 = a63 = a64 = a65 = a66 = a67 = a68 = a69 = a70 = \
1751 a71 = a72 = a73 = a74 = a75 = a76 = a77 = a78 = a79 = a80 = \
1752 a81 = a82 = a83 = a84 = a85 = a86 = a87 = a88 = a89 = a90 = \
1753 a91 = a92 = a93 = a94 = a95 = a96 = a97 = a98 = a99 = a100 = \
1754 a101 = a102 = a103 = a104 = a105 = a106 = a107 = a108 = a109 = a110 = \
1755 a111 = a112 = a113 = a114 = a115 = a116 = a117 = a118 = a119 = a120 = \
1756 a121 = a122 = a123 = a124 = a125 = a126 = a127 = a128 = a129 = a130 = \
1757 a131 = a132 = a133 = a134 = a135 = a136 = a137 = a138 = a139 = a140 = \
1758 a141 = a142 = a143 = a144 = a145 = a146 = a147 = a148 = a149 = a150 = \
1759 a151 = a152 = a153 = a154 = a155 = a156 = a157 = a158 = a159 = a160 = \
1760 a161 = a162 = a163 = a164 = a165 = a166 = a167 = a168 = a169 = a170 = \
1761 a171 = a172 = a173 = a174 = a175 = a176 = a177 = a178 = a179 = a180 = \
1762 a181 = a182 = a183 = a184 = a185 = a186 = a187 = a188 = a189 = a190 = \
1763 a191 = a192 = a193 = a194 = a195 = a196 = a197 = a198 = a199 = a200 = \
1764 a201 = a202 = a203 = a204 = a205 = a206 = a207 = a208 = a209 = a210 = \
1765 a211 = a212 = a213 = a214 = a215 = a216 = a217 = a218 = a219 = a220 = \
1766 a221 = a222 = a223 = a224 = a225 = a226 = a227 = a228 = a229 = a230 = \
1767 a231 = a232 = a233 = a234 = a235 = a236 = a237 = a238 = a239 = a240 = \
1768 a241 = a242 = a243 = a244 = a245 = a246 = a247 = a248 = a249 = a250 = \
1769 a251 = a252 = a253 = a254 = a255 = a256 = a257 = a258 = a259 = a260 = \
1770 a261 = a262 = a263 = a264 = a265 = a266 = a267 = a268 = a269 = a270 = \
1771 a271 = a272 = a273 = a274 = a275 = a276 = a277 = a278 = a279 = a280 = \
1772 a281 = a282 = a283 = a284 = a285 = a286 = a287 = a288 = a289 = a290 = \
1773 a291 = a292 = a293 = a294 = a295 = a296 = a297 = a298 = a299 = a300 = \
1774 a301 = a302 = a303 = a304 = a305 = a306 = a307 = a308 = a309 = a310 = \
1775 a311 = a312 = a313 = a314 = a315 = a316 = a317 = a318 = a319 = a320 = \
1776 a321 = a322 = a323 = a324 = a325 = a326 = a327 = a328 = a329 = a330 = \
1777 a331 = a332 = a333 = a334 = a335 = a336 = a337 = a338 = a339 = a340 = \
1778 a341 = a342 = a343 = a344 = a345 = a346 = a347 = a348 = a349 = a350 = \
1779 a351 = a352 = a353 = a354 = a355 = a356 = a357 = a358 = a359 = a360 = \
1780 a361 = a362 = a363 = a364 = a365 = a366 = a367 = a368 = a369 = a370 = \
1781 a371 = a372 = a373 = a374 = a375 = a376 = a377 = a378 = a379 = a380 = \
1782 a381 = a382 = a383 = a384 = a385 = a386 = a387 = a388 = a389 = a390 = \
1783 a391 = a392 = a393 = a394 = a395 = a396 = a397 = a398 = a399 = a400 = \
1784 a401 = a402 = a403 = a404 = a405 = a406 = a407 = a408 = a409 = a410 = \
1785 a411 = a412 = a413 = a414 = a415 = a416 = a417 = a418 = a419 = a420 = \
1786 a421 = a422 = a423 = a424 = a425 = a426 = a427 = a428 = a429 = a430 = \
1787 a431 = a432 = a433 = a434 = a435 = a436 = a437 = a438 = a439 = a440 = \
1788 a441 = a442 = a443 = a444 = a445 = a446 = a447 = a448 = a449 = a450 = \
1789 a451 = a452 = a453 = a454 = a455 = a456 = a457 = a458 = a459 = a460 = \
1790 a461 = a462 = a463 = a464 = a465 = a466 = a467 = a468 = a469 = a470 = \
1791 a471 = a472 = a473 = a474 = a475 = a476 = a477 = a478 = a479 = a480 = \
1792 a481 = a482 = a483 = a484 = a485 = a486 = a487 = a488 = a489 = a490 = \
1793 a491 = a492 = a493 = a494 = a495 = a496 = a497 = a498 = a499 = a500 = \
1794 a501 = a502 = a503 = a504 = a505 = a506 = a507 = a508 = a509 = a510 = \
1795 a511 = a512 = a513 = a514 = a515 = a516 = a517 = a518 = a519 = a520 = \
1796 a521 = a522 = a523 = a524 = a525 = a526 = a527 = a528 = a529 = a530 = \
1797 a531 = a532 = a533 = a534 = a535 = a536 = a537 = a538 = a539 = a540 = \
1798 a541 = a542 = a543 = a544 = a545 = a546 = a547 = a548 = a549 = a550 = \
1799 a551 = a552 = a553 = a554 = a555 = a556 = a557 = a558 = a559 = a560 = \
1800 a561 = a562 = a563 = a564 = a565 = a566 = a567 = a568 = a569 = a570 = \
1801 a571 = a572 = a573 = a574 = a575 = a576 = a577 = a578 = a579 = a580 = \
1802 a581 = a582 = a583 = a584 = a585 = a586 = a587 = a588 = a589 = a590 = \
1803 a591 = a592 = a593 = a594 = a595 = a596 = a597 = a598 = a599 = a600 = \
1804 a601 = a602 = a603 = a604 = a605 = a606 = a607 = a608 = a609 = a610 = \
1805 a611 = a612 = a613 = a614 = a615 = a616 = a617 = a618 = a619 = a620 = \
1806 a621 = a622 = a623 = a624 = a625 = a626 = a627 = a628 = a629 = a630 = \
1807 a631 = a632 = a633 = a634 = a635 = a636 = a637 = a638 = a639 = a640 = \
1808 a641 = a642 = a643 = a644 = a645 = a646 = a647 = a648 = a649 = a650 = \
1809 a651 = a652 = a653 = a654 = a655 = a656 = a657 = a658 = a659 = a660 = \
1810 a661 = a662 = a663 = a664 = a665 = a666 = a667 = a668 = a669 = a670 = \
1811 a671 = a672 = a673 = a674 = a675 = a676 = a677 = a678 = a679 = a680 = \
1812 a681 = a682 = a683 = a684 = a685 = a686 = a687 = a688 = a689 = a690 = \
1813 a691 = a692 = a693 = a694 = a695 = a696 = a697 = a698 = a699 = a700 = \
1814 a701 = a702 = a703 = a704 = a705 = a706 = a707 = a708 = a709 = a710 = \
1815 a711 = a712 = a713 = a714 = a715 = a716 = a717 = a718 = a719 = a720 = \
1816 a721 = a722 = a723 = a724 = a725 = a726 = a727 = a728 = a729 = a730 = \
1817 a731 = a732 = a733 = a734 = a735 = a736 = a737 = a738 = a739 = a740 = \
1818 a741 = a742 = a743 = a744 = a745 = a746 = a747 = a748 = a749 = a750 = \
1819 a751 = a752 = a753 = a754 = a755 = a756 = a757 = a758 = a759 = a760 = \
1820 a761 = a762 = a763 = a764 = a765 = a766 = a767 = a768 = a769 = a770 = \
1821 a771 = a772 = a773 = a774 = a775 = a776 = a777 = a778 = a779 = a780 = \
1822 a781 = a782 = a783 = a784 = a785 = a786 = a787 = a788 = a789 = a790 = \
1823 a791 = a792 = a793 = a794 = a795 = a796 = a797 = a798 = a799 = a800 \
1824 = None
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001825 print(a0)
1826
1827 try:
1828 f()
1829 except NameError as exc:
1830 with support.captured_stderr() as err:
1831 sys.__excepthook__(*sys.exc_info())
1832
Pablo Galindo3ab4bea2021-04-17 22:26:54 +01001833 self.assertNotIn("a1", err.getvalue())
Pablo Galindo5bf8bf22021-04-14 15:10:33 +01001834
1835 def test_name_error_with_custom_exceptions(self):
1836 def f():
1837 blech = None
1838 raise NameError()
1839
1840 try:
1841 f()
1842 except NameError as exc:
1843 with support.captured_stderr() as err:
1844 sys.__excepthook__(*sys.exc_info())
1845
1846 self.assertNotIn("blech", err.getvalue())
1847
1848 def f():
1849 blech = None
1850 raise NameError
1851
1852 try:
1853 f()
1854 except NameError as exc:
1855 with support.captured_stderr() as err:
1856 sys.__excepthook__(*sys.exc_info())
1857
1858 self.assertNotIn("blech", err.getvalue())
Antoine Pitroua7622852011-09-01 21:37:43 +02001859
Pablo Galindo0ad81d42021-04-16 17:12:03 +01001860 def test_unbound_local_error_doesn_not_match(self):
1861 def foo():
1862 something = 3
1863 print(somethong)
1864 somethong = 3
1865
1866 try:
1867 foo()
1868 except UnboundLocalError as exc:
1869 with support.captured_stderr() as err:
1870 sys.__excepthook__(*sys.exc_info())
1871
1872 self.assertNotIn("something", err.getvalue())
1873
1874
Pablo Galindo37494b42021-04-14 02:36:07 +01001875class AttributeErrorTests(unittest.TestCase):
1876 def test_attributes(self):
1877 # Setting 'attr' should not be a problem.
1878 exc = AttributeError('Ouch!')
1879 self.assertIsNone(exc.name)
1880 self.assertIsNone(exc.obj)
1881
1882 sentinel = object()
1883 exc = AttributeError('Ouch', name='carry', obj=sentinel)
1884 self.assertEqual(exc.name, 'carry')
1885 self.assertIs(exc.obj, sentinel)
1886
1887 def test_getattr_has_name_and_obj(self):
1888 class A:
1889 blech = None
1890
1891 obj = A()
1892 try:
1893 obj.bluch
1894 except AttributeError as exc:
1895 self.assertEqual("bluch", exc.name)
1896 self.assertEqual(obj, exc.obj)
1897
1898 def test_getattr_has_name_and_obj_for_method(self):
1899 class A:
1900 def blech(self):
1901 return
1902
1903 obj = A()
1904 try:
1905 obj.bluch()
1906 except AttributeError as exc:
1907 self.assertEqual("bluch", exc.name)
1908 self.assertEqual(obj, exc.obj)
1909
1910 def test_getattr_suggestions(self):
1911 class Substitution:
1912 noise = more_noise = a = bc = None
1913 blech = None
1914
1915 class Elimination:
1916 noise = more_noise = a = bc = None
1917 blch = None
1918
1919 class Addition:
1920 noise = more_noise = a = bc = None
1921 bluchin = None
1922
1923 class SubstitutionOverElimination:
1924 blach = None
1925 bluc = None
1926
1927 class SubstitutionOverAddition:
1928 blach = None
1929 bluchi = None
1930
1931 class EliminationOverAddition:
1932 blucha = None
1933 bluc = None
1934
Pablo Galindo7a041162021-04-19 23:35:53 +01001935 for cls, suggestion in [(Substitution, "'blech'?"),
1936 (Elimination, "'blch'?"),
1937 (Addition, "'bluchin'?"),
1938 (EliminationOverAddition, "'bluc'?"),
1939 (SubstitutionOverElimination, "'blach'?"),
1940 (SubstitutionOverAddition, "'blach'?")]:
Pablo Galindo37494b42021-04-14 02:36:07 +01001941 try:
1942 cls().bluch
1943 except AttributeError as exc:
1944 with support.captured_stderr() as err:
1945 sys.__excepthook__(*sys.exc_info())
1946
1947 self.assertIn(suggestion, err.getvalue())
1948
1949 def test_getattr_suggestions_do_not_trigger_for_long_attributes(self):
1950 class A:
1951 blech = None
1952
1953 try:
1954 A().somethingverywrong
1955 except AttributeError as exc:
1956 with support.captured_stderr() as err:
1957 sys.__excepthook__(*sys.exc_info())
1958
1959 self.assertNotIn("blech", err.getvalue())
1960
Dennis Sweeney284c52d2021-04-26 20:22:27 -04001961 def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self):
1962 class MyClass:
1963 vvv = mom = w = id = pytho = None
1964
1965 with self.subTest(name="b"):
1966 try:
1967 MyClass.b
1968 except AttributeError as exc:
1969 with support.captured_stderr() as err:
1970 sys.__excepthook__(*sys.exc_info())
1971 self.assertNotIn("you mean", err.getvalue())
1972 self.assertNotIn("vvv", err.getvalue())
1973 self.assertNotIn("mom", err.getvalue())
1974 self.assertNotIn("'id'", err.getvalue())
1975 self.assertNotIn("'w'", err.getvalue())
1976 self.assertNotIn("'pytho'", err.getvalue())
1977
1978 with self.subTest(name="v"):
1979 try:
1980 MyClass.v
1981 except AttributeError as exc:
1982 with support.captured_stderr() as err:
1983 sys.__excepthook__(*sys.exc_info())
1984 self.assertNotIn("you mean", err.getvalue())
1985 self.assertNotIn("vvv", err.getvalue())
1986 self.assertNotIn("mom", err.getvalue())
1987 self.assertNotIn("'id'", err.getvalue())
1988 self.assertNotIn("'w'", err.getvalue())
1989 self.assertNotIn("'pytho'", err.getvalue())
1990
1991 with self.subTest(name="m"):
1992 try:
1993 MyClass.m
1994 except AttributeError as exc:
1995 with support.captured_stderr() as err:
1996 sys.__excepthook__(*sys.exc_info())
1997 self.assertNotIn("you mean", err.getvalue())
1998 self.assertNotIn("vvv", err.getvalue())
1999 self.assertNotIn("mom", err.getvalue())
2000 self.assertNotIn("'id'", err.getvalue())
2001 self.assertNotIn("'w'", err.getvalue())
2002 self.assertNotIn("'pytho'", err.getvalue())
2003
2004 with self.subTest(name="py"):
2005 try:
2006 MyClass.py
2007 except AttributeError as exc:
2008 with support.captured_stderr() as err:
2009 sys.__excepthook__(*sys.exc_info())
2010 self.assertNotIn("you mean", err.getvalue())
2011 self.assertNotIn("vvv", err.getvalue())
2012 self.assertNotIn("mom", err.getvalue())
2013 self.assertNotIn("'id'", err.getvalue())
2014 self.assertNotIn("'w'", err.getvalue())
2015 self.assertNotIn("'pytho'", err.getvalue())
2016
2017
Pablo Galindo37494b42021-04-14 02:36:07 +01002018 def test_getattr_suggestions_do_not_trigger_for_big_dicts(self):
2019 class A:
2020 blech = None
2021 # A class with a very big __dict__ will not be consider
2022 # for suggestions.
Dennis Sweeney80a2a4e2021-05-03 11:47:27 -04002023 for index in range(2000):
Pablo Galindo37494b42021-04-14 02:36:07 +01002024 setattr(A, f"index_{index}", None)
2025
2026 try:
2027 A().bluch
2028 except AttributeError as exc:
2029 with support.captured_stderr() as err:
2030 sys.__excepthook__(*sys.exc_info())
2031
2032 self.assertNotIn("blech", err.getvalue())
2033
2034 def test_getattr_suggestions_no_args(self):
2035 class A:
2036 blech = None
2037 def __getattr__(self, attr):
2038 raise AttributeError()
2039
2040 try:
2041 A().bluch
2042 except AttributeError as exc:
2043 with support.captured_stderr() as err:
2044 sys.__excepthook__(*sys.exc_info())
2045
2046 self.assertIn("blech", err.getvalue())
2047
2048 class A:
2049 blech = None
2050 def __getattr__(self, attr):
2051 raise AttributeError
2052
2053 try:
2054 A().bluch
2055 except AttributeError as exc:
2056 with support.captured_stderr() as err:
2057 sys.__excepthook__(*sys.exc_info())
2058
2059 self.assertIn("blech", err.getvalue())
2060
2061 def test_getattr_suggestions_invalid_args(self):
2062 class NonStringifyClass:
2063 __str__ = None
2064 __repr__ = None
2065
2066 class A:
2067 blech = None
2068 def __getattr__(self, attr):
2069 raise AttributeError(NonStringifyClass())
2070
2071 class B:
2072 blech = None
2073 def __getattr__(self, attr):
2074 raise AttributeError("Error", 23)
2075
2076 class C:
2077 blech = None
2078 def __getattr__(self, attr):
2079 raise AttributeError(23)
2080
2081 for cls in [A, B, C]:
2082 try:
2083 cls().bluch
2084 except AttributeError as exc:
2085 with support.captured_stderr() as err:
2086 sys.__excepthook__(*sys.exc_info())
2087
2088 self.assertIn("blech", err.getvalue())
2089
Miss Islington (bot)a0b1d402021-07-16 14:16:08 -07002090 def test_getattr_suggestions_for_same_name(self):
2091 class A:
2092 def __dir__(self):
2093 return ['blech']
2094 try:
2095 A().blech
2096 except AttributeError as exc:
2097 with support.captured_stderr() as err:
2098 sys.__excepthook__(*sys.exc_info())
2099
2100 self.assertNotIn("Did you mean", err.getvalue())
2101
Pablo Galindoe07f4ab2021-04-14 18:58:28 +01002102 def test_attribute_error_with_failing_dict(self):
2103 class T:
2104 bluch = 1
2105 def __dir__(self):
2106 raise AttributeError("oh no!")
2107
2108 try:
2109 T().blich
2110 except AttributeError as exc:
2111 with support.captured_stderr() as err:
2112 sys.__excepthook__(*sys.exc_info())
2113
2114 self.assertNotIn("blech", err.getvalue())
2115 self.assertNotIn("oh no!", err.getvalue())
Pablo Galindo37494b42021-04-14 02:36:07 +01002116
Pablo Galindo0b1c1692021-04-17 23:28:45 +01002117 def test_attribute_error_with_bad_name(self):
2118 try:
2119 raise AttributeError(name=12, obj=23)
2120 except AttributeError as exc:
2121 with support.captured_stderr() as err:
2122 sys.__excepthook__(*sys.exc_info())
2123
2124 self.assertNotIn("?", err.getvalue())
2125
2126
Brett Cannon79ec55e2012-04-12 20:24:54 -04002127class ImportErrorTests(unittest.TestCase):
2128
2129 def test_attributes(self):
2130 # Setting 'name' and 'path' should not be a problem.
2131 exc = ImportError('test')
2132 self.assertIsNone(exc.name)
2133 self.assertIsNone(exc.path)
2134
2135 exc = ImportError('test', name='somemodule')
2136 self.assertEqual(exc.name, 'somemodule')
2137 self.assertIsNone(exc.path)
2138
2139 exc = ImportError('test', path='somepath')
2140 self.assertEqual(exc.path, 'somepath')
2141 self.assertIsNone(exc.name)
2142
2143 exc = ImportError('test', path='somepath', name='somename')
2144 self.assertEqual(exc.name, 'somename')
2145 self.assertEqual(exc.path, 'somepath')
2146
Michael Seifert64c8f702017-04-09 09:47:12 +02002147 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002148 with self.assertRaisesRegex(TypeError, msg):
2149 ImportError('test', invalid='keyword')
2150
2151 with self.assertRaisesRegex(TypeError, msg):
2152 ImportError('test', name='name', invalid='keyword')
2153
2154 with self.assertRaisesRegex(TypeError, msg):
2155 ImportError('test', path='path', invalid='keyword')
2156
2157 with self.assertRaisesRegex(TypeError, msg):
2158 ImportError(invalid='keyword')
2159
Serhiy Storchaka47dee112016-09-27 20:45:35 +03002160 with self.assertRaisesRegex(TypeError, msg):
2161 ImportError('test', invalid='keyword', another=True)
2162
Serhiy Storchakae9e44482016-09-28 07:53:32 +03002163 def test_reset_attributes(self):
2164 exc = ImportError('test', name='name', path='path')
2165 self.assertEqual(exc.args, ('test',))
2166 self.assertEqual(exc.msg, 'test')
2167 self.assertEqual(exc.name, 'name')
2168 self.assertEqual(exc.path, 'path')
2169
2170 # Reset not specified attributes
2171 exc.__init__()
2172 self.assertEqual(exc.args, ())
2173 self.assertEqual(exc.msg, None)
2174 self.assertEqual(exc.name, None)
2175 self.assertEqual(exc.path, None)
2176
Brett Cannon07c6e712012-08-24 13:05:09 -04002177 def test_non_str_argument(self):
2178 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02002179 with check_warnings(('', BytesWarning), quiet=True):
2180 arg = b'abc'
2181 exc = ImportError(arg)
2182 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04002183
Serhiy Storchakab7853962017-04-08 09:55:07 +03002184 def test_copy_pickle(self):
2185 for kwargs in (dict(),
2186 dict(name='somename'),
2187 dict(path='somepath'),
2188 dict(name='somename', path='somepath')):
2189 orig = ImportError('test', **kwargs)
2190 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2191 exc = pickle.loads(pickle.dumps(orig, proto))
2192 self.assertEqual(exc.args, ('test',))
2193 self.assertEqual(exc.msg, 'test')
2194 self.assertEqual(exc.name, orig.name)
2195 self.assertEqual(exc.path, orig.path)
2196 for c in copy.copy, copy.deepcopy:
2197 exc = c(orig)
2198 self.assertEqual(exc.args, ('test',))
2199 self.assertEqual(exc.msg, 'test')
2200 self.assertEqual(exc.name, orig.name)
2201 self.assertEqual(exc.path, orig.path)
2202
Pablo Galindoa77aac42021-04-23 14:27:05 +01002203class SyntaxErrorTests(unittest.TestCase):
2204 def test_range_of_offsets(self):
2205 cases = [
2206 # Basic range from 2->7
2207 (("bad.py", 1, 2, "abcdefg", 1, 7),
2208 dedent(
2209 """
2210 File "bad.py", line 1
2211 abcdefg
2212 ^^^^^
2213 SyntaxError: bad bad
2214 """)),
2215 # end_offset = start_offset + 1
2216 (("bad.py", 1, 2, "abcdefg", 1, 3),
2217 dedent(
2218 """
2219 File "bad.py", line 1
2220 abcdefg
2221 ^
2222 SyntaxError: bad bad
2223 """)),
2224 # Negative end offset
2225 (("bad.py", 1, 2, "abcdefg", 1, -2),
2226 dedent(
2227 """
2228 File "bad.py", line 1
2229 abcdefg
2230 ^
2231 SyntaxError: bad bad
2232 """)),
2233 # end offset before starting offset
2234 (("bad.py", 1, 4, "abcdefg", 1, 2),
2235 dedent(
2236 """
2237 File "bad.py", line 1
2238 abcdefg
2239 ^
2240 SyntaxError: bad bad
2241 """)),
2242 # Both offsets negative
2243 (("bad.py", 1, -4, "abcdefg", 1, -2),
2244 dedent(
2245 """
2246 File "bad.py", line 1
2247 abcdefg
2248 SyntaxError: bad bad
2249 """)),
2250 # Both offsets negative and the end more negative
2251 (("bad.py", 1, -4, "abcdefg", 1, -5),
2252 dedent(
2253 """
2254 File "bad.py", line 1
2255 abcdefg
2256 SyntaxError: bad bad
2257 """)),
2258 # Both offsets 0
2259 (("bad.py", 1, 0, "abcdefg", 1, 0),
2260 dedent(
2261 """
2262 File "bad.py", line 1
2263 abcdefg
2264 SyntaxError: bad bad
2265 """)),
2266 # Start offset 0 and end offset not 0
2267 (("bad.py", 1, 0, "abcdefg", 1, 5),
2268 dedent(
2269 """
2270 File "bad.py", line 1
2271 abcdefg
2272 SyntaxError: bad bad
2273 """)),
2274 # End offset pass the source lenght
2275 (("bad.py", 1, 2, "abcdefg", 1, 100),
2276 dedent(
2277 """
2278 File "bad.py", line 1
2279 abcdefg
2280 ^^^^^^
2281 SyntaxError: bad bad
2282 """)),
2283 ]
2284 for args, expected in cases:
2285 with self.subTest(args=args):
2286 try:
2287 raise SyntaxError("bad bad", args)
2288 except SyntaxError as exc:
2289 with support.captured_stderr() as err:
2290 sys.__excepthook__(*sys.exc_info())
2291 the_exception = exc
2292
Miss Islington (bot)c0496092021-06-08 17:29:21 -07002293 def test_encodings(self):
2294 source = (
2295 '# -*- coding: cp437 -*-\n'
2296 '"¢¢¢¢¢¢" + f(4, x for x in range(1))\n'
2297 )
2298 try:
2299 with open(TESTFN, 'w', encoding='cp437') as testfile:
2300 testfile.write(source)
2301 rc, out, err = script_helper.assert_python_failure('-Wd', '-X', 'utf8', TESTFN)
2302 err = err.decode('utf-8').splitlines()
2303
2304 self.assertEqual(err[-3], ' "¢¢¢¢¢¢" + f(4, x for x in range(1))')
2305 self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^')
2306 finally:
2307 unlink(TESTFN)
2308
Pablo Galindoa77aac42021-04-23 14:27:05 +01002309 def test_attributes_new_constructor(self):
2310 args = ("bad.py", 1, 2, "abcdefg", 1, 100)
2311 the_exception = SyntaxError("bad bad", args)
2312 filename, lineno, offset, error, end_lineno, end_offset = args
2313 self.assertEqual(filename, the_exception.filename)
2314 self.assertEqual(lineno, the_exception.lineno)
2315 self.assertEqual(end_lineno, the_exception.end_lineno)
2316 self.assertEqual(offset, the_exception.offset)
2317 self.assertEqual(end_offset, the_exception.end_offset)
2318 self.assertEqual(error, the_exception.text)
2319 self.assertEqual("bad bad", the_exception.msg)
2320
2321 def test_attributes_old_constructor(self):
2322 args = ("bad.py", 1, 2, "abcdefg")
2323 the_exception = SyntaxError("bad bad", args)
2324 filename, lineno, offset, error = args
2325 self.assertEqual(filename, the_exception.filename)
2326 self.assertEqual(lineno, the_exception.lineno)
2327 self.assertEqual(None, the_exception.end_lineno)
2328 self.assertEqual(offset, the_exception.offset)
2329 self.assertEqual(None, the_exception.end_offset)
2330 self.assertEqual(error, the_exception.text)
2331 self.assertEqual("bad bad", the_exception.msg)
2332
2333 def test_incorrect_constructor(self):
2334 args = ("bad.py", 1, 2)
2335 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2336
2337 args = ("bad.py", 1, 2, 4, 5, 6, 7)
2338 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2339
2340 args = ("bad.py", 1, 2, "abcdefg", 1)
2341 self.assertRaises(TypeError, SyntaxError, "bad bad", args)
2342
Brett Cannon79ec55e2012-04-12 20:24:54 -04002343
Mark Shannonbf353f32020-12-17 13:55:28 +00002344class PEP626Tests(unittest.TestCase):
2345
Mark Shannon0b6b2862021-06-24 13:09:14 +01002346 def lineno_after_raise(self, f, *expected):
Mark Shannonbf353f32020-12-17 13:55:28 +00002347 try:
2348 f()
2349 except Exception as ex:
2350 t = ex.__traceback__
Mark Shannon0b6b2862021-06-24 13:09:14 +01002351 else:
2352 self.fail("No exception raised")
2353 lines = []
2354 t = t.tb_next # Skip this function
2355 while t:
Mark Shannonbf353f32020-12-17 13:55:28 +00002356 frame = t.tb_frame
Mark Shannon0b6b2862021-06-24 13:09:14 +01002357 lines.append(
2358 None if frame.f_lineno is None else
2359 frame.f_lineno-frame.f_code.co_firstlineno
2360 )
2361 t = t.tb_next
2362 self.assertEqual(tuple(lines), expected)
Mark Shannonbf353f32020-12-17 13:55:28 +00002363
2364 def test_lineno_after_raise_simple(self):
2365 def simple():
2366 1/0
2367 pass
2368 self.lineno_after_raise(simple, 1)
2369
2370 def test_lineno_after_raise_in_except(self):
2371 def in_except():
2372 try:
2373 1/0
2374 except:
2375 1/0
2376 pass
2377 self.lineno_after_raise(in_except, 4)
2378
2379 def test_lineno_after_other_except(self):
2380 def other_except():
2381 try:
2382 1/0
2383 except TypeError as ex:
2384 pass
2385 self.lineno_after_raise(other_except, 3)
2386
2387 def test_lineno_in_named_except(self):
2388 def in_named_except():
2389 try:
2390 1/0
2391 except Exception as ex:
2392 1/0
2393 pass
2394 self.lineno_after_raise(in_named_except, 4)
2395
2396 def test_lineno_in_try(self):
2397 def in_try():
2398 try:
2399 1/0
2400 finally:
2401 pass
2402 self.lineno_after_raise(in_try, 4)
2403
2404 def test_lineno_in_finally_normal(self):
2405 def in_finally_normal():
2406 try:
2407 pass
2408 finally:
2409 1/0
2410 pass
2411 self.lineno_after_raise(in_finally_normal, 4)
2412
2413 def test_lineno_in_finally_except(self):
2414 def in_finally_except():
2415 try:
2416 1/0
2417 finally:
2418 1/0
2419 pass
2420 self.lineno_after_raise(in_finally_except, 4)
2421
2422 def test_lineno_after_with(self):
2423 class Noop:
2424 def __enter__(self):
2425 return self
2426 def __exit__(self, *args):
2427 pass
2428 def after_with():
2429 with Noop():
2430 1/0
2431 pass
2432 self.lineno_after_raise(after_with, 2)
2433
Mark Shannon088a15c2021-04-29 19:28:50 +01002434 def test_missing_lineno_shows_as_none(self):
2435 def f():
2436 1/0
2437 self.lineno_after_raise(f, 1)
2438 f.__code__ = f.__code__.replace(co_linetable=b'\x04\x80\xff\x80')
2439 self.lineno_after_raise(f, None)
Mark Shannonbf353f32020-12-17 13:55:28 +00002440
Mark Shannon0b6b2862021-06-24 13:09:14 +01002441 def test_lineno_after_raise_in_with_exit(self):
2442 class ExitFails:
2443 def __enter__(self):
2444 return self
2445 def __exit__(self, *args):
2446 raise ValueError
2447
2448 def after_with():
2449 with ExitFails():
2450 1/0
2451 self.lineno_after_raise(after_with, 1, 1)
2452
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00002453if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00002454 unittest.main()