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報告展示中文,效果如下:

