Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest - How to execute a function after specific tests

I have some tests organized in several classes. I already have a test fixture with scope=class so that it would run before suite(class) of tests. However, I need to execute a function after some specific tests. Lets say I have 100 tests in a class, I already have a fixture that will execute a function before these tests, but I also want to run a function after 2-3 of these tests.

What is the best approach to achieve that? Can it be done with fixtures or anything else ?

like image 235
Override12 Avatar asked Jul 18 '26 08:07

Override12


1 Answers

First, write a fixture that will execute after a test finishes:

@pytest.fixture
def foo():
    yield
    print("do stuff after test")

Docs: Fixture finalization / executing teardown code

Now mark each test that should invoke this fixture with usefixtures("foo"):

@pytest.mark.usefixtures("foo")
def test_spam():
    ...

Docs: Use fixtures in classes and modules with usefixtures

like image 88
hoefling Avatar answered Jul 19 '26 21:07

hoefling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!