blob: 10c1e076464e2c097bc1f1b21d23b5427a0455ba [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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00004import os
5import sys
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00006import unittest
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00007import pickle
Barry Warsaw8d109cb2008-05-08 04:26:35 +00008import weakref
Antoine Pitroua7622852011-09-01 21:37:43 +02009import errno
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000010
Martin Panter3263f682016-02-28 03:16:11 +000011from test.support import (TESTFN, captured_stderr, check_impl_detail,
Victor Stinner466e18e2019-07-01 19:01:52 +020012 check_warnings, cpython_only, gc_collect,
xdegaye56d1f5c2017-10-26 15:09:06 +020013 no_tracing, unlink, import_module, script_helper,
14 SuppressCrashReport)
Victor Stinnere4d300e2019-05-22 23:44:02 +020015from test import support
16
17
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010018class NaiveException(Exception):
19 def __init__(self, x):
20 self.x = x
21
22class SlottedNaiveException(Exception):
23 __slots__ = ('x',)
24 def __init__(self, x):
25 self.x = x
26
Martin Panter3263f682016-02-28 03:16:11 +000027class BrokenStrException(Exception):
28 def __str__(self):
29 raise Exception("str() is broken")
30
Guido van Rossum3bead091992-01-27 17:00:37 +000031# XXX This is not really enough, each *operation* should be tested!
32
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000033class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000034
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000035 def raise_catch(self, exc, excname):
36 try:
Collin Winter828f04a2007-08-31 00:04:24 +000037 raise exc("spam")
Guido van Rossumb940e112007-01-10 16:19:56 +000038 except exc as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000039 buf1 = str(err)
40 try:
41 raise exc("spam")
Guido van Rossumb940e112007-01-10 16:19:56 +000042 except exc as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000043 buf2 = str(err)
Ezio Melottib3aedd42010-11-20 19:04:17 +000044 self.assertEqual(buf1, buf2)
45 self.assertEqual(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000046
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000047 def testRaising(self):
48 self.raise_catch(AttributeError, "AttributeError")
49 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000050
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000051 self.raise_catch(EOFError, "EOFError")
52 fp = open(TESTFN, 'w')
53 fp.close()
54 fp = open(TESTFN, 'r')
55 savestdin = sys.stdin
56 try:
57 try:
58 import marshal
Antoine Pitrou4a90ef02012-03-03 02:35:32 +010059 marshal.loads(b'')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000060 except EOFError:
61 pass
62 finally:
63 sys.stdin = savestdin
64 fp.close()
65 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000066
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020067 self.raise_catch(OSError, "OSError")
68 self.assertRaises(OSError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000070 self.raise_catch(ImportError, "ImportError")
71 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000073 self.raise_catch(IndexError, "IndexError")
74 x = []
75 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000076
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000077 self.raise_catch(KeyError, "KeyError")
78 x = {}
79 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000080
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000081 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000083 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000084
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000085 self.raise_catch(NameError, "NameError")
86 try: x = undefined_variable
87 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000089 self.raise_catch(OverflowError, "OverflowError")
90 x = 1
91 for dummy in range(128):
92 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000093
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094 self.raise_catch(RuntimeError, "RuntimeError")
Yury Selivanovf488fb42015-07-03 01:04:23 -040095 self.raise_catch(RecursionError, "RecursionError")
Guido van Rossum3bead091992-01-27 17:00:37 +000096
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +000098 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000099 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000100
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000101 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(TabError, "TabError")
Georg Brandle1b5ac62008-06-04 13:06:58 +0000104 try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
105 '<string>', 'exec')
106 except TabError: pass
107 else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000108
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000109 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000110
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000111 self.raise_catch(SystemExit, "SystemExit")
112 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000113
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000114 self.raise_catch(TypeError, "TypeError")
115 try: [] + ()
116 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000117
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000118 self.raise_catch(ValueError, "ValueError")
Guido van Rossume63bae62007-07-17 00:34:25 +0000119 self.assertRaises(ValueError, chr, 17<<16)
Guido van Rossum3bead091992-01-27 17:00:37 +0000120
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000121 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
122 try: x = 1/0
123 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000124
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000125 self.raise_catch(Exception, "Exception")
126 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000127 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000128
Yury Selivanovccc897f2015-07-03 01:16:04 -0400129 self.raise_catch(StopAsyncIteration, "StopAsyncIteration")
130
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000131 def testSyntaxErrorMessage(self):
132 # make sure the right exception message is raised for each of
133 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000134
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000135 def ckmsg(src, msg):
136 try:
137 compile(src, '<fragment>', 'exec')
Guido van Rossumb940e112007-01-10 16:19:56 +0000138 except SyntaxError as e:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000139 if e.msg != msg:
140 self.fail("expected %s, got %s" % (msg, e.msg))
141 else:
142 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000143
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000144 s = '''if 1:
145 try:
146 continue
147 except:
148 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000149
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000150 ckmsg(s, "'continue' not properly in loop")
151 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000152
Martijn Pieters772d8092017-08-22 21:16:23 +0100153 def testSyntaxErrorMissingParens(self):
154 def ckmsg(src, msg, exception=SyntaxError):
155 try:
156 compile(src, '<fragment>', 'exec')
157 except exception as e:
158 if e.msg != msg:
159 self.fail("expected %s, got %s" % (msg, e.msg))
160 else:
161 self.fail("failed to get expected SyntaxError")
162
163 s = '''print "old style"'''
164 ckmsg(s, "Missing parentheses in call to 'print'. "
165 "Did you mean print(\"old style\")?")
166
167 s = '''print "old style",'''
168 ckmsg(s, "Missing parentheses in call to 'print'. "
169 "Did you mean print(\"old style\", end=\" \")?")
170
171 s = '''exec "old style"'''
172 ckmsg(s, "Missing parentheses in call to 'exec'")
173
174 # should not apply to subclasses, see issue #31161
175 s = '''if True:\nprint "No indent"'''
176 ckmsg(s, "expected an indented block", IndentationError)
177
178 s = '''if True:\n print()\n\texec "mixed tabs and spaces"'''
179 ckmsg(s, "inconsistent use of tabs and spaces in indentation", TabError)
180
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200181 def testSyntaxErrorOffset(self):
182 def check(src, lineno, offset):
183 with self.assertRaises(SyntaxError) as cm:
184 compile(src, '<fragment>', 'exec')
185 self.assertEqual(cm.exception.lineno, lineno)
186 self.assertEqual(cm.exception.offset, offset)
187
188 check('def fact(x):\n\treturn x!\n', 2, 10)
189 check('1 +\n', 1, 4)
190 check('def spam():\n print(1)\n print(2)', 3, 10)
191 check('Python = "Python" +', 1, 20)
192 check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20)
Ammar Askar025eb982018-09-24 17:12:49 -0400193 check('x = "a', 1, 7)
194 check('lambda x: x = 2', 1, 1)
195
196 # Errors thrown by compile.c
197 check('class foo:return 1', 1, 11)
198 check('def f():\n continue', 2, 3)
199 check('def f():\n break', 2, 3)
200 check('try:\n pass\nexcept:\n pass\nexcept ValueError:\n pass', 2, 3)
201
202 # Errors thrown by tokenizer.c
203 check('(0x+1)', 1, 3)
204 check('x = 0xI', 1, 6)
205 check('0010 + 2', 1, 4)
206 check('x = 32e-+4', 1, 8)
207 check('x = 0o9', 1, 6)
208
209 # Errors thrown by symtable.c
Serhiy Storchakab619b092018-11-27 09:40:29 +0200210 check('x = [(yield i) for i in range(3)]', 1, 5)
Ammar Askar025eb982018-09-24 17:12:49 -0400211 check('def f():\n from _ import *', 1, 1)
212 check('def f(x, x):\n pass', 1, 1)
213 check('def f(x):\n nonlocal x', 2, 3)
214 check('def f(x):\n x = 1\n global x', 3, 3)
215 check('nonlocal x', 1, 1)
216 check('def f():\n global x\n nonlocal x', 2, 3)
217
218 # Errors thrown by ast.c
219 check('for 1 in []: pass', 1, 5)
220 check('def f(*):\n pass', 1, 7)
221 check('[*x for x in xs]', 1, 2)
222 check('def f():\n x, y: int', 2, 3)
223 check('(yield i) = 2', 1, 1)
224 check('foo(x for x in range(10), 100)', 1, 5)
225 check('foo(1=2)', 1, 5)
226
227 # Errors thrown by future.c
228 check('from __future__ import doesnt_exist', 1, 1)
229 check('from __future__ import braces', 1, 1)
230 check('x=1\nfrom __future__ import division', 2, 1)
231
Serhiy Storchaka65fd0592014-01-21 22:26:52 +0200232
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000233 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000234 def testSettingException(self):
235 # test that setting an exception at the C level works even if the
236 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000237
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000238 class BadException(Exception):
239 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000240 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000241
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000242 class InvalidException:
243 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000244
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000245 def test_capi1():
246 import _testcapi
247 try:
248 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000249 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000250 exc, err, tb = sys.exc_info()
251 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000252 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000253 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000254 else:
255 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000256
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000257 def test_capi2():
258 import _testcapi
259 try:
260 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000261 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000262 exc, err, tb = sys.exc_info()
263 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000264 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000265 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000266 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000267 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000268 else:
269 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000270
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000271 def test_capi3():
272 import _testcapi
273 self.assertRaises(SystemError, _testcapi.raise_exception,
274 InvalidException, 1)
275
276 if not sys.platform.startswith('java'):
277 test_capi1()
278 test_capi2()
279 test_capi3()
280
Thomas Wouters89f507f2006-12-13 04:49:30 +0000281 def test_WindowsError(self):
282 try:
283 WindowsError
284 except NameError:
285 pass
286 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200287 self.assertIs(WindowsError, OSError)
288 self.assertEqual(str(OSError(1001)), "1001")
289 self.assertEqual(str(OSError(1001, "message")),
290 "[Errno 1001] message")
291 # POSIX errno (9 aka EBADF) is untranslated
292 w = OSError(9, 'foo', 'bar')
293 self.assertEqual(w.errno, 9)
294 self.assertEqual(w.winerror, None)
295 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
296 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
297 w = OSError(0, 'foo', 'bar', 3)
298 self.assertEqual(w.errno, 2)
299 self.assertEqual(w.winerror, 3)
300 self.assertEqual(w.strerror, 'foo')
301 self.assertEqual(w.filename, 'bar')
Martin Panter5487c132015-10-26 11:05:42 +0000302 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100303 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200304 # Unknown win error becomes EINVAL (22)
305 w = OSError(0, 'foo', None, 1001)
306 self.assertEqual(w.errno, 22)
307 self.assertEqual(w.winerror, 1001)
308 self.assertEqual(w.strerror, 'foo')
309 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000310 self.assertEqual(w.filename2, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100311 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200312 # Non-numeric "errno"
313 w = OSError('bar', 'foo')
314 self.assertEqual(w.errno, 'bar')
315 self.assertEqual(w.winerror, None)
316 self.assertEqual(w.strerror, 'foo')
317 self.assertEqual(w.filename, None)
Martin Panter5487c132015-10-26 11:05:42 +0000318 self.assertEqual(w.filename2, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319
Victor Stinnerd223fa62015-04-02 14:17:38 +0200320 @unittest.skipUnless(sys.platform == 'win32',
321 'test specific to Windows')
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300322 def test_windows_message(self):
323 """Should fill in unknown error code in Windows error message"""
Victor Stinnerd223fa62015-04-02 14:17:38 +0200324 ctypes = import_module('ctypes')
325 # this error code has no message, Python formats it as hexadecimal
326 code = 3765269347
327 with self.assertRaisesRegex(OSError, 'Windows Error 0x%x' % code):
328 ctypes.pythonapi.PyErr_SetFromWindowsErr(code)
Serhiy Storchakaf41f8f92015-04-02 09:47:27 +0300329
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000330 def testAttributes(self):
331 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000332
333 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000334 (BaseException, (), {'args' : ()}),
335 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000336 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000337 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000338 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000339 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000340 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000341 {'args' : ('foo',), 'code' : 'foo'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200342 (OSError, ('foo',),
Martin Panter5487c132015-10-26 11:05:42 +0000343 {'args' : ('foo',), 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000344 'errno' : None, 'strerror' : None}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200345 (OSError, ('foo', 'bar'),
Martin Panter5487c132015-10-26 11:05:42 +0000346 {'args' : ('foo', 'bar'),
347 'filename' : None, 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000348 'errno' : 'foo', 'strerror' : 'bar'}),
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200349 (OSError, ('foo', 'bar', 'baz'),
Martin Panter5487c132015-10-26 11:05:42 +0000350 {'args' : ('foo', 'bar'),
351 'filename' : 'baz', 'filename2' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000352 'errno' : 'foo', 'strerror' : 'bar'}),
Larry Hastingsb0827312014-02-09 22:05:19 -0800353 (OSError, ('foo', 'bar', 'baz', None, 'quux'),
354 {'args' : ('foo', 'bar'), 'filename' : 'baz', 'filename2': 'quux'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200355 (OSError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000356 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000357 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
358 'filename' : 'filenameStr'}),
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200359 (OSError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000360 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Martin Panter5487c132015-10-26 11:05:42 +0000361 'strerror' : 'strErrorStr',
362 'filename' : 'filenameStr', 'filename2' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000363 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000364 'filename' : None, 'lineno' : None, 'offset' : None,
365 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000366 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000367 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000368 'print_file_and_line' : None, 'msg' : 'msgStr',
369 'filename' : None, 'lineno' : None, 'offset' : None}),
370 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
371 'textStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000372 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000373 'args' : ('msgStr', ('filenameStr', 'linenoStr',
374 'offsetStr', 'textStr')),
375 'print_file_and_line' : None, 'msg' : 'msgStr',
376 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
377 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
378 'textStr', 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000379 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000380 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
381 'textStr', 'print_file_and_lineStr'),
382 'print_file_and_line' : None, 'msg' : 'msgStr',
383 'filename' : None, 'lineno' : None, 'offset' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000384 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000385 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
386 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000387 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000388 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000389 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000390 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000391 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000392 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000393 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000394 'ordinal not in range'),
395 'encoding' : 'ascii', 'object' : b'\xff',
396 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000397 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
398 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000399 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000400 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000401 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000402 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000403 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000404 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000405 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000406 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100407 (NaiveException, ('foo',),
408 {'args': ('foo',), 'x': 'foo'}),
409 (SlottedNaiveException, ('foo',),
410 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000411 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000412 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200413 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000414 exceptionList.append(
415 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000416 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200417 'strerror' : 'strErrorStr', 'winerror' : None,
Martin Panter5487c132015-10-26 11:05:42 +0000418 'errno' : 1,
419 'filename' : 'filenameStr', 'filename2' : None})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000420 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000421 except NameError:
422 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000423
Guido van Rossumebe3e162007-05-17 18:20:34 +0000424 for exc, args, expected in exceptionList:
425 try:
426 e = exc(*args)
427 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000428 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Guido van Rossumebe3e162007-05-17 18:20:34 +0000429 raise
430 else:
431 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100432 if not type(e).__name__.endswith('NaiveException'):
433 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000434 # Verify no ref leaks in Exc_str()
435 s = str(e)
436 for checkArgName in expected:
437 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000438 self.assertEqual(repr(value),
439 repr(expected[checkArgName]),
440 '%r.%s == %r, expected %r' % (
441 e, checkArgName,
442 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000443
Guido van Rossumebe3e162007-05-17 18:20:34 +0000444 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000445 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000446 for protocol in range(p.HIGHEST_PROTOCOL + 1):
447 s = p.dumps(e, protocol)
448 new = p.loads(s)
449 for checkArgName in expected:
450 got = repr(getattr(new, checkArgName))
451 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000452 self.assertEqual(got, want,
453 'pickled "%r", attribute "%s' %
454 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000455
Collin Winter828f04a2007-08-31 00:04:24 +0000456 def testWithTraceback(self):
457 try:
458 raise IndexError(4)
459 except:
460 tb = sys.exc_info()[2]
461
462 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000463 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000464 self.assertEqual(e.__traceback__, tb)
465
466 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000467 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000468 self.assertEqual(e.__traceback__, tb)
469
470 class MyException(Exception):
471 pass
472
473 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000474 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000475 self.assertEqual(e.__traceback__, tb)
476
477 def testInvalidTraceback(self):
478 try:
479 Exception().__traceback__ = 5
480 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000481 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000482 else:
483 self.fail("No exception raised")
484
Georg Brandlab6f2f62009-03-31 04:16:10 +0000485 def testInvalidAttrs(self):
486 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
487 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
488 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
489 self.assertRaises(TypeError, delattr, Exception(), '__context__')
490
Collin Winter828f04a2007-08-31 00:04:24 +0000491 def testNoneClearsTracebackAttr(self):
492 try:
493 raise IndexError(4)
494 except:
495 tb = sys.exc_info()[2]
496
497 e = Exception()
498 e.__traceback__ = tb
499 e.__traceback__ = None
500 self.assertEqual(e.__traceback__, None)
501
502 def testChainingAttrs(self):
503 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000504 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700505 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000506
507 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000508 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700509 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000510
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200511 class MyException(OSError):
Collin Winter828f04a2007-08-31 00:04:24 +0000512 pass
513
514 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000515 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700516 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000517
518 def testChainingDescriptors(self):
519 try:
520 raise Exception()
521 except Exception as exc:
522 e = exc
523
524 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700525 self.assertIsNone(e.__cause__)
526 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000527
528 e.__context__ = NameError()
529 e.__cause__ = None
530 self.assertIsInstance(e.__context__, NameError)
531 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700532 self.assertTrue(e.__suppress_context__)
533 e.__suppress_context__ = False
534 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000535
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000536 def testKeywordArgs(self):
537 # test that builtin exception don't take keyword args,
538 # but user-defined subclasses can if they want
539 self.assertRaises(TypeError, BaseException, a=1)
540
541 class DerivedException(BaseException):
542 def __init__(self, fancy_arg):
543 BaseException.__init__(self)
544 self.fancy_arg = fancy_arg
545
546 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000547 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000548
Brett Cannon31f59292011-02-21 19:29:56 +0000549 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000550 def testInfiniteRecursion(self):
551 def f():
552 return f()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400553 self.assertRaises(RecursionError, f)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000554
555 def g():
556 try:
557 return g()
558 except ValueError:
559 return -1
Yury Selivanovf488fb42015-07-03 01:04:23 -0400560 self.assertRaises(RecursionError, g)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000561
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000562 def test_str(self):
563 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000564 self.assertTrue(str(Exception))
565 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000566 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000567
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000568 def testExceptionCleanupNames(self):
569 # Make sure the local variable bound to the exception instance by
570 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000571 try:
572 raise Exception()
573 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000574 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000575 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000576 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000577
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000578 def testExceptionCleanupState(self):
579 # Make sure exception state is cleaned up as soon as the except
580 # block is left. See #2507
581
582 class MyException(Exception):
583 def __init__(self, obj):
584 self.obj = obj
585 class MyObj:
586 pass
587
588 def inner_raising_func():
589 # Create some references in exception value and traceback
590 local_ref = obj
591 raise MyException(obj)
592
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000593 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000594 obj = MyObj()
595 wr = weakref.ref(obj)
596 try:
597 inner_raising_func()
598 except MyException as e:
599 pass
600 obj = None
601 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300602 self.assertIsNone(obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000603
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000604 # Qualified "except" without "as"
605 obj = MyObj()
606 wr = weakref.ref(obj)
607 try:
608 inner_raising_func()
609 except MyException:
610 pass
611 obj = None
612 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300613 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000614
615 # Bare "except"
616 obj = MyObj()
617 wr = weakref.ref(obj)
618 try:
619 inner_raising_func()
620 except:
621 pass
622 obj = None
623 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300624 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000625
626 # "except" with premature block leave
627 obj = MyObj()
628 wr = weakref.ref(obj)
629 for i in [0]:
630 try:
631 inner_raising_func()
632 except:
633 break
634 obj = None
635 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300636 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000637
638 # "except" block raising another exception
639 obj = MyObj()
640 wr = weakref.ref(obj)
641 try:
642 try:
643 inner_raising_func()
644 except:
645 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000646 except KeyError as e:
647 # We want to test that the except block above got rid of
648 # the exception raised in inner_raising_func(), but it
649 # also ends up in the __context__ of the KeyError, so we
650 # must clear the latter manually for our test to succeed.
651 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000652 obj = None
653 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800654 # guarantee no ref cycles on CPython (don't gc_collect)
655 if check_impl_detail(cpython=False):
656 gc_collect()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300657 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000658
659 # Some complicated construct
660 obj = MyObj()
661 wr = weakref.ref(obj)
662 try:
663 inner_raising_func()
664 except MyException:
665 try:
666 try:
667 raise
668 finally:
669 raise
670 except MyException:
671 pass
672 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800673 if check_impl_detail(cpython=False):
674 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000675 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300676 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000677
678 # Inside an exception-silencing "with" block
679 class Context:
680 def __enter__(self):
681 return self
682 def __exit__ (self, exc_type, exc_value, exc_tb):
683 return True
684 obj = MyObj()
685 wr = weakref.ref(obj)
686 with Context():
687 inner_raising_func()
688 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800689 if check_impl_detail(cpython=False):
690 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000691 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300692 self.assertIsNone(obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000693
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000694 def test_exception_target_in_nested_scope(self):
695 # issue 4617: This used to raise a SyntaxError
696 # "can not delete variable 'e' referenced in nested scope"
697 def print_error():
698 e
699 try:
700 something
701 except Exception as e:
702 print_error()
703 # implicit "del e" here
704
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000705 def test_generator_leaking(self):
706 # Test that generator exception state doesn't leak into the calling
707 # frame
708 def yield_raise():
709 try:
710 raise KeyError("caught")
711 except KeyError:
712 yield sys.exc_info()[0]
713 yield sys.exc_info()[0]
714 yield sys.exc_info()[0]
715 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000716 self.assertEqual(next(g), KeyError)
717 self.assertEqual(sys.exc_info()[0], None)
718 self.assertEqual(next(g), KeyError)
719 self.assertEqual(sys.exc_info()[0], None)
720 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000721
722 # Same test, but inside an exception handler
723 try:
724 raise TypeError("foo")
725 except TypeError:
726 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000727 self.assertEqual(next(g), KeyError)
728 self.assertEqual(sys.exc_info()[0], TypeError)
729 self.assertEqual(next(g), KeyError)
730 self.assertEqual(sys.exc_info()[0], TypeError)
731 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000732 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000733 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000734
Benjamin Peterson83195c32011-07-03 13:44:00 -0500735 def test_generator_leaking2(self):
736 # See issue 12475.
737 def g():
738 yield
739 try:
740 raise RuntimeError
741 except RuntimeError:
742 it = g()
743 next(it)
744 try:
745 next(it)
746 except StopIteration:
747 pass
748 self.assertEqual(sys.exc_info(), (None, None, None))
749
Antoine Pitrouc4c19b32015-03-18 22:22:46 +0100750 def test_generator_leaking3(self):
751 # See issue #23353. When gen.throw() is called, the caller's
752 # exception state should be save and restored.
753 def g():
754 try:
755 yield
756 except ZeroDivisionError:
757 yield sys.exc_info()[1]
758 it = g()
759 next(it)
760 try:
761 1/0
762 except ZeroDivisionError as e:
763 self.assertIs(sys.exc_info()[1], e)
764 gen_exc = it.throw(e)
765 self.assertIs(sys.exc_info()[1], e)
766 self.assertIs(gen_exc, e)
767 self.assertEqual(sys.exc_info(), (None, None, None))
768
769 def test_generator_leaking4(self):
770 # See issue #23353. When an exception is raised by a generator,
771 # the caller's exception state should still be restored.
772 def g():
773 try:
774 1/0
775 except ZeroDivisionError:
776 yield sys.exc_info()[0]
777 raise
778 it = g()
779 try:
780 raise TypeError
781 except TypeError:
782 # The caller's exception state (TypeError) is temporarily
783 # saved in the generator.
784 tp = next(it)
785 self.assertIs(tp, ZeroDivisionError)
786 try:
787 next(it)
788 # We can't check it immediately, but while next() returns
789 # with an exception, it shouldn't have restored the old
790 # exception state (TypeError).
791 except ZeroDivisionError as e:
792 self.assertIs(sys.exc_info()[1], e)
793 # We used to find TypeError here.
794 self.assertEqual(sys.exc_info(), (None, None, None))
795
Benjamin Petersonac913412011-07-03 16:25:11 -0500796 def test_generator_doesnt_retain_old_exc(self):
797 def g():
798 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
799 yield
800 self.assertEqual(sys.exc_info(), (None, None, None))
801 it = g()
802 try:
803 raise RuntimeError
804 except RuntimeError:
805 next(it)
806 self.assertRaises(StopIteration, next, it)
807
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000808 def test_generator_finalizing_and_exc_info(self):
809 # See #7173
810 def simple_gen():
811 yield 1
812 def run_gen():
813 gen = simple_gen()
814 try:
815 raise RuntimeError
816 except RuntimeError:
817 return next(gen)
818 run_gen()
819 gc_collect()
820 self.assertEqual(sys.exc_info(), (None, None, None))
821
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200822 def _check_generator_cleanup_exc_state(self, testfunc):
823 # Issue #12791: exception state is cleaned up as soon as a generator
824 # is closed (reference cycles are broken).
825 class MyException(Exception):
826 def __init__(self, obj):
827 self.obj = obj
828 class MyObj:
829 pass
830
831 def raising_gen():
832 try:
833 raise MyException(obj)
834 except MyException:
835 yield
836
837 obj = MyObj()
838 wr = weakref.ref(obj)
839 g = raising_gen()
840 next(g)
841 testfunc(g)
842 g = obj = None
843 obj = wr()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300844 self.assertIsNone(obj)
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200845
846 def test_generator_throw_cleanup_exc_state(self):
847 def do_throw(g):
848 try:
849 g.throw(RuntimeError())
850 except RuntimeError:
851 pass
852 self._check_generator_cleanup_exc_state(do_throw)
853
854 def test_generator_close_cleanup_exc_state(self):
855 def do_close(g):
856 g.close()
857 self._check_generator_cleanup_exc_state(do_close)
858
859 def test_generator_del_cleanup_exc_state(self):
860 def do_del(g):
861 g = None
862 self._check_generator_cleanup_exc_state(do_del)
863
864 def test_generator_next_cleanup_exc_state(self):
865 def do_next(g):
866 try:
867 next(g)
868 except StopIteration:
869 pass
870 else:
871 self.fail("should have raised StopIteration")
872 self._check_generator_cleanup_exc_state(do_next)
873
874 def test_generator_send_cleanup_exc_state(self):
875 def do_send(g):
876 try:
877 g.send(None)
878 except StopIteration:
879 pass
880 else:
881 self.fail("should have raised StopIteration")
882 self._check_generator_cleanup_exc_state(do_send)
883
Benjamin Peterson27d63672008-06-15 20:09:12 +0000884 def test_3114(self):
885 # Bug #3114: in its destructor, MyObject retrieves a pointer to
886 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000887 class MyObject:
888 def __del__(self):
889 nonlocal e
890 e = sys.exc_info()
891 e = ()
892 try:
893 raise Exception(MyObject())
894 except:
895 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000896 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000897
Benjamin Peterson24dfb052014-04-02 12:05:35 -0400898 def test_unicode_change_attributes(self):
Eric Smith0facd772010-02-24 15:42:29 +0000899 # See issue 7309. This was a crasher.
900
901 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
902 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
903 u.end = 2
904 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
905 u.end = 5
906 u.reason = 0x345345345345345345
907 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
908 u.encoding = 4000
909 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
910 u.start = 1000
911 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
912
913 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
914 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
915 u.end = 2
916 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
917 u.end = 5
918 u.reason = 0x345345345345345345
919 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
920 u.encoding = 4000
921 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
922 u.start = 1000
923 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
924
925 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
926 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
927 u.end = 2
928 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
929 u.end = 5
930 u.reason = 0x345345345345345345
931 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
932 u.start = 1000
933 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +0000934
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400935 def test_unicode_errors_no_object(self):
936 # See issue #21134.
Benjamin Petersone3311212014-04-02 15:51:38 -0400937 klasses = UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError
Benjamin Peterson9b09ba12014-04-02 12:15:06 -0400938 for klass in klasses:
939 self.assertEqual(str(klass.__new__(klass)), "")
940
Brett Cannon31f59292011-02-21 19:29:56 +0000941 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000942 def test_badisinstance(self):
943 # Bug #2542: if issubclass(e, MyException) raises an exception,
944 # it should be ignored
945 class Meta(type):
946 def __subclasscheck__(cls, subclass):
947 raise ValueError()
948 class MyException(Exception, metaclass=Meta):
949 pass
950
Martin Panter3263f682016-02-28 03:16:11 +0000951 with captured_stderr() as stderr:
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000952 try:
953 raise KeyError()
954 except MyException as e:
955 self.fail("exception should not be a MyException")
956 except KeyError:
957 pass
958 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000959 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000960 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000961 self.fail("Should have raised KeyError")
962
963 def g():
964 try:
965 return g()
Yury Selivanovf488fb42015-07-03 01:04:23 -0400966 except RecursionError:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000967 return sys.exc_info()
968 e, v, tb = g()
Serhiy Storchakaf15c4d32017-03-30 18:05:08 +0300969 self.assertIsInstance(v, RecursionError, type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000970 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000971
xdegaye56d1f5c2017-10-26 15:09:06 +0200972 @cpython_only
973 def test_recursion_normalizing_exception(self):
974 # Issue #22898.
975 # Test that a RecursionError is raised when tstate->recursion_depth is
976 # equal to recursion_limit in PyErr_NormalizeException() and check
977 # that a ResourceWarning is printed.
978 # Prior to #22898, the recursivity of PyErr_NormalizeException() was
luzpaza5293b42017-11-05 07:37:50 -0600979 # controlled by tstate->recursion_depth and a PyExc_RecursionErrorInst
xdegaye56d1f5c2017-10-26 15:09:06 +0200980 # singleton was being used in that case, that held traceback data and
981 # locals indefinitely and would cause a segfault in _PyExc_Fini() upon
982 # finalization of these locals.
983 code = """if 1:
984 import sys
985 from _testcapi import get_recursion_depth
986
987 class MyException(Exception): pass
988
989 def setrecursionlimit(depth):
990 while 1:
991 try:
992 sys.setrecursionlimit(depth)
993 return depth
994 except RecursionError:
995 # sys.setrecursionlimit() raises a RecursionError if
996 # the new recursion limit is too low (issue #25274).
997 depth += 1
998
999 def recurse(cnt):
1000 cnt -= 1
1001 if cnt:
1002 recurse(cnt)
1003 else:
1004 generator.throw(MyException)
1005
1006 def gen():
1007 f = open(%a, mode='rb', buffering=0)
1008 yield
1009
1010 generator = gen()
1011 next(generator)
1012 recursionlimit = sys.getrecursionlimit()
1013 depth = get_recursion_depth()
1014 try:
1015 # Upon the last recursive invocation of recurse(),
1016 # tstate->recursion_depth is equal to (recursion_limit - 1)
1017 # and is equal to recursion_limit when _gen_throw() calls
1018 # PyErr_NormalizeException().
1019 recurse(setrecursionlimit(depth + 2) - depth - 1)
1020 finally:
1021 sys.setrecursionlimit(recursionlimit)
1022 print('Done.')
1023 """ % __file__
1024 rc, out, err = script_helper.assert_python_failure("-Wd", "-c", code)
1025 # Check that the program does not fail with SIGABRT.
1026 self.assertEqual(rc, 1)
1027 self.assertIn(b'RecursionError', err)
1028 self.assertIn(b'ResourceWarning', err)
1029 self.assertIn(b'Done.', out)
1030
1031 @cpython_only
1032 def test_recursion_normalizing_infinite_exception(self):
1033 # Issue #30697. Test that a RecursionError is raised when
1034 # PyErr_NormalizeException() maximum recursion depth has been
1035 # exceeded.
1036 code = """if 1:
1037 import _testcapi
1038 try:
1039 raise _testcapi.RecursingInfinitelyError
1040 finally:
1041 print('Done.')
1042 """
1043 rc, out, err = script_helper.assert_python_failure("-c", code)
1044 self.assertEqual(rc, 1)
1045 self.assertIn(b'RecursionError: maximum recursion depth exceeded '
1046 b'while normalizing an exception', err)
1047 self.assertIn(b'Done.', out)
1048
1049 @cpython_only
1050 def test_recursion_normalizing_with_no_memory(self):
1051 # Issue #30697. Test that in the abort that occurs when there is no
1052 # memory left and the size of the Python frames stack is greater than
1053 # the size of the list of preallocated MemoryError instances, the
1054 # Fatal Python error message mentions MemoryError.
1055 code = """if 1:
1056 import _testcapi
1057 class C(): pass
1058 def recurse(cnt):
1059 cnt -= 1
1060 if cnt:
1061 recurse(cnt)
1062 else:
1063 _testcapi.set_nomemory(0)
1064 C()
1065 recurse(16)
1066 """
1067 with SuppressCrashReport():
1068 rc, out, err = script_helper.assert_python_failure("-c", code)
1069 self.assertIn(b'Fatal Python error: Cannot recover from '
1070 b'MemoryErrors while normalizing exceptions.', err)
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001071
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001072 @cpython_only
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001073 def test_MemoryError(self):
1074 # PyErr_NoMemory always raises the same exception instance.
1075 # Check that the traceback is not doubled.
1076 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001077 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001078 def raiseMemError():
1079 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +00001080 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +00001081 except MemoryError as e:
1082 tb = e.__traceback__
1083 else:
1084 self.fail("Should have raises a MemoryError")
1085 return traceback.format_tb(tb)
1086
1087 tb1 = raiseMemError()
1088 tb2 = raiseMemError()
1089 self.assertEqual(tb1, tb2)
1090
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +00001091 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +00001092 def test_exception_with_doc(self):
1093 import _testcapi
1094 doc2 = "This is a test docstring."
1095 doc4 = "This is another test docstring."
1096
1097 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
1098 "error1")
1099
1100 # test basic usage of PyErr_NewException
1101 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
1102 self.assertIs(type(error1), type)
1103 self.assertTrue(issubclass(error1, Exception))
1104 self.assertIsNone(error1.__doc__)
1105
1106 # test with given docstring
1107 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
1108 self.assertEqual(error2.__doc__, doc2)
1109
1110 # test with explicit base (without docstring)
1111 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
1112 base=error2)
1113 self.assertTrue(issubclass(error3, error2))
1114
1115 # test with explicit base tuple
1116 class C(object):
1117 pass
1118 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
1119 (error3, C))
1120 self.assertTrue(issubclass(error4, error3))
1121 self.assertTrue(issubclass(error4, C))
1122 self.assertEqual(error4.__doc__, doc4)
1123
1124 # test with explicit dictionary
1125 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
1126 error4, {'a': 1})
1127 self.assertTrue(issubclass(error5, error4))
1128 self.assertEqual(error5.a, 1)
1129 self.assertEqual(error5.__doc__, "")
1130
Serhiy Storchaka5cfc79d2014-02-07 10:06:39 +02001131 @cpython_only
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001132 def test_memory_error_cleanup(self):
1133 # Issue #5437: preallocated MemoryError instances should not keep
1134 # traceback objects alive.
1135 from _testcapi import raise_memoryerror
1136 class C:
1137 pass
1138 wr = None
1139 def inner():
1140 nonlocal wr
1141 c = C()
1142 wr = weakref.ref(c)
1143 raise_memoryerror()
1144 # We cannot use assertRaises since it manually deletes the traceback
1145 try:
1146 inner()
1147 except MemoryError as e:
1148 self.assertNotEqual(wr(), None)
1149 else:
1150 self.fail("MemoryError not raised")
1151 self.assertEqual(wr(), None)
1152
Brett Cannon31f59292011-02-21 19:29:56 +00001153 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001154 def test_recursion_error_cleanup(self):
1155 # Same test as above, but with "recursion exceeded" errors
1156 class C:
1157 pass
1158 wr = None
1159 def inner():
1160 nonlocal wr
1161 c = C()
1162 wr = weakref.ref(c)
1163 inner()
1164 # We cannot use assertRaises since it manually deletes the traceback
1165 try:
1166 inner()
Yury Selivanovf488fb42015-07-03 01:04:23 -04001167 except RecursionError as e:
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001168 self.assertNotEqual(wr(), None)
1169 else:
Yury Selivanovf488fb42015-07-03 01:04:23 -04001170 self.fail("RecursionError not raised")
Antoine Pitrou07e20ef2010-10-28 22:56:58 +00001171 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +00001172
Antoine Pitroua7622852011-09-01 21:37:43 +02001173 def test_errno_ENOTDIR(self):
1174 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
1175 with self.assertRaises(OSError) as cm:
1176 os.listdir(__file__)
1177 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
1178
Martin Panter3263f682016-02-28 03:16:11 +00001179 def test_unraisable(self):
1180 # Issue #22836: PyErr_WriteUnraisable() should give sensible reports
1181 class BrokenDel:
1182 def __del__(self):
1183 exc = ValueError("del is broken")
1184 # The following line is included in the traceback report:
1185 raise exc
1186
Victor Stinnere4d300e2019-05-22 23:44:02 +02001187 obj = BrokenDel()
1188 with support.catch_unraisable_exception() as cm:
1189 del obj
Martin Panter3263f682016-02-28 03:16:11 +00001190
Victor Stinnere4d300e2019-05-22 23:44:02 +02001191 self.assertEqual(cm.unraisable.object, BrokenDel.__del__)
1192 self.assertIsNotNone(cm.unraisable.exc_traceback)
Martin Panter3263f682016-02-28 03:16:11 +00001193
1194 def test_unhandled(self):
1195 # Check for sensible reporting of unhandled exceptions
1196 for exc_type in (ValueError, BrokenStrException):
1197 with self.subTest(exc_type):
1198 try:
1199 exc = exc_type("test message")
1200 # The following line is included in the traceback report:
1201 raise exc
1202 except exc_type:
1203 with captured_stderr() as stderr:
1204 sys.__excepthook__(*sys.exc_info())
1205 report = stderr.getvalue()
1206 self.assertIn("test_exceptions.py", report)
1207 self.assertIn("raise exc", report)
1208 self.assertIn(exc_type.__name__, report)
1209 if exc_type is BrokenStrException:
1210 self.assertIn("<exception str() failed>", report)
1211 else:
1212 self.assertIn("test message", report)
1213 self.assertTrue(report.endswith("\n"))
1214
xdegaye66caacf2017-10-23 18:08:41 +02001215 @cpython_only
1216 def test_memory_error_in_PyErr_PrintEx(self):
1217 code = """if 1:
1218 import _testcapi
1219 class C(): pass
1220 _testcapi.set_nomemory(0, %d)
1221 C()
1222 """
1223
1224 # Issue #30817: Abort in PyErr_PrintEx() when no memory.
1225 # Span a large range of tests as the CPython code always evolves with
1226 # changes that add or remove memory allocations.
1227 for i in range(1, 20):
1228 rc, out, err = script_helper.assert_python_failure("-c", code % i)
1229 self.assertIn(rc, (1, 120))
1230 self.assertIn(b'MemoryError', err)
1231
Mark Shannonae3087c2017-10-22 22:41:51 +01001232 def test_yield_in_nested_try_excepts(self):
1233 #Issue #25612
1234 class MainError(Exception):
1235 pass
1236
1237 class SubError(Exception):
1238 pass
1239
1240 def main():
1241 try:
1242 raise MainError()
1243 except MainError:
1244 try:
1245 yield
1246 except SubError:
1247 pass
1248 raise
1249
1250 coro = main()
1251 coro.send(None)
1252 with self.assertRaises(MainError):
1253 coro.throw(SubError())
1254
1255 def test_generator_doesnt_retain_old_exc2(self):
1256 #Issue 28884#msg282532
1257 def g():
1258 try:
1259 raise ValueError
1260 except ValueError:
1261 yield 1
1262 self.assertEqual(sys.exc_info(), (None, None, None))
1263 yield 2
1264
1265 gen = g()
1266
1267 try:
1268 raise IndexError
1269 except IndexError:
1270 self.assertEqual(next(gen), 1)
1271 self.assertEqual(next(gen), 2)
1272
1273 def test_raise_in_generator(self):
1274 #Issue 25612#msg304117
1275 def g():
1276 yield 1
1277 raise
1278 yield 2
1279
1280 with self.assertRaises(ZeroDivisionError):
1281 i = g()
1282 try:
1283 1/0
1284 except:
1285 next(i)
1286 next(i)
1287
Antoine Pitroua7622852011-09-01 21:37:43 +02001288
Brett Cannon79ec55e2012-04-12 20:24:54 -04001289class ImportErrorTests(unittest.TestCase):
1290
1291 def test_attributes(self):
1292 # Setting 'name' and 'path' should not be a problem.
1293 exc = ImportError('test')
1294 self.assertIsNone(exc.name)
1295 self.assertIsNone(exc.path)
1296
1297 exc = ImportError('test', name='somemodule')
1298 self.assertEqual(exc.name, 'somemodule')
1299 self.assertIsNone(exc.path)
1300
1301 exc = ImportError('test', path='somepath')
1302 self.assertEqual(exc.path, 'somepath')
1303 self.assertIsNone(exc.name)
1304
1305 exc = ImportError('test', path='somepath', name='somename')
1306 self.assertEqual(exc.name, 'somename')
1307 self.assertEqual(exc.path, 'somepath')
1308
Michael Seifert64c8f702017-04-09 09:47:12 +02001309 msg = "'invalid' is an invalid keyword argument for ImportError"
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001310 with self.assertRaisesRegex(TypeError, msg):
1311 ImportError('test', invalid='keyword')
1312
1313 with self.assertRaisesRegex(TypeError, msg):
1314 ImportError('test', name='name', invalid='keyword')
1315
1316 with self.assertRaisesRegex(TypeError, msg):
1317 ImportError('test', path='path', invalid='keyword')
1318
1319 with self.assertRaisesRegex(TypeError, msg):
1320 ImportError(invalid='keyword')
1321
Serhiy Storchaka47dee112016-09-27 20:45:35 +03001322 with self.assertRaisesRegex(TypeError, msg):
1323 ImportError('test', invalid='keyword', another=True)
1324
Serhiy Storchakae9e44482016-09-28 07:53:32 +03001325 def test_reset_attributes(self):
1326 exc = ImportError('test', name='name', path='path')
1327 self.assertEqual(exc.args, ('test',))
1328 self.assertEqual(exc.msg, 'test')
1329 self.assertEqual(exc.name, 'name')
1330 self.assertEqual(exc.path, 'path')
1331
1332 # Reset not specified attributes
1333 exc.__init__()
1334 self.assertEqual(exc.args, ())
1335 self.assertEqual(exc.msg, None)
1336 self.assertEqual(exc.name, None)
1337 self.assertEqual(exc.path, None)
1338
Brett Cannon07c6e712012-08-24 13:05:09 -04001339 def test_non_str_argument(self):
1340 # Issue #15778
Nadeem Vawda6d708702012-10-14 01:42:32 +02001341 with check_warnings(('', BytesWarning), quiet=True):
1342 arg = b'abc'
1343 exc = ImportError(arg)
1344 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -04001345
Serhiy Storchakab7853962017-04-08 09:55:07 +03001346 def test_copy_pickle(self):
1347 for kwargs in (dict(),
1348 dict(name='somename'),
1349 dict(path='somepath'),
1350 dict(name='somename', path='somepath')):
1351 orig = ImportError('test', **kwargs)
1352 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
1353 exc = pickle.loads(pickle.dumps(orig, proto))
1354 self.assertEqual(exc.args, ('test',))
1355 self.assertEqual(exc.msg, 'test')
1356 self.assertEqual(exc.name, orig.name)
1357 self.assertEqual(exc.path, orig.path)
1358 for c in copy.copy, copy.deepcopy:
1359 exc = c(orig)
1360 self.assertEqual(exc.args, ('test',))
1361 self.assertEqual(exc.msg, 'test')
1362 self.assertEqual(exc.name, orig.name)
1363 self.assertEqual(exc.path, orig.path)
1364
Brett Cannon79ec55e2012-04-12 20:24:54 -04001365
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00001366if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +00001367 unittest.main()