blob: ebab91384b3bfefe29b41233f8c0af86a7c1e144 [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00003from test.test_support import TESTFN, unlink, run_unittest
Guido van Rossum83b120d2001-08-23 03:23:03 +00004import warnings
Martin v. Löwisa94568a2003-05-10 07:36:56 +00005import sys, traceback, os
Thomas Wouters4d70c3d2006-06-08 14:42:34 +00006import unittest
Guido van Rossum83b120d2001-08-23 03:23:03 +00007
Guido van Rossum3bead091992-01-27 17:00:37 +00008# XXX This is not really enough, each *operation* should be tested!
9
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000010class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000011
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000012 def testReload(self):
13 # Reloading the built-in exceptions module failed prior to Py2.2, while it
14 # should act the same as reloading built-in sys.
15 try:
16 import exceptions
17 reload(exceptions)
18 except ImportError, e:
19 self.fail("reloading exceptions: %s" % e)
Jeremy Hylton56c807d2000-06-20 18:52:57 +000020
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000021 def raise_catch(self, exc, excname):
22 try:
23 raise exc, "spam"
24 except exc, err:
25 buf1 = str(err)
26 try:
27 raise exc("spam")
28 except exc, err:
29 buf2 = str(err)
30 self.assertEquals(buf1, buf2)
31 self.assertEquals(exc.__name__, excname)
Guido van Rossum3bead091992-01-27 17:00:37 +000032
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000033 def testRaising(self):
34 self.raise_catch(AttributeError, "AttributeError")
35 self.assertRaises(AttributeError, getattr, sys, "undefined_attribute")
Guido van Rossum3bead091992-01-27 17:00:37 +000036
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000037 self.raise_catch(EOFError, "EOFError")
38 fp = open(TESTFN, 'w')
39 fp.close()
40 fp = open(TESTFN, 'r')
41 savestdin = sys.stdin
42 try:
43 try:
44 import marshal
45 marshal.loads('')
46 except EOFError:
47 pass
48 finally:
49 sys.stdin = savestdin
50 fp.close()
51 unlink(TESTFN)
Guido van Rossum3bead091992-01-27 17:00:37 +000052
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000053 self.raise_catch(IOError, "IOError")
54 self.assertRaises(IOError, open, 'this file does not exist', 'r')
Guido van Rossum3bead091992-01-27 17:00:37 +000055
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000056 self.raise_catch(ImportError, "ImportError")
57 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000058
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000059 self.raise_catch(IndexError, "IndexError")
60 x = []
61 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000062
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000063 self.raise_catch(KeyError, "KeyError")
64 x = {}
65 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000066
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000067 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000068
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000069 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000070
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000071 self.raise_catch(NameError, "NameError")
72 try: x = undefined_variable
73 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000074
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000075 self.raise_catch(OverflowError, "OverflowError")
76 x = 1
77 for dummy in range(128):
78 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000079
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000080 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000081
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000082 self.raise_catch(SyntaxError, "SyntaxError")
83 try: exec '/\n'
84 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000085
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000086 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000087
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000088 self.raise_catch(TabError, "TabError")
89 # can only be tested under -tt, and is the only test for -tt
90 #try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
91 #except TabError: pass
92 #else: self.fail("TabError not raised")
Fred Drake72e48bd2000-09-08 16:32:34 +000093
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000094 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +000095
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000096 self.raise_catch(SystemExit, "SystemExit")
97 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +000098
Thomas Wouters4d70c3d2006-06-08 14:42:34 +000099 self.raise_catch(TypeError, "TypeError")
100 try: [] + ()
101 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000102
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000103 self.raise_catch(ValueError, "ValueError")
104 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000105
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000106 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
107 try: x = 1/0
108 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000109
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000110 self.raise_catch(Exception, "Exception")
111 try: x = 1/0
112 except Exception, e: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000113
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000114 def testSyntaxErrorMessage(self):
115 # make sure the right exception message is raised for each of
116 # these code fragments
Guido van Rossum3bead091992-01-27 17:00:37 +0000117
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000118 def ckmsg(src, msg):
119 try:
120 compile(src, '<fragment>', 'exec')
121 except SyntaxError, e:
122 if e.msg != msg:
123 self.fail("expected %s, got %s" % (msg, e.msg))
124 else:
125 self.fail("failed to get expected SyntaxError")
Guido van Rossum3bead091992-01-27 17:00:37 +0000126
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000127 s = '''while 1:
128 try:
129 pass
130 finally:
131 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000132
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000133 if not sys.platform.startswith('java'):
134 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000135
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000136 s = '''if 1:
137 try:
138 continue
139 except:
140 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000141
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000142 ckmsg(s, "'continue' not properly in loop")
143 ckmsg("continue\n", "'continue' not properly in loop")
Thomas Wouters303de6a2006-04-20 22:42:37 +0000144
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000145 def testSettingException(self):
146 # test that setting an exception at the C level works even if the
147 # exception object can't be constructed.
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000148
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000149 class BadException(Exception):
150 def __init__(self_):
151 raise RuntimeError, "can't instantiate BadException"
Finn Bockaa3dc452001-12-08 10:15:48 +0000152
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000153 class InvalidException:
154 pass
Thomas Wouters303de6a2006-04-20 22:42:37 +0000155
Thomas Wouters4d70c3d2006-06-08 14:42:34 +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")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000167
Thomas Wouters4d70c3d2006-06-08 14:42:34 +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")
Thomas Wouters477c8d52006-05-27 19:21:47 +0000181
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000182 def test_capi3():
183 import _testcapi
184 self.assertRaises(SystemError, _testcapi.raise_exception,
185 InvalidException, 1)
186
187 if not sys.platform.startswith('java'):
188 test_capi1()
189 test_capi2()
190 test_capi3()
191
192 def testAttributes(self):
193 # test that exception attributes are happy
194 try: str(u'Hello \u00E1')
195 except Exception, e: sampleUnicodeEncodeError = e
196
197 try: unicode('\xff')
198 except Exception, e: sampleUnicodeDecodeError = e
199
200 exceptionList = [
201 (BaseException, (), {'message' : '', 'args' : ()}),
202 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
203 (BaseException, ('foo',),
204 {'message' : 'foo', 'args' : ('foo',)}),
205 (BaseException, ('foo', 1),
206 {'message' : '', 'args' : ('foo', 1)}),
207 (SystemExit, ('foo',),
208 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
209 (IOError, ('foo',),
210 {'message' : 'foo', 'args' : ('foo',)}),
211 (IOError, ('foo', 'bar'),
212 {'message' : '', 'args' : ('foo', 'bar')}),
213 (IOError, ('foo', 'bar', 'baz'),
214 {'message' : '', 'args' : ('foo', 'bar')}),
215 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
216 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
217 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
218 'filename' : 'filenameStr'}),
219 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
220 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
221 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
222 (SyntaxError, ('msgStr',),
223 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
224 'print_file_and_line' : None, 'msg' : 'msgStr',
225 'filename' : None, 'lineno' : None, 'offset' : None}),
226 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
227 'textStr')),
228 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
229 'args' : ('msgStr', ('filenameStr', 'linenoStr',
230 'offsetStr', 'textStr')),
231 'print_file_and_line' : None, 'msg' : 'msgStr',
232 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
233 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
234 'textStr', 'print_file_and_lineStr'),
235 {'message' : '', 'text' : None,
236 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
237 'textStr', 'print_file_and_lineStr'),
238 'print_file_and_line' : None, 'msg' : 'msgStr',
239 'filename' : None, 'lineno' : None, 'offset' : None}),
240 (UnicodeError, (), {'message' : '', 'args' : (),}),
241 (sampleUnicodeEncodeError,
242 {'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
243 'ordinal not in range(128)'),
244 'encoding' : 'ascii', 'object' : u'Hello \xe1',
245 'start' : 6, 'reason' : 'ordinal not in range(128)'}),
246 (sampleUnicodeDecodeError,
247 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
248 'ordinal not in range(128)'),
249 'encoding' : 'ascii', 'object' : '\xff',
250 'start' : 0, 'reason' : 'ordinal not in range(128)'}),
251 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
252 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
253 'object' : u'\u3042', 'reason' : 'ouch',
254 'start' : 0, 'end' : 1}),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000255 ]
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000256 try:
257 exceptionList.append(
258 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
259 {'message' : '', 'args' : (1, 'strErrorStr'),
260 'strerror' : 'strErrorStr', 'winerror' : 1,
261 'errno' : 22, 'filename' : 'filenameStr'})
262 )
263 except NameError: pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000264
Thomas Wouters4d70c3d2006-06-08 14:42:34 +0000265 import pickle, random
266
267 for args in exceptionList:
268 expected = args[-1]
269 try:
270 exc = args[0]
271 if len(args) == 2: raise exc
272 else: raise exc(*args[1])
273 except BaseException, e:
274 if (e is not exc and # needed for sampleUnicode errors
275 type(e) is not exc):
276 raise
277 # Verify no ref leaks in Exc_str()
278 s = str(e)
279 for checkArgName in expected:
280 self.assertEquals(repr(getattr(e, checkArgName)),
281 repr(expected[checkArgName]),
282 'exception "%s", attribute "%s"' %
283 (repr(e), checkArgName))
284
285 # test for pickling support
286 new = pickle.loads(pickle.dumps(e, random.randint(0, 2)))
287 for checkArgName in expected:
288 self.assertEquals(repr(getattr(e, checkArgName)),
289 repr(expected[checkArgName]),
290 'pickled exception "%s", attribute "%s' %
291 (repr(e), checkArgName))
292
293 def testKeywordArgs(self):
294 # test that builtin exception don't take keyword args,
295 # but user-defined subclasses can if they want
296 self.assertRaises(TypeError, BaseException, a=1)
297
298 class DerivedException(BaseException):
299 def __init__(self, fancy_arg):
300 BaseException.__init__(self)
301 self.fancy_arg = fancy_arg
302
303 x = DerivedException(fancy_arg=42)
304 self.assertEquals(x.fancy_arg, 42)
305
306def test_main():
307 run_unittest(ExceptionTests)
308
309if __name__ == '__main__':
310 test_main()