[英]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.