Search code examples
pythonpython-unittest

How to write stateful tests in python unittest?


I want to create a test suite for an existing library that is using unittest and is very hierarchical.

The Class hierarchy looks a bit like this:

A
|_B
|_C
  |_D
  |_E

Class A is created with an instance of B and C where C needs D and E. The instances are quite expensive to make so I want to reuse them for later testcases. What I would want is something like this:

class TestsClass(TestCase): 
    def test_00_test_e():
        self.e = E()
        ...

    def test_01_test_d():
        self.d = D()
        ...

    def test_02_test_c():
        self.c = C(self.d, self.e)
        ...

    ...

This however is not possible since unittest creates an unique object for each testcase. Is there a way to get this functionality within unittest so that I can work whithin the test framework of the project and don't have to add dependencies?


Solution

  • You could have setUpClass() and call it before all the methods in the class are executed:

    class TestsClass(unittest.TestCase):
    
        @classmethod
        def setUpClass(cls):
            cls.e = E()  
            cls.d = D()  
            cls.c = C(cls.d, cls.e)  
    
        def test_00_test_e(self):
            # Use self.e instance