长时间运行的py.test在第一次失败时停止

2024-04-28 11:08:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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


Tags: 方法命令行pytest编程时间sigtermsigint
3条回答
pytest -x             # stop after first failure
pytest --maxfail=2    # stop after two failures

请参阅http://pytest.org/en/latest/usage.html上的文档

pytest具有选项-x--exitfirst,该选项在第一个错误或失败的测试时立即停止执行测试。

pytest还有一个选项--max-fail=num,其中num表示停止执行测试所需的错误或失败数。

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

您可以在pytest.ini文件中使用addopts。它不需要调用任何命令行开关。

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

也可以在运行测试之前设置环境变量“PYTEST_ADDOPTS”。

如果要在第一次失败后使用python代码退出,可以使用以下代码:

import pytest

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

此代码将exit_pytest_first_failure fixture应用于所有测试,并在第一次失败时退出pytest。

相关问题 更多 >