pytest文檔8-html報告報錯截圖+失敗重跑

前言

作web自動化的小夥伴應該都但願在html報告中展現失敗後的截圖,提高報告的檔次,pytest-html也能夠生成帶截圖的報告。html

conftest.py

1.失敗截圖能夠寫到conftest.py文件裏,這樣用例運行時,只要檢測到用例實例,就調用截圖的方法,而且把截圖存到html報告上node

# conftest.py文件
# coding:utf-8

from selenium import webdriver
import pytest


driver = None

@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    當測試失敗的時候,自動截圖,展現到html報告中
    ** 做者:上海-悠悠 QQ交流羣:588402570**
    :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():
    '''
    ** 做者:上海-悠悠 QQ交流羣:588402570**
    截圖保存爲base64,展現到html中
    :return:
    '''
    return driver.get_screenshot_as_base64()


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

2.用例部分以下:web

# test_01.py文件

from selenium import webdriver
import time

#** 做者:上海-悠悠 QQ交流羣:588402570**

def test_yoyo_01(browser):

    browser.get("https://www.cnblogs.com/yoyoketang/")
    time.sleep(2)
    t = browser.title
    assert t == "上海-悠悠"

# test_02.py文件

from selenium import webdriver
import time

# ** 做者:上海-悠悠 QQ交流羣:588402570**

def test_yoyo_01(browser):

    browser.get("https://www.cnblogs.com/yoyoketang/")
    time.sleep(2)
    t = browser.title
    assert "上海-悠悠" in t

報告展現

1.cmd打開,cd到用例的目錄,執行指令session

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

2.生成報告以下測試

失敗重試

失敗重跑須要依賴pytest-rerunfailures插件,使用pip安裝就行this

$ pip install pytest-rerunfailures插件

用例失敗再重跑1次,命令行加個參數--reruns就好了命令行

$ py.test --reruns 1 --html=report.html --self-contained-html3d

關於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結合selenium自動化完整版-------------------------

全書購買地址 https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b

做者:上海-悠悠 QQ交流羣:874033608

也能夠關注下個人我的公衆號:yoyoketang

相關文章
相關標籤/搜索