test_exceptions.py

来自「mallet是自然语言处理、机器学习领域的一个开源项目。」· Python 代码 · 共 207 行

PY
207
字号
# Python test set -- part 5, built-in exceptionsfrom test_support import *from types import ClassTypeimport warningsimport sys, tracebackwarnings.filterwarnings("error", "", OverflowWarning, __name__)print '5. Built-in exceptions'# XXX This is not really enough, each *operation* should be tested!# Reloading the built-in exceptions module failed prior to Py2.2, while it# should act the same as reloading built-in sys.try:    import exceptions    reload(exceptions)except ImportError, e:    raise TestFailed, edef test_raise_catch(exc):    try:        raise exc, "spam"    except exc, err:        buf = str(err)    try:        raise exc("spam")    except exc, err:        buf = str(err)    print bufdef r(thing):    test_raise_catch(thing)    if isinstance(thing, ClassType):        print thing.__name__    else:        print thingr(AttributeError)import systry: x = sys.undefined_attributeexcept AttributeError: passr(EOFError)import sysfp = open(TESTFN, 'w')fp.close()fp = open(TESTFN, 'r')savestdin = sys.stdintry:    try:        sys.stdin = fp        x = raw_input()    except EOFError:        passfinally:    sys.stdin = savestdin    fp.close()r(IOError)try: open('this file does not exist', 'r')except IOError: passr(ImportError)try: import undefined_moduleexcept ImportError: passr(IndexError)x = []try: a = x[10]except IndexError: passr(KeyError)x = {}try: a = x['key']except KeyError: passr(KeyboardInterrupt)print '(not testable in a script)'r(MemoryError)print '(not safe to test)'r(NameError)try: x = undefined_variableexcept NameError: passr(OverflowError)x = 1try:    while 1: x = x+xexcept OverflowError: passr(RuntimeError)print '(not used any more?)'r(SyntaxError)try: exec '/\n'except SyntaxError: pass# make sure the right exception message is raised for each of these# code fragments:def ckmsg(src, msg):    try:        compile(src, '<fragment>', 'exec')    except SyntaxError, e:        print e.msg        if e.msg == msg:            print "ok"        else:            print "expected:", msg    else:        print "failed to get expected SyntaxError"s = '''\while 1:    try:        pass    finally:        continue'''if sys.platform.startswith('java'):    print "'continue' not supported inside 'finally' clause"    print "ok"else:    ckmsg(s, "'continue' not supported inside 'finally' clause")s = '''\try:    continueexcept:    pass'''ckmsg(s, "'continue' not properly in loop")ckmsg("continue\n", "'continue' not properly in loop")r(IndentationError)r(TabError)# can only be tested under -tt, and is the only test for -tt#try: compile("try:\n\t1/0\n    \t1/0\nfinally:\n pass\n", '<string>', 'exec')#except TabError: pass#else: raise TestFailedr(SystemError)print '(hard to reproduce)'r(SystemExit)import systry: sys.exit(0)except SystemExit: passr(TypeError)try: [] + ()except TypeError: passr(ValueError)try: x = chr(10000)except ValueError: passr(ZeroDivisionError)try: x = 1/0except ZeroDivisionError: passr(Exception)try: x = 1/0except Exception, e: pass# test that setting an exception at the C level works even if the# exception object can't be constructed.class BadException:    def __init__(self):        raise RuntimeError, "can't instantiate BadException"def test_capi1():    import _testcapi    try:        _testcapi.raise_exception(BadException, 1)    except TypeError, err:        exc, err, tb = sys.exc_info()        co = tb.tb_frame.f_code        assert co.co_name == "test_capi1"        assert co.co_filename.endswith('test_exceptions.py')    else:        print "Expected exception"def test_capi2():    import _testcapi    try:        _testcapi.raise_exception(BadException, 0)    except RuntimeError, err:        exc, err, tb = sys.exc_info()        co = tb.tb_frame.f_code        assert co.co_name == "__init__"        assert co.co_filename.endswith('test_exceptions.py')        co2 = tb.tb_frame.f_back.f_code        assert co2.co_name == "test_capi2"    else:        print "Expected exception"if not sys.platform.startswith('java'):    test_capi1()    test_capi2()unlink(TESTFN)

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?