blob: 1ad7f97b740ed300e1e9c30835a3aff515f6e94f [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00003import os
4import sys
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00005import unittest
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00006import pickle
Barry Warsaw8d109cb2008-05-08 04:26:35 +00007import weakref
Antoine Pitroua7622852011-09-01 21:37:43 +02008import errno
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00009
Philip Jenveyb37ac8e2012-11-14 14:37:24 -080010from test.support import (TESTFN, captured_output, check_impl_detail,
Philip Jenvey21c95eb2012-11-14 14:49:49 -080011 cpython_only, gc_collect, run_unittest, no_tracing,
12 unlink)
Guido van Rossum83b120d2001-08-23 03:23:03 +000013
Richard Oudkerk5562d9d2012-07-28 17:45:28 +010014class NaiveException(Exception):
15 def __init__(self, x):
16 self.x = x
17
18class SlottedNaiveException(Exception):
19 __slots__ = ('x',)
20 def __init__(self, x):
21 self.x = x
22
Guido van Rossum3bead091992-01-27 17:00:37 +000023# XXX This is not really enough, each *operation* should be tested!
24
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000025class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000026
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000027 def raise_catch(self, exc, excname):
28 try:
Collin Winter828f04a2007-08-31 00:04:24 +000029 raise exc("spam")
Guido van Rossumb940e112007-01-10 16:19:56 +000030 except exc as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000031 buf1 = str(err)
32 try:
33 raise exc("spam")
Guido van Rossumb940e112007-01-10 16:19:56 +000034 except exc as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000035 buf2 = str(err)
Ezio Melottib3aedd42010-11-20 19:04:17 +000036 self.assertEqual(buf1, buf2)
37 self.assertEqual(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000038
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000039 def testRaising(self):
40 self.raise_catch(AttributeError, "AttributeError")
41 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000042
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000043 self.raise_catch(EOFError, "EOFError")
44 fp = open(TESTFN, 'w')
45 fp.close()
46 fp = open(TESTFN, 'r')
47 savestdin = sys.stdin
48 try:
49 try:
50 import marshal
Antoine Pitrou4a90ef02012-03-03 02:35:32 +010051 marshal.loads(b'')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000052 except EOFError:
53 pass
54 finally:
55 sys.stdin = savestdin
56 fp.close()
57 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000058
Antoine Pitrou6b4883d2011-10-12 02:54:14 +020059 self.raise_catch(OSError, "OSError")
60 self.assertRaises(OSError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000061
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000062 self.raise_catch(ImportError, "ImportError")
63 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000064
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000065 self.raise_catch(IndexError, "IndexError")
66 x = []
67 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000068
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000069 self.raise_catch(KeyError, "KeyError")
70 x = {}
71 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000073 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000074
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000076
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000077 self.raise_catch(NameError, "NameError")
78 try: x = undefined_variable
79 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000080
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000081 self.raise_catch(OverflowError, "OverflowError")
82 x = 1
83 for dummy in range(128):
84 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000085
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000086 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000087
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000088 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +000089 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000090 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000091
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000092 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000093
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094 self.raise_catch(TabError, "TabError")
Georg Brandle1b5ac62008-06-04 13:06:58 +000095 try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n",
96 '<string>', 'exec')
97 except TabError: pass
98 else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +000099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000101
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000102 self.raise_catch(SystemExit, "SystemExit")
103 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000104
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000105 self.raise_catch(TypeError, "TypeError")
106 try: [] + ()
107 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000108
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000109 self.raise_catch(ValueError, "ValueError")
Guido van Rossume63bae62007-07-17 00:34:25 +0000110 self.assertRaises(ValueError, chr, 17<<16)
Guido van Rossum3bead091992-01-27 17:00:37 +0000111
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000112 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
113 try: x = 1/0
114 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000115
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000116 self.raise_catch(Exception, "Exception")
117 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000118 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000119
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000120 def testSyntaxErrorMessage(self):
121 # make sure the right exception message is raised for each of
122 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000123
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000124 def ckmsg(src, msg):
125 try:
126 compile(src, '<fragment>', 'exec')
Guido van Rossumb940e112007-01-10 16:19:56 +0000127 except SyntaxError as e:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000128 if e.msg != msg:
129 self.fail("expected %s, got %s" % (msg, e.msg))
130 else:
131 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000132
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000133 s = '''while 1:
134 try:
135 pass
136 finally:
137 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000138
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000139 if not sys.platform.startswith('java'):
140 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000141
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000142 s = '''if 1:
143 try:
144 continue
145 except:
146 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000147
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000148 ckmsg(s, "'continue' not properly in loop")
149 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000150
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000151 @cpython_only
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000152 def testSettingException(self):
153 # test that setting an exception at the C level works even if the
154 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000155
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000156 class BadException(Exception):
157 def __init__(self_):
Collin Winter828f04a2007-08-31 00:04:24 +0000158 raise RuntimeError("can't instantiate BadException")
Finn Bockaa3dc452001-12-08 10:15:48 +0000159
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000160 class InvalidException:
161 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000162
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000163 def test_capi1():
164 import _testcapi
165 try:
166 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000167 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000168 exc, err, tb = sys.exc_info()
169 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000170 self.assertEqual(co.co_name, "test_capi1")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000171 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000172 else:
173 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000174
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000175 def test_capi2():
176 import _testcapi
177 try:
178 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000179 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000180 exc, err, tb = sys.exc_info()
181 co = tb.tb_frame.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000182 self.assertEqual(co.co_name, "__init__")
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000183 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000184 co2 = tb.tb_frame.f_back.f_code
Ezio Melottib3aedd42010-11-20 19:04:17 +0000185 self.assertEqual(co2.co_name, "test_capi2")
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000186 else:
187 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000188
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000189 def test_capi3():
190 import _testcapi
191 self.assertRaises(SystemError, _testcapi.raise_exception,
192 InvalidException, 1)
193
194 if not sys.platform.startswith('java'):
195 test_capi1()
196 test_capi2()
197 test_capi3()
198
Thomas Wouters89f507f2006-12-13 04:49:30 +0000199 def test_WindowsError(self):
200 try:
201 WindowsError
202 except NameError:
203 pass
204 else:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200205 self.assertIs(WindowsError, OSError)
206 self.assertEqual(str(OSError(1001)), "1001")
207 self.assertEqual(str(OSError(1001, "message")),
208 "[Errno 1001] message")
209 # POSIX errno (9 aka EBADF) is untranslated
210 w = OSError(9, 'foo', 'bar')
211 self.assertEqual(w.errno, 9)
212 self.assertEqual(w.winerror, None)
213 self.assertEqual(str(w), "[Errno 9] foo: 'bar'")
214 # ERROR_PATH_NOT_FOUND (win error 3) becomes ENOENT (2)
215 w = OSError(0, 'foo', 'bar', 3)
216 self.assertEqual(w.errno, 2)
217 self.assertEqual(w.winerror, 3)
218 self.assertEqual(w.strerror, 'foo')
219 self.assertEqual(w.filename, 'bar')
Richard Oudkerk30147712012-08-28 19:33:26 +0100220 self.assertEqual(str(w), "[WinError 3] foo: 'bar'")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200221 # Unknown win error becomes EINVAL (22)
222 w = OSError(0, 'foo', None, 1001)
223 self.assertEqual(w.errno, 22)
224 self.assertEqual(w.winerror, 1001)
225 self.assertEqual(w.strerror, 'foo')
226 self.assertEqual(w.filename, None)
Richard Oudkerk30147712012-08-28 19:33:26 +0100227 self.assertEqual(str(w), "[WinError 1001] foo")
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200228 # Non-numeric "errno"
229 w = OSError('bar', 'foo')
230 self.assertEqual(w.errno, 'bar')
231 self.assertEqual(w.winerror, None)
232 self.assertEqual(w.strerror, 'foo')
233 self.assertEqual(w.filename, None)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000234
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000235 def testAttributes(self):
236 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000237
238 exceptionList = [
Guido van Rossumebe3e162007-05-17 18:20:34 +0000239 (BaseException, (), {'args' : ()}),
240 (BaseException, (1, ), {'args' : (1,)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000241 (BaseException, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000242 {'args' : ('foo',)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000243 (BaseException, ('foo', 1),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000244 {'args' : ('foo', 1)}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000245 (SystemExit, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000246 {'args' : ('foo',), 'code' : 'foo'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000247 (IOError, ('foo',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000248 {'args' : ('foo',), 'filename' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000249 'errno' : None, 'strerror' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000250 (IOError, ('foo', 'bar'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000251 {'args' : ('foo', 'bar'), 'filename' : None,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000252 'errno' : 'foo', 'strerror' : 'bar'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000253 (IOError, ('foo', 'bar', 'baz'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000254 {'args' : ('foo', 'bar'), 'filename' : 'baz',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000255 'errno' : 'foo', 'strerror' : 'bar'}),
256 (IOError, ('foo', 'bar', 'baz', 'quux'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000257 {'args' : ('foo', 'bar', 'baz', 'quux')}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000258 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000259 {'args' : ('errnoStr', 'strErrorStr'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000260 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
261 'filename' : 'filenameStr'}),
262 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000263 {'args' : (1, 'strErrorStr'), 'errno' : 1,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000264 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000265 (SyntaxError, (), {'msg' : None, 'text' : None,
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266 'filename' : None, 'lineno' : None, 'offset' : None,
267 'print_file_and_line' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000268 (SyntaxError, ('msgStr',),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000269 {'args' : ('msgStr',), 'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000270 'print_file_and_line' : None, 'msg' : 'msgStr',
271 'filename' : None, 'lineno' : None, 'offset' : None}),
272 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
273 'textStr')),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000274 {'offset' : 'offsetStr', 'text' : 'textStr',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000275 'args' : ('msgStr', ('filenameStr', 'linenoStr',
276 'offsetStr', 'textStr')),
277 'print_file_and_line' : None, 'msg' : 'msgStr',
278 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
279 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
280 'textStr', 'print_file_and_lineStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000281 {'text' : None,
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000282 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
283 'textStr', 'print_file_and_lineStr'),
284 'print_file_and_line' : None, 'msg' : 'msgStr',
285 'filename' : None, 'lineno' : None, 'offset' : None}),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000286 (UnicodeError, (), {'args' : (),}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000287 (UnicodeEncodeError, ('ascii', 'a', 0, 1,
288 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000289 {'args' : ('ascii', 'a', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000290 'ordinal not in range'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000291 'encoding' : 'ascii', 'object' : 'a',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292 'start' : 0, 'reason' : 'ordinal not in range'}),
Guido van Rossum254348e2007-11-21 19:29:53 +0000293 (UnicodeDecodeError, ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000294 'ordinal not in range'),
Guido van Rossum254348e2007-11-21 19:29:53 +0000295 {'args' : ('ascii', bytearray(b'\xff'), 0, 1,
Guido van Rossum98297ee2007-11-06 21:34:58 +0000296 'ordinal not in range'),
297 'encoding' : 'ascii', 'object' : b'\xff',
298 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000299 (UnicodeDecodeError, ('ascii', b'\xff', 0, 1,
300 'ordinal not in range'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000301 {'args' : ('ascii', b'\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 'ordinal not in range'),
Guido van Rossumb8142c32007-05-08 17:49:10 +0000303 'encoding' : 'ascii', 'object' : b'\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000304 'start' : 0, 'reason' : 'ordinal not in range'}),
Walter Dörwaldeceb0fb2007-05-24 17:49:56 +0000305 (UnicodeTranslateError, ("\u3042", 0, 1, "ouch"),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000306 {'args' : ('\u3042', 0, 1, 'ouch'),
Guido van Rossumef87d6e2007-05-02 19:09:54 +0000307 'object' : '\u3042', 'reason' : 'ouch',
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000308 'start' : 0, 'end' : 1}),
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100309 (NaiveException, ('foo',),
310 {'args': ('foo',), 'x': 'foo'}),
311 (SlottedNaiveException, ('foo',),
312 {'args': ('foo',), 'x': 'foo'}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000313 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000314 try:
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200315 # More tests are in test_WindowsError
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000316 exceptionList.append(
317 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
Guido van Rossumebe3e162007-05-17 18:20:34 +0000318 {'args' : (1, 'strErrorStr'),
Antoine Pitrou6b4883d2011-10-12 02:54:14 +0200319 'strerror' : 'strErrorStr', 'winerror' : None,
320 'errno' : 1, 'filename' : 'filenameStr'})
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000321 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000322 except NameError:
323 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000324
Guido van Rossumebe3e162007-05-17 18:20:34 +0000325 for exc, args, expected in exceptionList:
326 try:
327 e = exc(*args)
328 except:
Guido van Rossum98297ee2007-11-06 21:34:58 +0000329 print("\nexc=%r, args=%r" % (exc, args), file=sys.stderr)
Guido van Rossumebe3e162007-05-17 18:20:34 +0000330 raise
331 else:
332 # Verify module name
Richard Oudkerk5562d9d2012-07-28 17:45:28 +0100333 if not type(e).__name__.endswith('NaiveException'):
334 self.assertEqual(type(e).__module__, 'builtins')
Guido van Rossumebe3e162007-05-17 18:20:34 +0000335 # Verify no ref leaks in Exc_str()
336 s = str(e)
337 for checkArgName in expected:
338 value = getattr(e, checkArgName)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000339 self.assertEqual(repr(value),
340 repr(expected[checkArgName]),
341 '%r.%s == %r, expected %r' % (
342 e, checkArgName,
343 value, expected[checkArgName]))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000344
Guido van Rossumebe3e162007-05-17 18:20:34 +0000345 # test for pickling support
Guido van Rossum99603b02007-07-20 00:22:32 +0000346 for p in [pickle]:
Guido van Rossumebe3e162007-05-17 18:20:34 +0000347 for protocol in range(p.HIGHEST_PROTOCOL + 1):
348 s = p.dumps(e, protocol)
349 new = p.loads(s)
350 for checkArgName in expected:
351 got = repr(getattr(new, checkArgName))
352 want = repr(expected[checkArgName])
Ezio Melottib3aedd42010-11-20 19:04:17 +0000353 self.assertEqual(got, want,
354 'pickled "%r", attribute "%s' %
355 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000356
Collin Winter828f04a2007-08-31 00:04:24 +0000357 def testWithTraceback(self):
358 try:
359 raise IndexError(4)
360 except:
361 tb = sys.exc_info()[2]
362
363 e = BaseException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000364 self.assertIsInstance(e, BaseException)
Collin Winter828f04a2007-08-31 00:04:24 +0000365 self.assertEqual(e.__traceback__, tb)
366
367 e = IndexError(5).with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000368 self.assertIsInstance(e, IndexError)
Collin Winter828f04a2007-08-31 00:04:24 +0000369 self.assertEqual(e.__traceback__, tb)
370
371 class MyException(Exception):
372 pass
373
374 e = MyException().with_traceback(tb)
Ezio Melottie9615932010-01-24 19:26:24 +0000375 self.assertIsInstance(e, MyException)
Collin Winter828f04a2007-08-31 00:04:24 +0000376 self.assertEqual(e.__traceback__, tb)
377
378 def testInvalidTraceback(self):
379 try:
380 Exception().__traceback__ = 5
381 except TypeError as e:
Benjamin Peterson577473f2010-01-19 00:09:57 +0000382 self.assertIn("__traceback__ must be a traceback", str(e))
Collin Winter828f04a2007-08-31 00:04:24 +0000383 else:
384 self.fail("No exception raised")
385
Georg Brandlab6f2f62009-03-31 04:16:10 +0000386 def testInvalidAttrs(self):
387 self.assertRaises(TypeError, setattr, Exception(), '__cause__', 1)
388 self.assertRaises(TypeError, delattr, Exception(), '__cause__')
389 self.assertRaises(TypeError, setattr, Exception(), '__context__', 1)
390 self.assertRaises(TypeError, delattr, Exception(), '__context__')
391
Collin Winter828f04a2007-08-31 00:04:24 +0000392 def testNoneClearsTracebackAttr(self):
393 try:
394 raise IndexError(4)
395 except:
396 tb = sys.exc_info()[2]
397
398 e = Exception()
399 e.__traceback__ = tb
400 e.__traceback__ = None
401 self.assertEqual(e.__traceback__, None)
402
403 def testChainingAttrs(self):
404 e = Exception()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000405 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700406 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000407
408 e = TypeError()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000409 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700410 self.assertIsNone(e.__cause__)
Collin Winter828f04a2007-08-31 00:04:24 +0000411
412 class MyException(EnvironmentError):
413 pass
414
415 e = MyException()
Nick Coghlanab7bf212012-02-26 17:49:52 +1000416 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700417 self.assertIsNone(e.__cause__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000418
419 def testChainingDescriptors(self):
420 try:
421 raise Exception()
422 except Exception as exc:
423 e = exc
424
425 self.assertIsNone(e.__context__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700426 self.assertIsNone(e.__cause__)
427 self.assertFalse(e.__suppress_context__)
Nick Coghlanab7bf212012-02-26 17:49:52 +1000428
429 e.__context__ = NameError()
430 e.__cause__ = None
431 self.assertIsInstance(e.__context__, NameError)
432 self.assertIsNone(e.__cause__)
Benjamin Petersond5a1c442012-05-14 22:09:31 -0700433 self.assertTrue(e.__suppress_context__)
434 e.__suppress_context__ = False
435 self.assertFalse(e.__suppress_context__)
Collin Winter828f04a2007-08-31 00:04:24 +0000436
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000437 def testKeywordArgs(self):
438 # test that builtin exception don't take keyword args,
439 # but user-defined subclasses can if they want
440 self.assertRaises(TypeError, BaseException, a=1)
441
442 class DerivedException(BaseException):
443 def __init__(self, fancy_arg):
444 BaseException.__init__(self)
445 self.fancy_arg = fancy_arg
446
447 x = DerivedException(fancy_arg=42)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000448 self.assertEqual(x.fancy_arg, 42)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000449
Brett Cannon31f59292011-02-21 19:29:56 +0000450 @no_tracing
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000451 def testInfiniteRecursion(self):
452 def f():
453 return f()
454 self.assertRaises(RuntimeError, f)
455
456 def g():
457 try:
458 return g()
459 except ValueError:
460 return -1
461 self.assertRaises(RuntimeError, g)
462
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000463 def test_str(self):
464 # Make sure both instances and classes have a str representation.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000465 self.assertTrue(str(Exception))
466 self.assertTrue(str(Exception('a')))
Ezio Melotti2f5a78c2009-12-24 22:54:06 +0000467 self.assertTrue(str(Exception('a', 'b')))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000469 def testExceptionCleanupNames(self):
470 # Make sure the local variable bound to the exception instance by
471 # an "except" statement is only visible inside the except block.
Guido van Rossumb940e112007-01-10 16:19:56 +0000472 try:
473 raise Exception()
474 except Exception as e:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000475 self.assertTrue(e)
Guido van Rossumb940e112007-01-10 16:19:56 +0000476 del e
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000477 self.assertNotIn('e', locals())
Guido van Rossumb940e112007-01-10 16:19:56 +0000478
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000479 def testExceptionCleanupState(self):
480 # Make sure exception state is cleaned up as soon as the except
481 # block is left. See #2507
482
483 class MyException(Exception):
484 def __init__(self, obj):
485 self.obj = obj
486 class MyObj:
487 pass
488
489 def inner_raising_func():
490 # Create some references in exception value and traceback
491 local_ref = obj
492 raise MyException(obj)
493
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000494 # Qualified "except" with "as"
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000495 obj = MyObj()
496 wr = weakref.ref(obj)
497 try:
498 inner_raising_func()
499 except MyException as e:
500 pass
501 obj = None
502 obj = wr()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000503 self.assertTrue(obj is None, "%s" % obj)
Barry Warsaw8d109cb2008-05-08 04:26:35 +0000504
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000505 # Qualified "except" without "as"
506 obj = MyObj()
507 wr = weakref.ref(obj)
508 try:
509 inner_raising_func()
510 except MyException:
511 pass
512 obj = None
513 obj = wr()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000514 self.assertTrue(obj is None, "%s" % obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000515
516 # Bare "except"
517 obj = MyObj()
518 wr = weakref.ref(obj)
519 try:
520 inner_raising_func()
521 except:
522 pass
523 obj = None
524 obj = wr()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000525 self.assertTrue(obj is None, "%s" % obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000526
527 # "except" with premature block leave
528 obj = MyObj()
529 wr = weakref.ref(obj)
530 for i in [0]:
531 try:
532 inner_raising_func()
533 except:
534 break
535 obj = None
536 obj = wr()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000537 self.assertTrue(obj is None, "%s" % obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000538
539 # "except" block raising another exception
540 obj = MyObj()
541 wr = weakref.ref(obj)
542 try:
543 try:
544 inner_raising_func()
545 except:
546 raise KeyError
Guido van Rossumb4fb6e42008-06-14 20:20:24 +0000547 except KeyError as e:
548 # We want to test that the except block above got rid of
549 # the exception raised in inner_raising_func(), but it
550 # also ends up in the __context__ of the KeyError, so we
551 # must clear the latter manually for our test to succeed.
552 e.__context__ = None
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000553 obj = None
554 obj = wr()
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800555 # guarantee no ref cycles on CPython (don't gc_collect)
556 if check_impl_detail(cpython=False):
557 gc_collect()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000558 self.assertTrue(obj is None, "%s" % obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000559
560 # Some complicated construct
561 obj = MyObj()
562 wr = weakref.ref(obj)
563 try:
564 inner_raising_func()
565 except MyException:
566 try:
567 try:
568 raise
569 finally:
570 raise
571 except MyException:
572 pass
573 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800574 if check_impl_detail(cpython=False):
575 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000576 obj = wr()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000577 self.assertTrue(obj is None, "%s" % obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000578
579 # Inside an exception-silencing "with" block
580 class Context:
581 def __enter__(self):
582 return self
583 def __exit__ (self, exc_type, exc_value, exc_tb):
584 return True
585 obj = MyObj()
586 wr = weakref.ref(obj)
587 with Context():
588 inner_raising_func()
589 obj = None
Philip Jenveyb37ac8e2012-11-14 14:37:24 -0800590 if check_impl_detail(cpython=False):
591 gc_collect()
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000592 obj = wr()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000593 self.assertTrue(obj is None, "%s" % obj)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000594
Amaury Forgeot d'Arcba117ef2010-09-10 21:39:53 +0000595 def test_exception_target_in_nested_scope(self):
596 # issue 4617: This used to raise a SyntaxError
597 # "can not delete variable 'e' referenced in nested scope"
598 def print_error():
599 e
600 try:
601 something
602 except Exception as e:
603 print_error()
604 # implicit "del e" here
605
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000606 def test_generator_leaking(self):
607 # Test that generator exception state doesn't leak into the calling
608 # frame
609 def yield_raise():
610 try:
611 raise KeyError("caught")
612 except KeyError:
613 yield sys.exc_info()[0]
614 yield sys.exc_info()[0]
615 yield sys.exc_info()[0]
616 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000617 self.assertEqual(next(g), KeyError)
618 self.assertEqual(sys.exc_info()[0], None)
619 self.assertEqual(next(g), KeyError)
620 self.assertEqual(sys.exc_info()[0], None)
621 self.assertEqual(next(g), None)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000622
623 # Same test, but inside an exception handler
624 try:
625 raise TypeError("foo")
626 except TypeError:
627 g = yield_raise()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000628 self.assertEqual(next(g), KeyError)
629 self.assertEqual(sys.exc_info()[0], TypeError)
630 self.assertEqual(next(g), KeyError)
631 self.assertEqual(sys.exc_info()[0], TypeError)
632 self.assertEqual(next(g), TypeError)
Benjamin Petersoneec3d712008-06-11 15:59:43 +0000633 del g
Ezio Melottib3aedd42010-11-20 19:04:17 +0000634 self.assertEqual(sys.exc_info()[0], TypeError)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000635
Benjamin Peterson83195c32011-07-03 13:44:00 -0500636 def test_generator_leaking2(self):
637 # See issue 12475.
638 def g():
639 yield
640 try:
641 raise RuntimeError
642 except RuntimeError:
643 it = g()
644 next(it)
645 try:
646 next(it)
647 except StopIteration:
648 pass
649 self.assertEqual(sys.exc_info(), (None, None, None))
650
Benjamin Petersonac913412011-07-03 16:25:11 -0500651 def test_generator_doesnt_retain_old_exc(self):
652 def g():
653 self.assertIsInstance(sys.exc_info()[1], RuntimeError)
654 yield
655 self.assertEqual(sys.exc_info(), (None, None, None))
656 it = g()
657 try:
658 raise RuntimeError
659 except RuntimeError:
660 next(it)
661 self.assertRaises(StopIteration, next, it)
662
Benjamin Petersonae5f2f42010-03-07 17:10:51 +0000663 def test_generator_finalizing_and_exc_info(self):
664 # See #7173
665 def simple_gen():
666 yield 1
667 def run_gen():
668 gen = simple_gen()
669 try:
670 raise RuntimeError
671 except RuntimeError:
672 return next(gen)
673 run_gen()
674 gc_collect()
675 self.assertEqual(sys.exc_info(), (None, None, None))
676
Antoine Pitroua370fcf2011-08-20 14:15:03 +0200677 def _check_generator_cleanup_exc_state(self, testfunc):
678 # Issue #12791: exception state is cleaned up as soon as a generator
679 # is closed (reference cycles are broken).
680 class MyException(Exception):
681 def __init__(self, obj):
682 self.obj = obj
683 class MyObj:
684 pass
685
686 def raising_gen():
687 try:
688 raise MyException(obj)
689 except MyException:
690 yield
691
692 obj = MyObj()
693 wr = weakref.ref(obj)
694 g = raising_gen()
695 next(g)
696 testfunc(g)
697 g = obj = None
698 obj = wr()
699 self.assertIs(obj, None)
700
701 def test_generator_throw_cleanup_exc_state(self):
702 def do_throw(g):
703 try:
704 g.throw(RuntimeError())
705 except RuntimeError:
706 pass
707 self._check_generator_cleanup_exc_state(do_throw)
708
709 def test_generator_close_cleanup_exc_state(self):
710 def do_close(g):
711 g.close()
712 self._check_generator_cleanup_exc_state(do_close)
713
714 def test_generator_del_cleanup_exc_state(self):
715 def do_del(g):
716 g = None
717 self._check_generator_cleanup_exc_state(do_del)
718
719 def test_generator_next_cleanup_exc_state(self):
720 def do_next(g):
721 try:
722 next(g)
723 except StopIteration:
724 pass
725 else:
726 self.fail("should have raised StopIteration")
727 self._check_generator_cleanup_exc_state(do_next)
728
729 def test_generator_send_cleanup_exc_state(self):
730 def do_send(g):
731 try:
732 g.send(None)
733 except StopIteration:
734 pass
735 else:
736 self.fail("should have raised StopIteration")
737 self._check_generator_cleanup_exc_state(do_send)
738
Benjamin Peterson27d63672008-06-15 20:09:12 +0000739 def test_3114(self):
740 # Bug #3114: in its destructor, MyObject retrieves a pointer to
741 # obsolete and/or deallocated objects.
Benjamin Peterson979f3112008-06-15 00:05:44 +0000742 class MyObject:
743 def __del__(self):
744 nonlocal e
745 e = sys.exc_info()
746 e = ()
747 try:
748 raise Exception(MyObject())
749 except:
750 pass
Ezio Melottib3aedd42010-11-20 19:04:17 +0000751 self.assertEqual(e, (None, None, None))
Benjamin Peterson979f3112008-06-15 00:05:44 +0000752
Eric Smith0facd772010-02-24 15:42:29 +0000753 def testUnicodeChangeAttributes(self):
754 # See issue 7309. This was a crasher.
755
756 u = UnicodeEncodeError('baz', 'xxxxx', 1, 5, 'foo')
757 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: foo")
758 u.end = 2
759 self.assertEqual(str(u), "'baz' codec can't encode character '\\x78' in position 1: foo")
760 u.end = 5
761 u.reason = 0x345345345345345345
762 self.assertEqual(str(u), "'baz' codec can't encode characters in position 1-4: 965230951443685724997")
763 u.encoding = 4000
764 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1-4: 965230951443685724997")
765 u.start = 1000
766 self.assertEqual(str(u), "'4000' codec can't encode characters in position 1000-4: 965230951443685724997")
767
768 u = UnicodeDecodeError('baz', b'xxxxx', 1, 5, 'foo')
769 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: foo")
770 u.end = 2
771 self.assertEqual(str(u), "'baz' codec can't decode byte 0x78 in position 1: foo")
772 u.end = 5
773 u.reason = 0x345345345345345345
774 self.assertEqual(str(u), "'baz' codec can't decode bytes in position 1-4: 965230951443685724997")
775 u.encoding = 4000
776 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1-4: 965230951443685724997")
777 u.start = 1000
778 self.assertEqual(str(u), "'4000' codec can't decode bytes in position 1000-4: 965230951443685724997")
779
780 u = UnicodeTranslateError('xxxx', 1, 5, 'foo')
781 self.assertEqual(str(u), "can't translate characters in position 1-4: foo")
782 u.end = 2
783 self.assertEqual(str(u), "can't translate character '\\x78' in position 1: foo")
784 u.end = 5
785 u.reason = 0x345345345345345345
786 self.assertEqual(str(u), "can't translate characters in position 1-4: 965230951443685724997")
787 u.start = 1000
788 self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
Benjamin Peterson6e7740c2008-08-20 23:23:34 +0000789
Brett Cannon31f59292011-02-21 19:29:56 +0000790 @no_tracing
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000791 def test_badisinstance(self):
792 # Bug #2542: if issubclass(e, MyException) raises an exception,
793 # it should be ignored
794 class Meta(type):
795 def __subclasscheck__(cls, subclass):
796 raise ValueError()
797 class MyException(Exception, metaclass=Meta):
798 pass
799
800 with captured_output("stderr") as stderr:
801 try:
802 raise KeyError()
803 except MyException as e:
804 self.fail("exception should not be a MyException")
805 except KeyError:
806 pass
807 except:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000808 self.fail("Should have raised KeyError")
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000809 else:
Antoine Pitrouec569b72008-08-26 22:40:48 +0000810 self.fail("Should have raised KeyError")
811
812 def g():
813 try:
814 return g()
815 except RuntimeError:
816 return sys.exc_info()
817 e, v, tb = g()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000818 self.assertTrue(isinstance(v, RuntimeError), type(v))
Benjamin Peterson577473f2010-01-19 00:09:57 +0000819 self.assertIn("maximum recursion depth exceeded", str(v))
Benjamin Peterson69c88f72008-07-31 01:47:08 +0000820
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +0000821
822 def test_MemoryError(self):
823 # PyErr_NoMemory always raises the same exception instance.
824 # Check that the traceback is not doubled.
825 import traceback
Benjamin Peterson0067bd62008-08-16 16:11:03 +0000826 from _testcapi import raise_memoryerror
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +0000827 def raiseMemError():
828 try:
Benjamin Peterson0067bd62008-08-16 16:11:03 +0000829 raise_memoryerror()
Amaury Forgeot d'Arce19cadb2008-07-31 22:56:02 +0000830 except MemoryError as e:
831 tb = e.__traceback__
832 else:
833 self.fail("Should have raises a MemoryError")
834 return traceback.format_tb(tb)
835
836 tb1 = raiseMemError()
837 tb2 = raiseMemError()
838 self.assertEqual(tb1, tb2)
839
Benjamin Peterson17e0bbc2010-06-28 15:39:55 +0000840 @cpython_only
Georg Brandl1e28a272009-12-28 08:41:01 +0000841 def test_exception_with_doc(self):
842 import _testcapi
843 doc2 = "This is a test docstring."
844 doc4 = "This is another test docstring."
845
846 self.assertRaises(SystemError, _testcapi.make_exception_with_doc,
847 "error1")
848
849 # test basic usage of PyErr_NewException
850 error1 = _testcapi.make_exception_with_doc("_testcapi.error1")
851 self.assertIs(type(error1), type)
852 self.assertTrue(issubclass(error1, Exception))
853 self.assertIsNone(error1.__doc__)
854
855 # test with given docstring
856 error2 = _testcapi.make_exception_with_doc("_testcapi.error2", doc2)
857 self.assertEqual(error2.__doc__, doc2)
858
859 # test with explicit base (without docstring)
860 error3 = _testcapi.make_exception_with_doc("_testcapi.error3",
861 base=error2)
862 self.assertTrue(issubclass(error3, error2))
863
864 # test with explicit base tuple
865 class C(object):
866 pass
867 error4 = _testcapi.make_exception_with_doc("_testcapi.error4", doc4,
868 (error3, C))
869 self.assertTrue(issubclass(error4, error3))
870 self.assertTrue(issubclass(error4, C))
871 self.assertEqual(error4.__doc__, doc4)
872
873 # test with explicit dictionary
874 error5 = _testcapi.make_exception_with_doc("_testcapi.error5", "",
875 error4, {'a': 1})
876 self.assertTrue(issubclass(error5, error4))
877 self.assertEqual(error5.a, 1)
878 self.assertEqual(error5.__doc__, "")
879
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000880 def test_memory_error_cleanup(self):
881 # Issue #5437: preallocated MemoryError instances should not keep
882 # traceback objects alive.
883 from _testcapi import raise_memoryerror
884 class C:
885 pass
886 wr = None
887 def inner():
888 nonlocal wr
889 c = C()
890 wr = weakref.ref(c)
891 raise_memoryerror()
892 # We cannot use assertRaises since it manually deletes the traceback
893 try:
894 inner()
895 except MemoryError as e:
896 self.assertNotEqual(wr(), None)
897 else:
898 self.fail("MemoryError not raised")
899 self.assertEqual(wr(), None)
900
Brett Cannon31f59292011-02-21 19:29:56 +0000901 @no_tracing
Antoine Pitrou07e20ef2010-10-28 22:56:58 +0000902 def test_recursion_error_cleanup(self):
903 # Same test as above, but with "recursion exceeded" errors
904 class C:
905 pass
906 wr = None
907 def inner():
908 nonlocal wr
909 c = C()
910 wr = weakref.ref(c)
911 inner()
912 # We cannot use assertRaises since it manually deletes the traceback
913 try:
914 inner()
915 except RuntimeError as e:
916 self.assertNotEqual(wr(), None)
917 else:
918 self.fail("RuntimeError not raised")
919 self.assertEqual(wr(), None)
Georg Brandl1e28a272009-12-28 08:41:01 +0000920
Antoine Pitroua7622852011-09-01 21:37:43 +0200921 def test_errno_ENOTDIR(self):
922 # Issue #12802: "not a directory" errors are ENOTDIR even on Windows
923 with self.assertRaises(OSError) as cm:
924 os.listdir(__file__)
925 self.assertEqual(cm.exception.errno, errno.ENOTDIR, cm.exception)
926
927
Brett Cannon79ec55e2012-04-12 20:24:54 -0400928class ImportErrorTests(unittest.TestCase):
929
930 def test_attributes(self):
931 # Setting 'name' and 'path' should not be a problem.
932 exc = ImportError('test')
933 self.assertIsNone(exc.name)
934 self.assertIsNone(exc.path)
935
936 exc = ImportError('test', name='somemodule')
937 self.assertEqual(exc.name, 'somemodule')
938 self.assertIsNone(exc.path)
939
940 exc = ImportError('test', path='somepath')
941 self.assertEqual(exc.path, 'somepath')
942 self.assertIsNone(exc.name)
943
944 exc = ImportError('test', path='somepath', name='somename')
945 self.assertEqual(exc.name, 'somename')
946 self.assertEqual(exc.path, 'somepath')
947
Brett Cannon07c6e712012-08-24 13:05:09 -0400948 def test_non_str_argument(self):
949 # Issue #15778
950 arg = b'abc'
951 exc = ImportError(arg)
952 self.assertEqual(str(arg), str(exc))
Brett Cannon79ec55e2012-04-12 20:24:54 -0400953
954
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000955def test_main():
Brett Cannon79ec55e2012-04-12 20:24:54 -0400956 run_unittest(ExceptionTests, ImportErrorTests)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000957
958if __name__ == '__main__':
Guido van Rossumb8142c32007-05-08 17:49:10 +0000959 unittest.main()