blob: 27d88a0fd5f079df7180ce05097fde5eaacf10f8 [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',),
199 {'message' : 'foo', 'args' : ('foo',)}),
200 (IOError, ('foo', 'bar'),
201 {'message' : '', 'args' : ('foo', 'bar')}),
202 (IOError, ('foo', 'bar', 'baz'),
203 {'message' : '', 'args' : ('foo', 'bar')}),
204 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
205 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
206 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
207 'filename' : 'filenameStr'}),
208 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
209 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
210 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
211 (SyntaxError, ('msgStr',),
212 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
213 'print_file_and_line' : None, 'msg' : 'msgStr',
214 'filename' : None, 'lineno' : None, 'offset' : None}),
215 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
216 'textStr')),
217 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
218 'args' : ('msgStr', ('filenameStr', 'linenoStr',
219 'offsetStr', 'textStr')),
220 'print_file_and_line' : None, 'msg' : 'msgStr',
221 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
222 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
223 'textStr', 'print_file_and_lineStr'),
224 {'message' : '', 'text' : None,
225 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
226 'textStr', 'print_file_and_lineStr'),
227 'print_file_and_line' : None, 'msg' : 'msgStr',
228 'filename' : None, 'lineno' : None, 'offset' : None}),
229 (UnicodeError, (), {'message' : '', 'args' : (),}),
Georg Brandlecab6232006-09-06 06:47:02 +0000230 (UnicodeEncodeError, ('ascii', u'a', 0, 1, 'ordinal not in range'),
231 {'message' : '', 'args' : ('ascii', u'a', 0, 1,
232 'ordinal not in range'),
233 'encoding' : 'ascii', 'object' : u'a',
234 'start' : 0, 'reason' : 'ordinal not in range'}),
235 (UnicodeDecodeError, ('ascii', '\xff', 0, 1, 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000236 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
Georg Brandlecab6232006-09-06 06:47:02 +0000237 'ordinal not in range'),
Georg Brandle08940e2006-06-01 13:00:49 +0000238 'encoding' : 'ascii', 'object' : '\xff',
Georg Brandlecab6232006-09-06 06:47:02 +0000239 'start' : 0, 'reason' : 'ordinal not in range'}),
Georg Brandle08940e2006-06-01 13:00:49 +0000240 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
241 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
242 'object' : u'\u3042', 'reason' : 'ouch',
243 'start' : 0, 'end' : 1}),
244 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000245 try:
246 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000247 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
248 {'message' : '', 'args' : (1, 'strErrorStr'),
249 'strerror' : 'strErrorStr', 'winerror' : 1,
250 'errno' : 22, 'filename' : 'filenameStr'})
251 )
Tim Peters80dc76e2006-06-07 06:57:51 +0000252 except NameError:
253 pass
Georg Brandlcdcede62006-05-30 08:47:19 +0000254
Georg Brandlecab6232006-09-06 06:47:02 +0000255 for exc, args, expected in exceptionList:
Georg Brandlcdcede62006-05-30 08:47:19 +0000256 try:
Georg Brandlecab6232006-09-06 06:47:02 +0000257 raise exc(*args)
Georg Brandlcdcede62006-05-30 08:47:19 +0000258 except BaseException, e:
Georg Brandlecab6232006-09-06 06:47:02 +0000259 if type(e) is not exc:
Georg Brandle08940e2006-06-01 13:00:49 +0000260 raise
Georg Brandlecab6232006-09-06 06:47:02 +0000261 # Verify module name
262 self.assertEquals(type(e).__module__, 'exceptions')
Neal Norwitz38d4d4a2006-06-02 04:50:49 +0000263 # Verify no ref leaks in Exc_str()
264 s = str(e)
265 for checkArgName in expected:
Georg Brandlcdcede62006-05-30 08:47:19 +0000266 self.assertEquals(repr(getattr(e, checkArgName)),
267 repr(expected[checkArgName]),
268 'exception "%s", attribute "%s"' %
269 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000270
Georg Brandlcdcede62006-05-30 08:47:19 +0000271 # test for pickling support
Tim Peters80dc76e2006-06-07 06:57:51 +0000272 for p in pickle, cPickle:
273 for protocol in range(p.HIGHEST_PROTOCOL + 1):
274 new = p.loads(p.dumps(e, protocol))
275 for checkArgName in expected:
276 got = repr(getattr(new, checkArgName))
277 want = repr(expected[checkArgName])
278 self.assertEquals(got, want,
279 'pickled "%r", attribute "%s' %
280 (e, checkArgName))
Georg Brandlcdcede62006-05-30 08:47:19 +0000281
282 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000283 # test that builtin exception don't take keyword args,
284 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000285 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000286
Georg Brandlcdcede62006-05-30 08:47:19 +0000287 class DerivedException(BaseException):
288 def __init__(self, fancy_arg):
289 BaseException.__init__(self)
290 self.fancy_arg = fancy_arg
291
292 x = DerivedException(fancy_arg=42)
293 self.assertEquals(x.fancy_arg, 42)
294
Armin Rigo53c1692f2006-06-21 21:58:50 +0000295 def testInfiniteRecursion(self):
296 def f():
297 return f()
298 self.assertRaises(RuntimeError, f)
299
300 def g():
301 try:
302 return g()
303 except ValueError:
304 return -1
305 self.assertRaises(RuntimeError, g)
306
Brett Cannon19d76c52006-09-09 07:18:44 +0000307 def testUnicodeStrUsage(self):
308 # Make sure both instances and classes have a str and unicode
309 # representation.
310 self.failUnless(str(Exception))
311 self.failUnless(unicode(Exception))
312 self.failUnless(str(Exception('a')))
313 self.failUnless(unicode(Exception(u'a')))
314
315
Georg Brandlcdcede62006-05-30 08:47:19 +0000316def test_main():
317 run_unittest(ExceptionTests)
318
319if __name__ == '__main__':
320 test_main()