Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

long running py.test stop at first failure

Tags:

python

pytest

I am using pytest, and the test execution is supposed to run until it encounters an exception. If the test never encounters an exception it should continue running for the rest of time or until I send it a SIGINT/SIGTERM.

Is there a programmatic way to tell pytest to stop running on the first failure as opposed to having to do this at the command line?

like image 329
Matt Avatar asked Apr 22 '16 22:04

Matt


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 warnings in pytest?

Disabling warnings summary Although not recommended, you can use the --disable-warnings command-line option to suppress the warning summary entirely from the test run output.

How does py test work?

PyTest is a testing framework that allows users to write test codes using Python programming language. It helps you to write simple and scalable test cases for databases, APIs, or UI. PyTest is mainly used for writing tests for APIs. It helps to write tests from simple unit tests to complex functional tests.


3 Answers

pytest -x           # stop after first failure pytest --maxfail=2  # stop after two failures 

See the pytest documentation.

like image 66
Praveen Yalagandula Avatar answered Oct 14 '22 14:10

Praveen Yalagandula


pytest has the option -x or --exitfirst which stops the execution of the tests instanly on first error or failed test.

pytest also has the option --maxfail=num in which num indicates the number of errors or failures required to stop the execution of the tests.

pytest -x            # if 1 error or a test fails, test execution stops  pytest --exitfirst   # equivalent to previous command pytest --maxfail=2   # if 2 errors or failing tests, test execution stops 
like image 30
lmiguelvargasf Avatar answered Oct 14 '22 13:10

lmiguelvargasf


You can use addopts in pytest.ini file. It does not require invoking any command line switch.

# content of pytest.ini
[pytest]
addopts = --maxfail=2  # exit after 2 failures

You can also set env variable PYTEST_ADDOPTS before test is run.

If you want to use python code to exit after first failure, you can use this code:

import pytest

@pytest.fixture(scope='function', autouse=True)
def exit_pytest_first_failure():
    if pytest.TestReport.outcome == 'failed':
        pytest.exit('Exiting pytest')

This code applies exit_pytest_first_failure fixture to all test and exits pytest in case of first failure.

like image 20
SilentGuy Avatar answered Oct 14 '22 15:10

SilentGuy