一直用unittest框架在写测试脚本,想要加入异常截图和自动重跑的功能,以前用java的时候在junit上实现过
思路就是在tearDown里判断结果是否失败,截图保存,或者是重写rule,把执行它case的地方try起来
在unittest里一样可以,比如加装饰器,也有人封装断言
加装饰器的话,还得在case方法前面加一句注解,封装断言的话更是要改case层的代码
百度一下pytest,还是靠谱
pytest支持unittest框架的case运行
下载一个pytest-rerunfailures插件,运行命令中加参数:--reruns 3,即可
导出html报告,下载pytest-html插件,加入参数:--html=report.html,搞定
异常截图就实现一个conftest.py,pytest会自己加载这个文件,生成的html报告会带有截图的链接
这样的方式,不用自己造轮子,你原来写的脚本完全不用修改,so easy
@pytest.mark.hookwrapper
def pytest_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 = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
# path = os.path.dirname(item.fspath)
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"
_capture_screenshot(file_name)
if file_name:
html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % file_name
extra.append(pytest_html.extras.html(html))
report.extra = extra
def _capture_screenshot(filepath):
DEVICE.snapshot(filepath)#在这里实现截图