【发布时间】:2016-08-16 16:42:11
【问题描述】:
我正在使用pytest,测试执行应该一直运行到遇到异常为止。如果测试从未遇到异常,它应该继续运行剩下的时间,或者直到我向它发送一个 SIGINT/SIGTERM。
是否有一种编程方式告诉pytest 在第一次失败时停止运行,而不是在命令行中执行此操作?
【问题讨论】:
-
你能展示你的代码,说明你是如何以编程方式调用 pytest 的吗?
我正在使用pytest,测试执行应该一直运行到遇到异常为止。如果测试从未遇到异常,它应该继续运行剩下的时间,或者直到我向它发送一个 SIGINT/SIGTERM。
是否有一种编程方式告诉pytest 在第一次失败时停止运行,而不是在命令行中执行此操作?
【问题讨论】:
pytest -x # stop after first failure
pytest --maxfail=2 # stop after two failures
【讨论】:
pytest 有-x 或--exitfirst 选项,可在第一个错误或测试失败时立即停止执行测试。
pytest 也有--maxfail=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 夹具应用于所有测试并在第一次失败的情况下退出 pytest。
【讨论】: