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文件夹下)

posted on 2020-07-04 14:58  QiKa  阅读(783)  评论(0编辑  收藏  举报