pytest cleanup after a single test

by pratapan   Last Updated July 12, 2019 05:26 AM

With pytest is there a way to run cleanup code on a specific test function/method alone. I know we can do this to run for each test function. But here I want to place some cleanup logic specific to a single test function.

I can just put cleanup code at the end of the test. But if test fails then cleanup wont be done

Tags : python pytest


Answers 1


Create a fixture with your cleanup code and inject it only into the one test by using the fixture as an argument for your test or by explicitly marking the test with the pytest.mark.usefixtures decorator.

import pytest

@pytest.fixture
def my_cleanup_fixture():
    # Startup code
    ...
    yield
    # Cleanup code
    ...

@pytest.mark.usefixtures('my_cleanup_fixture')
def test_with_special_cleanup():
    pass

my_cleanup_fixture has scope function by default, so the startup and cleanup code will run for each function it is injected.

Alexander Fasching
Alexander Fasching
July 12, 2019 04:18 AM

Related Questions


Updated June 21, 2019 02:26 AM

Updated December 24, 2018 22:26 PM

Updated October 23, 2018 23:26 PM

Updated October 11, 2018 18:26 PM

Updated October 26, 2018 17:26 PM