blob: 7946142a2b179061b90c9e847ff85fa16b0a07ff [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)
Tim Petersd3925062002-04-16 01:27:44 +000084# XXX
Tim Petersc8854432004-08-25 02:14:08 +000085# Obscure: in 2.2 and 2.3, this test relied on changing OverflowWarning
86# into an error, in order to trigger OverflowError. In 2.4, OverflowWarning
87# should no longer be generated, so the focus of the test shifts to showing
88# that OverflowError *isn't* generated. OverflowWarning should be gone
89# in Python 2.5, and then the filterwarnings() call, and this comment,
90# should go away.
Tim Petersd3925062002-04-16 01:27:44 +000091warnings.filterwarnings("error", "", OverflowWarning, __name__)
Guido van Rossum3bead091992-01-27 17:00:37 +000092x = 1
Tim Petersc8854432004-08-25 02:14:08 +000093for dummy in range(128):
94 x += x # this simply shouldn't blow up
Guido van Rossum3bead091992-01-27 17:00:37 +000095
96r(RuntimeError)
97print '(not used any more?)'
98
99r(SyntaxError)
Guido van Rossume2cb7271995-08-11 14:24:47 +0000100try: exec '/\n'
Guido van Rossum3bead091992-01-27 17:00:37 +0000101except SyntaxError: pass
102
Fred Drake72e48bd2000-09-08 16:32:34 +0000103# make sure the right exception message is raised for each of these
104# code fragments:
105
106def ckmsg(src, msg):
107 try:
108 compile(src, '<fragment>', 'exec')
109 except SyntaxError, e:
110 print e.msg
111 if e.msg == msg:
112 print "ok"
113 else:
114 print "expected:", msg
115 else:
116 print "failed to get expected SyntaxError"
117
118s = '''\
119while 1:
120 try:
Fred Drake72e48bd2000-09-08 16:32:34 +0000121 pass
Fred Drake72e48bd2000-09-08 16:32:34 +0000122 finally:
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000123 continue
Fred Drake72e48bd2000-09-08 16:32:34 +0000124'''
Finn Bockaa3dc452001-12-08 10:15:48 +0000125if sys.platform.startswith('java'):
126 print "'continue' not supported inside 'finally' clause"
127 print "ok"
128else:
129 ckmsg(s, "'continue' not supported inside 'finally' clause")
Fred Drake72e48bd2000-09-08 16:32:34 +0000130s = '''\
131try:
132 continue
133except:
134 pass
135'''
136ckmsg(s, "'continue' not properly in loop")
137ckmsg("continue\n", "'continue' not properly in loop")
138
Fred Drake85f36392000-07-11 17:53:00 +0000139r(IndentationError)
140
141r(TabError)
142# can only be tested under -tt, and is the only test for -tt
143#try: compile("try:\n\t1/0\n \t1/0\nfinally:\n pass\n", '<string>', 'exec')
144#except TabError: pass
145#else: raise TestFailed
146
Guido van Rossum3bead091992-01-27 17:00:37 +0000147r(SystemError)
148print '(hard to reproduce)'
149
150r(SystemExit)
151import sys
152try: sys.exit(0)
153except SystemExit: pass
154
155r(TypeError)
156try: [] + ()
157except TypeError: pass
158
159r(ValueError)
160try: x = chr(10000)
161except ValueError: pass
162
163r(ZeroDivisionError)
164try: x = 1/0
165except ZeroDivisionError: pass
166
Barry Warsaw992cb8a2000-05-25 23:16:54 +0000167r(Exception)
168try: x = 1/0
169except Exception, e: pass
170
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000171# test that setting an exception at the C level works even if the
172# exception object can't be constructed.
173
Thomas Wouters303de6a2006-04-20 22:42:37 +0000174class BadException(Exception):
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000175 def __init__(self):
176 raise RuntimeError, "can't instantiate BadException"
177
Thomas Wouters303de6a2006-04-20 22:42:37 +0000178# Exceptions must inherit from BaseException, raising invalid exception
179# should instead raise SystemError
180class InvalidException:
181 pass
182
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000183def test_capi1():
Finn Bockaa3dc452001-12-08 10:15:48 +0000184 import _testcapi
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000185 try:
186 _testcapi.raise_exception(BadException, 1)
187 except TypeError, err:
188 exc, err, tb = sys.exc_info()
189 co = tb.tb_frame.f_code
190 assert co.co_name == "test_capi1"
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000191 assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000192 else:
193 print "Expected exception"
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000194
195def test_capi2():
Finn Bockaa3dc452001-12-08 10:15:48 +0000196 import _testcapi
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000197 try:
198 _testcapi.raise_exception(BadException, 0)
199 except RuntimeError, err:
200 exc, err, tb = sys.exc_info()
201 co = tb.tb_frame.f_code
202 assert co.co_name == "__init__"
Martin v. Löwisa94568a2003-05-10 07:36:56 +0000203 assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000204 co2 = tb.tb_frame.f_back.f_code
205 assert co2.co_name == "test_capi2"
206 else:
207 print "Expected exception"
Finn Bockaa3dc452001-12-08 10:15:48 +0000208
Thomas Wouters303de6a2006-04-20 22:42:37 +0000209def test_capi3():
210 import _testcapi
211 try:
212 _testcapi.raise_exception(InvalidException, 1)
213 except SystemError:
214 pass
215 except InvalidException:
216 raise AssertionError("Managed to raise InvalidException");
217 else:
218 print "Expected SystemError exception"
219
220
Finn Bockaa3dc452001-12-08 10:15:48 +0000221if not sys.platform.startswith('java'):
222 test_capi1()
223 test_capi2()
Thomas Wouters303de6a2006-04-20 22:42:37 +0000224 test_capi3()
Jeremy Hyltonede049b2001-09-26 20:01:13 +0000225
Guido van Rossum3bead091992-01-27 17:00:37 +0000226unlink(TESTFN)