BobDoolittle
BobDoolittle

Reputation: 1750

How to take action on a test failure with pytest?

I'm using pytest.

I would like to gather/save some data for postmortem analysis on a test failure. I can write a teardown_method, but I don't see a way to obtain test status in that context.

Is it possible to take an action on any test (or assertion) failure?

Upvotes: 11

Views: 12957

Answers (2)

Bruno Oliveira
Bruno Oliveira

Reputation: 15255

Implement a pytest_exception_interact in a conftest.py file, which according to the documentation:

called when an exception was raised which can potentially be interactively handled.

def pytest_exception_interact(node, call, report):
    if report.failed:
        # call.excinfo contains an ExceptionInfo instance

It's not clear from your question exactly what you want to gather from the error, but probably having access to an ExceptionInfo instance should be enough for your case.

Upvotes: 17

tex
tex

Reputation: 43

You can also do it in the second half of a yield fixture:

https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures

Upvotes: 4

Related Questions