看pytest-html官方說明
地址 https://github.com/pytest-dev/pytest-html#creating-a-self-contained-report
官方文檔表示,html的內容支持HTML,json,jpg,url等多種形式。還舉例說明。注意下面標記的地方,是報告內容變更需要我們替換的
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() extra = getattr(report, 'extra', []) if report.when == 'call': # always add url to report # screen = _capture_screenshot() filename = os.path.join(rootpath, 'screen.png') #獲取截圖文件位置 extra.append(pytest_html.extras.png(filename)) #傳入文件地址 xfail = hasattr(report, 'wasxfail') if (report.skipped and xfail) or (report.failed and not xfail): # only add additional html on failure extra.append(pytest_html.extras.html('<div>Additional HTML</div>')) report.extra = extra def _capture_screenshot(): return driver.get_screenshot_as_file('screen.png') # 截圖並保存
運行 pytest --html=report.html,發現代碼報錯,
再看官方文檔,發現給出了說明
命令行更改運行方式: pytest --html=report.html --self-contained-html
發現運行成功,但是有warning
報告截圖是有的
官方文檔表明存入png格式為:extra.png(image),可能是因為我直接傳的文件地址導致的問題
於是修改截圖存入的數據,改為base64
@pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() extra = getattr(report, 'extra', []) if report.when == 'call': # always add url to report screen = _capture_screenshot() # 修改后的代碼 # filename = os.path.join(rootpath, 'screen.png') extra.append(pytest_html.extras.png(screen)) # 修改后的代碼 xfail = hasattr(report, 'wasxfail') if (report.skipped and xfail) or (report.failed and not xfail): # only add additional html on failure extra.append(pytest_html.extras.html('<div>Additional HTML</div>')) report.extra = extra def _capture_screenshot(): return driver.get_screenshot_as_base64() # 修改后的代碼
運行 pytest --html=report.html --self-contained-html
有warning了,截圖也成功
現在我們將截圖的代碼調整到失敗判斷中,只有失敗的用例才需要截圖
執行命令 pytest --html=report.html --self-contained-html
只有失敗的用例才會截圖啦
最后源碼為

from selenium import webdriver import pytest driver = None @pytest.hookimpl(hookwrapper=True) def pytest_runtest_makereport(item, call): pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() extra = getattr(report, 'extra', []) if report.when == 'call': xfail = hasattr(report, 'wasxfail') if (report.skipped and xfail) or (report.failed and not xfail): screen = _capture_screenshot() extra.append(pytest_html.extras.png(screen)) # only add additional html on failure extra.append(pytest_html.extras.html('<div>Additional HTML</div>')) report.extra = extra def _capture_screenshot(): 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