blob: 0ff3b10dd97b204eb0edc237f7309511a1571747 [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 raise_catch(self, exc, excname):
19 try:
20 raise exc, "spam"
Guido van Rossumb940e112007-01-10 16:19:56 +000021 except exc as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000022 buf1 = str(err)
23 try:
24 raise exc("spam")
Guido van Rossumb940e112007-01-10 16:19:56 +000025 except exc as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000026 buf2 = str(err)
27 self.assertEquals(buf1, buf2)
28 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000029
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000030 def testRaising(self):
31 self.raise_catch(AttributeError, "AttributeError")
32 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000033
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000034 self.raise_catch(EOFError, "EOFError")
35 fp = open(TESTFN, 'w')
36 fp.close()
37 fp = open(TESTFN, 'r')
38 savestdin = sys.stdin
39 try:
40 try:
41 import marshal
42 marshal.loads('')
43 except EOFError:
44 pass
45 finally:
46 sys.stdin = savestdin
47 fp.close()
48 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000049
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000050 self.raise_catch(IOError, "IOError")
51 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000052
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000053 self.raise_catch(ImportError, "ImportError")
54 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000055
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000056 self.raise_catch(IndexError, "IndexError")
57 x = []
58 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000059
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000060 self.raise_catch(KeyError, "KeyError")
61 x = {}
62 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000063
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000064 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000065
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000066 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000067
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000068 self.raise_catch(NameError, "NameError")
69 try: x = undefined_variable
70 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000071
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000072 self.raise_catch(OverflowError, "OverflowError")
73 x = 1
74 for dummy in range(128):
75 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000076
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000077 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000078
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000079 self.raise_catch(SyntaxError, "SyntaxError")
Georg Brandl7cae87c2006-09-06 06:51:57 +000080 try: exec('/\n')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000081 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000083 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000084
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000085 self.raise_catch(TabError, "TabError")
86 # can only be tested under -tt, and is the only test for -tt
87 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
88 #except TabError: pass
89 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +000090
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000091 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +000092
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000093 self.raise_catch(SystemExit, "SystemExit")
94 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +000095
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000096 self.raise_catch(TypeError, "TypeError")
97 try: [] + ()
98 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +000099
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000100 self.raise_catch(ValueError, "ValueError")
101 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
104 try: x = 1/0
105 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000106
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000107 self.raise_catch(Exception, "Exception")
108 try: x = 1/0
Guido van Rossumb940e112007-01-10 16:19:56 +0000109 except Exception as e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000110
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000111 def testSyntaxErrorMessage(self):
112 # make sure the right exception message is raised for each of
113 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000114
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000115 def ckmsg(src, msg):
116 try:
117 compile(src, '<fragment>', 'exec')
Guido van Rossumb940e112007-01-10 16:19:56 +0000118 except SyntaxError as e:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000119 if e.msg != msg:
120 self.fail("expected %s, got %s" % (msg, e.msg))
121 else:
122 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000123
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000124 s = '''while 1:
125 try:
126 pass
127 finally:
128 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000129
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000130 if not sys.platform.startswith('java'):
131 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000132
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000133 s = '''if 1:
134 try:
135 continue
136 except:
137 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000138
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000139 ckmsg(s, "'continue' not properly in loop")
140 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000141
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000142 def testSettingException(self):
143 # test that setting an exception at the C level works even if the
144 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000145
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000146 class BadException(Exception):
147 def __init__(self_):
148 raise RuntimeError, "can't instantiate BadException"
Finn Bockaa3dc452001-12-08 10:15:48 +0000149
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000150 class InvalidException:
151 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000152
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000153 def test_capi1():
154 import _testcapi
155 try:
156 _testcapi.raise_exception(BadException, 1)
Guido van Rossumb940e112007-01-10 16:19:56 +0000157 except TypeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000158 exc, err, tb = sys.exc_info()
159 co = tb.tb_frame.f_code
160 self.assertEquals(co.co_name, "test_capi1")
161 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
162 else:
163 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000164
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000165 def test_capi2():
166 import _testcapi
167 try:
168 _testcapi.raise_exception(BadException, 0)
Guido van Rossumb940e112007-01-10 16:19:56 +0000169 except RuntimeError as err:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000170 exc, err, tb = sys.exc_info()
171 co = tb.tb_frame.f_code
172 self.assertEquals(co.co_name, "__init__")
173 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
174 co2 = tb.tb_frame.f_back.f_code
175 self.assertEquals(co2.co_name, "test_capi2")
176 else:
177 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000179 def test_capi3():
180 import _testcapi
181 self.assertRaises(SystemError, _testcapi.raise_exception,
182 InvalidException, 1)
183
184 if not sys.platform.startswith('java'):
185 test_capi1()
186 test_capi2()
187 test_capi3()
188
Thomas Wouters89f507f2006-12-13 04:49:30 +0000189 def test_WindowsError(self):
190 try:
191 WindowsError
192 except NameError:
193 pass
194 else:
195 self.failUnlessEqual(str(WindowsError(1001)),
196 "1001")
197 self.failUnlessEqual(str(WindowsError(1001, "message")),
198 "[Error 1001] message")
199 self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
200 self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
201
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000202 def testAttributes(self):
203 # test that exception attributes are happy
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000204
205 exceptionList = [
206 (BaseException, (), {'message' : '', 'args' : ()}),
207 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
208 (BaseException, ('foo',),
209 {'message' : 'foo', 'args' : ('foo',)}),
210 (BaseException, ('foo', 1),
211 {'message' : '', 'args' : ('foo', 1)}),
212 (SystemExit, ('foo',),
213 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
214 (IOError, ('foo',),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000215 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
216 'errno' : None, 'strerror' : None}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000217 (IOError, ('foo', 'bar'),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000218 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
219 'errno' : 'foo', 'strerror' : 'bar'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000220 (IOError, ('foo', 'bar', 'baz'),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000221 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
222 'errno' : 'foo', 'strerror' : 'bar'}),
223 (IOError, ('foo', 'bar', 'baz', 'quux'),
224 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000225 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
226 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
227 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
228 'filename' : 'filenameStr'}),
229 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
230 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
231 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
232 (SyntaxError, ('msgStr',),
233 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
234 'print_file_and_line' : None, 'msg' : 'msgStr',
235 'filename' : None, 'lineno' : None, 'offset' : None}),
236 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
237 'textStr')),
238 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
239 'args' : ('msgStr', ('filenameStr', 'linenoStr',
240 'offsetStr', 'textStr')),
241 'print_file_and_line' : None, 'msg' : 'msgStr',
242 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
243 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
244 'textStr', 'print_file_and_lineStr'),
245 {'message' : '', 'text' : None,
246 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
247 'textStr', 'print_file_and_lineStr'),
248 'print_file_and_line' : None, 'msg' : 'msgStr',
249 'filename' : None, 'lineno' : None, 'offset' : None}),
250 (UnicodeError, (), {'message' : '', 'args' : (),}),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000251 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
252 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
253 'ordinal not in range'),
254 'encoding' : 'ascii', 'object' : u'a',
255 'start' : 0, 'reason' : 'ordinal not in range'}),
256 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000257 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000258 'ordinal not in range'),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000259 'encoding' : 'ascii', 'object' : '\xff',
Thomas Wouters89f507f2006-12-13 04:49:30 +0000260 'start' : 0, 'reason' : 'ordinal not in range'}),
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000261 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
262 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
263 'object' : u'\u3042', 'reason' : 'ouch',
264 'start' : 0, 'end' : 1}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000265 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000266 try:
267 exceptionList.append(
268 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
269 {'message' : '', 'args' : (1, 'strErrorStr'),
270 'strerror' : 'strErrorStr', 'winerror' : 1,
271 'errno' : 22, 'filename' : 'filenameStr'})
272 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000273 except NameError:
274 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000275
Thomas Wouters89f507f2006-12-13 04:49:30 +0000276 for exc, args, expected in exceptionList:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000277 try:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000278 raise exc(*args)
Guido van Rossumb940e112007-01-10 16:19:56 +0000279 except BaseException as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280 if type(e) is not exc:
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000281 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000282 # Verify module name
Neal Norwitz2633c692007-02-26 22:22:47 +0000283 self.assertEquals(type(e).__module__, '__builtin__')
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000284 # Verify no ref leaks in Exc_str()
285 s = str(e)
286 for checkArgName in expected:
287 self.assertEquals(repr(getattr(e, checkArgName)),
288 repr(expected[checkArgName]),
289 'exception "%s", attribute "%s"' %
290 (repr(e), checkArgName))
291
292 # test for pickling support
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000293 for p in pickle, cPickle:
Guido van Rossumbf12cdb2006-08-17 20:24:18 +0000294 if p is None:
295 continue # cPickle not found -- skip it
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000296 for protocol in range(p.HIGHEST_PROTOCOL + 1):
297 new = p.loads(p.dumps(e, protocol))
298 for checkArgName in expected:
299 got = repr(getattr(new, checkArgName))
300 want = repr(expected[checkArgName])
301 self.assertEquals(got, want,
302 'pickled "%r", attribute "%s' %
303 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000304
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000305 def testSlicing(self):
306 # Test that you can slice an exception directly instead of requiring
307 # going through the 'args' attribute.
308 args = (1, 2, 3)
309 exc = BaseException(*args)
310 self.failUnlessEqual(exc[:], args)
311
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000312 def testKeywordArgs(self):
313 # test that builtin exception don't take keyword args,
314 # but user-defined subclasses can if they want
315 self.assertRaises(TypeError, BaseException, a=1)
316
317 class DerivedException(BaseException):
318 def __init__(self, fancy_arg):
319 BaseException.__init__(self)
320 self.fancy_arg = fancy_arg
321
322 x = DerivedException(fancy_arg=42)
323 self.assertEquals(x.fancy_arg, 42)
324
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000325 def testInfiniteRecursion(self):
326 def f():
327 return f()
328 self.assertRaises(RuntimeError, f)
329
330 def g():
331 try:
332 return g()
333 except ValueError:
334 return -1
335 self.assertRaises(RuntimeError, g)
336
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337 def testUnicodeStrUsage(self):
338 # Make sure both instances and classes have a str and unicode
339 # representation.
340 self.failUnless(str(Exception))
341 self.failUnless(unicode(Exception))
342 self.failUnless(str(Exception('a')))
343 self.failUnless(unicode(Exception(u'a')))
344
Guido van Rossumb940e112007-01-10 16:19:56 +0000345 def testExceptionCleanup(self):
346 # Make sure "except V as N" exceptions are cleaned up properly
347
348 try:
349 raise Exception()
350 except Exception as e:
351 self.failUnless(e)
352 del e
353 self.failIf('e' in locals())
354
Thomas Wouters89f507f2006-12-13 04:49:30 +0000355
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000356def test_main():
357 run_unittest(ExceptionTests)
358
359if __name__ == '__main__':
360 test_main()