blob: 585d6fe6cffc47ebd7f746f12e2f322a2db58534 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Tim Peters80dc76e2006-06-07 06:57:51 +00003import os
4import sys
Georg Brandlcdcede62006-05-30 08:47:19 +00005import unittest
Tim Peters80dc76e2006-06-07 06:57:51 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000013class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000014
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000036 def testRaising(self):
Tim Petersdd55b0a2006-05-30 23:28:02 +000037 self.raise_catch(AttributeError, "AttributeError")
Georg Brandlcdcede62006-05-30 08:47:19 +000038 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000039
Georg Brandlcdcede62006-05-30 08:47:19 +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 sys.stdin = fp
48 x = raw_input()
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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000059 self.raise_catch(ImportError, "ImportError")
60 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000061
Georg Brandlcdcede62006-05-30 08:47:19 +000062 self.raise_catch(IndexError, "IndexError")
63 x = []
64 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000065
Georg Brandlcdcede62006-05-30 08:47:19 +000066 self.raise_catch(KeyError, "KeyError")
67 x = {}
68 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000069
Georg Brandlcdcede62006-05-30 08:47:19 +000070 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000071
Georg Brandlcdcede62006-05-30 08:47:19 +000072 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000073
Georg Brandlcdcede62006-05-30 08:47:19 +000074 self.raise_catch(NameError, "NameError")
75 try: x = undefined_variable
76 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000077
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000083 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000084
Georg Brandlcdcede62006-05-30 08:47:19 +000085 self.raise_catch(SyntaxError, "SyntaxError")
86 try: exec '/\n'
87 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000088
Georg Brandlcdcede62006-05-30 08:47:19 +000089 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000090
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000097 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +000098
Georg Brandlcdcede62006-05-30 08:47:19 +000099 self.raise_catch(SystemExit, "SystemExit")
100 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000101
Georg Brandlcdcede62006-05-30 08:47:19 +0000102 self.raise_catch(TypeError, "TypeError")
103 try: [] + ()
104 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000105
Georg Brandlcdcede62006-05-30 08:47:19 +0000106 self.raise_catch(ValueError, "ValueError")
107 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000108
Georg Brandlcdcede62006-05-30 08:47:19 +0000109 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
110 try: x = 1/0
111 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000112
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +0000117 def testSyntaxErrorMessage(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000118 # make sure the right exception message is raised for each of
119 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000120
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +0000130 s = '''while 1:
131 try:
132 pass
133 finally:
134 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000135
Georg Brandlcdcede62006-05-30 08:47:19 +0000136 if not sys.platform.startswith('java'):
137 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000138
Georg Brandlcdcede62006-05-30 08:47:19 +0000139 s = '''if 1:
140 try:
141 continue
142 except:
143 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000144
Georg Brandlcdcede62006-05-30 08:47:19 +0000145 ckmsg(s, "'continue' not properly in loop")
146 ckmsg("continue\n", "'continue' not properly in loop")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000147
Georg Brandlcdcede62006-05-30 08:47:19 +0000148 def testSettingException(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000149 # test that setting an exception at the C level works even if the
150 # exception object can't be constructed.
Finn Bockaa3dc452001-12-08 10:15:48 +0000151
Georg Brandlcdcede62006-05-30 08:47:19 +0000152 class BadException:
153 def __init__(self_):
154 raise RuntimeError, "can't instantiate BadException"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000155
Georg Brandlcdcede62006-05-30 08:47:19 +0000156 def test_capi1():
157 import _testcapi
158 try:
159 _testcapi.raise_exception(BadException, 1)
160 except TypeError, err:
161 exc, err, tb = sys.exc_info()
162 co = tb.tb_frame.f_code
163 self.assertEquals(co.co_name, "test_capi1")
164 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
165 else:
166 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000167
Georg Brandlcdcede62006-05-30 08:47:19 +0000168 def test_capi2():
169 import _testcapi
170 try:
171 _testcapi.raise_exception(BadException, 0)
172 except RuntimeError, err:
173 exc, err, tb = sys.exc_info()
174 co = tb.tb_frame.f_code
175 self.assertEquals(co.co_name, "__init__")
176 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
177 co2 = tb.tb_frame.f_back.f_code
178 self.assertEquals(co2.co_name, "test_capi2")
179 else:
180 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000181
Georg Brandlcdcede62006-05-30 08:47:19 +0000182 if not sys.platform.startswith('java'):
183 test_capi1()
184 test_capi2()
Georg Brandl05f97bf2006-05-30 07:13:29 +0000185
Georg Brandlcdcede62006-05-30 08:47:19 +0000186 def testAttributes(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000187 # test that exception attributes are happy
Tim Petersdd55b0a2006-05-30 23:28:02 +0000188
Georg Brandlcdcede62006-05-30 08:47:19 +0000189 exceptionList = [
Georg Brandle08940e2006-06-01 13:00:49 +0000190 (BaseException, (), {'message' : '', 'args' : ()}),
191 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
192 (BaseException, ('foo',),
193 {'message' : 'foo', 'args' : ('foo',)}),
194 (BaseException, ('foo', 1),
195 {'message' : '', 'args' : ('foo', 1)}),
196 (SystemExit, ('foo',),
197 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
198 (IOError, ('foo',),
Georg Brandl3267d282006-09-30 09:03:42 +0000199 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
200 'errno' : None, 'strerror' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000201 (IOError, ('foo', 'bar'),
Georg Brandl3267d282006-09-30 09:03:42 +0000202 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
203 'errno' : 'foo', 'strerror' : 'bar'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000204 (IOError, ('foo', 'bar', 'baz'),
Georg Brandl3267d282006-09-30 09:03:42 +0000205 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
206 'errno' : 'foo', 'strerror' : 'bar'}),
207 (IOError, ('foo', 'bar', 'baz', 'quux'),
208 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Georg Brandle08940e2006-06-01 13:00:49 +0000209 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
210 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
211 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
212 'filename' : 'filenameStr'}),
213 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
214 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
215 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
216 (SyntaxError, ('msgStr',),
217 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
218 'print_file_and_line' : None, 'msg' : 'msgStr',
219 'filename' : None, 'lineno' : None, 'offset' : None}),
220 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
221 'textStr')),
222 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
223 'args' : ('msgStr', ('filenameStr', 'linenoStr',
224 'offsetStr', 'textStr')),
225 'print_file_and_line' : None, 'msg' : 'msgStr',
226 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
227 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
228 'textStr', 'print_file_and_lineStr'),
229 {'message' : '', 'text' : None,
230 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
231 'textStr', 'print_file_and_lineStr'),
232 'print_file_and_line' : None, 'msg' : 'msgStr',
233 'filename' : None, 'lineno' : None, 'offset' : None}),
234 (UnicodeError, (), {'message' : '', 'args' : (),}),
Georg Brandl38f62372006-09-06 06:50:05 +0000235 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
236 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
237 'ordinal not in range'),
238 'encoding' : 'ascii', 'object' : u'a',
239 'start' : 0, 'reason' : 'ordinal not in range'}),
240 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000241 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Georg Brandl38f62372006-09-06 06:50:05 +0000242 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000243 'encoding' : 'ascii', 'object' : '\xff',
Georg Brandl38f62372006-09-06 06:50:05 +0000244 'start' : 0, 'reason' : 'ordinal not in range'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000245 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
246 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
247 'object' : u'\u3042', 'reason' : 'ouch',
248 'start' : 0, 'end' : 1}),
249 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000250 try:
251 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000252 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
253 {'message' : '', 'args' : (1, 'strErrorStr'),
254 'strerror' : 'strErrorStr', 'winerror' : 1,
255 'errno' : 22, 'filename' : 'filenameStr'})
256 )
Tim Peters80dc76e2006-06-07 06:57:51 +0000257 except NameError:
258 pass
Georg Brandlcdcede62006-05-30 08:47:19 +0000259
Georg Brandl38f62372006-09-06 06:50:05 +0000260 for exc, args, expected in exceptionList:
Georg Brandlcdcede62006-05-30 08:47:19 +0000261 try:
Georg Brandl38f62372006-09-06 06:50:05 +0000262 raise exc(*args)
Georg Brandlcdcede62006-05-30 08:47:19 +0000263 except BaseException, e:
Georg Brandl38f62372006-09-06 06:50:05 +0000264 if type(e) is not exc:
Georg Brandle08940e2006-06-01 13:00:49 +0000265 raise
Georg Brandl38f62372006-09-06 06:50:05 +0000266 # Verify module name
267 self.assertEquals(type(e).__module__, 'exceptions')
Neal Norwitz38d4d4a2006-06-02 04:50:49 +0000268 # Verify no ref leaks in Exc_str()
269 s = str(e)
270 for checkArgName in expected:
Georg Brandlcdcede62006-05-30 08:47:19 +0000271 self.assertEquals(repr(getattr(e, checkArgName)),
272 repr(expected[checkArgName]),
273 'exception "%s", attribute "%s"' %
274 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000275
Georg Brandlcdcede62006-05-30 08:47:19 +0000276 # test for pickling support
Tim Peters80dc76e2006-06-07 06:57:51 +0000277 for p in pickle, cPickle:
278 for protocol in range(p.HIGHEST_PROTOCOL + 1):
279 new = p.loads(p.dumps(e, protocol))
280 for checkArgName in expected:
281 got = repr(getattr(new, checkArgName))
282 want = repr(expected[checkArgName])
283 self.assertEquals(got, want,
284 'pickled "%r", attribute "%s' %
285 (e, checkArgName))
Georg Brandlcdcede62006-05-30 08:47:19 +0000286
287 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000288 # test that builtin exception don't take keyword args,
289 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000290 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000291
Georg Brandlcdcede62006-05-30 08:47:19 +0000292 class DerivedException(BaseException):
293 def __init__(self, fancy_arg):
294 BaseException.__init__(self)
295 self.fancy_arg = fancy_arg
296
297 x = DerivedException(fancy_arg=42)
298 self.assertEquals(x.fancy_arg, 42)
299
Armin Rigo53c1692f2006-06-21 21:58:50 +0000300 def testInfiniteRecursion(self):
301 def f():
302 return f()
303 self.assertRaises(RuntimeError, f)
304
305 def g():
306 try:
307 return g()
308 except ValueError:
309 return -1
310 self.assertRaises(RuntimeError, g)
311
Brett Cannonca2ca792006-09-09 07:11:46 +0000312 def testUnicodeStrUsage(self):
313 # Make sure both instances and classes have a str and unicode
314 # representation.
315 self.failUnless(str(Exception))
316 self.failUnless(unicode(Exception))
317 self.failUnless(str(Exception('a')))
318 self.failUnless(unicode(Exception(u'a')))
319
320
Georg Brandlcdcede62006-05-30 08:47:19 +0000321def test_main():
322 run_unittest(ExceptionTests)
323
324if __name__ == '__main__':
325 test_main()