blob: 5a0039e168a2ff012610ed4e317176e49c6e4104 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Tim Peters80dc76e2006-06-07 06:57:51 +00003import os
4import sys
Georg Brandlcdcede62006-05-30 08:47:19 +00005import unittest
Tim Peters80dc76e2006-06-07 06:57:51 +00006import pickle, cPickle
7
Brett Cannon229cee22007-05-05 01:34:02 +00008from test.test_support import (TESTFN, unlink, run_unittest,
Amaury Forgeot d'Arc246daed2008-07-31 00:42:16 +00009 catch_warning, captured_output)
Brett Cannon229cee22007-05-05 01:34:02 +000010from test.test_pep352 import ignore_message_warning
Guido van Rossum83b120d2001-08-23 03:23:03 +000011
Guido van Rossum3bead091992-01-27 17:00:37 +000012# XXX This is not really enough, each *operation* should be tested!
13
Georg Brandlcdcede62006-05-30 08:47:19 +000014class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000015
Amaury Forgeot d'Arc246daed2008-07-31 00:42:16 +000016 def test00(self):
17 try:
18 sys.exit(ValueError('aaa'))
19 except SystemExit:
20 pass
21 finally:
22 pass
23
Georg Brandlcdcede62006-05-30 08:47:19 +000024 def testReload(self):
25 # Reloading the built-in exceptions module failed prior to Py2.2, while it
26 # should act the same as reloading built-in sys.
27 try:
28 import exceptions
29 reload(exceptions)
30 except ImportError, e:
31 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000032
Georg Brandlcdcede62006-05-30 08:47:19 +000033 def raise_catch(self, exc, excname):
34 try:
35 raise exc, "spam"
36 except exc, err:
37 buf1 = str(err)
38 try:
39 raise exc("spam")
40 except exc, err:
41 buf2 = str(err)
42 self.assertEquals(buf1, buf2)
43 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000044
Georg Brandlcdcede62006-05-30 08:47:19 +000045 def testRaising(self):
Tim Petersdd55b0a2006-05-30 23:28:02 +000046 self.raise_catch(AttributeError, "AttributeError")
Georg Brandlcdcede62006-05-30 08:47:19 +000047 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000048
Georg Brandlcdcede62006-05-30 08:47:19 +000049 self.raise_catch(EOFError, "EOFError")
50 fp = open(TESTFN, 'w')
51 fp.close()
52 fp = open(TESTFN, 'r')
53 savestdin = sys.stdin
54 try:
55 try:
56 sys.stdin = fp
57 x = raw_input()
58 except EOFError:
59 pass
60 finally:
61 sys.stdin = savestdin
62 fp.close()
63 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000064
Georg Brandlcdcede62006-05-30 08:47:19 +000065 self.raise_catch(IOError, "IOError")
66 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000067
Georg Brandlcdcede62006-05-30 08:47:19 +000068 self.raise_catch(ImportError, "ImportError")
69 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000070
Georg Brandlcdcede62006-05-30 08:47:19 +000071 self.raise_catch(IndexError, "IndexError")
72 x = []
73 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000074
Georg Brandlcdcede62006-05-30 08:47:19 +000075 self.raise_catch(KeyError, "KeyError")
76 x = {}
77 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000078
Georg Brandlcdcede62006-05-30 08:47:19 +000079 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000080
Georg Brandlcdcede62006-05-30 08:47:19 +000081 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Georg Brandlcdcede62006-05-30 08:47:19 +000083 self.raise_catch(NameError, "NameError")
84 try: x = undefined_variable
85 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000086
Georg Brandlcdcede62006-05-30 08:47:19 +000087 self.raise_catch(OverflowError, "OverflowError")
88 x = 1
89 for dummy in range(128):
90 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000091
Georg Brandlcdcede62006-05-30 08:47:19 +000092 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000093
Georg Brandlcdcede62006-05-30 08:47:19 +000094 self.raise_catch(SyntaxError, "SyntaxError")
95 try: exec '/\n'
96 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000097
Georg Brandlcdcede62006-05-30 08:47:19 +000098 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000099
Georg Brandlcdcede62006-05-30 08:47:19 +0000100 self.raise_catch(TabError, "TabError")
101 # can only be tested under -tt, and is the only test for -tt
102 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
103 #except TabError: pass
104 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000105
Georg Brandlcdcede62006-05-30 08:47:19 +0000106 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000107
Georg Brandlcdcede62006-05-30 08:47:19 +0000108 self.raise_catch(SystemExit, "SystemExit")
109 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000110
Georg Brandlcdcede62006-05-30 08:47:19 +0000111 self.raise_catch(TypeError, "TypeError")
112 try: [] + ()
113 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000114
Georg Brandlcdcede62006-05-30 08:47:19 +0000115 self.raise_catch(ValueError, "ValueError")
116 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000117
Georg Brandlcdcede62006-05-30 08:47:19 +0000118 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
119 try: x = 1/0
120 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000121
Georg Brandlcdcede62006-05-30 08:47:19 +0000122 self.raise_catch(Exception, "Exception")
123 try: x = 1/0
124 except Exception, e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000125
Georg Brandlcdcede62006-05-30 08:47:19 +0000126 def testSyntaxErrorMessage(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000127 # make sure the right exception message is raised for each of
128 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000129
Georg Brandlcdcede62006-05-30 08:47:19 +0000130 def ckmsg(src, msg):
131 try:
132 compile(src, '<fragment>', 'exec')
133 except SyntaxError, e:
134 if e.msg != msg:
135 self.fail("expected %s, got %s" % (msg, e.msg))
136 else:
137 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000138
Georg Brandlcdcede62006-05-30 08:47:19 +0000139 s = '''while 1:
140 try:
141 pass
142 finally:
143 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000144
Georg Brandlcdcede62006-05-30 08:47:19 +0000145 if not sys.platform.startswith('java'):
146 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000147
Georg Brandlcdcede62006-05-30 08:47:19 +0000148 s = '''if 1:
149 try:
150 continue
151 except:
152 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000153
Georg Brandlcdcede62006-05-30 08:47:19 +0000154 ckmsg(s, "'continue' not properly in loop")
155 ckmsg("continue\n", "'continue' not properly in loop")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000156
Georg Brandlcdcede62006-05-30 08:47:19 +0000157 def testSettingException(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000158 # test that setting an exception at the C level works even if the
159 # exception object can't be constructed.
Finn Bockaa3dc452001-12-08 10:15:48 +0000160
Georg Brandlcdcede62006-05-30 08:47:19 +0000161 class BadException:
162 def __init__(self_):
163 raise RuntimeError, "can't instantiate BadException"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000164
Georg Brandlcdcede62006-05-30 08:47:19 +0000165 def test_capi1():
166 import _testcapi
167 try:
168 _testcapi.raise_exception(BadException, 1)
169 except TypeError, err:
170 exc, err, tb = sys.exc_info()
171 co = tb.tb_frame.f_code
172 self.assertEquals(co.co_name, "test_capi1")
173 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
174 else:
175 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000176
Georg Brandlcdcede62006-05-30 08:47:19 +0000177 def test_capi2():
178 import _testcapi
179 try:
180 _testcapi.raise_exception(BadException, 0)
181 except RuntimeError, err:
182 exc, err, tb = sys.exc_info()
183 co = tb.tb_frame.f_code
184 self.assertEquals(co.co_name, "__init__")
185 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
186 co2 = tb.tb_frame.f_back.f_code
187 self.assertEquals(co2.co_name, "test_capi2")
188 else:
189 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000190
Georg Brandlcdcede62006-05-30 08:47:19 +0000191 if not sys.platform.startswith('java'):
192 test_capi1()
193 test_capi2()
Georg Brandl05f97bf2006-05-30 07:13:29 +0000194
Thomas Hellerdf08f0b2006-10-27 18:31:36 +0000195 def test_WindowsError(self):
196 try:
197 WindowsError
198 except NameError:
199 pass
200 else:
201 self.failUnlessEqual(str(WindowsError(1001)),
202 "1001")
203 self.failUnlessEqual(str(WindowsError(1001, "message")),
204 "[Error 1001] message")
205 self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
206 self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
207
Georg Brandlcdcede62006-05-30 08:47:19 +0000208 def testAttributes(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000209 # test that exception attributes are happy
Tim Petersdd55b0a2006-05-30 23:28:02 +0000210
Georg Brandlcdcede62006-05-30 08:47:19 +0000211 exceptionList = [
Georg Brandle08940e2006-06-01 13:00:49 +0000212 (BaseException, (), {'message' : '', 'args' : ()}),
213 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
214 (BaseException, ('foo',),
215 {'message' : 'foo', 'args' : ('foo',)}),
216 (BaseException, ('foo', 1),
217 {'message' : '', 'args' : ('foo', 1)}),
218 (SystemExit, ('foo',),
219 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
220 (IOError, ('foo',),
Georg Brandl3267d282006-09-30 09:03:42 +0000221 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
222 'errno' : None, 'strerror' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000223 (IOError, ('foo', 'bar'),
Georg Brandl3267d282006-09-30 09:03:42 +0000224 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
225 'errno' : 'foo', 'strerror' : 'bar'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000226 (IOError, ('foo', 'bar', 'baz'),
Georg Brandl3267d282006-09-30 09:03:42 +0000227 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
228 'errno' : 'foo', 'strerror' : 'bar'}),
229 (IOError, ('foo', 'bar', 'baz', 'quux'),
230 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Georg Brandle08940e2006-06-01 13:00:49 +0000231 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
232 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
233 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
234 'filename' : 'filenameStr'}),
235 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
236 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
237 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
Brett Cannonf8267df2007-02-28 18:15:00 +0000238 (SyntaxError, (), {'message' : '', 'msg' : None, 'text' : None,
239 'filename' : None, 'lineno' : None, 'offset' : None,
240 'print_file_and_line' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000241 (SyntaxError, ('msgStr',),
242 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
243 'print_file_and_line' : None, 'msg' : 'msgStr',
244 'filename' : None, 'lineno' : None, 'offset' : None}),
245 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
246 'textStr')),
247 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
248 'args' : ('msgStr', ('filenameStr', 'linenoStr',
249 'offsetStr', 'textStr')),
250 'print_file_and_line' : None, 'msg' : 'msgStr',
251 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
252 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
253 'textStr', 'print_file_and_lineStr'),
254 {'message' : '', 'text' : None,
255 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
256 'textStr', 'print_file_and_lineStr'),
257 'print_file_and_line' : None, 'msg' : 'msgStr',
258 'filename' : None, 'lineno' : None, 'offset' : None}),
259 (UnicodeError, (), {'message' : '', 'args' : (),}),
Georg Brandl38f62372006-09-06 06:50:05 +0000260 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
261 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
262 'ordinal not in range'),
263 'encoding' : 'ascii', 'object' : u'a',
264 'start' : 0, 'reason' : 'ordinal not in range'}),
265 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000266 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Georg Brandl38f62372006-09-06 06:50:05 +0000267 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000268 'encoding' : 'ascii', 'object' : '\xff',
Georg Brandl38f62372006-09-06 06:50:05 +0000269 'start' : 0, 'reason' : 'ordinal not in range'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000270 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
271 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
272 'object' : u'\u3042', 'reason' : 'ouch',
273 'start' : 0, 'end' : 1}),
274 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000275 try:
276 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000277 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
278 {'message' : '', 'args' : (1, 'strErrorStr'),
279 'strerror' : 'strErrorStr', 'winerror' : 1,
280 'errno' : 22, 'filename' : 'filenameStr'})
281 )
Tim Peters80dc76e2006-06-07 06:57:51 +0000282 except NameError:
283 pass
Georg Brandlcdcede62006-05-30 08:47:19 +0000284
Brett Cannon2ee41282007-08-14 05:51:06 +0000285 with catch_warning():
Brett Cannon229cee22007-05-05 01:34:02 +0000286 ignore_message_warning()
287 for exc, args, expected in exceptionList:
288 try:
289 raise exc(*args)
290 except BaseException, e:
291 if type(e) is not exc:
292 raise
293 # Verify module name
Georg Brandld7e9f602007-08-21 06:03:43 +0000294 self.assertEquals(type(e).__module__, 'exceptions')
Brett Cannon229cee22007-05-05 01:34:02 +0000295 # Verify no ref leaks in Exc_str()
296 s = str(e)
297 for checkArgName in expected:
298 self.assertEquals(repr(getattr(e, checkArgName)),
299 repr(expected[checkArgName]),
300 'exception "%s", attribute "%s"' %
301 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000302
Brett Cannon229cee22007-05-05 01:34:02 +0000303 # test for pickling support
304 for p in pickle, cPickle:
305 for protocol in range(p.HIGHEST_PROTOCOL + 1):
306 new = p.loads(p.dumps(e, protocol))
307 for checkArgName in expected:
308 got = repr(getattr(new, checkArgName))
309 want = repr(expected[checkArgName])
310 self.assertEquals(got, want,
Brett Cannonb13f70d2007-11-03 06:47:02 +0000311 'pickled "%r", attribute "%s"' %
Brett Cannon229cee22007-05-05 01:34:02 +0000312 (e, checkArgName))
Georg Brandlcdcede62006-05-30 08:47:19 +0000313
Brett Cannone05e6b02007-01-29 04:41:44 +0000314 def testSlicing(self):
315 # Test that you can slice an exception directly instead of requiring
316 # going through the 'args' attribute.
317 args = (1, 2, 3)
318 exc = BaseException(*args)
319 self.failUnlessEqual(exc[:], args)
320
Georg Brandlcdcede62006-05-30 08:47:19 +0000321 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000322 # test that builtin exception don't take keyword args,
323 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000324 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000325
Georg Brandlcdcede62006-05-30 08:47:19 +0000326 class DerivedException(BaseException):
327 def __init__(self, fancy_arg):
328 BaseException.__init__(self)
329 self.fancy_arg = fancy_arg
330
331 x = DerivedException(fancy_arg=42)
332 self.assertEquals(x.fancy_arg, 42)
333
Armin Rigo53c1692f2006-06-21 21:58:50 +0000334 def testInfiniteRecursion(self):
335 def f():
336 return f()
337 self.assertRaises(RuntimeError, f)
338
339 def g():
340 try:
341 return g()
342 except ValueError:
343 return -1
344 self.assertRaises(RuntimeError, g)
345
Brett Cannonca2ca792006-09-09 07:11:46 +0000346 def testUnicodeStrUsage(self):
347 # Make sure both instances and classes have a str and unicode
348 # representation.
349 self.failUnless(str(Exception))
350 self.failUnless(unicode(Exception))
351 self.failUnless(str(Exception('a')))
352 self.failUnless(unicode(Exception(u'a')))
Nick Coghlan524b7772008-07-08 14:08:04 +0000353 self.failUnless(unicode(Exception(u'\xe1')))
Brett Cannonca2ca792006-09-09 07:11:46 +0000354
Amaury Forgeot d'Arc246daed2008-07-31 00:42:16 +0000355 def test_badisinstance(self):
356 # Bug #2542: if issubclass(e, MyException) raises an exception,
357 # it should be ignored
358 class Meta(type):
359 def __subclasscheck__(cls, subclass):
360 raise ValueError()
361
362 class MyException(Exception):
363 __metaclass__ = Meta
364 pass
365
366 with captured_output("stderr") as stderr:
367 try:
368 raise KeyError()
369 except MyException, e:
370 self.fail("exception should not be a MyException")
371 except KeyError:
372 pass
373 except:
374 self.fail("Should have raised TypeError")
375 else:
376 self.fail("Should have raised TypeError")
377 self.assertEqual(stderr.getvalue(),
378 "Exception ValueError: ValueError() in "
379 "<type 'exceptions.KeyError'> ignored\n")
Brett Cannonca2ca792006-09-09 07:11:46 +0000380
Georg Brandlcdcede62006-05-30 08:47:19 +0000381def test_main():
382 run_unittest(ExceptionTests)
383
384if __name__ == '__main__':
385 test_main()