代码之家  ›  专栏  ›  技术社区  ›  Gaurang Tandon

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

  •  0
  • Gaurang Tandon  · 技术社区  · 4 年前

    我有一个参数化的pytest测试套件。每个参数都是一个特定的网站,测试套件使用Selenium automation运行。在考虑了参数之后,我总共有数百个测试,它们都是按顺序运行的。

    每周一次,硒会因各种原因失效。连接丢失,无法实例化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
    

    或者其他一些机制,可以让我根据检测到的条件提前退出完整的测试套件。

    0 回复  |  直到 4 年前
        1
  •  1
  •   Gaurang Tandon    4 年前

    经过更多的测试,我让这个工作。这使用了 pytest_exception_interact 胡克和 pytest.exit 作用 WebDriverException是所有Selenium问题的父类(请参阅 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)