pytest UI自動化 失敗截圖


分享一個使用pytest失敗自動截圖的方法

1. 功能當用例運行失敗時,在當前界面截圖並保存到測試報告中。

  支持pytest-html

  支持allure

代碼如下:

_driver = None

@pytest.fixture(scope="function")
def driver(request):
    global _driver
    _driver = init_driver()

    def fin():
        _driver.quit()

    request.addfinalizer(fin)
    return _driver


# 如果用例執行失敗,截圖
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    pytest_html = item.config.pluginmanager.getplugin("html")
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, "extra", [])

    if report.when == "call" or report.when == "setup":
        xfail = hasattr(report, "wasxfail")
        if (report.skipped and xfail) or (report.failed and not xfail):
            file_name = report.nodeid.replace("::", "_") + ".png"
            if file_name and _driver:
                screen_img = _driver.get_screenshot_as_base64()
                html = (
                    '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" '
                    'onclick="window.open(this.src)" align="right"/></div>' % screen_img
                )
                extra.append(pytest_html.extras.html(html))

                allure.attach(
                    _driver.get_screenshot_as_png(), "失敗截圖", allure.attachment_type.PNG
                )

        report.extra = extra
        report.description = str(item.function.__doc__)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM