如何确保自定义函数在每次Python单元测试执行后运行?
我想确保在每次测试后都会运行自定义函数 现在,我有下面的解决方案,包括在每个unitTest模块中添加一个如何确保自定义函数在每次Python单元测试执行后运行?,python,python-unittest,Python,Python Unittest,我想确保在每次测试后都会运行自定义函数 现在,我有下面的解决方案,包括在每个unitTest模块中添加一个tearDown()调用,这似乎是一种过度使用 import unittest custom_descr = [] def do_something(test): custom_descr.append('from '.format(test)) class Tester(unittest.TestCase): def test_1(self): do_
tearDown()
调用,这似乎是一种过度使用
import unittest
custom_descr = []
def do_something(test):
custom_descr.append('from '.format(test))
class Tester(unittest.TestCase):
def test_1(self):
do_something('test_1')
def tearDown(self):
for descr in custom_descr:
print(descr)
通过按照下面的想法将任何描述集中在任何基类中,是否可以避免在每个模块中编写tearDown()
(但以下方法不起作用):
import unittest
# in common_module.py
custom_descr = []
def do_something(test):
custom_descr.append('from '.format(test))
class Test_Base(unittest.TestCase):
def tearDown(self):
for descr in custom_descr:
print(descr)
# in module1.py
class Tester1(Test_Base):
def test_1(self):
do_something('test_1')
# in module2.py
class Tester2(Test_Base):
def test_2(self):
do_something('test_2')
一个简单的解决方案是在每个测试模块的设置中添加
self.tearDown=Test_Base.warn
,但这远远不是我想要的-因为我仍然需要在每个模块中重复代码(无论多么小)
import unittest
// in common_module.py
custom_descr = []
def do_something(test):
custom_descr.append('from '.format(test))
class Test_Base(unittest.TestCase):
def final(self):
for descr in custom_descr:
print(descr)
//in module1.py
class Tester1(Test_Base):
def setUp(self):
self.tearDown = Test_Base.final
def test_1(self):
do_something('test_1')
//in module2.py
class Tester2(Test_Base):
def setUp(self):
self.tearDown = Test_Base.final
def test_2(self):
do_something('test_2')
我想你回答了你的问题correctly@Pynchia-但上述解决方案不起作用。测试后不调用基类拆卸。只有它自己的撕裂被称为。