blob: 8f995f7fcc30d8d5fa10beb7d2a7b678c094987c [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:
Neal Norwitzce96f692006-03-17 06:49:51 +000047 import marshal
48 marshal.loads('')
Fred Drake2e6d25c2000-10-23 17:00:30 +000049 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
Thomas Wouters303de6a2006-04-20 22:42:37 +0000166class BadException(Exception):
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000167 def __init__(self):
168 raise RuntimeError, "can't instantiate BadException"
169
Thomas Wouters303de6a2006-04-20 22:42:37 +0000170# Exceptions must inherit from BaseException, raising invalid exception
171# should instead raise SystemError
172class InvalidException:
173 pass
174
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000175def test_capi1():
Finn Bockaa3dc452001-12-08 10:15:48 +0000176 import _testcapi
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000177 try:
178 _testcapi.raise_exception(BadException, 1)
179 except TypeError, err:
180 exc, err, tb = sys.exc_info()
181 co = tb.tb_frame.f_code
182 assert co.co_name == "test_capi1"
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000183 assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000184 else:
185 print "Expected exception"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000186
187def test_capi2():
Finn Bockaa3dc452001-12-08 10:15:48 +0000188 import _testcapi
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000189 try:
190 _testcapi.raise_exception(BadException, 0)
191 except RuntimeError, err:
192 exc, err, tb = sys.exc_info()
193 co = tb.tb_frame.f_code
194 assert co.co_name == "__init__"
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000195 assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000196 co2 = tb.tb_frame.f_back.f_code
197 assert co2.co_name == "test_capi2"
198 else:
199 print "Expected exception"
Finn Bockaa3dc452001-12-08 10:15:48 +0000200
Thomas Wouters303de6a2006-04-20 22:42:37 +0000201def test_capi3():
202 import _testcapi
203 try:
204 _testcapi.raise_exception(InvalidException, 1)
205 except SystemError:
206 pass
207 except InvalidException:
208 raise AssertionError("Managed to raise InvalidException");
209 else:
210 print "Expected SystemError exception"
211
212
Finn Bockaa3dc452001-12-08 10:15:48 +0000213if not sys.platform.startswith('java'):
214 test_capi1()
215 test_capi2()
Thomas Wouters303de6a2006-04-20 22:42:37 +0000216 test_capi3()
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000217
Guido van Rossum3bead091992-01-27 17:00:37 +0000218unlink(TESTFN)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000219
220# test that exception attributes are happy.
221try: str(u'Hello \u00E1')
222except Exception, e: sampleUnicodeEncodeError = e
223try: unicode('\xff')
224except Exception, e: sampleUnicodeDecodeError = e
225exceptionList = [
226 ( BaseException, (), { 'message' : '', 'args' : () }),
227 ( BaseException, (1, ), { 'message' : 1, 'args' : ( 1, ) }),
228 ( BaseException, ('foo', ), { 'message' : 'foo', 'args' : ( 'foo', ) }),
229 ( BaseException, ('foo', 1), { 'message' : '', 'args' : ( 'foo', 1 ) }),
230 ( SystemExit, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ),
231 'code' : 'foo' }),
232 ( IOError, ('foo',), { 'message' : 'foo', 'args' : ( 'foo', ), }),
233 ( IOError, ('foo', 'bar'), { 'message' : '',
234 'args' : ('foo', 'bar'), }),
235 ( IOError, ('foo', 'bar', 'baz'),
236 { 'message' : '', 'args' : ('foo', 'bar'), }),
237 ( EnvironmentError, ('errnoStr', 'strErrorStr', 'filenameStr'),
238 { 'message' : '', 'args' : ('errnoStr', 'strErrorStr'),
239 'strerror' : 'strErrorStr',
240 'errno' : 'errnoStr', 'filename' : 'filenameStr' }),
241 ( EnvironmentError, (1, 'strErrorStr', 'filenameStr'),
242 { 'message' : '', 'args' : (1, 'strErrorStr'),
243 'strerror' : 'strErrorStr', 'errno' : 1,
244 'filename' : 'filenameStr' }),
245 ( SyntaxError, ('msgStr',),
246 { 'message' : 'msgStr', 'args' : ('msgStr', ),
247 'print_file_and_line' : None, 'msg' : 'msgStr',
248 'filename' : None, 'lineno' : None, 'offset' : None,
249 'text' : None }),
250 ( SyntaxError, ('msgStr', ('filenameStr', 'linenoStr', 'offsetStr',
251 'textStr')),
252 { 'message' : '', 'args' : ('msgStr', ('filenameStr',
253 'linenoStr', 'offsetStr', 'textStr' )),
254 'print_file_and_line' : None, 'msg' : 'msgStr',
255 'filename' : 'filenameStr', 'lineno' : 'linenoStr',
256 'offset' : 'offsetStr', 'text' : 'textStr' }),
257 ( SyntaxError, ('msgStr', 'filenameStr', 'linenoStr', 'offsetStr',
258 'textStr', 'print_file_and_lineStr'),
259 { 'message' : '', 'args' : ('msgStr', 'filenameStr',
260 'linenoStr', 'offsetStr', 'textStr',
261 'print_file_and_lineStr'),
262 'print_file_and_line' : None, 'msg' : 'msgStr',
263 'filename' : None, 'lineno' : None, 'offset' : None,
264 'text' : None }),
265 ( UnicodeError, (),
266 { 'message' : '', 'args' : (), }),
267 ( sampleUnicodeEncodeError,
268 { 'message' : '', 'args' : ('ascii', u'Hello \xe1', 6, 7,
269 'ordinal not in range(128)'),
270 'encoding' : 'ascii', 'object' : u'Hello \xe1',
271 'start' : 6, 'reason' : 'ordinal not in range(128)' }),
272 ( sampleUnicodeDecodeError,
273 { 'message' : '', 'args' : ('ascii', '\xff', 0, 1,
274 'ordinal not in range(128)'),
275 'encoding' : 'ascii', 'object' : '\xff',
276 'start' : 0, 'reason' : 'ordinal not in range(128)' }),
277 ( UnicodeTranslateError, (u"\u3042", 0, 1, "ouch"),
278 { 'message' : '', 'args' : (u'\u3042', 0, 1, 'ouch'),
279 'object' : u'\u3042', 'reason' : 'ouch',
280 'start' : 0, 'end' : 1 }),
281 ]
282try:
283 exceptionList.append(
284 ( WindowsError, (1, 'strErrorStr', 'filenameStr'),
285 { 'message' : '', 'args' : (1, 'strErrorStr'),
286 'strerror' : 'strErrorStr',
287 'errno' : 22, 'filename' : 'filenameStr',
288 'winerror' : 1 }))
289except NameError: pass
290
291for args in exceptionList:
292 expected = args[-1]
293 try:
294 if len(args) == 2: raise args[0]
295 else: raise apply(args[0], args[1])
296 except BaseException, e:
297 for checkArgName in expected.keys():
298 if repr(getattr(e, checkArgName)) != repr(expected[checkArgName]):
299 raise TestFailed('Checking exception arguments, exception '
300 '"%s", attribute "%s" expected %s got %s.' %
301 ( repr(e), checkArgName,
302 repr(expected[checkArgName]),
303 repr(getattr(e, checkArgName)) ))