【pytest-10】report报告+失败重跑

前言

做web自动化的小伙伴应该都希望在html报告中展示失败后的截图,提升报告的档次,pytest-html也可以生成带截图的报告

conftest.py

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

#encoding:utf-8
#@Time:2020/11/30 13:54
#@Author:sunny


from selenium import webdriver
import pytest

#调用谷歌驱动
driver = webdriver.Chrome()

@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 = '<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:
    '''
    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

test_001.py

#encoding:utf-8
#@Time:2020/12/1 15:44
#@Author:sunny

from selenium import webdriver
import time

def test_xiaoxiao_01(browser):

    browser.get("https://www.cnblogs.com/june-/")
    time.sleep(2)
    t = browser.title
    assert t == "做一只热爱生活的小透明"

test_002.py

#encoding:utf-8
#@Time:2020/12/1 15:45
#@Author:sunny

from selenium import webdriver
import time


def test_xiaoxiao_02(browser):

    browser.get("https://www.cnblogs.com/june-/")
    time.sleep(2)
    t = browser.title
    assert "做一只热爱生活的小透明" in t

切换到项目所在的根目录运行:

pytest --html=report.html --self-contained-html

 生成报告如下:

 失败重试

失败重跑需要依赖pytest-rerunfailures插件,使用pip安装就行

pip install pytest-rerunfailures

  用例失败再重跑1次,命令行加个参数--reruns就行了

 关于reruns参数的2个用法

re-run failing tests to eliminate flaky failures:

--reruns=重新运行失败测试的次数。默认为0。
--reruns delay=重播延迟
添加重新运行之间的时间(秒)延迟。

 

posted @ 2020-12-01 18:03  做一只热爱生活的小透明  阅读(217)  评论(0)    收藏  举报