Python assertRaise在用户定义的异常上引发 [英] Python assertRaises on user-defined exceptions

查看:398
本文介绍了Python assertRaise在用户定义的异常上引发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下问题是由中的讨论触发的

假定两个文件( foobar.py foobar_unittest.py )。文件 foobar.py 包含一个类( FooBar ),该类具有两个功能( foo bar )。函数 bar 引发一个内置的异常,函数 foo 引发一个用户定义的异常。

Assume two files (foobar.py and foobar_unittest.py). File foobar.py contains a class (FooBar) with two functions (foo and bar). Function bar raises a built-in exception, function foo a user-defined exception.

# foobar.py
class MyException(Exception):
    pass
class FooBar:
    def __init__(self):
        pass
    def bar(self):
        raise ValueError('Hello World.')
    def foo(self):
        raise MyException('Hello World.')

# foobar_unittest.py
import unittest
import foobar as fb
class MyException(Exception):
    pass
class FooBarTestCases(unittest.TestCase):
    def test_bar(self):
        with self.assertRaises(ValueError):
            fb.FooBar().bar()
    def test_foo(self):
        with self.assertRaises(MyException):
            fb.FooBar().foo()
if __name__ == '__main__':
    unittest.main()

foobar.py 上运行单元测试时,为什么会这么有趣引发用户定义的异常( foo )的部分无法通过测试?

When running unit-test on foobar.py, why does the function raising the user-defined exception (foo) fail to pass the test?

>>> python2.7 foobar_unittest.py 
.E
======================================================================
ERROR: test_foo (__main__.FooBarTestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "foobar_unittest.py", line 11, in test_foo
    fb.FooBar().foo()
  File "/a_path/foobar.py", line 9, in foo
    raise MyException('Hello World.')
MyException: Hello World.

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)


推荐答案

从foobar导入MyException,请不要重新定义

import MyException from foobar, don't redefine it.

import unittest
from foobar import MyException
import foobar as fb

class FooBarTestCases(unittest.TestCase):
    def test_bar(self):
        with self.assertRaises(ValueError):
            fb.FooBar().bar()
    def test_foo(self):
        with self.assertRaises(MyException):
            fb.FooBar().foo()
if __name__ == '__main__':
    unittest.main()

此代码现在应该像

..
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

这篇关于Python assertRaise在用户定义的异常上引发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆