第一次失败时测试停止

我使用的是 pytest,测试执行应该一直运行到遇到异常为止。如果测试从未遇到异常,那么它应该在余下的时间内继续运行,或者直到我给它发送 SIGINT/SIGTERM。

是否有一种编程方式告诉 pytest在第一次失败时停止运行,而不是必须在命令行执行此操作?

39293 次浏览
pytest -x           # stop after first failure
pytest --maxfail=2  # stop after two failures

See the pytest documentation.

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.

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