blob: 84d2798e6ea5af9a267f83962498b33ad4f158f1 [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):
Tim Petersdd55b0a2006-05-30 23:28:02 +000034 self.raise_catch(AttributeError, "AttributeError")
Georg Brandlcdcede62006-05-30 08:47:19 +000035 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):
Neal Norwitze152aab2006-06-02 04:45:53 +0000115 # 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):
Neal Norwitze152aab2006-06-02 04:45:53 +0000146 # 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):
Neal Norwitze152aab2006-06-02 04:45:53 +0000184 # test that exception attributes are happy
Georg Brandlcdcede62006-05-30 08:47:19 +0000185 try: str(u'Hello \u00E1')
186 except Exception, e: sampleUnicodeEncodeError = e
Tim Petersdd55b0a2006-05-30 23:28:02 +0000187
Georg Brandlcdcede62006-05-30 08:47:19 +0000188 try: unicode('\xff')
189 except Exception, e: sampleUnicodeDecodeError = e
Tim Petersdd55b0a2006-05-30 23:28:02 +0000190
Georg Brandlcdcede62006-05-30 08:47:19 +0000191 exceptionList = [
Georg Brandle08940e2006-06-01 13:00:49 +0000192 (BaseException, (), {'message' : '', 'args' : ()}),
193 (BaseException, (1, ), {'message' : 1, 'args' : (1,)}),
194 (BaseException, ('foo',),
195 {'message' : 'foo', 'args' : ('foo',)}),
196 (BaseException, ('foo', 1),
197 {'message' : '', 'args' : ('foo', 1)}),
198 (SystemExit, ('foo',),
199 {'message' : 'foo', 'args' : ('foo',), 'code' : 'foo'}),
200 (IOError, ('foo',),
201 {'message' : 'foo', 'args' : ('foo',)}),
202 (IOError, ('foo', 'bar'),
203 {'message' : '', 'args' : ('foo', 'bar')}),
204 (IOError, ('foo', 'bar', 'baz'),
205 {'message' : '', 'args' : ('foo', 'bar')}),
206 (EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
207 {'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
208 'strerror' : 'strErrorStr', 'errno' : 'errnoStr',
209 'filename' : 'filenameStr'}),
210 (EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
211 {'message' : '', 'args' : (1, 'strErrorStr'), 'errno' : 1,
212 'strerror' : 'strErrorStr', 'filename' : 'filenameStr'}),
213 (SyntaxError, ('msgStr',),
214 {'message' : 'msgStr', 'args' : ('msgStr',), 'text' : None,
215 'print_file_and_line' : None, 'msg' : 'msgStr',
216 'filename' : None, 'lineno' : None, 'offset' : None}),
217 (SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
218 'textStr')),
219 {'message' : '', 'offset' : 'offsetStr', 'text' : 'textStr',
220 'args' : ('msgStr', ('filenameStr', 'linenoStr',
221 'offsetStr', 'textStr')),
222 'print_file_and_line' : None, 'msg' : 'msgStr',
223 'filename' : 'filenameStr', 'lineno' : 'linenoStr'}),
224 (SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
225 'textStr', 'print_file_and_lineStr'),
226 {'message' : '', 'text' : None,
227 'args' : ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
228 'textStr', 'print_file_and_lineStr'),
229 'print_file_and_line' : None, 'msg' : 'msgStr',
230 'filename' : None, 'lineno' : None, 'offset' : None}),
231 (UnicodeError, (), {'message' : '', 'args' : (),}),
232 (sampleUnicodeEncodeError,
233 {'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
234 'ordinal not in range(128)'),
235 'encoding' : 'ascii', 'object' : u'Hello \xe1',
236 'start' : 6, 'reason' : 'ordinal not in range(128)'}),
237 (sampleUnicodeDecodeError,
238 {'message' : '', 'args' : ('ascii', '\xff', 0, 1,
239 'ordinal not in range(128)'),
240 'encoding' : 'ascii', 'object' : '\xff',
241 'start' : 0, 'reason' : 'ordinal not in range(128)'}),
242 (UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
243 {'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
244 'object' : u'\u3042', 'reason' : 'ouch',
245 'start' : 0, 'end' : 1}),
246 ]
Georg Brandlcdcede62006-05-30 08:47:19 +0000247 try:
248 exceptionList.append(
Georg Brandle08940e2006-06-01 13:00:49 +0000249 (WindowsError, (1, 'strErrorStr', 'filenameStr'),
250 {'message' : '', 'args' : (1, 'strErrorStr'),
251 'strerror' : 'strErrorStr', 'winerror' : 1,
252 'errno' : 22, 'filename' : 'filenameStr'})
253 )
Georg Brandlcdcede62006-05-30 08:47:19 +0000254 except NameError: pass
Georg Brandl861089f2006-05-30 07:34:45 +0000255
Georg Brandlcdcede62006-05-30 08:47:19 +0000256 import pickle, random
257
258 for args in exceptionList:
259 expected = args[-1]
260 try:
Georg Brandle08940e2006-06-01 13:00:49 +0000261 exc = args[0]
262 if len(args) == 2: raise exc
263 else: raise exc(*args[1])
Georg Brandlcdcede62006-05-30 08:47:19 +0000264 except BaseException, e:
Georg Brandle08940e2006-06-01 13:00:49 +0000265 if (e is not exc and # needed for sampleUnicode errors
266 type(e) is not exc):
267 raise
Neal Norwitz38d4d4a2006-06-02 04:50:49 +0000268 # Verify no ref leaks in Exc_str()
269 s = str(e)
270 for checkArgName in expected:
Georg Brandlcdcede62006-05-30 08:47:19 +0000271 self.assertEquals(repr(getattr(e, checkArgName)),
272 repr(expected[checkArgName]),
273 'exception "%s", attribute "%s"' %
274 (repr(e), checkArgName))
Tim Petersdd55b0a2006-05-30 23:28:02 +0000275
Georg Brandlcdcede62006-05-30 08:47:19 +0000276 # test for pickling support
277 new = pickle.loads(pickle.dumps(e, random.randint(0, 2)))
Neal Norwitz38d4d4a2006-06-02 04:50:49 +0000278 for checkArgName in expected:
Georg Brandlcdcede62006-05-30 08:47:19 +0000279 self.assertEquals(repr(getattr(e, checkArgName)),
280 repr(expected[checkArgName]),
281 'pickled exception "%s", attribute "%s' %
282 (repr(e), checkArgName))
283
284 def testKeywordArgs(self):
Neal Norwitze152aab2006-06-02 04:45:53 +0000285 # test that builtin exception don't take keyword args,
286 # but user-defined subclasses can if they want
Georg Brandlcdcede62006-05-30 08:47:19 +0000287 self.assertRaises(TypeError, BaseException, a=1)
Georg Brandle08940e2006-06-01 13:00:49 +0000288
Georg Brandlcdcede62006-05-30 08:47:19 +0000289 class DerivedException(BaseException):
290 def __init__(self, fancy_arg):
291 BaseException.__init__(self)
292 self.fancy_arg = fancy_arg
293
294 x = DerivedException(fancy_arg=42)
295 self.assertEquals(x.fancy_arg, 42)
296
297def test_main():
298 run_unittest(ExceptionTests)
299
300if __name__ == '__main__':
301 test_main()