blob: d9a00b9f77d665626471ffc937b4d0a04e66f61f [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 pickle, cPickle
7
8from test.test_support import TESTFN, unlink, run_unittest
Guido van Rossum83b120d2001-08-23 03:23:03 +00009
Guido van Rossum3bead091992-01-27 17:00:37 +000010# XXX This is not really enough, each *operation* should be tested!
11
Georg Brandlcdcede62006-05-30 08:47:19 +000012class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000013
Georg Brandlcdcede62006-05-30 08:47:19 +000014 def testReload(self):
15 # Reloading the built-in exceptions module failed prior to Py2.2, while it
16 # should act the same as reloading built-in sys.
17 try:
18 import exceptions
19 reload(exceptions)
20 except ImportError, e:
21 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000022
Georg Brandlcdcede62006-05-30 08:47:19 +000023 def raise_catch(self, exc, excname):
24 try:
25 raise exc, "spam"
26 except exc, err:
27 buf1 = str(err)
28 try:
29 raise exc("spam")
30 except exc, err:
31 buf2 = str(err)
32 self.assertEquals(buf1, buf2)
33 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000034
Georg Brandlcdcede62006-05-30 08:47:19 +000035 def testRaising(self):
Tim Petersdd55b0a2006-05-30 23:28:02 +000036 self.raise_catch(AttributeError, "AttributeError")
Georg Brandlcdcede62006-05-30 08:47:19 +000037 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000038
Georg Brandlcdcede62006-05-30 08:47:19 +000039 self.raise_catch(EOFError, "EOFError")
40 fp = open(TESTFN, 'w')
41 fp.close()
42 fp = open(TESTFN, 'r')
43 savestdin = sys.stdin
44 try:
45 try:
46 sys.stdin = fp
47 x = raw_input()
48 except EOFError:
49 pass
50 finally:
51 sys.stdin = savestdin
52 fp.close()
53 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000054
Georg Brandlcdcede62006-05-30 08:47:19 +000055 self.raise_catch(IOError, "IOError")
56 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000057
Georg Brandlcdcede62006-05-30 08:47:19 +000058 self.raise_catch(ImportError, "ImportError")
59 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000060
Georg Brandlcdcede62006-05-30 08:47:19 +000061 self.raise_catch(IndexError, "IndexError")
62 x = []
63 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000064
Georg Brandlcdcede62006-05-30 08:47:19 +000065 self.raise_catch(KeyError, "KeyError")
66 x = {}
67 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000068
Georg Brandlcdcede62006-05-30 08:47:19 +000069 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000070
Georg Brandlcdcede62006-05-30 08:47:19 +000071 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000072
Georg Brandlcdcede62006-05-30 08:47:19 +000073 self.raise_catch(NameError, "NameError")
74 try: x = undefined_variable
75 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000076
Georg Brandlcdcede62006-05-30 08:47:19 +000077 self.raise_catch(OverflowError, "OverflowError")
78 x = 1
79 for dummy in range(128):
80 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000081
Georg Brandlcdcede62006-05-30 08:47:19 +000082 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000083
Georg Brandlcdcede62006-05-30 08:47:19 +000084 self.raise_catch(SyntaxError, "SyntaxError")
85 try: exec '/\n'
86 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000087
Georg Brandlcdcede62006-05-30 08:47:19 +000088 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000089
Georg Brandlcdcede62006-05-30 08:47:19 +000090 self.raise_catch(TabError, "TabError")
91 # can only be tested under -tt, and is the only test for -tt
92 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
93 #except TabError: pass
94 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +000095
Georg Brandlcdcede62006-05-30 08:47:19 +000096 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +000097
Georg Brandlcdcede62006-05-30 08:47:19 +000098 self.raise_catch(SystemExit, "SystemExit")
99 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +0000100
Georg Brandlcdcede62006-05-30 08:47:19 +0000101 self.raise_catch(TypeError, "TypeError")
102 try: [] + ()
103 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000104
Georg Brandlcdcede62006-05-30 08:47:19 +0000105 self.raise_catch(ValueError, "ValueError")
106 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000107
Georg Brandlcdcede62006-05-30 08:47:19 +0000108 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
109 try: x = 1/0
110 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000111
Georg Brandlcdcede62006-05-30 08:47:19 +0000112 self.raise_catch(Exception, "Exception")
113 try: x = 1/0
114 except Exception, e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000115
Georg Brandlcdcede62006-05-30 08:47:19 +0000116 def testSyntaxErrorMessage(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000117 # make sure the right exception message is raised for each of
118 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000119
Georg Brandlcdcede62006-05-30 08:47:19 +0000120 def ckmsg(src, msg):
121 try:
122 compile(src, '<fragment>', 'exec')
123 except SyntaxError, e:
124 if e.msg != msg:
125 self.fail("expected %s, got %s" % (msg, e.msg))
126 else:
127 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000128
Georg Brandlcdcede62006-05-30 08:47:19 +0000129 s = '''while 1:
130 try:
131 pass
132 finally:
133 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000134
Georg Brandlcdcede62006-05-30 08:47:19 +0000135 if not sys.platform.startswith('java'):
136 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000137
Georg Brandlcdcede62006-05-30 08:47:19 +0000138 s = '''if 1:
139 try:
140 continue
141 except:
142 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000143
Georg Brandlcdcede62006-05-30 08:47:19 +0000144 ckmsg(s, "'continue' not properly in loop")
145 ckmsg("continue\n", "'continue' not properly in loop")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000146
Georg Brandlcdcede62006-05-30 08:47:19 +0000147 def testSettingException(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000148 # test that setting an exception at the C level works even if the
149 # exception object can't be constructed.
Finn Bockaa3dc452001-12-08 10:15:48 +0000150
Georg Brandlcdcede62006-05-30 08:47:19 +0000151 class BadException:
152 def __init__(self_):
153 raise RuntimeError, "can't instantiate BadException"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000154
Georg Brandlcdcede62006-05-30 08:47:19 +0000155 def test_capi1():
156 import _testcapi
157 try:
158 _testcapi.raise_exception(BadException, 1)
159 except TypeError, err:
160 exc, err, tb = sys.exc_info()
161 co = tb.tb_frame.f_code
162 self.assertEquals(co.co_name, "test_capi1")
163 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
164 else:
165 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000166
Georg Brandlcdcede62006-05-30 08:47:19 +0000167 def test_capi2():
168 import _testcapi
169 try:
170 _testcapi.raise_exception(BadException, 0)
171 except RuntimeError, err:
172 exc, err, tb = sys.exc_info()
173 co = tb.tb_frame.f_code
174 self.assertEquals(co.co_name, "__init__")
175 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
176 co2 = tb.tb_frame.f_back.f_code
177 self.assertEquals(co2.co_name, "test_capi2")
178 else:
179 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000180
Georg Brandlcdcede62006-05-30 08:47:19 +0000181 if not sys.platform.startswith('java'):
182 test_capi1()
183 test_capi2()
Georg Brandl05f97bf2006-05-30 07:13:29 +0000184
Thomas Hellerdf08f0b2006-10-27 18:31:36 +0000185 def test_WindowsError(self):
186 try:
187 WindowsError
188 except NameError:
189 pass
190 else:
191 self.failUnlessEqual(str(WindowsError(1001)),
192 "1001")
193 self.failUnlessEqual(str(WindowsError(1001, "message")),
194 "[Error 1001] message")
195 self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
196 self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
197
Georg Brandlcdcede62006-05-30 08:47:19 +0000198 def testAttributes(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000199 # test that exception attributes are happy
Tim Petersdd55b0a2006-05-30 23:28:02 +0000200
Georg Brandlcdcede62006-05-30 08:47:19 +0000201 exceptionList = [
Georg Brandle08940e2006-06-01 13:00:49 +0000202 (BaseException, (), {'message' : '', 'args' : ()}),
203 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
204 (BaseException, ('foo',),
205 {'message' : 'foo', 'args' : ('foo',)}),
206 (BaseException, ('foo', 1),
207 {'message' : '', 'args' : ('foo', 1)}),
208 (SystemExit, ('foo',),
209 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
210 (IOError, ('foo',),
Georg Brandl3267d282006-09-30 09:03:42 +0000211 {'message' : 'foo', 'args' : ('foo',), 'filename' : None,
212 'errno' : None, 'strerror' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000213 (IOError, ('foo', 'bar'),
Georg Brandl3267d282006-09-30 09:03:42 +0000214 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : None,
215 'errno' : 'foo', 'strerror' : 'bar'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000216 (IOError, ('foo', 'bar', 'baz'),
Georg Brandl3267d282006-09-30 09:03:42 +0000217 {'message' : '', 'args' : ('foo', 'bar'), 'filename' : 'baz',
218 'errno' : 'foo', 'strerror' : 'bar'}),
219 (IOError, ('foo', 'bar', 'baz', 'quux'),
220 {'message' : '', 'args' : ('foo', 'bar', 'baz', 'quux')}),
Georg Brandle08940e2006-06-01 13:00:49 +0000221 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
222 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
223 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
224 'filename' : 'filenameStr'}),
225 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
226 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
227 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
Brett Cannonf8267df2007-02-28 18:15:00 +0000228 (SyntaxError, (), {'message' : '', 'msg' : None, 'text' : None,
229 'filename' : None, 'lineno' : None, 'offset' : None,
230 'print_file_and_line' : None}),
Georg Brandle08940e2006-06-01 13:00:49 +0000231 (SyntaxError, ('msgStr',),
232 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
233 'print_file_and_line' : None, 'msg' : 'msgStr',
234 'filename' : None, 'lineno' : None, 'offset' : None}),
235 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
236 'textStr')),
237 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
238 'args' : ('msgStr', ('filenameStr', 'linenoStr',
239 'offsetStr', 'textStr')),
240 'print_file_and_line' : None, 'msg' : 'msgStr',
241 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
242 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
243 'textStr', 'print_file_and_lineStr'),
244 {'message' : '', 'text' : None,
245 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
246 'textStr', 'print_file_and_lineStr'),
247 'print_file_and_line' : None, 'msg' : 'msgStr',
248 'filename' : None, 'lineno' : None, 'offset' : None}),
249 (UnicodeError, (), {'message' : '', 'args' : (),}),
Georg Brandl38f62372006-09-06 06:50:05 +0000250 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
251 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
252 'ordinal not in range'),
253 'encoding' : 'ascii', 'object' : u'a',
254 'start' : 0, 'reason' : 'ordinal not in range'}),
255 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000256 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Georg Brandl38f62372006-09-06 06:50:05 +0000257 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000258 'encoding' : 'ascii', 'object' : '\xff',
Georg Brandl38f62372006-09-06 06:50:05 +0000259 'start' : 0, 'reason' : 'ordinal not in range'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000260 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
261 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
262 'object' : u'\u3042', 'reason' : 'ouch',
263 'start' : 0, 'end' : 1}),
264 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000265 try:
266 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000267 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
268 {'message' : '', 'args' : (1, 'strErrorStr'),
269 'strerror' : 'strErrorStr', 'winerror' : 1,
270 'errno' : 22, 'filename' : 'filenameStr'})
271 )
Tim Peters80dc76e2006-06-07 06:57:51 +0000272 except NameError:
273 pass
Georg Brandlcdcede62006-05-30 08:47:19 +0000274
Georg Brandl38f62372006-09-06 06:50:05 +0000275 for exc, args, expected in exceptionList:
Georg Brandlcdcede62006-05-30 08:47:19 +0000276 try:
Georg Brandl38f62372006-09-06 06:50:05 +0000277 raise exc(*args)
Georg Brandlcdcede62006-05-30 08:47:19 +0000278 except BaseException, e:
Georg Brandl38f62372006-09-06 06:50:05 +0000279 if type(e) is not exc:
Georg Brandle08940e2006-06-01 13:00:49 +0000280 raise
Georg Brandl38f62372006-09-06 06:50:05 +0000281 # Verify module name
282 self.assertEquals(type(e).__module__, 'exceptions')
Neal Norwitz38d4d4a2006-06-02 04:50:49 +0000283 # Verify no ref leaks in Exc_str()
284 s = str(e)
285 for checkArgName in expected:
Georg Brandlcdcede62006-05-30 08:47:19 +0000286 self.assertEquals(repr(getattr(e, checkArgName)),
287 repr(expected[checkArgName]),
288 'exception "%s", attribute "%s"' %
289 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000290
Georg Brandlcdcede62006-05-30 08:47:19 +0000291 # test for pickling support
Tim Peters80dc76e2006-06-07 06:57:51 +0000292 for p in pickle, cPickle:
293 for protocol in range(p.HIGHEST_PROTOCOL + 1):
294 new = p.loads(p.dumps(e, protocol))
295 for checkArgName in expected:
296 got = repr(getattr(new, checkArgName))
297 want = repr(expected[checkArgName])
298 self.assertEquals(got, want,
299 'pickled "%r", attribute "%s' %
300 (e, checkArgName))
Georg Brandlcdcede62006-05-30 08:47:19 +0000301
Brett Cannone05e6b02007-01-29 04:41:44 +0000302 def testSlicing(self):
303 # Test that you can slice an exception directly instead of requiring
304 # going through the 'args' attribute.
305 args = (1, 2, 3)
306 exc = BaseException(*args)
307 self.failUnlessEqual(exc[:], args)
308
Georg Brandlcdcede62006-05-30 08:47:19 +0000309 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000310 # test that builtin exception don't take keyword args,
311 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000312 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000313
Georg Brandlcdcede62006-05-30 08:47:19 +0000314 class DerivedException(BaseException):
315 def __init__(self, fancy_arg):
316 BaseException.__init__(self)
317 self.fancy_arg = fancy_arg
318
319 x = DerivedException(fancy_arg=42)
320 self.assertEquals(x.fancy_arg, 42)
321
Armin Rigo53c1692f2006-06-21 21:58:50 +0000322 def testInfiniteRecursion(self):
323 def f():
324 return f()
325 self.assertRaises(RuntimeError, f)
326
327 def g():
328 try:
329 return g()
330 except ValueError:
331 return -1
332 self.assertRaises(RuntimeError, g)
333
Brett Cannonca2ca792006-09-09 07:11:46 +0000334 def testUnicodeStrUsage(self):
335 # Make sure both instances and classes have a str and unicode
336 # representation.
337 self.failUnless(str(Exception))
338 self.failUnless(unicode(Exception))
339 self.failUnless(str(Exception('a')))
340 self.failUnless(unicode(Exception(u'a')))
341
342
Georg Brandlcdcede62006-05-30 08:47:19 +0000343def test_main():
344 run_unittest(ExceptionTests)
345
346if __name__ == '__main__':
347 test_main()