PyXR

c:\python24\lib \ test \ test_exceptions.py



0001 # Python test set -- part 5, built-in exceptions
0002 
0003 from test.test_support import TestFailed, TESTFN, unlink
0004 from types import ClassType
0005 import warnings
0006 import sys, traceback, os
0007 
0008 print '5. Built-in exceptions'
0009 # XXX This is not really enough, each *operation* should be tested!
0010 
0011 # Reloading the built-in exceptions module failed prior to Py2.2, while it
0012 # should act the same as reloading built-in sys.
0013 try:
0014     import exceptions
0015     reload(exceptions)
0016 except ImportError, e:
0017     raise TestFailed, e
0018 
0019 def test_raise_catch(exc):
0020     try:
0021         raise exc, "spam"
0022     except exc, err:
0023         buf = str(err)
0024     try:
0025         raise exc("spam")
0026     except exc, err:
0027         buf = str(err)
0028     print buf
0029 
0030 def r(thing):
0031     test_raise_catch(thing)
0032     if isinstance(thing, ClassType):
0033         print thing.__name__
0034     else:
0035         print thing
0036 
0037 r(AttributeError)
0038 import sys
0039 try: x = sys.undefined_attribute
0040 except AttributeError: pass
0041 
0042 r(EOFError)
0043 import sys
0044 fp = open(TESTFN, 'w')
0045 fp.close()
0046 fp = open(TESTFN, 'r')
0047 savestdin = sys.stdin
0048 try:
0049     try:
0050         sys.stdin = fp
0051         x = raw_input()
0052     except EOFError:
0053         pass
0054 finally:
0055     sys.stdin = savestdin
0056     fp.close()
0057 
0058 r(IOError)
0059 try: open('this file does not exist', 'r')
0060 except IOError: pass
0061 
0062 r(ImportError)
0063 try: import undefined_module
0064 except ImportError: pass
0065 
0066 r(IndexError)
0067 x = []
0068 try: a = x[10]
0069 except IndexError: pass
0070 
0071 r(KeyError)
0072 x = {}
0073 try: a = x['key']
0074 except KeyError: pass
0075 
0076 r(KeyboardInterrupt)
0077 print '(not testable in a script)'
0078 
0079 r(MemoryError)
0080 print '(not safe to test)'
0081 
0082 r(NameError)
0083 try: x = undefined_variable
0084 except NameError: pass
0085 
0086 r(OverflowError)
0087 # XXX
0088 # Obscure:  in 2.2 and 2.3, this test relied on changing OverflowWarning
0089 # into an error, in order to trigger OverflowError.  In 2.4, OverflowWarning
0090 # should no longer be generated, so the focus of the test shifts to showing
0091 # that OverflowError *isn't* generated.  OverflowWarning should be gone
0092 # in Python 2.5, and then the filterwarnings() call, and this comment,
0093 # should go away.
0094 warnings.filterwarnings("error", "", OverflowWarning, __name__)
0095 x = 1
0096 for dummy in range(128):
0097     x += x  # this simply shouldn't blow up
0098 
0099 r(RuntimeError)
0100 print '(not used any more?)'
0101 
0102 r(SyntaxError)
0103 try: exec '/\n'
0104 except SyntaxError: pass
0105 
0106 # make sure the right exception message is raised for each of these
0107 # code fragments:
0108 
0109 def ckmsg(src, msg):
0110     try:
0111         compile(src, '<fragment>', 'exec')
0112     except SyntaxError, e:
0113         print e.msg
0114         if e.msg == msg:
0115             print "ok"
0116         else:
0117             print "expected:", msg
0118     else:
0119         print "failed to get expected SyntaxError"
0120 
0121 s = '''\
0122 while 1:
0123     try:
0124         pass
0125     finally:
0126         continue
0127 '''
0128 if sys.platform.startswith('java'):
0129     print "'continue' not supported inside 'finally' clause"
0130     print "ok"
0131 else:
0132     ckmsg(s, "'continue' not supported inside 'finally' clause")
0133 s = '''\
0134 try:
0135     continue
0136 except:
0137     pass
0138 '''
0139 ckmsg(s, "'continue' not properly in loop")
0140 ckmsg("continue\n", "'continue' not properly in loop")
0141 
0142 r(IndentationError)
0143 
0144 r(TabError)
0145 # can only be tested under -tt, and is the only test for -tt
0146 #try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>', 'exec')
0147 #except TabError: pass
0148 #else: raise TestFailed
0149 
0150 r(SystemError)
0151 print '(hard to reproduce)'
0152 
0153 r(SystemExit)
0154 import sys
0155 try: sys.exit(0)
0156 except SystemExit: pass
0157 
0158 r(TypeError)
0159 try: [] + ()
0160 except TypeError: pass
0161 
0162 r(ValueError)
0163 try: x = chr(10000)
0164 except ValueError: pass
0165 
0166 r(ZeroDivisionError)
0167 try: x = 1/0
0168 except ZeroDivisionError: pass
0169 
0170 r(Exception)
0171 try: x = 1/0
0172 except Exception, e: pass
0173 
0174 # test that setting an exception at the C level works even if the
0175 # exception object can't be constructed.
0176 
0177 class BadException:
0178     def __init__(self):
0179         raise RuntimeError, "can't instantiate BadException"
0180 
0181 def test_capi1():
0182     import _testcapi
0183     try:
0184         _testcapi.raise_exception(BadException, 1)
0185     except TypeError, err:
0186         exc, err, tb = sys.exc_info()
0187         co = tb.tb_frame.f_code
0188         assert co.co_name == "test_capi1"
0189         assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
0190     else:
0191         print "Expected exception"
0192 
0193 def test_capi2():
0194     import _testcapi
0195     try:
0196         _testcapi.raise_exception(BadException, 0)
0197     except RuntimeError, err:
0198         exc, err, tb = sys.exc_info()
0199         co = tb.tb_frame.f_code
0200         assert co.co_name == "__init__"
0201         assert co.co_filename.endswith('test_exceptions'+os.extsep+'py')
0202         co2 = tb.tb_frame.f_back.f_code
0203         assert co2.co_name == "test_capi2"
0204     else:
0205         print "Expected exception"
0206 
0207 if not sys.platform.startswith('java'):
0208     test_capi1()
0209     test_capi2()
0210 
0211 unlink(TESTFN)
0212 

Generated by PyXR 0.9.4
SourceForge.net Logo