Pytest中完整测试套件的有条件提前退出



我有一个参数化的pytest测试套件。每个参数都是一个特定的网站,测试套件使用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钩子和pytest.exit函数。WebDriverException是所有Selenium问题的父类(请参阅源代码(。

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)

最新更新