pytest-html最新版中文乱码解决

问题

这两天在测试过程中发现使用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运行后生成的报告展示

img


检查

问题出现了,参数化后生成的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")

重新运行代码并生成报告

img

发现乱码的那些文字已经成功显示为中文了!!!问题解决


失败的用例

上面这三个都是执行通过的,显示中文正常,接着测试一下执行失败的

给其中一个用例加入失败语句,然后执行

img

可以看到结果依然显示为中文


结果

说明通过对一行代码的注释,我们已经解决了在pytest.mark.parametrize参数化时,生成的pytest-html报告里中文显示乱码的问题。

喜欢python自动化测试或正在学习自动化测试的同学
欢迎加入我的QQ群:299524235(python自动化测试学习)

猜你喜欢

转载自www.cnblogs.com/wxhou/p/12759332.html