我观察到,当测试运行中止时,不会调用任何拆卸方法。
如果测试运行中止,是否可以添加调用的处理程序?
下面的示例显示如何跳过分解方法。
import unittest
class Test1(unittest.TestCase):
def setUp(self):
print("hi from setup")
# start_nuclear_reactor_core()
def tearDown(self):
print("hi from teardown")
# safely_shutdown_nuclear_reactor_core()
@classmethod
def setUpClass(cls):
print("hi from setupClass")
@classmethod
def tearDownClass(cls):
print("hi from tearDownClass")
def case1(self):
print("case1")
def caseInterrupt(self):
# Do dangerous experiment
print("caseInterrupt")
# nuclear reactor core will not be safely shut down
raise KeyboardInterrupt()
if __name__ == '__main__':
test_suite = unittest.TestSuite()
# test_suite.addTest(Test1('case1'))
test_suite.addTest(Test1('caseInterrupt'))
runner = unittest.TextTestRunner()
runner.run(test_suite)
输出:
> python teardown_not_called.py
hi from setupClass
hi from setup
caseInterrupt
Traceback (most recent call last):
File "teardown_not_called.py", line 34, in
runner.run(test_suite)
File "C:\programs\Python37\lib\unittest\runner.py", line 176, in run
test(result)
File "C:\programs\Python37\lib\unittest\suite.py", line 84, in __call__
return self.run(*args, **kwds)
File "C:\programs\Python37\lib\unittest\suite.py", line 122, in run
test(result)
File "C:\programs\Python37\lib\unittest\case.py", line 663, in __call__
return self.run(*args, **kwds)
File "C:\programs\Python37\lib\unittest\case.py", line 615, in run
testMethod()
File "teardown_not_called.py", line 27, in caseInterrupt
raise KeyboardInterrupt()
KeyboardInterrupt