Python2--Pytest_html测试报告优化(解决中文输出问题)
1、报告的输出:
pytest.main(["-s","Auto_test.py","--html=Result_test.html"])
2、此时输出的报告为英文版,如果需要在用例中加上中文描述,需要参数化的修饰器中,添加参数ids,举例如下:
@pytest.mark.parametrize("devtype,mac,dev_servaddr",dev_method_data,ids = [u"中文描述"])
3、此时直接执行用例,输出的报告,该字段显示为\x....,查看编码方式为ascii编码
4、为了将中文显示出来,需要修改编码方式,尝试在html下的plugs.py修改report.nodeid,发现encode("utf-8")编码无效,编码后还是ascii
5、根据官方给出的文档,发现可以在conftest.py文件中,自定义添加删除修改列内容,于是创建conftest.py,源码如下
#coding=utf-8 from datetime import datetime from py.xml import html import pytest import re import sys reload(sys) sys.setdefaultencoding('utf8') @pytest.mark.hookwrapper def pytest_runtest_makereport(item): ''' 修改Description里面的内容,增加中文显示 ''' # pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape") @pytest.mark.optionalhook def pytest_html_results_table_header(cells): cells.insert(1, html.th('Description')) # cells.insert(2, html.th('Test_nodeid')) # cells.insert(1, html.th('Time', class_='sortable time', col='time')) cells.pop(2) @pytest.mark.optionalhook def pytest_html_results_table_row(report, cells): cells.insert(1, html.td(report.nodeid)) # cells.insert(2, html.td(report.nodeid)) # cells.insert(1, html.td(datetime.utcnow(), class_='col-time')) cells.pop(2)
6、注意以上使用sys包,修改默认编码方式为utf8
import sys reload(sys) sys.setdefaultencoding('utf8')
7、进一步优化,因为输出的report.nodeid包含了文件名,测试类名,测试函数名,为了更直观的展示用例描述,以下可以将描述输出进一步优化
#coding=utf-8 from datetime import datetime from py.xml import html import pytest import re import sys reload(sys) sys.setdefaultencoding('utf8') @pytest.mark.hookwrapper def pytest_runtest_makereport(item): ''' 修改Description里面的内容,增加中文显示 ''' # pytest_html = item.config.pluginmanager.getplugin('html') outcome = yield report = outcome.get_result() _description = "" report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape") for i in range(len(report.nodeid)): if report.nodeid[i] == "[": _description = report.nodeid[i+1:-1] report._nodeid = _description @pytest.mark.optionalhook def pytest_html_results_table_header(cells): cells.insert(1, html.th('Description')) # cells.insert(2, html.th('Test_nodeid')) # cells.insert(1, html.th('Time', class_='sortable time', col='time')) cells.pop(2) @pytest.mark.optionalhook def pytest_html_results_table_row(report, cells): cells.insert(1, html.td(report._nodeid)) # cells.insert(2, html.td(report.nodeid)) # cells.insert(1, html.td(datetime.utcnow(), class_='col-time')) cells.pop(2)
8、最后pytest_html报告展示中文,效果如下: