分享一個使用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__)