home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 2004 #2 / K-CD-2-2004.ISO / OpenOffice Sv / f_0397 / python-core-2.2.2 / lib / test / test_exceptions.py < prev    next >
Encoding:
Python Source  |  2003-07-18  |  4.1 KB  |  207 lines

  1. # Python test set -- part 5, built-in exceptions
  2.  
  3. from test_support import *
  4. from types import ClassType
  5. import warnings
  6. import sys, traceback
  7.  
  8. warnings.filterwarnings("error", "", OverflowWarning, __name__)
  9.  
  10. print '5. Built-in exceptions'
  11. # XXX This is not really enough, each *operation* should be tested!
  12.  
  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.     raise TestFailed, e
  20.  
  21. def test_raise_catch(exc):
  22.     try:
  23.         raise exc, "spam"
  24.     except exc, err:
  25.         buf = str(err)
  26.     try:
  27.         raise exc("spam")
  28.     except exc, err:
  29.         buf = str(err)
  30.     print buf
  31.  
  32. def r(thing):
  33.     test_raise_catch(thing)
  34.     if isinstance(thing, ClassType):
  35.         print thing.__name__
  36.     else:
  37.         print thing
  38.  
  39. r(AttributeError)
  40. import sys
  41. try: x = sys.undefined_attribute
  42. except AttributeError: pass
  43.  
  44. r(EOFError)
  45. import sys
  46. fp = open(TESTFN, 'w')
  47. fp.close()
  48. fp = open(TESTFN, 'r')
  49. savestdin = sys.stdin
  50. try:
  51.     try:
  52.         sys.stdin = fp
  53.         x = raw_input()
  54.     except EOFError:
  55.         pass
  56. finally:
  57.     sys.stdin = savestdin
  58.     fp.close()
  59.  
  60. r(IOError)
  61. try: open('this file does not exist', 'r')
  62. except IOError: pass
  63.  
  64. r(ImportError)
  65. try: import undefined_module
  66. except ImportError: pass
  67.  
  68. r(IndexError)
  69. x = []
  70. try: a = x[10]
  71. except IndexError: pass
  72.  
  73. r(KeyError)
  74. x = {}
  75. try: a = x['key']
  76. except KeyError: pass
  77.  
  78. r(KeyboardInterrupt)
  79. print '(not testable in a script)'
  80.  
  81. r(MemoryError)
  82. print '(not safe to test)'
  83.  
  84. r(NameError)
  85. try: x = undefined_variable
  86. except NameError: pass
  87.  
  88. r(OverflowError)
  89. x = 1
  90. try:
  91.     while 1: x = x+x
  92. except OverflowError: pass
  93.  
  94. r(RuntimeError)
  95. print '(not used any more?)'
  96.  
  97. r(SyntaxError)
  98. try: exec '/\n'
  99. except SyntaxError: pass
  100.  
  101. # make sure the right exception message is raised for each of these
  102. # code fragments:
  103.  
  104. def ckmsg(src, msg):
  105.     try:
  106.         compile(src, '<fragment>', 'exec')
  107.     except SyntaxError, e:
  108.         print e.msg
  109.         if e.msg == msg:
  110.             print "ok"
  111.         else:
  112.             print "expected:", msg
  113.     else:
  114.         print "failed to get expected SyntaxError"
  115.  
  116. s = '''\
  117. while 1:
  118.     try:
  119.         pass
  120.     finally:
  121.         continue
  122. '''
  123. if sys.platform.startswith('java'):
  124.     print "'continue' not supported inside 'finally' clause"
  125.     print "ok"
  126. else:
  127.     ckmsg(s, "'continue' not supported inside 'finally' clause")
  128. s = '''\
  129. try:
  130.     continue
  131. except:
  132.     pass
  133. '''
  134. ckmsg(s, "'continue' not properly in loop")
  135. ckmsg("continue\n", "'continue' not properly in loop")
  136.  
  137. r(IndentationError)
  138.  
  139. r(TabError)
  140. # can only be tested under -tt, and is the only test for -tt
  141. #try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>', 'exec')
  142. #except TabError: pass
  143. #else: raise TestFailed
  144.  
  145. r(SystemError)
  146. print '(hard to reproduce)'
  147.  
  148. r(SystemExit)
  149. import sys
  150. try: sys.exit(0)
  151. except SystemExit: pass
  152.  
  153. r(TypeError)
  154. try: [] + ()
  155. except TypeError: pass
  156.  
  157. r(ValueError)
  158. try: x = chr(10000)
  159. except ValueError: pass
  160.  
  161. r(ZeroDivisionError)
  162. try: x = 1/0
  163. except ZeroDivisionError: pass
  164.  
  165. r(Exception)
  166. try: x = 1/0
  167. except Exception, e: pass
  168.  
  169. # test that setting an exception at the C level works even if the
  170. # exception object can't be constructed.
  171.  
  172. class BadException:
  173.     def __init__(self):
  174.         raise RuntimeError, "can't instantiate BadException"
  175.  
  176. def test_capi1():
  177.     import _testcapi
  178.     try:
  179.         _testcapi.raise_exception(BadException, 1)
  180.     except TypeError, err:
  181.         exc, err, tb = sys.exc_info()
  182.         co = tb.tb_frame.f_code
  183.         assert co.co_name == "test_capi1"
  184.         assert co.co_filename.endswith('test_exceptions.py')
  185.     else:
  186.         print "Expected exception"
  187.  
  188. def test_capi2():
  189.     import _testcapi
  190.     try:
  191.         _testcapi.raise_exception(BadException, 0)
  192.     except RuntimeError, err:
  193.         exc, err, tb = sys.exc_info()
  194.         co = tb.tb_frame.f_code
  195.         assert co.co_name == "__init__"
  196.         assert co.co_filename.endswith('test_exceptions.py')
  197.         co2 = tb.tb_frame.f_back.f_code
  198.         assert co2.co_name == "test_capi2"
  199.     else:
  200.         print "Expected exception"
  201.  
  202. if not sys.platform.startswith('java'):
  203.     test_capi1()
  204.     test_capi2()
  205.  
  206. unlink(TESTFN)
  207.