pytest插件:pytest-html (執行用例失敗后,自動截圖到報告 + 失敗用例重跑)


1、先pip安裝插件: pytest-html、pytest-rerunfailures

2、用例執行失敗自動截圖到報告內 ,這個其實可以寫到conftest.py文件。
    當運行用例時遇到錯誤就會自己調用截圖方法,並把截圖存到html報告內

 

#固定腳本,可根據需要更改

from selenium import webdriver
import pytest
import os
driver = None

@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', [])

if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
dirpng=r'./report/png/'
if os.path.exists(dirpng) and os.path.isdir(dirpng):
  pass
else:
  os.mkdir(dirpng)
file_name = dirpng + report.nodeid.replace("::", "_")+".png"
file_name1=r'./png/'+ 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_name1
  extra.append(pytest_html.extras.html(html))
  report.extra = extra

def _capture_screenshot(name):
  driver.get_screenshot_as_file(name)


@pytest.fixture(scope='session', autouse=True)
def browser():
  global driver
  if driver is None:
    driver = webdriver.Chrome()
  return driver

 

 

3、失敗重跑操作(以下2種方法)
pytest --reruns 重試次數
pytest --reruns 重試次數 --reruns-delay 次數之間的延時設置(單位:秒)


例:
cmd: pytest --html=./report/test_report.html -v --reruns 2 --reruns-delay 3
(表示失敗用例重跑2次,且重跑延遲間隔時間3s,輸入報告test_report.html到用例所屬目錄的同級文件夾report文件夾下)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM