[英]How to fail a python unittest if the setUpClass throws exception
我在使用 python setUpClass 时遇到了一些麻烦。
例如考虑以下情况
class MyTest(unittest.case.TestCase):
@classmethod
def setUpClass(cls):
print "Test setup"
try:
1/0
except:
raise
@classmethod
def tearDownClass(cls):
print "Test teardown"
几个问题
上面的代码是否是处理测试 setUpClass 异常的正确方法(通过引发它以便 python unittest 可以处理它),有 fail()、skip() 方法,但这些方法只能由测试实例使用,而不是测试类。
当出现setUpClass异常时,如何保证tearDownClass运行(unittest不运行,应该手动调用)。
您可以像 Jeff 指出的那样对异常调用tearDownClass
,但您也可以实现__del__(cls)
方法:
import unittest
class MyTest(unittest.case.TestCase):
@classmethod
def setUpClass(cls):
print "Test setup"
try:
1/0
except:
raise
@classmethod
def __del__(cls):
print "Test teardown"
def test_hello(cls):
print "Hello"
if __name__ == '__main__':
unittest.main()
将有以下输出:
Test setup
E
======================================================================
ERROR: setUpClass (__main__.MyTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "my_test.py", line 8, in setUpClass
1/0
ZeroDivisionError: integer division or modulo by zero
----------------------------------------------------------------------
Ran 0 tests in 0.000s
FAILED (errors=1)
Test teardown
注意:您应该知道__del__
方法将在程序执行结束时被调用,如果您有一个以上的测试类,这可能不是您想要的。
希望能帮助到你
最好的选择是为调用tearDownClass 并重新引发异常的except 添加处理程序。
@classmethod
def setUpClass(cls):
try:
super(MyTest, cls).setUpClass()
# setup routine...
except Exception: # pylint: disable = W0703
super(MyTest, cls).tearDownClass()
raise
import contextlib
class MyTestCase(unitest.TestCase):
@classmethod
def setUpClass(cls):
with contextlib.ExitStack() as stack:
# ensure teardown is called if error occurs
stack.callback(cls.tearDownClass)
# Do the things here!
# remove callback at the end if no error found
stack.pop_all()
使用tearDownModule。 它应该在 setUpClass 运行后调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.