blob: abce41eef71c11759b736c7b4afe67b365254104 [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
Thomas Wouters73e5a5b2006-06-08 15:35:45 +00006import warnings
Guido van Rossumbf12cdb2006-08-17 20:24:18 +00007import pickle
8try:
9 import cPickle
10except ImportError:
11 cPickle = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000012
13from test.test_support import TESTFN, unlink, run_unittest
Guido van Rossum83b120d2001-08-23 03:23:03 +000014
Guido van Rossum3bead091992-01-27 17:00:37 +000015# XXX This is not really enough, each *operation* should be tested!
16
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000017class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000018
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000019 def testReload(self):
20 # Reloading the built-in exceptions module failed prior to Py2.2, while it
21 # should act the same as reloading built-in sys.
22 try:
23 import exceptions
24 reload(exceptions)
25 except ImportError, e:
26 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000027
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000028 def raise_catch(self, exc, excname):
29 try:
30 raise exc, "spam"
31 except exc, err:
32 buf1 = str(err)
33 try:
34 raise exc("spam")
35 except exc, err:
36 buf2 = str(err)
37 self.assertEquals(buf1, buf2)
38 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000039
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000040 def testRaising(self):
41 self.raise_catch(AttributeError, "AttributeError")
42 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000043
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000044 self.raise_catch(EOFError, "EOFError")
45 fp = open(TESTFN, 'w')
46 fp.close()
47 fp = open(TESTFN, 'r')
48 savestdin = sys.stdin
49 try:
50 try:
51 import marshal
52 marshal.loads('')
53 except EOFError:
54 pass
55 finally:
56 sys.stdin = savestdin
57 fp.close()
58 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000059
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000060 self.raise_catch(IOError, "IOError")
61 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000062
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000063 self.raise_catch(ImportError, "ImportError")
64 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000065
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000066 self.raise_catch(IndexError, "IndexError")
67 x = []
68 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000070 self.raise_catch(KeyError, "KeyError")
71 x = {}
72 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000073
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000074 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000075
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000076 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000077
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000078 self.raise_catch(NameError, "NameError")
79 try: x = undefined_variable
80 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000081
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000082 self.raise_catch(OverflowError, "OverflowError")
83 x = 1
84 for dummy in range(128):
85 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000086
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000087 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000089 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +000090 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000091 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000092
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000093 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000094
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000095 self.raise_catch(TabError, "TabError")
96 # can only be tested under -tt, and is the only test for -tt
97 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
98 #except TabError: pass
99 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +0000100
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000101 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(SystemExit, "SystemExit")
104 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000105
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000106 self.raise_catch(TypeError, "TypeError")
107 try: [] + ()
108 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000109
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000110 self.raise_catch(ValueError, "ValueError")
111 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000112
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000113 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
114 try: x = 1/0
115 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000116
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000117 self.raise_catch(Exception, "Exception")
118 try: x = 1/0
119 except Exception, e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000120
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000121 def testSyntaxErrorMessage(self):
122 # make sure the right exception message is raised for each of
123 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000124
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000125 def ckmsg(src, msg):
126 try:
127 compile(src, '<fragment>', 'exec')
128 except SyntaxError, e:
129 if e.msg != msg:
130 self.fail("expected %s, got %s" % (msg, e.msg))
131 else:
132 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000133
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000134 s = '''while 1:
135 try:
136 pass
137 finally:
138 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000139
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000140 if not sys.platform.startswith('java'):
141 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000142
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000143 s = '''if 1:
144 try:
145 continue
146 except:
147 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000148
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000149 ckmsg(s, "'continue' not properly in loop")
150 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000151
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_):
158 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)
167 except TypeError, err:
168 exc, err, tb = sys.exc_info()
169 co = tb.tb_frame.f_code
170 self.assertEquals(co.co_name, "test_capi1")
171 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
172 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)
179 except RuntimeError, err:
180 exc, err, tb = sys.exc_info()
181 co = tb.tb_frame.f_code
182 self.assertEquals(co.co_name, "__init__")
183 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
184 co2 = tb.tb_frame.f_back.f_code
185 self.assertEquals(co2.co_name, "test_capi2")
186 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:
205 self.failUnlessEqual(str(WindowsError(1001)),
206 "1001")
207 self.failUnlessEqual(str(WindowsError(1001, "message")),
208 "[Error 1001] message")
209 self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
210 self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
211
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000212 def testAttributes(self):
213 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000214
215 exceptionList = [
216 (BaseException, (), {'message' : '', 'args' : ()}),
217 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
218 (BaseException, ('foo',),
219 {'message' : 'foo', 'args' : ('foo',)}),
220 (BaseException, ('foo', 1),
221 {'message' : '', 'args' : ('foo', 1)}),
222 (SystemExit, ('foo',),
223 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
224 (IOError, ('foo',),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000225 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
226 'errno' : None, 'strerror' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000227 (IOError, ('foo', 'bar'),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000228 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
229 'errno' : 'foo', 'strerror' : 'bar'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000230 (IOError, ('foo', 'bar', 'baz'),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000231 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
232 'errno' : 'foo', 'strerror' : 'bar'}),
233 (IOError, ('foo', 'bar', 'baz', 'quux'),
234 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000235 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
236 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
237 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
238 'filename' : 'filenameStr'}),
239 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
240 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
241 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
242 (SyntaxError, ('msgStr',),
243 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
244 'print_file_and_line' : None, 'msg' : 'msgStr',
245 'filename' : None, 'lineno' : None, 'offset' : None}),
246 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
247 'textStr')),
248 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
249 'args' : ('msgStr', ('filenameStr', 'linenoStr',
250 'offsetStr', 'textStr')),
251 'print_file_and_line' : None, 'msg' : 'msgStr',
252 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
253 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
254 'textStr', 'print_file_and_lineStr'),
255 {'message' : '', 'text' : None,
256 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
257 'textStr', 'print_file_and_lineStr'),
258 'print_file_and_line' : None, 'msg' : 'msgStr',
259 'filename' : None, 'lineno' : None, 'offset' : None}),
260 (UnicodeError, (), {'message' : '', 'args' : (),}),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000261 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
262 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
263 'ordinal not in range'),
264 'encoding' : 'ascii', 'object' : u'a',
265 'start' : 0, 'reason' : 'ordinal not in range'}),
266 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000267 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000268 'ordinal not in range'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000269 'encoding' : 'ascii', 'object' : '\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000270 'start' : 0, 'reason' : 'ordinal not in range'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000271 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
272 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
273 'object' : u'\u3042', 'reason' : 'ouch',
274 'start' : 0, 'end' : 1}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000275 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000276 try:
277 exceptionList.append(
278 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
279 {'message' : '', 'args' : (1, 'strErrorStr'),
280 'strerror' : 'strErrorStr', 'winerror' : 1,
281 'errno' : 22, 'filename' : 'filenameStr'})
282 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000283 except NameError:
284 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000285
Thomas Wouters89f507f2006-12-13 04:49:30 +0000286 for exc, args, expected in exceptionList:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000287 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000288 raise exc(*args)
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000289 except BaseException, e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000290 if type(e) is not exc:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000291 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292 # Verify module name
293 self.assertEquals(type(e).__module__, 'exceptions')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000294 # Verify no ref leaks in Exc_str()
295 s = str(e)
296 for checkArgName in expected:
297 self.assertEquals(repr(getattr(e, checkArgName)),
298 repr(expected[checkArgName]),
299 'exception "%s", attribute "%s"' %
300 (repr(e), checkArgName))
301
302 # test for pickling support
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000303 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +0000304 if p is None:
305 continue # cPickle not found -- skip it
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000306 for protocol in range(p.HIGHEST_PROTOCOL + 1):
307 new = p.loads(p.dumps(e, protocol))
308 for checkArgName in expected:
309 got = repr(getattr(new, checkArgName))
310 want = repr(expected[checkArgName])
311 self.assertEquals(got, want,
312 'pickled "%r", attribute "%s' %
313 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000314
315 def testKeywordArgs(self):
316 # test that builtin exception don't take keyword args,
317 # but user-defined subclasses can if they want
318 self.assertRaises(TypeError, BaseException, a=1)
319
320 class DerivedException(BaseException):
321 def __init__(self, fancy_arg):
322 BaseException.__init__(self)
323 self.fancy_arg = fancy_arg
324
325 x = DerivedException(fancy_arg=42)
326 self.assertEquals(x.fancy_arg, 42)
327
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000328 def testInfiniteRecursion(self):
329 def f():
330 return f()
331 self.assertRaises(RuntimeError, f)
332
333 def g():
334 try:
335 return g()
336 except ValueError:
337 return -1
338 self.assertRaises(RuntimeError, g)
339
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 def testUnicodeStrUsage(self):
341 # Make sure both instances and classes have a str and unicode
342 # representation.
343 self.failUnless(str(Exception))
344 self.failUnless(unicode(Exception))
345 self.failUnless(str(Exception('a')))
346 self.failUnless(unicode(Exception(u'a')))
347
348
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000349def test_main():
350 run_unittest(ExceptionTests)
351
352if __name__ == '__main__':
353 test_main()