前言
pytest-html測試報告默認是不展示用例描述Description內容,之前用unittest生成的報告是可以展示用例的描述,也就是test開頭的用例下三個引號里面的注釋(docstring)內容。
pytest-html框架是可以修改生成的報告內容的,可以自己添加和刪除html報告的table內容。
修改報告
pytest-html官方文檔地址【https://pypi.org/project/pytest-html/】
l可以通過為標題行實現自定義鈎子來修改列,下面的示例在conftest.py腳本中使用測試函數docstring添加描述(Description)列,添加可排序時間(Time)列,並刪除鏈接(Link)列:
from datetime import datetime
from py.xml import html
import pytest
@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
cells.insert(2, html.th('Description'))
cells.insert(1, html.th('Time', class_='sortable time', col='time'))
cells.pop()
@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
cells.insert(2, html.td(report.description))
cells.insert(1, html.td(datetime.utcnow(), class_='col-time'))
cells.pop()
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__)
還可以通過pytest_html_results_table_row 掛鈎刪除所有單元格來刪除結果。下面的示例從報表中刪除所有測試通過的結果:
import pytest
@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
if report.passed:
del cells[:]
日志輸出和附加HTML可以通過pytest_html_results_table_html掛鈎來修改。下面的示例清空測試通過的日志輸出:
import pytest
@pytest.mark.optionalhook
def pytest_html_results_table_html(report, data):
if report.passed:
del data[:]
data.append(html.div('No log output captured.', class_='empty log'))
添加Description
通過上面的官方文檔,可以自己修改下測試報告,在報告里面添加一列的內容,添加到第二列,於是修改如下,紅色代碼全部注釋掉
第三個@pytest.mark.hookwrapper,這個在之前測試報告里面添加截圖時候,已經寫過了,只需在最后加一句代碼即可
report.description = str(item.function.doc)
代碼參考
from datetime import datetime
from py.xml import html
import pytest
@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
report.description = str(item.function.__doc__)
@pytest.mark.optionalhook
def pytest_html_results_table_header(cells):
cells.insert(1, html.th('Description'))
@pytest.mark.optionalhook
def pytest_html_results_table_row(report, cells):
cells.insert(1, html.td(report.description))
效果展示
修改完之后cmd運行
pytest --html=report.html --self-contained-html
---------------------------------pytest結合selenium自動化完整版-------------------------
全書購買地址 https://yuedu.baidu.com/ebook/902224ab27fff705cc1755270722192e4536582b
作者:上海-悠悠 QQ交流群:874033608
也可以關注下我的個人公眾號:yoyoketang