blob: b4a766e89b62736940bc04fc23248e2db2b53cbb [file] [log] [blame]
Guido van Rossum3bead091992-01-27 17:00:37 +00001# Python test set -- part 5, built-in exceptions
2
Barry Warsaw408b6d32002-07-30 23:27:12 +00003from test.test_support import TestFailed, TESTFN, unlink
Barry Warsaw6ed41a01997-08-29 21:58:25 +00004from types import ClassType
Guido van Rossum83b120d2001-08-23 03:23:03 +00005import warnings
Martin v. Löwisa94568a2003-05-10 07:36:56 +00006import sys, traceback, os
Guido van Rossum83b120d2001-08-23 03:23:03 +00007
Guido van Rossum3bead091992-01-27 17:00:37 +00008print '5. Built-in exceptions'
9# XXX This is not really enough, each *operation* should be tested!
10
Barry Warsawb9c1d3d2001-08-13 23:07:00 +000011# Reloading the built-in exceptions module failed prior to Py2.2, while it
12# should act the same as reloading built-in sys.
13try:
14 import exceptions
15 reload(exceptions)
16except ImportError, e:
17 raise TestFailed, e
18
Jeremy Hylton56c807d2000-06-20 18:52:57 +000019def test_raise_catch(exc):
20 try:
21 raise exc, "spam"
22 except exc, err:
23 buf = str(err)
24 try:
25 raise exc("spam")
26 except exc, err:
27 buf = str(err)
28 print buf
29
Barry Warsaw6ed41a01997-08-29 21:58:25 +000030def r(thing):
Jeremy Hylton56c807d2000-06-20 18:52:57 +000031 test_raise_catch(thing)
Brett Cannonbf364092006-03-01 04:25:17 +000032 print getattr(thing, '__name__', thing)
Guido van Rossum3bead091992-01-27 17:00:37 +000033
34r(AttributeError)
35import sys
36try: x = sys.undefined_attribute
37except AttributeError: pass
38
39r(EOFError)
40import sys
41fp = open(TESTFN, 'w')
42fp.close()
43fp = open(TESTFN, 'r')
44savestdin = sys.stdin
45try:
Fred Drake2e6d25c2000-10-23 17:00:30 +000046 try:
47 sys.stdin = fp
48 x = raw_input()
49 except EOFError:
50 pass
Guido van Rossum3bead091992-01-27 17:00:37 +000051finally:
Fred Drake2e6d25c2000-10-23 17:00:30 +000052 sys.stdin = savestdin
53 fp.close()
Guido van Rossum3bead091992-01-27 17:00:37 +000054
55r(IOError)
56try: open('this file does not exist', 'r')
57except IOError: pass
58
59r(ImportError)
60try: import undefined_module
61except ImportError: pass
62
63r(IndexError)
64x = []
65try: a = x[10]
66except IndexError: pass
67
68r(KeyError)
69x = {}
70try: a = x['key']
71except KeyError: pass
72
73r(KeyboardInterrupt)
74print '(not testable in a script)'
75
76r(MemoryError)
77print '(not safe to test)'
78
79r(NameError)
80try: x = undefined_variable
81except NameError: pass
82
83r(OverflowError)
84x = 1
Tim Petersc8854432004-08-25 02:14:08 +000085for dummy in range(128):
86 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000087
88r(RuntimeError)
89print '(not used any more?)'
90
91r(SyntaxError)
Guido van Rossume2cb7271995-08-11 14:24:47 +000092try: exec '/\n'
Guido van Rossum3bead091992-01-27 17:00:37 +000093except SyntaxError: pass
94
Fred Drake72e48bd2000-09-08 16:32:34 +000095# make sure the right exception message is raised for each of these
96# code fragments:
97
98def ckmsg(src, msg):
99 try:
100 compile(src, '<fragment>', 'exec')
101 except SyntaxError, e:
102 print e.msg
103 if e.msg == msg:
104 print "ok"
105 else:
106 print "expected:", msg
107 else:
108 print "failed to get expected SyntaxError"
109
110s = '''\
111while 1:
112 try:
Fred Drake72e48bd2000-09-08 16:32:34 +0000113 pass
Fred Drake72e48bd2000-09-08 16:32:34 +0000114 finally:
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000115 continue
Fred Drake72e48bd2000-09-08 16:32:34 +0000116'''
Finn Bockaa3dc452001-12-08 10:15:48 +0000117if sys.platform.startswith('java'):
118 print "'continue' not supported inside 'finally' clause"
119 print "ok"
120else:
121 ckmsg(s, "'continue' not supported inside 'finally' clause")
Fred Drake72e48bd2000-09-08 16:32:34 +0000122s = '''\
123try:
124 continue
125except:
126 pass
127'''
128ckmsg(s, "'continue' not properly in loop")
129ckmsg("continue\n", "'continue' not properly in loop")
130
Fred Drake85f36392000-07-11 17:53:00 +0000131r(IndentationError)
132
133r(TabError)
134# can only be tested under -tt, and is the only test for -tt
135#try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
136#except TabError: pass
137#else: raise TestFailed
138
Guido van Rossum3bead091992-01-27 17:00:37 +0000139r(SystemError)
140print '(hard to reproduce)'
141
142r(SystemExit)
143import sys
144try: sys.exit(0)
145except SystemExit: pass
146
147r(TypeError)
148try: [] + ()
149except TypeError: pass
150
151r(ValueError)
152try: x = chr(10000)
153except ValueError: pass
154
155r(ZeroDivisionError)
156try: x = 1/0
157except ZeroDivisionError: pass
158
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000159r(Exception)
160try: x = 1/0
161except Exception, e: pass
162
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000163# test that setting an exception at the C level works even if the
164# exception object can't be constructed.
165
166class BadException:
167 def __init__(self):
168 raise RuntimeError, "can't instantiate BadException"
169
170def test_capi1():
Finn Bockaa3dc452001-12-08 10:15:48 +0000171 import _testcapi
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000172 try:
173 _testcapi.raise_exception(BadException, 1)
174 except TypeError, err:
175 exc, err, tb = sys.exc_info()
176 co = tb.tb_frame.f_code
177 assert co.co_name == "test_capi1"
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000178 assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000179 else:
180 print "Expected exception"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000181
182def test_capi2():
Finn Bockaa3dc452001-12-08 10:15:48 +0000183 import _testcapi
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000184 try:
185 _testcapi.raise_exception(BadException, 0)
186 except RuntimeError, err:
187 exc, err, tb = sys.exc_info()
188 co = tb.tb_frame.f_code
189 assert co.co_name == "__init__"
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000190 assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000191 co2 = tb.tb_frame.f_back.f_code
192 assert co2.co_name == "test_capi2"
193 else:
194 print "Expected exception"
Finn Bockaa3dc452001-12-08 10:15:48 +0000195
196if not sys.platform.startswith('java'):
197 test_capi1()
198 test_capi2()
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000199
Guido van Rossum3bead091992-01-27 17:00:37 +0000200unlink(TESTFN)
Richard Jones7b9558d2006-05-27 12:29:24 +0000201
202# test that exception attributes are happy.
203try: str(u'Hello \u00E1')
204except Exception, e: sampleUnicodeEncodeError = e
205try: unicode('\xff')
206except Exception, e: sampleUnicodeDecodeError = e
207exceptionList = [
208 ( BaseException, (), { 'message' : '', 'args' : () }),
209 ( BaseException, (1, ), { 'message' : 1, 'args' : ( 1, ) }),
210 ( BaseException, ('foo', ), { 'message' : 'foo', 'args' : ( 'foo', ) }),
211 ( BaseException, ('foo', 1), { 'message' : '', 'args' : ( 'foo', 1 ) }),
212 ( SystemExit, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ),
213 'code' : 'foo' }),
214 ( IOError, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ), }),
215 ( IOError, ('foo', 'bar'), { 'message' : '',
216 'args' : ('foo', 'bar'), }),
217 ( IOError, ('foo', 'bar', 'baz'),
218 { 'message' : '', 'args' : ('foo', 'bar'), }),
219 ( EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
220 { 'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
221 'strerror' : 'strErrorStr',
222 'errno' : 'errnoStr', 'filename' : 'filenameStr' }),
223 ( EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
224 { 'message' : '', 'args' : (1, 'strErrorStr'),
225 'strerror' : 'strErrorStr', 'errno' : 1,
226 'filename' : 'filenameStr' }),
227 ( SyntaxError, ('msgStr',),
228 { 'message' : 'msgStr', 'args' : ('msgStr', ),
229 'print_file_and_line' : None, 'msg' : 'msgStr',
230 'filename' : None, 'lineno' : None, 'offset' : None,
231 'text' : None }),
232 ( SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
233 'textStr')),
234 { 'message' : '', 'args' : ('msgStr', ('filenameStr',
235 'linenoStr', 'offsetStr', 'textStr' )),
236 'print_file_and_line' : None, 'msg' : 'msgStr',
237 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
238 'offset' : 'offsetStr', 'text' : 'textStr' }),
239 ( SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
240 'textStr', 'print_file_and_lineStr'),
241 { 'message' : '', 'args' : ('msgStr', 'filenameStr',
242 'linenoStr', 'offsetStr', 'textStr',
243 'print_file_and_lineStr'),
244 'print_file_and_line' : None, 'msg' : 'msgStr',
245 'filename' : None, 'lineno' : None, 'offset' : None,
246 'text' : None }),
247 ( UnicodeError, (),
248 { 'message' : '', 'args' : (), }),
249 ( sampleUnicodeEncodeError,
250 { 'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
251 'ordinal not in range(128)'),
252 'encoding' : 'ascii', 'object' : u'Hello \xe1',
253 'start' : 6, 'reason' : 'ordinal not in range(128)' }),
254 ( sampleUnicodeDecodeError,
255 { 'message' : '', 'args' : ('ascii', '\xff', 0, 1,
256 'ordinal not in range(128)'),
257 'encoding' : 'ascii', 'object' : '\xff',
258 'start' : 0, 'reason' : 'ordinal not in range(128)' }),
259 ( UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
260 { 'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
261 'object' : u'\u3042', 'reason' : 'ouch',
262 'start' : 0, 'end' : 1 }),
263 ]
264try:
265 exceptionList.append(
266 ( WindowsError, (1, 'strErrorStr', 'filenameStr'),
267 { 'message' : '', 'args' : (1, 'strErrorStr'),
268 'strerror' : 'strErrorStr',
269 'errno' : 22, 'filename' : 'filenameStr',
270 'winerror' : 1 }))
271except NameError: pass
272
Georg Brandl05f97bf2006-05-30 07:13:29 +0000273import pickle, random
274
Richard Jones7b9558d2006-05-27 12:29:24 +0000275for args in exceptionList:
276 expected = args[-1]
277 try:
278 if len(args) == 2: raise args[0]
279 else: raise apply(args[0], args[1])
280 except BaseException, e:
281 for checkArgName in expected.keys():
282 if repr(getattr(e, checkArgName)) != repr(expected[checkArgName]):
283 raise TestFailed('Checking exception arguments, exception '
284 '"%s", attribute "%s" expected %s got %s.' %
285 ( repr(e), checkArgName,
286 repr(expected[checkArgName]),
287 repr(getattr(e, checkArgName)) ))
Georg Brandl05f97bf2006-05-30 07:13:29 +0000288
289 # test for pickling support
290 new = pickle.loads(pickle.dumps(e, random.randint(0, 2)))
291 for checkArgName in expected.keys():
292 if repr(getattr(e, checkArgName)) != repr(expected[checkArgName]):
293 raise TestFailed('Checking unpickled exception arguments, '
294 'exception '
295 '"%s", attribute "%s" expected %s got %s.' %
296 ( repr(e), checkArgName,
297 repr(expected[checkArgName]),
298 repr(getattr(e, checkArgName)) ))