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__)
鸡肉是我的最爱!