Search code examples
pythonunit-testingpython-unittest

How can you cleanup a Python UnitTest when setUpClass fails?


Say I have the following Python UnitTest:

import unittest

def Test(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # Get some resources
        ...

        if error_occurred:
            assert(False)

    @classmethod
    def tearDownClass(cls):
        # release resources
        ...

If the setUpClass call fails, the tearDownClass is not called so the resources are never released. This is a problem during a test run if the resources are required by the next test.

Is there a way to do a clean up when the setUpClass call fails?


Solution

  • In the meanwhile, addClassCleanup class method has been added to unittest.TestCase for exactly that purpose: https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanup