Search code examples
pythonpytestpython-unittest

Pytest or Unittest: How to run tests independent from each other?


I want to test a simple class A:

class A:
    _cache = None

    def func(self):
        if not A._cache:
            A._cache = 'Get value from some service'


class TestA:
    def test_cache_after_func(self):
        a = A()
        a.func()
        assert A._cache is not None

    def test_cache_empty(self):
        a = A()
        assert A._cache is None

These two tests pass when run separately from VSCode. But when they are run together then second test fails because the first one already has modified the _cache field.

How to run these tests isolated without affecting one another? (I would appreciate examples both for unittest and pytest if they differ)


Solution

  • Method setUp() of the class unittest.TestCase

    You can use the module unittest and the method setUp() of the class unittest.TestCase to set to None the class variable _cache.

    About the method setUp() doumentation reports this sentence:

    The setUp() method allows you to define instructions that will be executed before each test method.

    Your code could be inserted in a subclass of the unittest.TestCase, defining a setUp() method which init the class variable _cache. So your code could become as following:

    import unittest
    
    class A:
        _cache = None
    
        def func(self):
            if not A._cache:
                A._cache = 'Get value from some service'
    
    
    class MyTestCase(unittest.TestCase):
    
        def setUp(self) -> None:
            A._cache = None
    
        def test_cache_after_func(self):
            a = A()
            a.func()
            assert A._cache is not None
    
        def test_cache_empty(self):
            a = A()
            assert A._cache is None
    
    
    if __name__ == '__main__':
        unittest.main()
    

    If you execute the previous code the 2 tests pass, while if you remove the setUp() method, the second one fails.

    This post also adds other explanations about methods setUp() and tearDown() with other useful links.