1、失败截图
一般会把失败截图放在conftest.py文件内,运行时,只要检测到用例实例,就调用该方法
from selenium import webdriver
import pytest
driver = None
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""当测试失败的时候,自动截图,展示到html报告中"""
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"
screen_img = _capture_screenshot()
if file_name:
html = '
'onclick="window.open(this.src)" align="right"/>
extra.append(pytest_html.extras.html(html))
report.extra = extra
def _capture_screenshot():
"""截图保存为base64,展示到html中 """
return driver.get_screenshot_as_base64()
@pytest.fixture(scope='session', autouse=True)
def browser():
global driver
if driver is None:
driver = webdriver.Chrome()
return driver
如果未安装selenium,可以在file->setting->project:pytest-> Project Interprester 这个会话中,双击pip,在搜索框中输入selenium 然后点击左下方install 即可
生成报告:pytest --html=./report/report.html --self-contained-html
如果遇到如下:AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_base64'错误,可能是因为未对想打开的浏览器中添加相应版本的driver驱动
谷歌驱动下载地址:http://chromedriver.storage.googleapis.com/index.html
为了方便可直接将谷歌浏览器驱动chromedriver.exe放到项目的目录下
执行命令后生成报告
2、 失败重试
失败重试需要依赖插件pytest-rerunfailures插件
执行:pip install pytest-rerunfailures 命令安装
用例失败再重跑n次,命令行增加参数--reruns n 其中n是次数 默认是0次
pytest --reruns 1 --html=./report/report.html --self-contained-html
添加延迟n秒再重跑1次,命令行增加参数 --reruns-delay=n 其中n是多少秒
pytest --reruns=1 --reruns-delay=3 --html=./report/report.html --self-contained-html