nercon 2019-12-27
看pytest-html官方说明
地址 https://github.com/pytest-dev/pytest-html#creating-a-self-contained-report
官方文档表示,html的内容支持HTML,json,jpg,url等多种形式。还举例说明。注意下面标记的地方,是报告内容变更需要我们替换的
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin(‘html‘) outcome = yield report = outcome.get_result() extra = getattr(report, ‘extra‘, []) if report.when == ‘call‘: # always add url to report # screen = _capture_screenshot() filename = os.path.join(rootpath, ‘screen.png‘) #获取截图文件位置 extra.append(pytest_html.extras.png(filename)) #传入文件地址 xfail = hasattr(report, ‘wasxfail‘) if (report.skipped and xfail) or (report.failed and not xfail): # only add additional html on failure extra.append(pytest_html.extras.html(‘<div>Additional HTML</div>‘)) report.extra = extra def _capture_screenshot(): return driver.get_screenshot_as_file(‘screen.png‘) # 截图并保存
运行 pytest --html=report.html,发现代码报错,
再看官方文档,发现给出了说明
命令行更改运行方式: pytest --html=report.html --self-contained-html
发现运行成功,但是有warning
报告截图是有的
官方文档表明存入png格式为:extra.png(image),可能是因为我直接传的文件地址导致的问题
于是修改截图存入的数据,改为base64
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin(‘html‘) outcome = yield report = outcome.get_result() extra = getattr(report, ‘extra‘, []) if report.when == ‘call‘: # always add url to report screen = _capture_screenshot() # 修改后的代码 # filename = os.path.join(rootpath, ‘screen.png‘) extra.append(pytest_html.extras.png(screen)) # 修改后的代码 xfail = hasattr(report, ‘wasxfail‘) if (report.skipped and xfail) or (report.failed and not xfail): # only add additional html on failure extra.append(pytest_html.extras.html(‘<div>Additional HTML</div>‘)) report.extra = extra def _capture_screenshot(): return driver.get_screenshot_as_base64() # 修改后的代码
运行 pytest --html=report.html --self-contained-html
有warning了,截图也成功
现在我们将截图的代码调整到失败判断中,只有失败的用例才需要截图
执行命令 pytest --html=report.html --self-contained-html
只有失败的用例才会截图啦
最后源码为
from selenium import webdriver import pytest driver = None @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin(‘html‘) outcome = yield report = outcome.get_result() extra = getattr(report, ‘extra‘, []) if report.when == ‘call‘: xfail = hasattr(report, ‘wasxfail‘) if (report.skipped and xfail) or (report.failed and not xfail): screen = _capture_screenshot() extra.append(pytest_html.extras.png(screen)) # only add additional html on failure extra.append(pytest_html.extras.html(‘<div>Additional HTML</div>‘)) report.extra = extra def _capture_screenshot(): return driver.get_screenshot_as_base64() @pytest.fixture(scope=‘session‘, autouse=True) def browser(): global driver if driver is None: driver = webdriver.Firefox() return driver