pytest-html 3.2.0版本中文乱码问题

版本:pytest-html 3.2.0

代码如下:
pytest-html 3.2.0版本中文乱码问题_第1张图片
在终端执行 pytest cases --html=report.html --self-contained-html 后,

终端上显示报错信息为”UnicodeEncodeError: ‘gbk’ codec can’t encode character ‘\xe7’ in position 13974: illegal multibyte sequence“。

根据网上资料,在python安装目录下的 lib\site-packages\pytest_html\result.py 中找到下述代码【注:3.2.0之前的旧版本是在plugin.py文件里】:

class TestResult:
      def __init__(self, outcome, report, logfile, config):
          self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")

将其改为:

  class TestResult:
      def __init__(self, outcome, report, logfile, config):
          # 白月黑羽修改方法,解决乱码问题
          # self.test_id = report.nodeid.encode("utf-8").decode("unicode_escape")
          self.test_id = report.nodeid

保存后再执行,终端输出正常,且没有乱码。

但是在生成的report.html报告中,显示乱码,如图:
pytest-html 3.2.0版本中文乱码问题_第2张图片
网上找了很多方法,都不行,然后试用网上找到的以下办法,摘录如下:

使用编辑器nodepad++打开html正常显示,猜想应该是meta字符集编码问题,于是把utf-8修改为GB2312,重新用浏览器打开,即正常显示了。
pytest-html 3.2.0版本中文乱码问题_第3张图片

打开报告如下:
pytest-html 3.2.0版本中文乱码问题_第4张图片
于是找到 lib\site-packages\pytest_html\html_report.py,找到如下代码:

head = html.head(html.meta(charset="utf-8"), html.title(self.title), html_css)

将上述meta的字符编码为GB2312

保存,重新终端执行生成报告,终端显示正常,生成的报告也显示正常

以此解决了pytest-html 3.2.0版本中文乱码问题

参考博客

你可能感兴趣的:(pytest,html,python)