自动化工具 pytest 框架修改 html 报告插入描述列和获取用例描述

steven · 2018年09月25日 · 1785 次阅读

unittest 框架是有实现读取用例的描述功能的,在运行的时候就可以显示出来,也可以在 html 报告中显示,规则是在 test_method 下面用 ‘’‘ ’‘’ 注释。

初用 pytset 框架直接运行我的 unittest 用例,生成了 html 报告,发现描述不见了,百度了一圈没有找到相关文章提及此事。

去 pypi 上看 pytest-html 的主页(https://pypi.org/project/pytest-html/conftest.py 上实现),直接贴出来:),终于找到了插入一列的方法(在

from datetime import datetime
from py.xml import html
import pytest

@user1hook
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()

@user2hook
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()

@user3per
def pytest_runtest_makereport(item, call):
    outcome = yield
    report = outcome.get_result()
    report.description = str(item.function.__doc__)

这里要修改的是获取描述的部分,在 pytest_runtest_makereport 接口里传入的 item,我的 unittest case 并没有找到这个 function 的变量,所以我打断点找了一下,发现是在 item._testcase._testMethodDoc 的变量里存放的用例描述,把它赋值给 report.description 即可。这里还有一点要注意,pytest_runtest_makereport 会多次被调用,setup 时,teardown 时,在 teardown 时调用,就没有_testMethodDoc 这个变量,这里会有空指针的错。所以我用 report.when 的值判断了一下:if report.when == 'call' or report.when == "setup":

效果图就不上了,就是 results 列表中多了一列 Discription。

共收到 0 条回复 时间 点赞
1楼 已删除
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册