—— Pytest基礎使用教程【2】
從測驗報告說起
承接上一篇中最后的測驗結果圖,使用過的pytest-html 插件原生態的報告的話,可能會發現 內容樣式都有些不同,其實是做了些擴展相關設定所呈現的效果,當然可以定制的更深度一些,更加中文、本地化,又或者根據公司需要進行定向研發,例如就上文中的測驗報告進行一些中文定制改造后效果如下圖所示,這篇就如何優化、定制pytest-html 測驗報告進行些講解

Pytest-html 擴展
目前最新的 pytest-html版本為2.1.1 ,這個版本共提供 5個Hook,分別是:
def pytest_html_report_title(report)
設定測驗報告的標題
def pytest_html_results_summary(prefix, summary, postfix)
在Summary部分,添加自定義內容
def pytest_html_results_table_header(cells)
定制 Result 部分,表單的頭部
def pytest_html_results_table_row(report, cells)
定制Result部分,每行測驗Case的內容
def pytest_html_results_table_html(report, data)
在完成Result渲染后,詳情新增寫HTMl標記語言內容
測驗報告Title
所謂Title指代的是報告圖中【豆瓣網自動化測驗示例(基于Pytest)】行文字內容,Report 其實是 插件的HTMLReport物件,簡單看下原始碼,相信使用上就能很好的把握理解,關鍵部分見紅框

所以,這個擴展而言只需要 conftest.py 對于擴展hook中設定下report title欄位就能夠,按需修改標題,
@pytest.hookimpl(optionalhook=True)
def pytest_html_report_title(report):
report.title = "豆瓣網自動化測驗示例(基于Pytest)"
擴展Summary部分
Summary擴展設計,允許對于 整個模塊進行定制,分為前(prefix)、中(summary)、后(postfix)三個部分進行設定,同樣的 看下原始碼,更好的把握如何來使用,關鍵部分見紅框

其實,就是把 前中后三個部分的html拼接起來,中部(summary) 會有些插件默認的html內容,

所以,擴展使用上就很明晰了,只需要把html設定進去即可,
@pytest.hookimpl(optionalhook=True)
def pytest_html_results_summary(prefix, summary, postfix):
prefix.extend([html.p("測驗人: 姜子軒")])
Result 表格的擴展
可以分成兩部分,一部分是表頭的設定,同樣的通過 cells 來生成 Result 表格的頭部,

看完上述原始碼相信,pytest_html_results_table_header 使用上就非常明確了,主要就是對cells進行操作,
@pytest.hookimpl(optionalhook=True)
def pytest_html_results_table_header(cells):
cells.insert(2, html.th('模塊'))
cells.insert(3, html.th('描述'))
cells.insert(4, html.th('時間', class_='sortable time', col='time'))
cells.pop()
對于每一行資料進行擴展上,也就是 pytest_html_results_table_row、pytest_html_results_table_html,這兩個的使用,同樣先看下原始碼,

其中兩個函式的關鍵點在于 report 引數,cells 與 data用來制定擴展的html標簽,而內容上通過 report 來進行透傳,所以 這里一般會結合pytest內置的hook來使用,pytest_runtest_makereport,具體來說如下:

具體代碼演示,
@pytest.hookimpl(optionalhook=True)
def pytest_html_results_table_row(report, cells):
cells.insert(2, html.td(report.module))
cells.insert(3, html.td(report.description))
cells.insert(4, html.td(datetime.utcnow(), class_='col-time'))
cells.pop()
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
report.description = str(item.function.__doc__)
report.module = str(item.module.__doc__)
深度定制
以上內容,可以看到Pytest-html v2.1.2版本 提供的全部擴展功能,能夠對 title、summary、table 進行內容擴展研發,不過,無法實作本文最前面全中文報告,所以 想要完美 的根據公司、業務需求改造,這里提供一個思路方法可以將 Pytest-html 原始碼下載下來進行改造,其 整體的實作并不復雜,主要邏輯 在 plugin.py 里面,

其中,整個報告的生成 在 _generate_report 函式 中,在本篇中就不深入來說實作,計劃在后續 pytest插件研發、Pytest-html實作中進一步分享
如果對本文 深度定制中文版報告 改造或者 是上文中擴展原始碼有興趣的可以關注 公眾號私信交流,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/141153.html
標籤:Python
上一篇:Java集合多執行緒安全
下一篇:寫個基于WSGI的web框架
