如何确保自定义函数在执行每个 Python 单元测试后运行?

How to ensure that a custom function runs after execution of every 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_something('test_1')

    def tearDown(self):
        for descr in custom_descr:
            print(descr)

是否可以按照下面的想法 (以下不起作用)通过集中任何 base_class 中的任何描述来避免在每个模块中写入 tearDown() =22=]:

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')