blob: 1ca56f218c9449df75b0881c04ec604b7a420d8f [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000010class ExceptionTests(unittest.TestCase):
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000011
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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 sys.stdin = fp
45 x = raw_input()
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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000056 self.raise_catch(ImportError, "ImportError")
57 self.assertRaises(ImportError, __import__, "undefined_module")
Guido van Rossum3bead091992-01-27 17:00:37 +000058
Georg Brandlcdcede62006-05-30 08:47:19 +000059 self.raise_catch(IndexError, "IndexError")
60 x = []
61 self.assertRaises(IndexError, x.__getitem__, 10)
Guido van Rossum3bead091992-01-27 17:00:37 +000062
Georg Brandlcdcede62006-05-30 08:47:19 +000063 self.raise_catch(KeyError, "KeyError")
64 x = {}
65 self.assertRaises(KeyError, x.__getitem__, 'key')
Guido van Rossum3bead091992-01-27 17:00:37 +000066
Georg Brandlcdcede62006-05-30 08:47:19 +000067 self.raise_catch(KeyboardInterrupt, "KeyboardInterrupt")
Guido van Rossum3bead091992-01-27 17:00:37 +000068
Georg Brandlcdcede62006-05-30 08:47:19 +000069 self.raise_catch(MemoryError, "MemoryError")
Guido van Rossum3bead091992-01-27 17:00:37 +000070
Georg Brandlcdcede62006-05-30 08:47:19 +000071 self.raise_catch(NameError, "NameError")
72 try: x = undefined_variable
73 except NameError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000074
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000080 self.raise_catch(RuntimeError, "RuntimeError")
Guido van Rossum3bead091992-01-27 17:00:37 +000081
Georg Brandlcdcede62006-05-30 08:47:19 +000082 self.raise_catch(SyntaxError, "SyntaxError")
83 try: exec '/\n'
84 except SyntaxError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +000085
Georg Brandlcdcede62006-05-30 08:47:19 +000086 self.raise_catch(IndentationError, "IndentationError")
Fred Drake72e48bd2000-09-08 16:32:34 +000087
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +000094 self.raise_catch(SystemError, "SystemError")
Fred Drake72e48bd2000-09-08 16:32:34 +000095
Georg Brandlcdcede62006-05-30 08:47:19 +000096 self.raise_catch(SystemExit, "SystemExit")
97 self.assertRaises(SystemExit, sys.exit, 0)
Fred Drake85f36392000-07-11 17:53:00 +000098
Georg Brandlcdcede62006-05-30 08:47:19 +000099 self.raise_catch(TypeError, "TypeError")
100 try: [] + ()
101 except TypeError: pass
Fred Drake85f36392000-07-11 17:53:00 +0000102
Georg Brandlcdcede62006-05-30 08:47:19 +0000103 self.raise_catch(ValueError, "ValueError")
104 self.assertRaises(ValueError, chr, 10000)
Guido van Rossum3bead091992-01-27 17:00:37 +0000105
Georg Brandlcdcede62006-05-30 08:47:19 +0000106 self.raise_catch(ZeroDivisionError, "ZeroDivisionError")
107 try: x = 1/0
108 except ZeroDivisionError: pass
Guido van Rossum3bead091992-01-27 17:00:37 +0000109
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +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
Georg Brandlcdcede62006-05-30 08:47:19 +0000127 s = '''while 1:
128 try:
129 pass
130 finally:
131 continue'''
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000132
Georg Brandlcdcede62006-05-30 08:47:19 +0000133 if not sys.platform.startswith('java'):
134 ckmsg(s, "'continue' not supported inside 'finally' clause")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000135
Georg Brandlcdcede62006-05-30 08:47:19 +0000136 s = '''if 1:
137 try:
138 continue
139 except:
140 pass'''
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000141
Georg Brandlcdcede62006-05-30 08:47:19 +0000142 ckmsg(s, "'continue' not properly in loop")
143 ckmsg("continue\n", "'continue' not properly in loop")
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000144
Georg Brandlcdcede62006-05-30 08:47:19 +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."""
Finn Bockaa3dc452001-12-08 10:15:48 +0000148
Georg Brandlcdcede62006-05-30 08:47:19 +0000149 class BadException:
150 def __init__(self_):
151 raise RuntimeError, "can't instantiate BadException"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000152
Georg Brandlcdcede62006-05-30 08:47:19 +0000153 def test_capi1():
154 import _testcapi
155 try:
156 _testcapi.raise_exception(BadException, 1)
157 except TypeError, err:
158 exc, err, tb = sys.exc_info()
159 co = tb.tb_frame.f_code
160 self.assertEquals(co.co_name, "test_capi1")
161 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
162 else:
163 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000164
Georg Brandlcdcede62006-05-30 08:47:19 +0000165 def test_capi2():
166 import _testcapi
167 try:
168 _testcapi.raise_exception(BadException, 0)
169 except RuntimeError, err:
170 exc, err, tb = sys.exc_info()
171 co = tb.tb_frame.f_code
172 self.assertEquals(co.co_name, "__init__")
173 self.assert_(co.co_filename.endswith('test_exceptions'+os.extsep+'py'))
174 co2 = tb.tb_frame.f_back.f_code
175 self.assertEquals(co2.co_name, "test_capi2")
176 else:
177 self.fail("Expected exception")
Richard Jones7b9558d2006-05-27 12:29:24 +0000178
Georg Brandlcdcede62006-05-30 08:47:19 +0000179 if not sys.platform.startswith('java'):
180 test_capi1()
181 test_capi2()
Georg Brandl05f97bf2006-05-30 07:13:29 +0000182
Georg Brandlcdcede62006-05-30 08:47:19 +0000183 def testAttributes(self):
184 """test that exception attributes are happy."""
185 try: str(u'Hello \u00E1')
186 except Exception, e: sampleUnicodeEncodeError = e
Georg Brandl05f97bf2006-05-30 07:13:29 +0000187
Georg Brandlcdcede62006-05-30 08:47:19 +0000188 try: unicode('\xff')
189 except Exception, e: sampleUnicodeDecodeError = e
190
191 exceptionList = [
192 ( BaseException, (), { 'message' : '', 'args' : () }),
193 ( BaseException, (1, ), { 'message' : 1, 'args' : ( 1, ) }),
194 ( BaseException, ('foo', ), { 'message' : 'foo', 'args' : ( 'foo', ) }),
195 ( BaseException, ('foo', 1), { 'message' : '', 'args' : ( 'foo', 1 ) }),
196 ( SystemExit, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ),
197 'code' : 'foo' }),
198 ( IOError, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ), }),
199 ( IOError, ('foo', 'bar'), { 'message' : '',
200 'args' : ('foo', 'bar'), }),
201 ( IOError, ('foo', 'bar', 'baz'),
202 { 'message' : '', 'args' : ('foo', 'bar'), }),
203 ( EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
204 { 'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
205 'strerror' : 'strErrorStr',
206 'errno' : 'errnoStr', 'filename' : 'filenameStr' }),
207 ( EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
208 { 'message' : '', 'args' : (1, 'strErrorStr'),
209 'strerror' : 'strErrorStr', 'errno' : 1,
210 'filename' : 'filenameStr' }),
211 ( SyntaxError, ('msgStr',),
212 { 'message' : 'msgStr', 'args' : ('msgStr', ),
213 'print_file_and_line' : None, 'msg' : 'msgStr',
214 'filename' : None, 'lineno' : None, 'offset' : None,
215 'text' : None }),
216 ( SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
217 'textStr')),
218 { 'message' : '', 'args' : ('msgStr', ('filenameStr',
219 'linenoStr', 'offsetStr', 'textStr' )),
220 'print_file_and_line' : None, 'msg' : 'msgStr',
221 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
222 'offset' : 'offsetStr', 'text' : 'textStr' }),
223 ( SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
224 'textStr', 'print_file_and_lineStr'),
225 { 'message' : '', 'args' : ('msgStr', 'filenameStr',
226 'linenoStr', 'offsetStr', 'textStr',
227 'print_file_and_lineStr'),
228 'print_file_and_line' : None, 'msg' : 'msgStr',
229 'filename' : None, 'lineno' : None, 'offset' : None,
230 'text' : None }),
231 ( UnicodeError, (),
232 { 'message' : '', 'args' : (), }),
233 ( sampleUnicodeEncodeError,
234 { 'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
235 'ordinal not in range(128)'),
236 'encoding' : 'ascii', 'object' : u'Hello \xe1',
237 'start' : 6, 'reason' : 'ordinal not in range(128)' }),
238 ( sampleUnicodeDecodeError,
239 { 'message' : '', 'args' : ('ascii', '\xff', 0, 1,
240 'ordinal not in range(128)'),
241 'encoding' : 'ascii', 'object' : '\xff',
242 'start' : 0, 'reason' : 'ordinal not in range(128)' }),
243 ( UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
244 { 'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
245 'object' : u'\u3042', 'reason' : 'ouch',
246 'start' : 0, 'end' : 1 }),
247 ]
248 try:
249 exceptionList.append(
250 ( WindowsError, (1, 'strErrorStr', 'filenameStr'),
251 { 'message' : '', 'args' : (1, 'strErrorStr'),
252 'strerror' : 'strErrorStr',
253 'errno' : 22, 'filename' : 'filenameStr',
254 'winerror' : 1 }))
255 except NameError: pass
Georg Brandl861089f2006-05-30 07:34:45 +0000256
Georg Brandlcdcede62006-05-30 08:47:19 +0000257 import pickle, random
258
259 for args in exceptionList:
260 expected = args[-1]
261 try:
262 if len(args) == 2: raise args[0]
263 else: raise apply(args[0], args[1])
264 except BaseException, e:
265 for checkArgName in expected.keys():
266 self.assertEquals(repr(getattr(e, checkArgName)),
267 repr(expected[checkArgName]),
268 'exception "%s", attribute "%s"' %
269 (repr(e), checkArgName))
270
271 # test for pickling support
272 new = pickle.loads(pickle.dumps(e, random.randint(0, 2)))
273 for checkArgName in expected.keys():
274 self.assertEquals(repr(getattr(e, checkArgName)),
275 repr(expected[checkArgName]),
276 'pickled exception "%s", attribute "%s' %
277 (repr(e), checkArgName))
278
279 def testKeywordArgs(self):
280 """test that builtin exception don't take keyword args,
281 but user-defined subclasses can if they want"""
282 self.assertRaises(TypeError, BaseException, a=1)
283 class DerivedException(BaseException):
284 def __init__(self, fancy_arg):
285 BaseException.__init__(self)
286 self.fancy_arg = fancy_arg
287
288 x = DerivedException(fancy_arg=42)
289 self.assertEquals(x.fancy_arg, 42)
290
291def test_main():
292 run_unittest(ExceptionTests)
293
294if __name__ == '__main__':
295 test_main()