blob: 0eb6b46a75bfeef9693b1dfdf9d33126779f5ef9 [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")
90 try: exec '/\n'
91 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
199 def testAttributes(self):
200 # test that exception attributes are happy
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000201 try:
202 str(u'Hello \u00E1')
203 except Exception, e:
204 sampleUnicodeEncodeError = e
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000205
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000206 try:
207 unicode('\xff')
208 except Exception, e:
209 sampleUnicodeDecodeError = e
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000210
211 exceptionList = [
212 (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',),
221 {'message' : 'foo', 'args' : ('foo',)}),
222 (IOError, ('foo', 'bar'),
223 {'message' : '', 'args' : ('foo', 'bar')}),
224 (IOError, ('foo', 'bar', 'baz'),
225 {'message' : '', 'args' : ('foo', 'bar')}),
226 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
227 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
228 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
229 'filename' : 'filenameStr'}),
230 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
231 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
232 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
233 (SyntaxError, ('msgStr',),
234 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
235 'print_file_and_line' : None, 'msg' : 'msgStr',
236 'filename' : None, 'lineno' : None, 'offset' : None}),
237 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
238 'textStr')),
239 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
240 'args' : ('msgStr', ('filenameStr', 'linenoStr',
241 'offsetStr', 'textStr')),
242 'print_file_and_line' : None, 'msg' : 'msgStr',
243 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
244 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
245 'textStr', 'print_file_and_lineStr'),
246 {'message' : '', 'text' : None,
247 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
248 'textStr', 'print_file_and_lineStr'),
249 'print_file_and_line' : None, 'msg' : 'msgStr',
250 'filename' : None, 'lineno' : None, 'offset' : None}),
251 (UnicodeError, (), {'message' : '', 'args' : (),}),
252 (sampleUnicodeEncodeError,
253 {'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
254 'ordinal not in range(128)'),
255 'encoding' : 'ascii', 'object' : u'Hello \xe1',
256 'start' : 6, 'reason' : 'ordinal not in range(128)'}),
257 (sampleUnicodeDecodeError,
258 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
259 'ordinal not in range(128)'),
260 'encoding' : 'ascii', 'object' : '\xff',
261 'start' : 0, 'reason' : 'ordinal not in range(128)'}),
262 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
263 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
264 'object' : u'\u3042', 'reason' : 'ouch',
265 'start' : 0, 'end' : 1}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000266 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000267 try:
268 exceptionList.append(
269 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
270 {'message' : '', 'args' : (1, 'strErrorStr'),
271 'strerror' : 'strErrorStr', 'winerror' : 1,
272 'errno' : 22, 'filename' : 'filenameStr'})
273 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000274 except NameError:
275 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000276
277 for args in exceptionList:
278 expected = args[-1]
279 try:
280 exc = args[0]
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000281 if len(args) == 2:
282 raise exc
283 else:
284 raise exc(*args[1])
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000285 except BaseException, e:
286 if (e is not exc and # needed for sampleUnicode errors
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000287 type(e) is not exc):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000288 raise
289 # Verify no ref leaks in Exc_str()
290 s = str(e)
291 for checkArgName in expected:
292 self.assertEquals(repr(getattr(e, checkArgName)),
293 repr(expected[checkArgName]),
294 'exception "%s", attribute "%s"' %
295 (repr(e), checkArgName))
296
297 # test for pickling support
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000298 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +0000299 if p is None:
300 continue # cPickle not found -- skip it
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000301 for protocol in range(p.HIGHEST_PROTOCOL + 1):
302 new = p.loads(p.dumps(e, protocol))
303 for checkArgName in expected:
304 got = repr(getattr(new, checkArgName))
305 want = repr(expected[checkArgName])
306 self.assertEquals(got, want,
307 'pickled "%r", attribute "%s' %
308 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000309
310 def testKeywordArgs(self):
311 # test that builtin exception don't take keyword args,
312 # but user-defined subclasses can if they want
313 self.assertRaises(TypeError, BaseException, a=1)
314
315 class DerivedException(BaseException):
316 def __init__(self, fancy_arg):
317 BaseException.__init__(self)
318 self.fancy_arg = fancy_arg
319
320 x = DerivedException(fancy_arg=42)
321 self.assertEquals(x.fancy_arg, 42)
322
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000323 def testInfiniteRecursion(self):
324 def f():
325 return f()
326 self.assertRaises(RuntimeError, f)
327
328 def g():
329 try:
330 return g()
331 except ValueError:
332 return -1
333 self.assertRaises(RuntimeError, g)
334
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000335def test_main():
336 run_unittest(ExceptionTests)
337
338if __name__ == '__main__':
339 test_main()