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
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
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.