問題
這兩天在測試過程中發現使用pytest.mark.parametrize參數化裝飾器測試完成后生成的報告有亂碼情況
注意事項:本文中使用的pytest和pytest-html版本
- pytest 5.4.1
- pytest-html 2.1.1
代碼展示
@pytest.mark.parametrize("name",["文化活動", "招商合作", "專題專欄"])
def test_003(self, drivers, name):
"""活動新建並審核""
pass
使用pytest運行后生成的報告展示
檢查
問題出現了,參數化后生成的TEST_ID是亂碼,我檢查了我的conftest.py代碼是這樣子的
@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
"""
當測試失敗的時候,自動截圖,展示到html報告中
:param item:
"""
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if report.when == 'call' or report.when == "setup":
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
file_name = report.nodeid.replace("::", "_") + ".png"
screen_img = _capture_screenshot()
if file_name:
html = '<div><img src="data:image/png;base64,%s" alt="screenshot" style="width:600px;height:300px;" ' \
'onclick="window.open(this.src)" align="right"/></div>' % screen_img
extra.append(pytest_html.extras.html(html))
report.extra = extra
report.description = str(item.function.__doc__)
report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")
對比上海悠悠的博客說明,沒有什么問題
博客鏈接: https://www.cnblogs.com/yoyoketang/p/9749050.html
追溯問題
問題依然存在,於是我翻看pytest-html源碼,在plugin.py文件里面瞧出了端倪,找到了下面一段話
class TestResult:
def __init__(self, outcome, report, logfile, config):
self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")
if getattr(report, "when", "call") != "call":
self.test_id = "::".join([report.nodeid, report.when])
最新版的源碼中已經有轉碼語句了
self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")
這行轉碼了與conftest.py轉碼語句發生了沖突,所以嘗試一下解決
解決問題
把conftest.py文件中的轉碼語句進行了注釋
# report.nodeid = report.nodeid.encode("utf-8").decode("unicode_escape")
重新運行代碼並生成報告
發現亂碼的那些文字已經成功顯示為中文了!!!問題解決
失敗的用例
上面這三個都是執行通過的,顯示中文正常,接着測試一下執行失敗的
給其中一個用例加入失敗語句,然后執行
可以看到結果依然顯示為中文
在命令行中亂碼
在conftest.py
文件中增加下面的函數。
def pytest_collection_modifyitems(items):
# item表示每個測試用例,解決用例名稱中文顯示問題
for item in items:
item.name = item.name.encode("utf-8").decode("unicode-escape")
item._nodeid = item._nodeid.encode("utf-8").decode("unicode-escape")
結果展示
結果
說明通過對一行代碼的注釋,我們已經解決了在pytest.mark.parametrize參數化時,生成的pytest-html報告里中文顯示亂碼的問題。