Search code examples
pythonpytestfixtures

Using pytest to do setup and teardown


I have a handful of tests in my test module that need some common setup and teardown to run before and after the test. I don't need the setup and teardown to run for every function, just a handful of them. I've found I can kind of do this with fixtures

@pytest.fixture
def reset_env():
    env = copy.deepcopy(os.environ)
    yield None
    os.environ = env


def test_that_does_some_env_manipulation(reset_env):
    # do some tests

I don't actually need to return anything from the fixture to use in the test function, though, so I really don't need the argument. I'm only using it to trigger setup and teardown.

Is there a way to specify that a test function uses a setup/teardown fixture without needing the fixture argument? Maybe a decorator to say that a test function uses a certain fixture?


Solution

  • Thanks to hoefling's comment above

    @pytest.mark.usefixtures('reset_env')
    def test_that_does_some_env_manipulation():
        # do some tests