一、html报告错误截图
这次介绍pytest第三方插件pytest-html
这里不介绍怎么使用,因为怎么使用网上已经很多了,这里给个地址给大家参考,pytest-html生成html报告
今天在这里介绍pytest生成的报告怎么带有截图,这在web自动化测试非常有用。
需求是测试用例错误就截图,方法如下:
我们要新建一个关于截图的插件文件conftest.py,注意,文件名不能变,因为pytest-html会自动找这个自己写的插件,内容如下:
from selenium importwebdriverimportpytest
driver=None
@pytest.mark.hookwrapperdefpytest_runtest_makereport(item):"""Extends the PyTest Plugin to take and embed screenshot in html report, whenever test fails.
:param item:"""pytest_html= item.config.pluginmanager.getplugin('html')
outcome= yieldreport=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 notxfail):
file_name= report.nodeid.replace("::", "_")+".png"_capture_screenshot(file_name)iffile_name:
html= '
extra.append(pytest_html.extras.html(html))
report.extra=extradef_capture_screenshot(name):
driver.get_screenshot_as_file(name)
@pytest.fixture(scope='session', autouse=True)defbrowser():globaldriverif driver isNone:
driver=webdriver.Firefox()return driver
关于conftest.py文件怎么应用,可以查看文档:conftest.py how to put
接下来,就是写用例了,在与conftest当前文件夹下写用例文件test_aa.py,如下
deftest_screenshot_on_test_failure(browser):
browser.get("https://www.baidu.com")assert False
然后再次用pytest运行,运行方式如下:
E:\>pytest -s -v test_aa.py --html=report.html
然后我们可以在E盘下看到生成了report.html文件及测试用例为名的png截图文件
打开html文件,详情如下:
参考:
二、失败重试
使用的插件是pytest-rerunfailures,官网这里
使用方法:
在测试时加入–rerun参数
py.test --rerun 2用例失败再重测2次