blob: b99e24783585f0454365208a8492e3e4d5783877 [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'}),
228 (SyntaxError, ('msgStr',),
229 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
230 'print_file_and_line' : None, 'msg' : 'msgStr',
231 'filename' : None, 'lineno' : None, 'offset' : None}),
232 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
233 'textStr')),
234 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
235 'args' : ('msgStr', ('filenameStr', 'linenoStr',
236 'offsetStr', 'textStr')),
237 'print_file_and_line' : None, 'msg' : 'msgStr',
238 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
239 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
240 'textStr', 'print_file_and_lineStr'),
241 {'message' : '', 'text' : None,
242 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
243 'textStr', 'print_file_and_lineStr'),
244 'print_file_and_line' : None, 'msg' : 'msgStr',
245 'filename' : None, 'lineno' : None, 'offset' : None}),
246 (UnicodeError, (), {'message' : '', 'args' : (),}),
Georg Brandl38f62372006-09-06 06:50:05 +0000247 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
248 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
249 'ordinal not in range'),
250 'encoding' : 'ascii', 'object' : u'a',
251 'start' : 0, 'reason' : 'ordinal not in range'}),
252 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000253 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Georg Brandl38f62372006-09-06 06:50:05 +0000254 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000255 'encoding' : 'ascii', 'object' : '\xff',
Georg Brandl38f62372006-09-06 06:50:05 +0000256 'start' : 0, 'reason' : 'ordinal not in range'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000257 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
258 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
259 'object' : u'\u3042', 'reason' : 'ouch',
260 'start' : 0, 'end' : 1}),
261 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000262 try:
263 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000264 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
265 {'message' : '', 'args' : (1, 'strErrorStr'),
266 'strerror' : 'strErrorStr', 'winerror' : 1,
267 'errno' : 22, 'filename' : 'filenameStr'})
268 )
Tim Peters80dc76e2006-06-07 06:57:51 +0000269 except NameError:
270 pass
Georg Brandlcdcede62006-05-30 08:47:19 +0000271
Georg Brandl38f62372006-09-06 06:50:05 +0000272 for exc, args, expected in exceptionList:
Georg Brandlcdcede62006-05-30 08:47:19 +0000273 try:
Georg Brandl38f62372006-09-06 06:50:05 +0000274 raise exc(*args)
Georg Brandlcdcede62006-05-30 08:47:19 +0000275 except BaseException, e:
Georg Brandl38f62372006-09-06 06:50:05 +0000276 if type(e) is not exc:
Georg Brandle08940e2006-06-01 13:00:49 +0000277 raise
Georg Brandl38f62372006-09-06 06:50:05 +0000278 # Verify module name
279 self.assertEquals(type(e).__module__, 'exceptions')
Neal Norwitz38d4d4a2006-06-02 04:50:49 +0000280 # Verify no ref leaks in Exc_str()
281 s = str(e)
282 for checkArgName in expected:
Georg Brandlcdcede62006-05-30 08:47:19 +0000283 self.assertEquals(repr(getattr(e, checkArgName)),
284 repr(expected[checkArgName]),
285 'exception "%s", attribute "%s"' %
286 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000287
Georg Brandlcdcede62006-05-30 08:47:19 +0000288 # test for pickling support
Tim Peters80dc76e2006-06-07 06:57:51 +0000289 for p in pickle, cPickle:
290 for protocol in range(p.HIGHEST_PROTOCOL + 1):
291 new = p.loads(p.dumps(e, protocol))
292 for checkArgName in expected:
293 got = repr(getattr(new, checkArgName))
294 want = repr(expected[checkArgName])
295 self.assertEquals(got, want,
296 'pickled "%r", attribute "%s' %
297 (e, checkArgName))
Georg Brandlcdcede62006-05-30 08:47:19 +0000298
Brett Cannone05e6b02007-01-29 04:41:44 +0000299 def testSlicing(self):
300 # Test that you can slice an exception directly instead of requiring
301 # going through the 'args' attribute.
302 args = (1, 2, 3)
303 exc = BaseException(*args)
304 self.failUnlessEqual(exc[:], args)
305
Georg Brandlcdcede62006-05-30 08:47:19 +0000306 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000307 # test that builtin exception don't take keyword args,
308 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000309 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000310
Georg Brandlcdcede62006-05-30 08:47:19 +0000311 class DerivedException(BaseException):
312 def __init__(self, fancy_arg):
313 BaseException.__init__(self)
314 self.fancy_arg = fancy_arg
315
316 x = DerivedException(fancy_arg=42)
317 self.assertEquals(x.fancy_arg, 42)
318
Armin Rigo53c1692f2006-06-21 21:58:50 +0000319 def testInfiniteRecursion(self):
320 def f():
321 return f()
322 self.assertRaises(RuntimeError, f)
323
324 def g():
325 try:
326 return g()
327 except ValueError:
328 return -1
329 self.assertRaises(RuntimeError, g)
330
Brett Cannonca2ca792006-09-09 07:11:46 +0000331 def testUnicodeStrUsage(self):
332 # Make sure both instances and classes have a str and unicode
333 # representation.
334 self.failUnless(str(Exception))
335 self.failUnless(unicode(Exception))
336 self.failUnless(str(Exception('a')))
337 self.failUnless(unicode(Exception(u'a')))
338
339
Georg Brandlcdcede62006-05-30 08:47:19 +0000340def test_main():
341 run_unittest(ExceptionTests)
342
343if __name__ == '__main__':
344 test_main()