Search code examples
pythonparametersautomated-testspytestfixtures

How to run teardown function / fixture after parametrize


I am trying to run teardown function / fixture for whole parametrization of one testcase. So I want to have in my conftest.py file something like this

@pytest.fixture(autouse=True, scope="parametrization")
def parametrization_scope():
    print("First run of parametrization fixture")
    # Executing 100 parametrizations
    yield
    print("Yield run of parametrization fixture")

and in my test.py something like

@pytest.mark.parametrize(n-params)
# run initiate fixture here of parametrization
def test():
    # executing n number of times

# run yield fixture here of parametrization

Solution

  • You could use a test class to workaround the missing "parametrization" scope like this:

    import pytest
    
    @pytest.fixture(scope="class")
    def foo():
        print("setup")
        yield None
        print("teardown")
    
    class TestSum:
        @pytest.mark.parametrize(
            "a,b,c",
            [(3, 5, 8), (2, 4, 6)],
        )
        def test_eval(self, a, b, c, foo):
            assert a + b == c
    

    If only the TestSum class uses the fixture foo, you could even place the definition of foo inside the class.