blob: 2f57f3df5040145a9ea69cb98a8fd3e78cfadff7 [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,
Brett Cannon2ee41282007-08-14 05:51:06 +00009 catch_warning)
Brett Cannon229cee22007-05-05 01:34:02 +000010from test.test_pep352 import ignore_message_warning
Guido van Rossum83b120d2001-08-23 03:23:03 +000011
Georg Brandlfdca6d82007-08-21 06:01:18 +000012class NaiveException(Exception):
13 def __init__(self, x):
14 self.x = x
15
16class SomewhatNaiveException(Exception):
17 def __init__(self, x):
18 self.x = x
19 Exception.__init__(self)
20
21
Guido van Rossum3bead091992-01-27 17:00:37 +000022# XXX This is not really enough, each *operation* should be tested!
23
Georg Brandlcdcede62006-05-30 08:47:19 +000024class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000025
Georg Brandlcdcede62006-05-30 08:47:19 +000026 def testReload(self):
27 # Reloading the built-in exceptions module failed prior to Py2.2, while it
28 # should act the same as reloading built-in sys.
29 try:
30 import exceptions
31 reload(exceptions)
32 except ImportError, e:
33 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000034
Georg Brandlcdcede62006-05-30 08:47:19 +000035 def raise_catch(self, exc, excname):
36 try:
37 raise exc, "spam"
38 except exc, err:
39 buf1 = str(err)
40 try:
41 raise exc("spam")
42 except exc, err:
43 buf2 = str(err)
44 self.assertEquals(buf1, buf2)
45 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000046
Georg Brandlcdcede62006-05-30 08:47:19 +000047 def testRaising(self):
Tim Petersdd55b0a2006-05-30 23:28:02 +000048 self.raise_catch(AttributeError, "AttributeError")
Georg Brandlcdcede62006-05-30 08:47:19 +000049 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000050
Georg Brandlcdcede62006-05-30 08:47:19 +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 sys.stdin = fp
59 x = raw_input()
60 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
Georg Brandlcdcede62006-05-30 08:47:19 +000067 self.raise_catch(IOError, "IOError")
68 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Georg Brandlcdcede62006-05-30 08:47:19 +000070 self.raise_catch(ImportError, "ImportError")
71 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Georg Brandlcdcede62006-05-30 08:47:19 +000073 self.raise_catch(IndexError, "IndexError")
74 x = []
75 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000076
Georg Brandlcdcede62006-05-30 08:47:19 +000077 self.raise_catch(KeyError, "KeyError")
78 x = {}
79 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000080
Georg Brandlcdcede62006-05-30 08:47:19 +000081 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Georg Brandlcdcede62006-05-30 08:47:19 +000083 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000084
Georg Brandlcdcede62006-05-30 08:47:19 +000085 self.raise_catch(NameError, "NameError")
86 try: x = undefined_variable
87 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000094 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000095
Georg Brandlcdcede62006-05-30 08:47:19 +000096 self.raise_catch(SyntaxError, "SyntaxError")
97 try: exec '/\n'
98 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000099
Georg Brandlcdcede62006-05-30 08:47:19 +0000100 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000101
Georg Brandlcdcede62006-05-30 08:47:19 +0000102 self.raise_catch(TabError, "TabError")
103 # can only be tested under -tt, and is the only test for -tt
104 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
105 #except TabError: pass
106 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000107
Georg Brandlcdcede62006-05-30 08:47:19 +0000108 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000109
Georg Brandlcdcede62006-05-30 08:47:19 +0000110 self.raise_catch(SystemExit, "SystemExit")
111 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000112
Georg Brandlcdcede62006-05-30 08:47:19 +0000113 self.raise_catch(TypeError, "TypeError")
114 try: [] + ()
115 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000116
Georg Brandlcdcede62006-05-30 08:47:19 +0000117 self.raise_catch(ValueError, "ValueError")
118 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000119
Georg Brandlcdcede62006-05-30 08:47:19 +0000120 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
121 try: x = 1/0
122 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000123
Georg Brandlcdcede62006-05-30 08:47:19 +0000124 self.raise_catch(Exception, "Exception")
125 try: x = 1/0
126 except Exception, e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000127
Georg Brandlcdcede62006-05-30 08:47:19 +0000128 def testSyntaxErrorMessage(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000129 # make sure the right exception message is raised for each of
130 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000131
Georg Brandlcdcede62006-05-30 08:47:19 +0000132 def ckmsg(src, msg):
133 try:
134 compile(src, '<fragment>', 'exec')
135 except SyntaxError, e:
136 if e.msg != msg:
137 self.fail("expected %s, got %s" % (msg, e.msg))
138 else:
139 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000140
Georg Brandlcdcede62006-05-30 08:47:19 +0000141 s = '''while 1:
142 try:
143 pass
144 finally:
145 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000146
Georg Brandlcdcede62006-05-30 08:47:19 +0000147 if not sys.platform.startswith('java'):
148 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000149
Georg Brandlcdcede62006-05-30 08:47:19 +0000150 s = '''if 1:
151 try:
152 continue
153 except:
154 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000155
Georg Brandlcdcede62006-05-30 08:47:19 +0000156 ckmsg(s, "'continue' not properly in loop")
157 ckmsg("continue\n", "'continue' not properly in loop")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000158
Georg Brandlcdcede62006-05-30 08:47:19 +0000159 def testSettingException(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000160 # test that setting an exception at the C level works even if the
161 # exception object can't be constructed.
Finn Bockaa3dc452001-12-08 10:15:48 +0000162
Georg Brandlcdcede62006-05-30 08:47:19 +0000163 class BadException:
164 def __init__(self_):
165 raise RuntimeError, "can't instantiate BadException"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000166
Georg Brandlcdcede62006-05-30 08:47:19 +0000167 def test_capi1():
168 import _testcapi
169 try:
170 _testcapi.raise_exception(BadException, 1)
171 except TypeError, err:
172 exc, err, tb = sys.exc_info()
173 co = tb.tb_frame.f_code
174 self.assertEquals(co.co_name, "test_capi1")
175 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
176 else:
177 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000178
Georg Brandlcdcede62006-05-30 08:47:19 +0000179 def test_capi2():
180 import _testcapi
181 try:
182 _testcapi.raise_exception(BadException, 0)
183 except RuntimeError, err:
184 exc, err, tb = sys.exc_info()
185 co = tb.tb_frame.f_code
186 self.assertEquals(co.co_name, "__init__")
187 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
188 co2 = tb.tb_frame.f_back.f_code
189 self.assertEquals(co2.co_name, "test_capi2")
190 else:
191 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000192
Georg Brandlcdcede62006-05-30 08:47:19 +0000193 if not sys.platform.startswith('java'):
194 test_capi1()
195 test_capi2()
Georg Brandl05f97bf2006-05-30 07:13:29 +0000196
Thomas Hellerdf08f0b2006-10-27 18:31:36 +0000197 def test_WindowsError(self):
198 try:
199 WindowsError
200 except NameError:
201 pass
202 else:
203 self.failUnlessEqual(str(WindowsError(1001)),
204 "1001")
205 self.failUnlessEqual(str(WindowsError(1001, "message")),
206 "[Error 1001] message")
207 self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
208 self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
209
Georg Brandlcdcede62006-05-30 08:47:19 +0000210 def testAttributes(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000211 # test that exception attributes are happy
Tim Petersdd55b0a2006-05-30 23:28:02 +0000212
Georg Brandlcdcede62006-05-30 08:47:19 +0000213 exceptionList = [
Georg Brandle08940e2006-06-01 13:00:49 +0000214 (BaseException, (), {'message' : '', 'args' : ()}),
215 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
216 (BaseException, ('foo',),
217 {'message' : 'foo', 'args' : ('foo',)}),
218 (BaseException, ('foo', 1),
219 {'message' : '', 'args' : ('foo', 1)}),
220 (SystemExit, ('foo',),
221 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
222 (IOError, ('foo',),
Georg Brandl3267d282006-09-30 09:03:42 +0000223 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
224 'errno' : None, 'strerror' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000225 (IOError, ('foo', 'bar'),
Georg Brandl3267d282006-09-30 09:03:42 +0000226 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
227 'errno' : 'foo', 'strerror' : 'bar'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000228 (IOError, ('foo', 'bar', 'baz'),
Georg Brandl3267d282006-09-30 09:03:42 +0000229 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
230 'errno' : 'foo', 'strerror' : 'bar'}),
231 (IOError, ('foo', 'bar', 'baz', 'quux'),
232 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Georg Brandle08940e2006-06-01 13:00:49 +0000233 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
234 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
235 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
236 'filename' : 'filenameStr'}),
237 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
238 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
239 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
Brett Cannonf8267df2007-02-28 18:15:00 +0000240 (SyntaxError, (), {'message' : '', 'msg' : None, 'text' : None,
241 'filename' : None, 'lineno' : None, 'offset' : None,
242 'print_file_and_line' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000243 (SyntaxError, ('msgStr',),
244 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
245 'print_file_and_line' : None, 'msg' : 'msgStr',
246 'filename' : None, 'lineno' : None, 'offset' : None}),
247 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
248 'textStr')),
249 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
250 'args' : ('msgStr', ('filenameStr', 'linenoStr',
251 'offsetStr', 'textStr')),
252 'print_file_and_line' : None, 'msg' : 'msgStr',
253 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
254 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
255 'textStr', 'print_file_and_lineStr'),
256 {'message' : '', 'text' : None,
257 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
258 'textStr', 'print_file_and_lineStr'),
259 'print_file_and_line' : None, 'msg' : 'msgStr',
260 'filename' : None, 'lineno' : None, 'offset' : None}),
261 (UnicodeError, (), {'message' : '', 'args' : (),}),
Georg Brandl38f62372006-09-06 06:50:05 +0000262 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
263 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
264 'ordinal not in range'),
265 'encoding' : 'ascii', 'object' : u'a',
266 'start' : 0, 'reason' : 'ordinal not in range'}),
267 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000268 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Georg Brandl38f62372006-09-06 06:50:05 +0000269 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000270 'encoding' : 'ascii', 'object' : '\xff',
Georg Brandl38f62372006-09-06 06:50:05 +0000271 'start' : 0, 'reason' : 'ordinal not in range'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000272 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
273 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
274 'object' : u'\u3042', 'reason' : 'ouch',
275 'start' : 0, 'end' : 1}),
Georg Brandlfdca6d82007-08-21 06:01:18 +0000276 (NaiveException, ('foo',),
277 {'message': '', 'args': ('foo',), 'x': 'foo'}),
278 (SomewhatNaiveException, ('foo',),
279 {'message': '', 'args': (), 'x': 'foo'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000280 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000281 try:
282 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000283 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
284 {'message' : '', 'args' : (1, 'strErrorStr'),
285 'strerror' : 'strErrorStr', 'winerror' : 1,
286 'errno' : 22, 'filename' : 'filenameStr'})
287 )
Tim Peters80dc76e2006-06-07 06:57:51 +0000288 except NameError:
289 pass
Georg Brandlcdcede62006-05-30 08:47:19 +0000290
Brett Cannon2ee41282007-08-14 05:51:06 +0000291 with catch_warning():
Brett Cannon229cee22007-05-05 01:34:02 +0000292 ignore_message_warning()
293 for exc, args, expected in exceptionList:
294 try:
295 raise exc(*args)
296 except BaseException, e:
297 if type(e) is not exc:
298 raise
299 # Verify module name
Georg Brandlfdca6d82007-08-21 06:01:18 +0000300 if not type(e).__name__.endswith('NaiveException'):
301 self.assertEquals(type(e).__module__, 'exceptions')
Brett Cannon229cee22007-05-05 01:34:02 +0000302 # Verify no ref leaks in Exc_str()
303 s = str(e)
304 for checkArgName in expected:
305 self.assertEquals(repr(getattr(e, checkArgName)),
306 repr(expected[checkArgName]),
307 'exception "%s", attribute "%s"' %
308 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000309
Brett Cannon229cee22007-05-05 01:34:02 +0000310 # test for pickling support
311 for p in pickle, cPickle:
312 for protocol in range(p.HIGHEST_PROTOCOL + 1):
313 new = p.loads(p.dumps(e, protocol))
314 for checkArgName in expected:
315 got = repr(getattr(new, checkArgName))
316 want = repr(expected[checkArgName])
317 self.assertEquals(got, want,
318 'pickled "%r", attribute "%s' %
319 (e, checkArgName))
Georg Brandlcdcede62006-05-30 08:47:19 +0000320
Brett Cannone05e6b02007-01-29 04:41:44 +0000321 def testSlicing(self):
322 # Test that you can slice an exception directly instead of requiring
323 # going through the 'args' attribute.
324 args = (1, 2, 3)
325 exc = BaseException(*args)
326 self.failUnlessEqual(exc[:], args)
327
Georg Brandlcdcede62006-05-30 08:47:19 +0000328 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000329 # test that builtin exception don't take keyword args,
330 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000331 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000332
Georg Brandlcdcede62006-05-30 08:47:19 +0000333 class DerivedException(BaseException):
334 def __init__(self, fancy_arg):
335 BaseException.__init__(self)
336 self.fancy_arg = fancy_arg
337
338 x = DerivedException(fancy_arg=42)
339 self.assertEquals(x.fancy_arg, 42)
340
Armin Rigo53c1692f2006-06-21 21:58:50 +0000341 def testInfiniteRecursion(self):
342 def f():
343 return f()
344 self.assertRaises(RuntimeError, f)
345
346 def g():
347 try:
348 return g()
349 except ValueError:
350 return -1
351 self.assertRaises(RuntimeError, g)
352
Brett Cannonca2ca792006-09-09 07:11:46 +0000353 def testUnicodeStrUsage(self):
354 # Make sure both instances and classes have a str and unicode
355 # representation.
356 self.failUnless(str(Exception))
357 self.failUnless(unicode(Exception))
358 self.failUnless(str(Exception('a')))
359 self.failUnless(unicode(Exception(u'a')))
360
361
Georg Brandlcdcede62006-05-30 08:47:19 +0000362def test_main():
363 run_unittest(ExceptionTests)
364
365if __name__ == '__main__':
366 test_main()