pythonpytestpytest-fixtures

Can a pytest fixture know whether a test has passed or failed?


I'm writing some tests in pytest, and I'd like to make the fixture do something only if the test passes (update a value in a DB). It doesn't seem like fixtures in general know about whether the tests they run pass or fail -- is there a way to make them?

import pytest


@pytest.fixture
def my_fixture(request):
    ...
    yield
    [if test passes]:
        db.write(new_value)


def test_foo(my_fixture):
    assert False

Trying to catch an exception doesn't work as pytest has its own exception handling which handles things before we'd hit my own:

@pytest.fixture
def my_fixture(request):
    ...
    try:
        yield
    except Exception as e:
        raise e
    else:
        db.write('new_value')

I've also tried inspecting the pytest request object, but it doesn't seem to have what I want

I suspect doing things this way doesn't follow the philosophy of pytest, so I'll probably end up doing things a different way in reality, but I'm interested to know the answer nonetheless :)


Solution

  • You can introspect the test context by requesting the request object in the fixture. There you can get request.session.testsfailed

    @pytest.fixture
    def my_fixture(request):
        failed_count = request.session.testsfailed
        yield
        if request.session.testsfailed > failed_count:
            print("this test failed")