有条件地提前退出 Pytest 中的完整测试套件
Conditional early exit from full test suite in Pytest
我有一个参数化的 pytest 测试套件。每个参数都是一个特定的网站,测试套件 运行s 使用 Selenium 自动化。考虑参数后,我总共有数百个测试,而且它们都是运行顺序。
每周一次,Selenium 会因为各种原因而失败。连接丢失,无法实例化 chrome 实例等。如果它在测试 运行 中失败一次,它将导致所有即将进行的测试崩溃。这是一个失败日志示例:
test_example[parameter] failed; it passed 0 out of the required 1 times.
<class 'selenium.common.exceptions.WebDriverException'>
Message: chrome not reachable
(Session info: chrome=91.0.4472.106)
[<TracebackEntry test.py:122>, <TracebackEntry another.py:92>, <TracebackEntry /usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py:669>, <TracebackEntry /usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py:321>, <TracebackEntry /usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py:242>]
理想情况下,我希望在发生 Selenium 故障时立即退出套件,因为我知道所有即将进行的测试也会失败。
有没有这种方法:
def pytest_on_test_fail(err): # this will be a pytest hook
if is_selenium(err): # user defined function
pytest_earlyexit() # this will be a pytest function
或者其他一些机制,可以让我根据检测到的情况提前退出完整的测试套件。
经过更多测试后,我让它工作了。这使用 pytest_exception_interact
hook and the pytest.exit
函数。
WebDriverException 是所有 Selenium 问题的父 class(参见 source code)。
def pytest_exception_interact(node, call, report):
error_class = call.excinfo.type
is_selenium_issue = issubclass(error_class, WebDriverException)
if is_selenium_issue:
pytest.exit('Selenium error detected, exiting test suite early', 1)
我有一个参数化的 pytest 测试套件。每个参数都是一个特定的网站,测试套件 运行s 使用 Selenium 自动化。考虑参数后,我总共有数百个测试,而且它们都是运行顺序。
每周一次,Selenium 会因为各种原因而失败。连接丢失,无法实例化 chrome 实例等。如果它在测试 运行 中失败一次,它将导致所有即将进行的测试崩溃。这是一个失败日志示例:
test_example[parameter] failed; it passed 0 out of the required 1 times.
<class 'selenium.common.exceptions.WebDriverException'>
Message: chrome not reachable
(Session info: chrome=91.0.4472.106)
[<TracebackEntry test.py:122>, <TracebackEntry another.py:92>, <TracebackEntry /usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py:669>, <TracebackEntry /usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/webdriver.py:321>, <TracebackEntry /usr/local/lib/python3.7/site-packages/selenium/webdriver/remote/errorhandler.py:242>]
理想情况下,我希望在发生 Selenium 故障时立即退出套件,因为我知道所有即将进行的测试也会失败。
有没有这种方法:
def pytest_on_test_fail(err): # this will be a pytest hook
if is_selenium(err): # user defined function
pytest_earlyexit() # this will be a pytest function
或者其他一些机制,可以让我根据检测到的情况提前退出完整的测试套件。
经过更多测试后,我让它工作了。这使用 pytest_exception_interact
hook and the pytest.exit
函数。
WebDriverException 是所有 Selenium 问题的父 class(参见 source code)。
def pytest_exception_interact(node, call, report):
error_class = call.excinfo.type
is_selenium_issue = issubclass(error_class, WebDriverException)
if is_selenium_issue:
pytest.exit('Selenium error detected, exiting test suite early', 1)