blob: e752ab72ccff3370cc8f747cd304f04d4322e198 [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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000011
Hai Shi46605972020-08-04 00:49:18 +080012from test.support import (captured_stderr, check_impl_detail,
13 cpython_only, gc_collect,
14 no_tracing, script_helper,
xdegaye56d1f5c2017-10-26 15:09:06 +020015 SuppressCrashReport)
Hai Shi46605972020-08-04 00:49:18 +080016from test.support.import_helper import import_module
17from test.support.os_helper import TESTFN, unlink
18from test.support.warnings_helper import check_warnings
Victor Stinnere4d300e2019-05-22 23:44:02 +020019from test import support
20
21
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010022class NaiveException(Exception):
23 def __init__(self, x):
24 self.x = x
25
26class SlottedNaiveException(Exception):
27 __slots__ = ('x',)
28 def __init__(self, x):
29 self.x = x
30
Martin Panter3263f682016-02-28 03:16:11 +000031class BrokenStrException(Exception):
32 def __str__(self):
33 raise Exception("str() is broken")
34
Guido van Rossum3bead091992-01-27 17:00:37 +000035# XXX This is not really enough, each *operation* should be tested!
36
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000037class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000038
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000039 def raise_catch(self, exc, excname):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +010040 with self.subTest(exc=exc, excname=excname):
41 try:
42 raise exc("spam")
43 except exc as err:
44 buf1 = str(err)
45 try:
46 raise exc("spam")
47 except exc as err:
48 buf2 = str(err)
49 self.assertEqual(buf1, buf2)
50 self.assertEqual(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000051
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000052 def testRaising(self):
53 self.raise_catch(AttributeError, "AttributeError")
54 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000055
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000056 self.raise_catch(EOFError, "EOFError")
57 fp = open(TESTFN, 'w')
58 fp.close()
59 fp = open(TESTFN, 'r')
60 savestdin = sys.stdin
61 try:
62 try:
63 import marshal
Antoine Pitrou4a90ef02012-03-03 02:35:32 +010064 marshal.loads(b'')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000065 except EOFError:
66 pass
67 finally:
68 sys.stdin = savestdin
69 fp.close()
70 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000071
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020072 self.raise_catch(OSError, "OSError")
73 self.assertRaises(OSError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000074
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075 self.raise_catch(ImportError, "ImportError")
76 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000077
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000078 self.raise_catch(IndexError, "IndexError")
79 x = []
80 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000081
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000082 self.raise_catch(KeyError, "KeyError")
83 x = {}
84 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000085
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000086 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000087
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000088 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000089
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000090 self.raise_catch(NameError, "NameError")
91 try: x = undefined_variable
92 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000093
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094 self.raise_catch(OverflowError, "OverflowError")
95 x = 1
96 for dummy in range(128):
97 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000098
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000099 self.raise_catch(RuntimeError, "RuntimeError")
Yury Selivanovf488fb42015-07-03 01:04:23 -0400100 self.raise_catch(RecursionError, "RecursionError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000101
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000102 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +0000103 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000104 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000105
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000106 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000107
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000108 self.raise_catch(TabError, "TabError")
Georg Brandle1b5ac62008-06-04 13:06:58 +0000109 try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
110 '<string>', 'exec')
111 except TabError: pass
112 else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000113
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000114 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000115
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000116 self.raise_catch(SystemExit, "SystemExit")
117 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000118
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000119 self.raise_catch(TypeError, "TypeError")
120 try: [] + ()
121 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000122
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000123 self.raise_catch(ValueError, "ValueError")
Guido van Rossume63bae62007-07-17 00:34:25 +0000124 self.assertRaises(ValueError, chr, 17<<16)
Guido van Rossum3bead091992-01-27 17:00:37 +0000125
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000126 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
127 try: x = 1/0
128 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000129
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000130 self.raise_catch(Exception, "Exception")
131 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000132 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000133
Yury Selivanovccc897f2015-07-03 01:16:04 -0400134 self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
135
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000136 def testSyntaxErrorMessage(self):
137 # make sure the right exception message is raised for each of
138 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000139
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000140 def ckmsg(src, msg):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100141 with self.subTest(src=src, msg=msg):
142 try:
143 compile(src, '<fragment>', 'exec')
144 except SyntaxError as e:
145 if e.msg != msg:
146 self.fail("expected %s, got %s" % (msg, e.msg))
147 else:
148 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000149
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000150 s = '''if 1:
151 try:
152 continue
153 except:
154 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000155
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000156 ckmsg(s, "'continue' not properly in loop")
157 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000158
Martijn Pieters772d8092017-08-22 21:16:23 +0100159 def testSyntaxErrorMissingParens(self):
160 def ckmsg(src, msg, exception=SyntaxError):
161 try:
162 compile(src, '<fragment>', 'exec')
163 except exception as e:
164 if e.msg != msg:
165 self.fail("expected %s, got %s" % (msg, e.msg))
166 else:
167 self.fail("failed to get expected SyntaxError")
168
169 s = '''print "old style"'''
170 ckmsg(s, "Missing parentheses in call to 'print'. "
171 "Did you mean print(\"old style\")?")
172
173 s = '''print "old style",'''
174 ckmsg(s, "Missing parentheses in call to 'print'. "
175 "Did you mean print(\"old style\", end=\" \")?")
176
177 s = '''exec "old style"'''
178 ckmsg(s, "Missing parentheses in call to 'exec'")
179
180 # should not apply to subclasses, see issue #31161
181 s = '''if True:\nprint "No indent"'''
182 ckmsg(s, "expected an indented block", IndentationError)
183
184 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
185 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
186
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300187 def check(self, src, lineno, offset, encoding='utf-8'):
Pablo Galindoaf8e5f82020-05-17 01:22:00 +0100188 with self.subTest(source=src, lineno=lineno, offset=offset):
189 with self.assertRaises(SyntaxError) as cm:
190 compile(src, '<fragment>', 'exec')
191 self.assertEqual(cm.exception.lineno, lineno)
192 self.assertEqual(cm.exception.offset, offset)
193 if cm.exception.text is not None:
194 if not isinstance(src, str):
195 src = src.decode(encoding, 'replace')
196 line = src.split('\n')[lineno-1]
197 self.assertIn(line, cm.exception.text)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200198
Batuhan Taskaya76c1b4d2020-05-01 16:13:43 +0300199 def testSyntaxErrorOffset(self):
200 check = self.check
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200201 check('def fact(x):\n\treturn x!\n', 2, 10)
202 check('1 +\n', 1, 4)
203 check('def spam():\n print(1)\n print(2)', 3, 10)
204 check('Python = "Python" +', 1, 20)
205 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200206 check(b'# -*- coding: cp1251 -*-\nPython = "\xcf\xb3\xf2\xee\xed" +',
207 2, 19, encoding='cp1251')
208 check(b'Python = "\xcf\xb3\xf2\xee\xed" +', 1, 18)
Ammar Askar025eb982018-09-24 17:12:49 -0400209 check('x = "a', 1, 7)
210 check('lambda x: x = 2', 1, 1)
Lysandros Nikolaou15acc4e2020-10-27 20:54:20 +0200211 check('f{a + b + c}', 1, 2)
Ammar Askar025eb982018-09-24 17:12:49 -0400212
213 # Errors thrown by compile.c
214 check('class foo:return 1', 1, 11)
215 check('def f():\n continue', 2, 3)
216 check('def f():\n break', 2, 3)
217 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 2, 3)
218
219 # Errors thrown by tokenizer.c
220 check('(0x+1)', 1, 3)
221 check('x = 0xI', 1, 6)
222 check('0010 + 2', 1, 4)
223 check('x = 32e-+4', 1, 8)
224 check('x = 0o9', 1, 6)
Serhiy Storchaka0cc6b5e2020-02-12 12:17:00 +0200225 check('\u03b1 = 0xI', 1, 6)
226 check(b'\xce\xb1 = 0xI', 1, 6)
227 check(b'# -*- coding: iso8859-7 -*-\n\xe1 = 0xI', 2, 6,
228 encoding='iso8859-7')
Pablo Galindo11a7f152020-04-21 01:53:04 +0100229 check(b"""if 1:
230 def foo():
231 '''
232
233 def bar():
234 pass
235
236 def baz():
237 '''quux'''
238 """, 9, 20)
Pablo Galindobcc30362020-05-14 21:11:48 +0100239 check("pass\npass\npass\n(1+)\npass\npass\npass", 4, 4)
240 check("(1+)", 1, 4)
Ammar Askar025eb982018-09-24 17:12:49 -0400241
242 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200243 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400244 check('def f():\n from _ import *', 1, 1)
245 check('def f(x, x):\n pass', 1, 1)
246 check('def f(x):\n nonlocal x', 2, 3)
247 check('def f(x):\n x = 1\n global x', 3, 3)
248 check('nonlocal x', 1, 1)
249 check('def f():\n global x\n nonlocal x', 2, 3)
250
Ammar Askar025eb982018-09-24 17:12:49 -0400251 # Errors thrown by future.c
252 check('from __future__ import doesnt_exist', 1, 1)
253 check('from __future__ import braces', 1, 1)
254 check('x=1\nfrom __future__ import division', 2, 1)
Pablo Galindo43c4fb62020-12-13 16:46:48 +0000255 check('foo(1=2)', 1, 6)
Lysandros Nikolaoua15c9b32020-05-13 22:36:27 +0300256 check('def f():\n x, y: int', 2, 3)
257 check('[*x for x in xs]', 1, 2)
258 check('foo(x for x in range(10), 100)', 1, 5)
Lysandros Nikolaou01ece632020-06-19 02:10:43 +0300259 check('for 1 in []: pass', 1, 5)
Pablo Galindo1ed83ad2020-06-11 17:30:46 +0100260 check('(yield i) = 2', 1, 2)
261 check('def f(*):\n pass', 1, 8)
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200262
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000263 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000264 def testSettingException(self):
265 # test that setting an exception at the C level works even if the
266 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000267
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000268 class BadException(Exception):
269 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000270 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000271
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000272 class InvalidException:
273 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000274
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000275 def test_capi1():
276 import _testcapi
277 try:
278 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000279 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000280 exc, err, tb = sys.exc_info()
281 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000282 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000283 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000284 else:
285 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000286
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000287 def test_capi2():
288 import _testcapi
289 try:
290 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000291 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000292 exc, err, tb = sys.exc_info()
293 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000294 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000295 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000296 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000297 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000298 else:
299 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000300
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000301 def test_capi3():
302 import _testcapi
303 self.assertRaises(SystemError, _testcapi.raise_exception,
304 InvalidException, 1)
305
306 if not sys.platform.startswith('java'):
307 test_capi1()
308 test_capi2()
309 test_capi3()
310
Thomas Wouters89f507f2006-12-13 04:49:30 +0000311 def test_WindowsError(self):
312 try:
313 WindowsError
314 except NameError:
315 pass
316 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200317 self.assertIs(WindowsError, OSError)
318 self.assertEqual(str(OSError(1001)), "1001")
319 self.assertEqual(str(OSError(1001, "message")),
320 "[Errno 1001] message")
321 # POSIX errno (9 aka EBADF) is untranslated
322 w = OSError(9, 'foo', 'bar')
323 self.assertEqual(w.errno, 9)
324 self.assertEqual(w.winerror, None)
325 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
326 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
327 w = OSError(0, 'foo', 'bar', 3)
328 self.assertEqual(w.errno, 2)
329 self.assertEqual(w.winerror, 3)
330 self.assertEqual(w.strerror, 'foo')
331 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000332 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100333 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200334 # Unknown win error becomes EINVAL (22)
335 w = OSError(0, 'foo', None, 1001)
336 self.assertEqual(w.errno, 22)
337 self.assertEqual(w.winerror, 1001)
338 self.assertEqual(w.strerror, 'foo')
339 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000340 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100341 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200342 # Non-numeric "errno"
343 w = OSError('bar', 'foo')
344 self.assertEqual(w.errno, 'bar')
345 self.assertEqual(w.winerror, None)
346 self.assertEqual(w.strerror, 'foo')
347 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000348 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000349
Victor Stinnerd223fa62015-04-02 14:17:38 +0200350 @unittest.skipUnless(sys.platform == 'win32',
351 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300352 def test_windows_message(self):
353 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200354 ctypes = import_module('ctypes')
355 # this error code has no message, Python formats it as hexadecimal
356 code = 3765269347
357 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
358 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300359
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000360 def testAttributes(self):
361 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000362
363 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000364 (BaseException, (), {'args' : ()}),
365 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000366 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000367 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000368 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000369 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000370 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000371 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200372 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000373 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000374 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200375 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000376 {'args' : ('foo', 'bar'),
377 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000378 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200379 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000380 {'args' : ('foo', 'bar'),
381 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000382 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800383 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
384 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200385 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000386 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000387 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
388 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200389 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000390 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000391 'strerror' : 'strErrorStr',
392 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000393 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000394 'filename' : None, 'lineno' : None, 'offset' : None,
395 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000396 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000397 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000398 'print_file_and_line' : None, 'msg' : 'msgStr',
399 'filename' : None, 'lineno' : None, 'offset' : None}),
400 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
401 'textStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000402 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000403 'args' : ('msgStr', ('filenameStr', 'linenoStr',
404 'offsetStr', 'textStr')),
405 'print_file_and_line' : None, 'msg' : 'msgStr',
406 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
407 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
408 'textStr', 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000409 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000410 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
411 'textStr', 'print_file_and_lineStr'),
412 'print_file_and_line' : None, 'msg' : 'msgStr',
413 'filename' : None, 'lineno' : None, 'offset' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000414 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000415 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
416 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000417 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000418 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000419 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000420 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000421 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000422 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000423 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000424 'ordinal not in range'),
425 'encoding' : 'ascii', 'object' : b'\xff',
426 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000427 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
428 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000429 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000431 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000432 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000433 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000434 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000435 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000436 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100437 (NaiveException, ('foo',),
438 {'args': ('foo',), 'x': 'foo'}),
439 (SlottedNaiveException, ('foo',),
440 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000441 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000442 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200443 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000444 exceptionList.append(
445 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000446 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200447 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000448 'errno' : 1,
449 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000450 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000451 except NameError:
452 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000453
Guido van Rossumebe3e162007-05-17 18:20:34 +0000454 for exc, args, expected in exceptionList:
455 try:
456 e = exc(*args)
457 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000458 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Guido van Rossumebe3e162007-05-17 18:20:34 +0000459 raise
460 else:
461 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100462 if not type(e).__name__.endswith('NaiveException'):
463 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000464 # Verify no ref leaks in Exc_str()
465 s = str(e)
466 for checkArgName in expected:
467 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000468 self.assertEqual(repr(value),
469 repr(expected[checkArgName]),
470 '%r.%s == %r, expected %r' % (
471 e, checkArgName,
472 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000473
Guido van Rossumebe3e162007-05-17 18:20:34 +0000474 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000475 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000476 for protocol in range(p.HIGHEST_PROTOCOL + 1):
477 s = p.dumps(e, protocol)
478 new = p.loads(s)
479 for checkArgName in expected:
480 got = repr(getattr(new, checkArgName))
481 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000482 self.assertEqual(got, want,
483 'pickled "%r", attribute "%s' %
484 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000485
Collin Winter828f04a2007-08-31 00:04:24 +0000486 def testWithTraceback(self):
487 try:
488 raise IndexError(4)
489 except:
490 tb = sys.exc_info()[2]
491
492 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000493 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000494 self.assertEqual(e.__traceback__, tb)
495
496 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000497 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000498 self.assertEqual(e.__traceback__, tb)
499
500 class MyException(Exception):
501 pass
502
503 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000504 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000505 self.assertEqual(e.__traceback__, tb)
506
507 def testInvalidTraceback(self):
508 try:
509 Exception().__traceback__ = 5
510 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000511 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000512 else:
513 self.fail("No exception raised")
514
Georg Brandlab6f2f62009-03-31 04:16:10 +0000515 def testInvalidAttrs(self):
516 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
517 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
518 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
519 self.assertRaises(TypeError, delattr, Exception(), '__context__')
520
Collin Winter828f04a2007-08-31 00:04:24 +0000521 def testNoneClearsTracebackAttr(self):
522 try:
523 raise IndexError(4)
524 except:
525 tb = sys.exc_info()[2]
526
527 e = Exception()
528 e.__traceback__ = tb
529 e.__traceback__ = None
530 self.assertEqual(e.__traceback__, None)
531
532 def testChainingAttrs(self):
533 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000534 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700535 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000536
537 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000538 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700539 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000540
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200541 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000542 pass
543
544 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000545 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700546 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000547
548 def testChainingDescriptors(self):
549 try:
550 raise Exception()
551 except Exception as exc:
552 e = exc
553
554 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700555 self.assertIsNone(e.__cause__)
556 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000557
558 e.__context__ = NameError()
559 e.__cause__ = None
560 self.assertIsInstance(e.__context__, NameError)
561 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700562 self.assertTrue(e.__suppress_context__)
563 e.__suppress_context__ = False
564 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000565
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000566 def testKeywordArgs(self):
567 # test that builtin exception don't take keyword args,
568 # but user-defined subclasses can if they want
569 self.assertRaises(TypeError, BaseException, a=1)
570
571 class DerivedException(BaseException):
572 def __init__(self, fancy_arg):
573 BaseException.__init__(self)
574 self.fancy_arg = fancy_arg
575
576 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000577 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000578
Brett Cannon31f59292011-02-21 19:29:56 +0000579 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000580 def testInfiniteRecursion(self):
581 def f():
582 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400583 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000584
585 def g():
586 try:
587 return g()
588 except ValueError:
589 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400590 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000591
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000592 def test_str(self):
593 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000594 self.assertTrue(str(Exception))
595 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000596 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000597
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000598 def testExceptionCleanupNames(self):
599 # Make sure the local variable bound to the exception instance by
600 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000601 try:
602 raise Exception()
603 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000604 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000605 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000606 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000607
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000608 def testExceptionCleanupState(self):
609 # Make sure exception state is cleaned up as soon as the except
610 # block is left. See #2507
611
612 class MyException(Exception):
613 def __init__(self, obj):
614 self.obj = obj
615 class MyObj:
616 pass
617
618 def inner_raising_func():
619 # Create some references in exception value and traceback
620 local_ref = obj
621 raise MyException(obj)
622
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000623 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000624 obj = MyObj()
625 wr = weakref.ref(obj)
626 try:
627 inner_raising_func()
628 except MyException as e:
629 pass
630 obj = None
631 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300632 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000633
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000634 # Qualified "except" without "as"
635 obj = MyObj()
636 wr = weakref.ref(obj)
637 try:
638 inner_raising_func()
639 except MyException:
640 pass
641 obj = None
642 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300643 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000644
645 # Bare "except"
646 obj = MyObj()
647 wr = weakref.ref(obj)
648 try:
649 inner_raising_func()
650 except:
651 pass
652 obj = None
653 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300654 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000655
656 # "except" with premature block leave
657 obj = MyObj()
658 wr = weakref.ref(obj)
659 for i in [0]:
660 try:
661 inner_raising_func()
662 except:
663 break
664 obj = None
665 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300666 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000667
668 # "except" block raising another exception
669 obj = MyObj()
670 wr = weakref.ref(obj)
671 try:
672 try:
673 inner_raising_func()
674 except:
675 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000676 except KeyError as e:
677 # We want to test that the except block above got rid of
678 # the exception raised in inner_raising_func(), but it
679 # also ends up in the __context__ of the KeyError, so we
680 # must clear the latter manually for our test to succeed.
681 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000682 obj = None
683 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800684 # guarantee no ref cycles on CPython (don't gc_collect)
685 if check_impl_detail(cpython=False):
686 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300687 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000688
689 # Some complicated construct
690 obj = MyObj()
691 wr = weakref.ref(obj)
692 try:
693 inner_raising_func()
694 except MyException:
695 try:
696 try:
697 raise
698 finally:
699 raise
700 except MyException:
701 pass
702 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800703 if check_impl_detail(cpython=False):
704 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000705 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300706 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000707
708 # Inside an exception-silencing "with" block
709 class Context:
710 def __enter__(self):
711 return self
712 def __exit__ (self, exc_type, exc_value, exc_tb):
713 return True
714 obj = MyObj()
715 wr = weakref.ref(obj)
716 with Context():
717 inner_raising_func()
718 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800719 if check_impl_detail(cpython=False):
720 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000721 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300722 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000723
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000724 def test_exception_target_in_nested_scope(self):
725 # issue 4617: This used to raise a SyntaxError
726 # "can not delete variable 'e' referenced in nested scope"
727 def print_error():
728 e
729 try:
730 something
731 except Exception as e:
732 print_error()
733 # implicit "del e" here
734
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000735 def test_generator_leaking(self):
736 # Test that generator exception state doesn't leak into the calling
737 # frame
738 def yield_raise():
739 try:
740 raise KeyError("caught")
741 except KeyError:
742 yield sys.exc_info()[0]
743 yield sys.exc_info()[0]
744 yield sys.exc_info()[0]
745 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000746 self.assertEqual(next(g), KeyError)
747 self.assertEqual(sys.exc_info()[0], None)
748 self.assertEqual(next(g), KeyError)
749 self.assertEqual(sys.exc_info()[0], None)
750 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000751
752 # Same test, but inside an exception handler
753 try:
754 raise TypeError("foo")
755 except TypeError:
756 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000757 self.assertEqual(next(g), KeyError)
758 self.assertEqual(sys.exc_info()[0], TypeError)
759 self.assertEqual(next(g), KeyError)
760 self.assertEqual(sys.exc_info()[0], TypeError)
761 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000762 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000763 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000764
Benjamin Peterson83195c32011-07-03 13:44:00 -0500765 def test_generator_leaking2(self):
766 # See issue 12475.
767 def g():
768 yield
769 try:
770 raise RuntimeError
771 except RuntimeError:
772 it = g()
773 next(it)
774 try:
775 next(it)
776 except StopIteration:
777 pass
778 self.assertEqual(sys.exc_info(), (None, None, None))
779
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100780 def test_generator_leaking3(self):
781 # See issue #23353. When gen.throw() is called, the caller's
782 # exception state should be save and restored.
783 def g():
784 try:
785 yield
786 except ZeroDivisionError:
787 yield sys.exc_info()[1]
788 it = g()
789 next(it)
790 try:
791 1/0
792 except ZeroDivisionError as e:
793 self.assertIs(sys.exc_info()[1], e)
794 gen_exc = it.throw(e)
795 self.assertIs(sys.exc_info()[1], e)
796 self.assertIs(gen_exc, e)
797 self.assertEqual(sys.exc_info(), (None, None, None))
798
799 def test_generator_leaking4(self):
800 # See issue #23353. When an exception is raised by a generator,
801 # the caller's exception state should still be restored.
802 def g():
803 try:
804 1/0
805 except ZeroDivisionError:
806 yield sys.exc_info()[0]
807 raise
808 it = g()
809 try:
810 raise TypeError
811 except TypeError:
812 # The caller's exception state (TypeError) is temporarily
813 # saved in the generator.
814 tp = next(it)
815 self.assertIs(tp, ZeroDivisionError)
816 try:
817 next(it)
818 # We can't check it immediately, but while next() returns
819 # with an exception, it shouldn't have restored the old
820 # exception state (TypeError).
821 except ZeroDivisionError as e:
822 self.assertIs(sys.exc_info()[1], e)
823 # We used to find TypeError here.
824 self.assertEqual(sys.exc_info(), (None, None, None))
825
Benjamin Petersonac913412011-07-03 16:25:11 -0500826 def test_generator_doesnt_retain_old_exc(self):
827 def g():
828 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
829 yield
830 self.assertEqual(sys.exc_info(), (None, None, None))
831 it = g()
832 try:
833 raise RuntimeError
834 except RuntimeError:
835 next(it)
836 self.assertRaises(StopIteration, next, it)
837
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000838 def test_generator_finalizing_and_exc_info(self):
839 # See #7173
840 def simple_gen():
841 yield 1
842 def run_gen():
843 gen = simple_gen()
844 try:
845 raise RuntimeError
846 except RuntimeError:
847 return next(gen)
848 run_gen()
849 gc_collect()
850 self.assertEqual(sys.exc_info(), (None, None, None))
851
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200852 def _check_generator_cleanup_exc_state(self, testfunc):
853 # Issue #12791: exception state is cleaned up as soon as a generator
854 # is closed (reference cycles are broken).
855 class MyException(Exception):
856 def __init__(self, obj):
857 self.obj = obj
858 class MyObj:
859 pass
860
861 def raising_gen():
862 try:
863 raise MyException(obj)
864 except MyException:
865 yield
866
867 obj = MyObj()
868 wr = weakref.ref(obj)
869 g = raising_gen()
870 next(g)
871 testfunc(g)
872 g = obj = None
873 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300874 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200875
876 def test_generator_throw_cleanup_exc_state(self):
877 def do_throw(g):
878 try:
879 g.throw(RuntimeError())
880 except RuntimeError:
881 pass
882 self._check_generator_cleanup_exc_state(do_throw)
883
884 def test_generator_close_cleanup_exc_state(self):
885 def do_close(g):
886 g.close()
887 self._check_generator_cleanup_exc_state(do_close)
888
889 def test_generator_del_cleanup_exc_state(self):
890 def do_del(g):
891 g = None
892 self._check_generator_cleanup_exc_state(do_del)
893
894 def test_generator_next_cleanup_exc_state(self):
895 def do_next(g):
896 try:
897 next(g)
898 except StopIteration:
899 pass
900 else:
901 self.fail("should have raised StopIteration")
902 self._check_generator_cleanup_exc_state(do_next)
903
904 def test_generator_send_cleanup_exc_state(self):
905 def do_send(g):
906 try:
907 g.send(None)
908 except StopIteration:
909 pass
910 else:
911 self.fail("should have raised StopIteration")
912 self._check_generator_cleanup_exc_state(do_send)
913
Benjamin Peterson27d63672008-06-15 20:09:12 +0000914 def test_3114(self):
915 # Bug #3114: in its destructor, MyObject retrieves a pointer to
916 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000917 class MyObject:
918 def __del__(self):
919 nonlocal e
920 e = sys.exc_info()
921 e = ()
922 try:
923 raise Exception(MyObject())
924 except:
925 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000926 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000927
Benjamin Peterson24dfb052014-04-02 12:05:35 -0400928 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +0000929 # See issue 7309. This was a crasher.
930
931 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
932 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
933 u.end = 2
934 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
935 u.end = 5
936 u.reason = 0x345345345345345345
937 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
938 u.encoding = 4000
939 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
940 u.start = 1000
941 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
942
943 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
944 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
945 u.end = 2
946 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
947 u.end = 5
948 u.reason = 0x345345345345345345
949 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
950 u.encoding = 4000
951 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
952 u.start = 1000
953 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
954
955 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
956 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
957 u.end = 2
958 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
959 u.end = 5
960 u.reason = 0x345345345345345345
961 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
962 u.start = 1000
963 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +0000964
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400965 def test_unicode_errors_no_object(self):
966 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -0400967 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400968 for klass in klasses:
969 self.assertEqual(str(klass.__new__(klass)), "")
970
Brett Cannon31f59292011-02-21 19:29:56 +0000971 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000972 def test_badisinstance(self):
973 # Bug #2542: if issubclass(e, MyException) raises an exception,
974 # it should be ignored
975 class Meta(type):
976 def __subclasscheck__(cls, subclass):
977 raise ValueError()
978 class MyException(Exception, metaclass=Meta):
979 pass
980
Martin Panter3263f682016-02-28 03:16:11 +0000981 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000982 try:
983 raise KeyError()
984 except MyException as e:
985 self.fail("exception should not be a MyException")
986 except KeyError:
987 pass
988 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000989 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000990 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000991 self.fail("Should have raised KeyError")
992
993 def g():
994 try:
995 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400996 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000997 return sys.exc_info()
998 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300999 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +00001000 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +00001001
xdegaye56d1f5c2017-10-26 15:09:06 +02001002 @cpython_only
1003 def test_recursion_normalizing_exception(self):
1004 # Issue #22898.
1005 # Test that a RecursionError is raised when tstate->recursion_depth is
1006 # equal to recursion_limit in PyErr_NormalizeException() and check
1007 # that a ResourceWarning is printed.
1008 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -06001009 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +02001010 # singleton was being used in that case, that held traceback data and
1011 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
1012 # finalization of these locals.
1013 code = """if 1:
1014 import sys
Victor Stinner3f2f4fe2020-03-13 13:07:31 +01001015 from _testinternalcapi import get_recursion_depth
xdegaye56d1f5c2017-10-26 15:09:06 +02001016
1017 class MyException(Exception): pass
1018
1019 def setrecursionlimit(depth):
1020 while 1:
1021 try:
1022 sys.setrecursionlimit(depth)
1023 return depth
1024 except RecursionError:
1025 # sys.setrecursionlimit() raises a RecursionError if
1026 # the new recursion limit is too low (issue #25274).
1027 depth += 1
1028
1029 def recurse(cnt):
1030 cnt -= 1
1031 if cnt:
1032 recurse(cnt)
1033 else:
1034 generator.throw(MyException)
1035
1036 def gen():
1037 f = open(%a, mode='rb', buffering=0)
1038 yield
1039
1040 generator = gen()
1041 next(generator)
1042 recursionlimit = sys.getrecursionlimit()
1043 depth = get_recursion_depth()
1044 try:
1045 # Upon the last recursive invocation of recurse(),
1046 # tstate->recursion_depth is equal to (recursion_limit - 1)
1047 # and is equal to recursion_limit when _gen_throw() calls
1048 # PyErr_NormalizeException().
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001049 recurse(setrecursionlimit(depth + 2) - depth)
xdegaye56d1f5c2017-10-26 15:09:06 +02001050 finally:
1051 sys.setrecursionlimit(recursionlimit)
1052 print('Done.')
1053 """ % __file__
1054 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1055 # Check that the program does not fail with SIGABRT.
1056 self.assertEqual(rc, 1)
1057 self.assertIn(b'RecursionError', err)
1058 self.assertIn(b'ResourceWarning', err)
1059 self.assertIn(b'Done.', out)
1060
1061 @cpython_only
1062 def test_recursion_normalizing_infinite_exception(self):
1063 # Issue #30697. Test that a RecursionError is raised when
1064 # PyErr_NormalizeException() maximum recursion depth has been
1065 # exceeded.
1066 code = """if 1:
1067 import _testcapi
1068 try:
1069 raise _testcapi.RecursingInfinitelyError
1070 finally:
1071 print('Done.')
1072 """
1073 rc, out, err = script_helper.assert_python_failure("-c", code)
1074 self.assertEqual(rc, 1)
1075 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1076 b'while normalizing an exception', err)
1077 self.assertIn(b'Done.', out)
1078
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001079
1080 def test_recursion_in_except_handler(self):
1081
1082 def set_relative_recursion_limit(n):
1083 depth = 1
1084 while True:
1085 try:
1086 sys.setrecursionlimit(depth)
1087 except RecursionError:
1088 depth += 1
1089 else:
1090 break
1091 sys.setrecursionlimit(depth+n)
1092
1093 def recurse_in_except():
1094 try:
1095 1/0
1096 except:
1097 recurse_in_except()
1098
1099 def recurse_after_except():
1100 try:
1101 1/0
1102 except:
1103 pass
1104 recurse_after_except()
1105
1106 def recurse_in_body_and_except():
1107 try:
1108 recurse_in_body_and_except()
1109 except:
1110 recurse_in_body_and_except()
1111
1112 recursionlimit = sys.getrecursionlimit()
1113 try:
1114 set_relative_recursion_limit(10)
1115 for func in (recurse_in_except, recurse_after_except, recurse_in_body_and_except):
1116 with self.subTest(func=func):
1117 try:
1118 func()
1119 except RecursionError:
1120 pass
1121 else:
1122 self.fail("Should have raised a RecursionError")
1123 finally:
1124 sys.setrecursionlimit(recursionlimit)
1125
1126
xdegaye56d1f5c2017-10-26 15:09:06 +02001127 @cpython_only
1128 def test_recursion_normalizing_with_no_memory(self):
1129 # Issue #30697. Test that in the abort that occurs when there is no
1130 # memory left and the size of the Python frames stack is greater than
1131 # the size of the list of preallocated MemoryError instances, the
1132 # Fatal Python error message mentions MemoryError.
1133 code = """if 1:
1134 import _testcapi
1135 class C(): pass
1136 def recurse(cnt):
1137 cnt -= 1
1138 if cnt:
1139 recurse(cnt)
1140 else:
1141 _testcapi.set_nomemory(0)
1142 C()
1143 recurse(16)
1144 """
1145 with SuppressCrashReport():
1146 rc, out, err = script_helper.assert_python_failure("-c", code)
Victor Stinner9e5d30c2020-03-07 00:54:20 +01001147 self.assertIn(b'Fatal Python error: _PyErr_NormalizeException: '
1148 b'Cannot recover from MemoryErrors while '
1149 b'normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001150
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001151 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001152 def test_MemoryError(self):
1153 # PyErr_NoMemory always raises the same exception instance.
1154 # Check that the traceback is not doubled.
1155 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001156 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001157 def raiseMemError():
1158 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001159 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001160 except MemoryError as e:
1161 tb = e.__traceback__
1162 else:
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001163 self.fail("Should have raised a MemoryError")
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001164 return traceback.format_tb(tb)
1165
1166 tb1 = raiseMemError()
1167 tb2 = raiseMemError()
1168 self.assertEqual(tb1, tb2)
1169
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001170 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001171 def test_exception_with_doc(self):
1172 import _testcapi
1173 doc2 = "This is a test docstring."
1174 doc4 = "This is another test docstring."
1175
1176 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1177 "error1")
1178
1179 # test basic usage of PyErr_NewException
1180 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1181 self.assertIs(type(error1), type)
1182 self.assertTrue(issubclass(error1, Exception))
1183 self.assertIsNone(error1.__doc__)
1184
1185 # test with given docstring
1186 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1187 self.assertEqual(error2.__doc__, doc2)
1188
1189 # test with explicit base (without docstring)
1190 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1191 base=error2)
1192 self.assertTrue(issubclass(error3, error2))
1193
1194 # test with explicit base tuple
1195 class C(object):
1196 pass
1197 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1198 (error3, C))
1199 self.assertTrue(issubclass(error4, error3))
1200 self.assertTrue(issubclass(error4, C))
1201 self.assertEqual(error4.__doc__, doc4)
1202
1203 # test with explicit dictionary
1204 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1205 error4, {'a': 1})
1206 self.assertTrue(issubclass(error5, error4))
1207 self.assertEqual(error5.a, 1)
1208 self.assertEqual(error5.__doc__, "")
1209
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001210 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001211 def test_memory_error_cleanup(self):
1212 # Issue #5437: preallocated MemoryError instances should not keep
1213 # traceback objects alive.
1214 from _testcapi import raise_memoryerror
1215 class C:
1216 pass
1217 wr = None
1218 def inner():
1219 nonlocal wr
1220 c = C()
1221 wr = weakref.ref(c)
1222 raise_memoryerror()
1223 # We cannot use assertRaises since it manually deletes the traceback
1224 try:
1225 inner()
1226 except MemoryError as e:
1227 self.assertNotEqual(wr(), None)
1228 else:
1229 self.fail("MemoryError not raised")
1230 self.assertEqual(wr(), None)
1231
Brett Cannon31f59292011-02-21 19:29:56 +00001232 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001233 def test_recursion_error_cleanup(self):
1234 # Same test as above, but with "recursion exceeded" errors
1235 class C:
1236 pass
1237 wr = None
1238 def inner():
1239 nonlocal wr
1240 c = C()
1241 wr = weakref.ref(c)
1242 inner()
1243 # We cannot use assertRaises since it manually deletes the traceback
1244 try:
1245 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001246 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001247 self.assertNotEqual(wr(), None)
1248 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001249 self.fail("RecursionError not raised")
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001250 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001251
Antoine Pitroua7622852011-09-01 21:37:43 +02001252 def test_errno_ENOTDIR(self):
1253 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1254 with self.assertRaises(OSError) as cm:
1255 os.listdir(__file__)
1256 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1257
Martin Panter3263f682016-02-28 03:16:11 +00001258 def test_unraisable(self):
1259 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1260 class BrokenDel:
1261 def __del__(self):
1262 exc = ValueError("del is broken")
1263 # The following line is included in the traceback report:
1264 raise exc
1265
Victor Stinnere4d300e2019-05-22 23:44:02 +02001266 obj = BrokenDel()
1267 with support.catch_unraisable_exception() as cm:
1268 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001269
Victor Stinnere4d300e2019-05-22 23:44:02 +02001270 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1271 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001272
1273 def test_unhandled(self):
1274 # Check for sensible reporting of unhandled exceptions
1275 for exc_type in (ValueError, BrokenStrException):
1276 with self.subTest(exc_type):
1277 try:
1278 exc = exc_type("test message")
1279 # The following line is included in the traceback report:
1280 raise exc
1281 except exc_type:
1282 with captured_stderr() as stderr:
1283 sys.__excepthook__(*sys.exc_info())
1284 report = stderr.getvalue()
1285 self.assertIn("test_exceptions.py", report)
1286 self.assertIn("raise exc", report)
1287 self.assertIn(exc_type.__name__, report)
1288 if exc_type is BrokenStrException:
1289 self.assertIn("<exception str() failed>", report)
1290 else:
1291 self.assertIn("test message", report)
1292 self.assertTrue(report.endswith("\n"))
1293
xdegaye66caacf2017-10-23 18:08:41 +02001294 @cpython_only
1295 def test_memory_error_in_PyErr_PrintEx(self):
1296 code = """if 1:
1297 import _testcapi
1298 class C(): pass
1299 _testcapi.set_nomemory(0, %d)
1300 C()
1301 """
1302
1303 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1304 # Span a large range of tests as the CPython code always evolves with
1305 # changes that add or remove memory allocations.
1306 for i in range(1, 20):
1307 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1308 self.assertIn(rc, (1, 120))
1309 self.assertIn(b'MemoryError', err)
1310
Mark Shannonae3087c2017-10-22 22:41:51 +01001311 def test_yield_in_nested_try_excepts(self):
1312 #Issue #25612
1313 class MainError(Exception):
1314 pass
1315
1316 class SubError(Exception):
1317 pass
1318
1319 def main():
1320 try:
1321 raise MainError()
1322 except MainError:
1323 try:
1324 yield
1325 except SubError:
1326 pass
1327 raise
1328
1329 coro = main()
1330 coro.send(None)
1331 with self.assertRaises(MainError):
1332 coro.throw(SubError())
1333
1334 def test_generator_doesnt_retain_old_exc2(self):
1335 #Issue 28884#msg282532
1336 def g():
1337 try:
1338 raise ValueError
1339 except ValueError:
1340 yield 1
1341 self.assertEqual(sys.exc_info(), (None, None, None))
1342 yield 2
1343
1344 gen = g()
1345
1346 try:
1347 raise IndexError
1348 except IndexError:
1349 self.assertEqual(next(gen), 1)
1350 self.assertEqual(next(gen), 2)
1351
1352 def test_raise_in_generator(self):
1353 #Issue 25612#msg304117
1354 def g():
1355 yield 1
1356 raise
1357 yield 2
1358
1359 with self.assertRaises(ZeroDivisionError):
1360 i = g()
1361 try:
1362 1/0
1363 except:
1364 next(i)
1365 next(i)
1366
Zackery Spytzce6a0702019-08-25 03:44:09 -06001367 @unittest.skipUnless(__debug__, "Won't work if __debug__ is False")
1368 def test_assert_shadowing(self):
1369 # Shadowing AssertionError would cause the assert statement to
1370 # misbehave.
1371 global AssertionError
1372 AssertionError = TypeError
1373 try:
1374 assert False, 'hello'
1375 except BaseException as e:
1376 del AssertionError
1377 self.assertIsInstance(e, AssertionError)
1378 self.assertEqual(str(e), 'hello')
1379 else:
1380 del AssertionError
1381 self.fail('Expected exception')
1382
Pablo Galindo9b648a92020-09-01 19:39:46 +01001383 def test_memory_error_subclasses(self):
1384 # bpo-41654: MemoryError instances use a freelist of objects that are
1385 # linked using the 'dict' attribute when they are inactive/dead.
1386 # Subclasses of MemoryError should not participate in the freelist
1387 # schema. This test creates a MemoryError object and keeps it alive
1388 # (therefore advancing the freelist) and then it creates and destroys a
1389 # subclass object. Finally, it checks that creating a new MemoryError
1390 # succeeds, proving that the freelist is not corrupted.
1391
1392 class TestException(MemoryError):
1393 pass
1394
1395 try:
1396 raise MemoryError
1397 except MemoryError as exc:
1398 inst = exc
1399
1400 try:
1401 raise TestException
1402 except Exception:
1403 pass
1404
1405 for _ in range(10):
1406 try:
1407 raise MemoryError
1408 except MemoryError as exc:
1409 pass
1410
1411 gc_collect()
1412
Antoine Pitroua7622852011-09-01 21:37:43 +02001413
Brett Cannon79ec55e2012-04-12 20:24:54 -04001414class ImportErrorTests(unittest.TestCase):
1415
1416 def test_attributes(self):
1417 # Setting 'name' and 'path' should not be a problem.
1418 exc = ImportError('test')
1419 self.assertIsNone(exc.name)
1420 self.assertIsNone(exc.path)
1421
1422 exc = ImportError('test', name='somemodule')
1423 self.assertEqual(exc.name, 'somemodule')
1424 self.assertIsNone(exc.path)
1425
1426 exc = ImportError('test', path='somepath')
1427 self.assertEqual(exc.path, 'somepath')
1428 self.assertIsNone(exc.name)
1429
1430 exc = ImportError('test', path='somepath', name='somename')
1431 self.assertEqual(exc.name, 'somename')
1432 self.assertEqual(exc.path, 'somepath')
1433
Michael Seifert64c8f702017-04-09 09:47:12 +02001434 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001435 with self.assertRaisesRegex(TypeError, msg):
1436 ImportError('test', invalid='keyword')
1437
1438 with self.assertRaisesRegex(TypeError, msg):
1439 ImportError('test', name='name', invalid='keyword')
1440
1441 with self.assertRaisesRegex(TypeError, msg):
1442 ImportError('test', path='path', invalid='keyword')
1443
1444 with self.assertRaisesRegex(TypeError, msg):
1445 ImportError(invalid='keyword')
1446
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001447 with self.assertRaisesRegex(TypeError, msg):
1448 ImportError('test', invalid='keyword', another=True)
1449
Serhiy Storchakae9e44482016-09-28 07:53:32 +03001450 def test_reset_attributes(self):
1451 exc = ImportError('test', name='name', path='path')
1452 self.assertEqual(exc.args, ('test',))
1453 self.assertEqual(exc.msg, 'test')
1454 self.assertEqual(exc.name, 'name')
1455 self.assertEqual(exc.path, 'path')
1456
1457 # Reset not specified attributes
1458 exc.__init__()
1459 self.assertEqual(exc.args, ())
1460 self.assertEqual(exc.msg, None)
1461 self.assertEqual(exc.name, None)
1462 self.assertEqual(exc.path, None)
1463
Brett Cannon07c6e712012-08-24 13:05:09 -04001464 def test_non_str_argument(self):
1465 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02001466 with check_warnings(('', BytesWarning), quiet=True):
1467 arg = b'abc'
1468 exc = ImportError(arg)
1469 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04001470
Serhiy Storchakab7853962017-04-08 09:55:07 +03001471 def test_copy_pickle(self):
1472 for kwargs in (dict(),
1473 dict(name='somename'),
1474 dict(path='somepath'),
1475 dict(name='somename', path='somepath')):
1476 orig = ImportError('test', **kwargs)
1477 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1478 exc = pickle.loads(pickle.dumps(orig, proto))
1479 self.assertEqual(exc.args, ('test',))
1480 self.assertEqual(exc.msg, 'test')
1481 self.assertEqual(exc.name, orig.name)
1482 self.assertEqual(exc.path, orig.path)
1483 for c in copy.copy, copy.deepcopy:
1484 exc = c(orig)
1485 self.assertEqual(exc.args, ('test',))
1486 self.assertEqual(exc.msg, 'test')
1487 self.assertEqual(exc.name, orig.name)
1488 self.assertEqual(exc.path, orig.path)
1489
Brett Cannon79ec55e2012-04-12 20:24:54 -04001490
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001491if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00001492 unittest.main()