1、失敗截圖
一般會(huì)把失敗截圖放在conftest.py文件內(nèi),運(yùn)行時(shí),只要檢測(cè)到用例實(shí)例,就調(diào)用該方法
from selenium import webdriver
import pytest
driver = None
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
? ? """當(dāng)測(cè)試失敗的時(shí)候,自動(dòng)截圖,展示到html報(bào)告中"""
? ? 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 = '<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))
? ? ? ? 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? 這個(gè)會(huì)話中,雙擊pip,在搜索框中輸入selenium 然后點(diǎn)擊左下方install 即可
生成報(bào)告:pytest --html=./report/report.html --self-contained-html
如果遇到如下:AttributeError: 'NoneType' object has no attribute 'get_screenshot_as_base64'錯(cuò)誤,可能是因?yàn)槲磳?duì)想打開的瀏覽器中添加相應(yīng)版本的driver驅(qū)動(dòng)

谷歌驅(qū)動(dòng)下載地址:http://chromedriver.storage.googleapis.com/index.html
為了方便可直接將谷歌瀏覽器驅(qū)動(dòng)chromedriver.exe放到項(xiàng)目的目錄下


執(zhí)行命令后生成報(bào)告

2、? 失敗重試
失敗重試需要依賴插件pytest-rerunfailures插件
執(zhí)行:pip install pytest-rerunfailures 命令安裝
用例失敗再重跑n次,命令行增加參數(shù)--reruns n 其中n是次數(shù) 默認(rèn)是0次
pytest --reruns 1 --html=./report/report.html --self-contained-html

添加延遲n秒再重跑1次,命令行增加參數(shù) --reruns-delay=n 其中n是多少秒
pytest --reruns=1 --reruns-delay=3 --html=./report/report.html --self-contained-html
