一、html報告錯誤截圖
這次介紹pytest第三方插件pytest-html
這里不介紹怎么使用,因為怎么使用網上已經很多了,這里給個地址給大家參考,pytest-html生成html報告
今天在這里介紹pytest生成的報告怎么帶有截圖,這在web自動化測試非常有用。
需求是測試用例錯誤就截圖,方法如下:
我們要新建一個關於截圖的插件文件conftest.py,注意,文件名不能變,因為pytest-html會自動找這個自己寫的插件,內容如下:
from selenium import webdriver import pytest 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): file_name = 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_name 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.Firefox() return driver
關於conftest.py文件怎么應用,可以查看文檔:conftest.py how to put
接下來,就是寫用例了,在與conftest當前文件夾下寫用例文件test_aa.py,如下
def test_screenshot_on_test_failure(browser): browser.get("https://www.baidu.com") assert False
然后再次用pytest運行,運行方式如下:
E:\>pytest -s -v test_aa.py --html=report.html
然后我們可以在E盤下看到生成了report.html文件及測試用例為名的png截圖文件
打開html文件,詳情如下:

參考:
https://pypi.python.org/pypi/pytest-html
二、失敗重試
使用的插件是pytest-rerunfailures,官網這里
使用方法:
在測試時加入--rerun參數
py.test --rerun 2
用例失敗再重測2次
