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
@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_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。