blob: ebe60c1eb0367dfb69c53f32599cbf3b4d8920f0 [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
7import pickle, cPickle
8
9from test.test_support import TESTFN, unlink, run_unittest
Guido van Rossum83b120d2001-08-23 03:23:03 +000010
Guido van Rossum3bead091992-01-27 17:00:37 +000011# XXX This is not really enough, each *operation* should be tested!
12
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000013class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000014
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000015 def testReload(self):
16 # Reloading the built-in exceptions module failed prior to Py2.2, while it
17 # should act the same as reloading built-in sys.
18 try:
19 import exceptions
20 reload(exceptions)
21 except ImportError, e:
22 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000023
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000024 def raise_catch(self, exc, excname):
25 try:
26 raise exc, "spam"
27 except exc, err:
28 buf1 = str(err)
29 try:
30 raise exc("spam")
31 except exc, err:
32 buf2 = str(err)
33 self.assertEquals(buf1, buf2)
34 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000035
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000036 def testRaising(self):
37 self.raise_catch(AttributeError, "AttributeError")
38 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000039
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000040 self.raise_catch(EOFError, "EOFError")
41 fp = open(TESTFN, 'w')
42 fp.close()
43 fp = open(TESTFN, 'r')
44 savestdin = sys.stdin
45 try:
46 try:
47 import marshal
48 marshal.loads('')
49 except EOFError:
50 pass
51 finally:
52 sys.stdin = savestdin
53 fp.close()
54 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000055
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000056 self.raise_catch(IOError, "IOError")
57 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000058
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000059 self.raise_catch(ImportError, "ImportError")
60 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000061
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000062 self.raise_catch(IndexError, "IndexError")
63 x = []
64 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000065
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000066 self.raise_catch(KeyError, "KeyError")
67 x = {}
68 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000070 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000071
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000072 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000073
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000074 self.raise_catch(NameError, "NameError")
75 try: x = undefined_variable
76 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000077
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000078 self.raise_catch(OverflowError, "OverflowError")
79 x = 1
80 for dummy in range(128):
81 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000082
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000083 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000084
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000085 self.raise_catch(SyntaxError, "SyntaxError")
86 try: exec '/\n'
87 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000089 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000090
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000091 self.raise_catch(TabError, "TabError")
92 # can only be tested under -tt, and is the only test for -tt
93 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
94 #except TabError: pass
95 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +000096
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000097 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +000098
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000099 self.raise_catch(SystemExit, "SystemExit")
100 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000101
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000102 self.raise_catch(TypeError, "TypeError")
103 try: [] + ()
104 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000105
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000106 self.raise_catch(ValueError, "ValueError")
107 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000108
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000109 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
110 try: x = 1/0
111 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000112
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000113 self.raise_catch(Exception, "Exception")
114 try: x = 1/0
115 except Exception, e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000116
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000117 def testSyntaxErrorMessage(self):
118 # make sure the right exception message is raised for each of
119 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000120
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000121 def ckmsg(src, msg):
122 try:
123 compile(src, '<fragment>', 'exec')
124 except SyntaxError, e:
125 if e.msg != msg:
126 self.fail("expected %s, got %s" % (msg, e.msg))
127 else:
128 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000129
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000130 s = '''while 1:
131 try:
132 pass
133 finally:
134 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000135
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000136 if not sys.platform.startswith('java'):
137 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000138
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000139 s = '''if 1:
140 try:
141 continue
142 except:
143 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000144
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000145 ckmsg(s, "'continue' not properly in loop")
146 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000147
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000148 def testSettingException(self):
149 # test that setting an exception at the C level works even if the
150 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000151
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000152 class BadException(Exception):
153 def __init__(self_):
154 raise RuntimeError, "can't instantiate BadException"
Finn Bockaa3dc452001-12-08 10:15:48 +0000155
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000156 class InvalidException:
157 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000158
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000159 def test_capi1():
160 import _testcapi
161 try:
162 _testcapi.raise_exception(BadException, 1)
163 except TypeError, err:
164 exc, err, tb = sys.exc_info()
165 co = tb.tb_frame.f_code
166 self.assertEquals(co.co_name, "test_capi1")
167 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
168 else:
169 self.fail("Expected exception")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000170
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000171 def test_capi2():
172 import _testcapi
173 try:
174 _testcapi.raise_exception(BadException, 0)
175 except RuntimeError, err:
176 exc, err, tb = sys.exc_info()
177 co = tb.tb_frame.f_code
178 self.assertEquals(co.co_name, "__init__")
179 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
180 co2 = tb.tb_frame.f_back.f_code
181 self.assertEquals(co2.co_name, "test_capi2")
182 else:
183 self.fail("Expected exception")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000184
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000185 def test_capi3():
186 import _testcapi
187 self.assertRaises(SystemError, _testcapi.raise_exception,
188 InvalidException, 1)
189
190 if not sys.platform.startswith('java'):
191 test_capi1()
192 test_capi2()
193 test_capi3()
194
195 def testAttributes(self):
196 # test that exception attributes are happy
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000197 try:
198 str(u'Hello \u00E1')
199 except Exception, e:
200 sampleUnicodeEncodeError = e
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000201
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000202 try:
203 unicode('\xff')
204 except Exception, e:
205 sampleUnicodeDecodeError = e
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000206
207 exceptionList = [
208 (BaseException, (), {'message' : '', 'args' : ()}),
209 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
210 (BaseException, ('foo',),
211 {'message' : 'foo', 'args' : ('foo',)}),
212 (BaseException, ('foo', 1),
213 {'message' : '', 'args' : ('foo', 1)}),
214 (SystemExit, ('foo',),
215 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
216 (IOError, ('foo',),
217 {'message' : 'foo', 'args' : ('foo',)}),
218 (IOError, ('foo', 'bar'),
219 {'message' : '', 'args' : ('foo', 'bar')}),
220 (IOError, ('foo', 'bar', 'baz'),
221 {'message' : '', 'args' : ('foo', 'bar')}),
222 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
223 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
224 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
225 'filename' : 'filenameStr'}),
226 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
227 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
228 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
229 (SyntaxError, ('msgStr',),
230 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
231 'print_file_and_line' : None, 'msg' : 'msgStr',
232 'filename' : None, 'lineno' : None, 'offset' : None}),
233 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
234 'textStr')),
235 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
236 'args' : ('msgStr', ('filenameStr', 'linenoStr',
237 'offsetStr', 'textStr')),
238 'print_file_and_line' : None, 'msg' : 'msgStr',
239 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
240 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
241 'textStr', 'print_file_and_lineStr'),
242 {'message' : '', 'text' : None,
243 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
244 'textStr', 'print_file_and_lineStr'),
245 'print_file_and_line' : None, 'msg' : 'msgStr',
246 'filename' : None, 'lineno' : None, 'offset' : None}),
247 (UnicodeError, (), {'message' : '', 'args' : (),}),
248 (sampleUnicodeEncodeError,
249 {'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
250 'ordinal not in range(128)'),
251 'encoding' : 'ascii', 'object' : u'Hello \xe1',
252 'start' : 6, 'reason' : 'ordinal not in range(128)'}),
253 (sampleUnicodeDecodeError,
254 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
255 'ordinal not in range(128)'),
256 'encoding' : 'ascii', 'object' : '\xff',
257 'start' : 0, 'reason' : 'ordinal not in range(128)'}),
258 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
259 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
260 'object' : u'\u3042', 'reason' : 'ouch',
261 'start' : 0, 'end' : 1}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000262 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000263 try:
264 exceptionList.append(
265 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
266 {'message' : '', 'args' : (1, 'strErrorStr'),
267 'strerror' : 'strErrorStr', 'winerror' : 1,
268 'errno' : 22, 'filename' : 'filenameStr'})
269 )
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000270 except NameError:
271 pass
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000272
273 for args in exceptionList:
274 expected = args[-1]
275 try:
276 exc = args[0]
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000277 if len(args) == 2:
278 raise exc
279 else:
280 raise exc(*args[1])
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000281 except BaseException, e:
282 if (e is not exc and # needed for sampleUnicode errors
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000283 type(e) is not exc):
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000284 raise
285 # Verify no ref leaks in Exc_str()
286 s = str(e)
287 for checkArgName in expected:
288 self.assertEquals(repr(getattr(e, checkArgName)),
289 repr(expected[checkArgName]),
290 'exception "%s", attribute "%s"' %
291 (repr(e), checkArgName))
292
293 # test for pickling support
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000294 for p in pickle, cPickle:
295 for protocol in range(p.HIGHEST_PROTOCOL + 1):
296 new = p.loads(p.dumps(e, protocol))
297 for checkArgName in expected:
298 got = repr(getattr(new, checkArgName))
299 want = repr(expected[checkArgName])
300 self.assertEquals(got, want,
301 'pickled "%r", attribute "%s' %
302 (e, checkArgName))
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000303
304 def testKeywordArgs(self):
305 # test that builtin exception don't take keyword args,
306 # but user-defined subclasses can if they want
307 self.assertRaises(TypeError, BaseException, a=1)
308
309 class DerivedException(BaseException):
310 def __init__(self, fancy_arg):
311 BaseException.__init__(self)
312 self.fancy_arg = fancy_arg
313
314 x = DerivedException(fancy_arg=42)
315 self.assertEquals(x.fancy_arg, 42)
316
317def test_main():
318 run_unittest(ExceptionTests)
319
320if __name__ == '__main__':
321 test_main()