Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest: how to take action on test failure?

Tags:

python

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?

like image 856
BobDoolittle Avatar asked Jan 28 '15 17:01

BobDoolittle


People also ask

How do you run failed test cases in pytest?

The plugin provides two command line options to rerun failures from the last pytest invocation: --lf , --last-failed - to only re-run the failures. --ff , --failed-first - to run the failures first and then the rest of the tests.

How do I ignore a test in pytest?

The simplest way to skip a test function is to mark it with the skip decorator which may be passed an optional reason : @pytest. mark.

Are pytest fixtures cached?

Pytest only caches one instance of a fixture at a time, which means that when using a parametrized fixture, pytest may invoke a fixture more than once in the given scope.

Can pytest take arguments?

Summary. You can pass arguments to fixtures with the params keyword argument in the fixture decorator, and you can also pass arguments to tests with the @pytest. mark. parametrize decorator for individual tests.


2 Answers

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.

like image 142
Bruno Oliveira Avatar answered Sep 18 '22 16:09

Bruno Oliveira


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

like image 34
tex Avatar answered Sep 22 '22 16:09

tex