8.pytest_失败截图和重跑机制

做web自动化时候经常希望在html报告中展示失败后的截图,提升报告的档次,pytest-html也可以生成带截图的报告。

失败截图

1.失败截图可以写到conftest.py文件里,这样用例运行时,只要检测到用例实例,就调用截图的方法,并且把截图存到html报告上;

rom selenium import webdriver
import pytest
import os

driver = None


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    当测试失败的时候,自动截图,展示到html报告中
    :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):
            file_name = report.nodeid.replace("::", "_")+".png"
            screen_img = _capture_screenshot()
            if file_name:
                html = '
screenshot \ 'οnclick="window.open(this.src)" align="right"/>
'
% screen_img extra.append(pytest_html.extras.html(html)) report.extra = extra def _capture_screenshot(): ''' 截图保存为base64,展示到html中 :return: ''' return driver.get_screenshot_as_base64() @pytest.fixture(scope='session', autouse=True) def browser(request): global driver if driver is None: driver = webdriver.Chrome() def end(): driver.quit() request.addfinalizer(end) return driver
  1. 测试用例如下:
#test_01.py
import time


def test_01(browser):

    browser.get("https://blog.csdn.net/qq_34400745")
    time.sleep(2)
    t = browser.title
    assert t == "安小静"



test_02.py

mport time


def test_02(browser):

    browser.get("https://blog.csdn.net/qq_34400745")
    time.sleep(2)
    t = browser.title
    assert "静静" in t
  1. 执行测试用例并生成测试报告:
pytest --html=report.html --self-contained-html
  1. 生成的测试报告如下:
    8.pytest_失败截图和重跑机制_第1张图片

失败重试

在web、APP⾃动化测试中,经常出现超时导致测试失败

  1. 失败重跑需要依赖pytest-rerunfailures插件,使用pip安装就行
pip install pytest-rerunfailures
  1. 执行重试需要--reruns 重跑次数
    下面是重跑两次
py.test --reruns 2 --html=report.html --self-contained-html

关于reruns参数的2个用法:
可以在重试时间中间增加延迟时间:

re-run failing tests to eliminate flaky failures:
  --reruns=RERUNS       number of times to re-run failed tests. defaults to 0.
  --reruns-delay=RERUNS_DELAY
                        add time (seconds) delay between reruns.

你可能感兴趣的:(Pytest)