在 Python unittest 中,如何在执行完 TestCase 中的所有测试后调用函数?

In Python unittest, how can I call a function after all tests in a TestCase have been executed?

我 运行 在 Python 中进行了一些单元测试,并希望在所有测试用例完成后调用一个函数 运行。

class MyTestCase(TestCase):
    def setUp(self):
        self.credentials = credentials

    def tearDown(self):
        print("finished running " + self._testMethodName)

    def tearDownModule(self):
        print("finished running all tests")

    def test_1(self):
        #do something

    def test_2(self):
        #do something else

setUp 和 tearDown 运行ning 在每个单独的测试之前和之后。然而,我想在所有测试完成后调用一个函数 运行ning(在本例中为 test_1 和 test_2)。

从文档来看,tearDownModule() 函数应该可以执行此操作,但它似乎并未被调用。

tearDownModule is for use on the module scope, not as a method. Instead, you probably want tearDownClass:

class MyTestCase(TestCase):

    @classmethod
    def tearDownClass(cls):
        ...