blob: 4891f4be50c732006f8ba71981d67d98829df6f1 [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
7try:
8 import cPickle
9except ImportError:
10 cPickle = None
Thomas Wouters73e5a5b2006-06-08 15:35:45 +000011
12from test.test_support import TESTFN, unlink, run_unittest
Guido van Rossum83b120d2001-08-23 03:23:03 +000013
Guido van Rossum3bead091992-01-27 17:00:37 +000014# XXX This is not really enough, each *operation* should be tested!
15
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000016class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000017
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000018 def testReload(self):
19 # Reloading the built-in exceptions module failed prior to Py2.2, while it
20 # should act the same as reloading built-in sys.
21 try:
22 import exceptions
23 reload(exceptions)
Guido van Rossumb940e112007-01-10 16:19:56 +000024 except ImportError as e:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000025 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000026
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000027 def raise_catch(self, exc, excname):
28 try:
29 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)
36 self.assertEquals(buf1, buf2)
37 self.assertEquals(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
51 marshal.loads('')
52 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
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000059 self.raise_catch(IOError, "IOError")
60 self.assertRaises(IOError, 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")
95 # can only be tested under -tt, and is the only test for -tt
96 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<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")
110 self.assertRaises(ValueError, chr, 10000)
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
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000151 def testSettingException(self):
152 # test that setting an exception at the C level works even if the
153 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000154
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000155 class BadException(Exception):
156 def __init__(self_):
157 raise RuntimeError, "can't instantiate BadException"
Finn Bockaa3dc452001-12-08 10:15:48 +0000158
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000159 class InvalidException:
160 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000161
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000162 def test_capi1():
163 import _testcapi
164 try:
165 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000166 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000167 exc, err, tb = sys.exc_info()
168 co = tb.tb_frame.f_code
169 self.assertEquals(co.co_name, "test_capi1")
170 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
171 else:
172 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000173
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000174 def test_capi2():
175 import _testcapi
176 try:
177 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000178 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000179 exc, err, tb = sys.exc_info()
180 co = tb.tb_frame.f_code
181 self.assertEquals(co.co_name, "__init__")
182 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
183 co2 = tb.tb_frame.f_back.f_code
184 self.assertEquals(co2.co_name, "test_capi2")
185 else:
186 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000187
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000188 def test_capi3():
189 import _testcapi
190 self.assertRaises(SystemError, _testcapi.raise_exception,
191 InvalidException, 1)
192
193 if not sys.platform.startswith('java'):
194 test_capi1()
195 test_capi2()
196 test_capi3()
197
Thomas Wouters89f507f2006-12-13 04:49:30 +0000198 def test_WindowsError(self):
199 try:
200 WindowsError
201 except NameError:
202 pass
203 else:
204 self.failUnlessEqual(str(WindowsError(1001)),
205 "1001")
206 self.failUnlessEqual(str(WindowsError(1001, "message")),
207 "[Error 1001] message")
208 self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
209 self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
210
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000211 def testAttributes(self):
212 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000213
214 exceptionList = [
215 (BaseException, (), {'message' : '', 'args' : ()}),
216 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
217 (BaseException, ('foo',),
218 {'message' : 'foo', 'args' : ('foo',)}),
219 (BaseException, ('foo', 1),
220 {'message' : '', 'args' : ('foo', 1)}),
221 (SystemExit, ('foo',),
222 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
223 (IOError, ('foo',),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000224 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
225 'errno' : None, 'strerror' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000226 (IOError, ('foo', 'bar'),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000227 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
228 'errno' : 'foo', 'strerror' : 'bar'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000229 (IOError, ('foo', 'bar', 'baz'),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000230 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
231 'errno' : 'foo', 'strerror' : 'bar'}),
232 (IOError, ('foo', 'bar', 'baz', 'quux'),
233 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000234 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
235 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
236 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
237 'filename' : 'filenameStr'}),
238 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
239 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
240 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
241 (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' : (),}),
Thomas Wouters89f507f2006-12-13 04:49:30 +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'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000266 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 'ordinal not in range'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000268 'encoding' : 'ascii', 'object' : '\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000269 'start' : 0, 'reason' : 'ordinal not in range'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +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}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000274 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000275 try:
276 exceptionList.append(
277 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
278 {'message' : '', 'args' : (1, 'strErrorStr'),
279 'strerror' : 'strErrorStr', 'winerror' : 1,
280 'errno' : 22, 'filename' : 'filenameStr'})
281 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000282 except NameError:
283 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000284
Thomas Wouters89f507f2006-12-13 04:49:30 +0000285 for exc, args, expected in exceptionList:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000286 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000287 raise exc(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +0000288 except BaseException as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000289 if type(e) is not exc:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000290 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000291 # Verify module name
292 self.assertEquals(type(e).__module__, 'exceptions')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000293 # Verify no ref leaks in Exc_str()
294 s = str(e)
295 for checkArgName in expected:
296 self.assertEquals(repr(getattr(e, checkArgName)),
297 repr(expected[checkArgName]),
298 'exception "%s", attribute "%s"' %
299 (repr(e), checkArgName))
300
301 # test for pickling support
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000302 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +0000303 if p is None:
304 continue # cPickle not found -- skip it
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000305 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,
311 'pickled "%r", attribute "%s' %
312 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000313
Thomas Wouters9fe394c2007-02-05 01:24:16 +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
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000321 def testKeywordArgs(self):
322 # test that builtin exception don't take keyword args,
323 # but user-defined subclasses can if they want
324 self.assertRaises(TypeError, BaseException, a=1)
325
326 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
Thomas Wouters0e3f5912006-08-11 14:57:12 +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
Thomas Wouters89f507f2006-12-13 04:49:30 +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')))
353
Guido van Rossumb940e112007-01-10 16:19:56 +0000354 def testExceptionCleanup(self):
355 # Make sure "except V as N" exceptions are cleaned up properly
356
357 try:
358 raise Exception()
359 except Exception as e:
360 self.failUnless(e)
361 del e
362 self.failIf('e' in locals())
363
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000365def test_main():
366 run_unittest(ExceptionTests)
367
368if __name__ == '__main__':
369 test_main()