Python3 HtmlTestRunner兼容中文

本文介绍如何解决使用Python3和HtmlTestRunner生成测试报告时出现的中文乱码问题。通过修改result.py文件中generate_file方法的写文件操作,添加正确的编码方式,可以有效解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Python3环境下,引用HtmlTestRunner生成测试报告,report_title传了中文,结果生成的报告中文是乱码:
这里写图片描述

解决方法直接拖到文末


港真,看到这个还挺崩溃的,因为我用的是Python3!!
调了一下代码,发现了问题,在HtmlTestRunner/result.py中有这样的代码:

    def generate_file(self, output, report_name, report):
        """ Generate the report file in the given path. """
        ......
        with open(path_file, 'w') as report_file:
            report_file.write(report)

写文件那行,在python3里应该指定编码方式,否则中文就是乱码。


解决方法:
修改…\Lib\site-packages\HtmlTestRunner\result.py文件中的generate_file方法,在写文件时添加encoding方式,改成这样就可以了

    def generate_file(self, output, report_name, report):
        """ Generate the report file in the given path. """
        ......
        with open(path_file, 'w', encoding='utf-8') as report_file:
            report_file.write(report)

献出结果:
这里写图片描述

HtmlTestRunner源码:https://github.com/oldani/HtmlTestRunner

1.将 HTMLTestRunner.py 放置在 C:\Python36\Lib 下 2.涉及到创建目录和时间,需要在脚本开头 import os import time 3.执行脚本中删除语句 unittest.main() ,一般在脚本最后,然后添加如下语句: #导入HTMLTestRunner库,这句也可以放在脚本开头 from HTMLTestRunner import HTMLTestRunner #定义脚本标题,加u为了防止中文乱码 report_title = u'登陆模块测试报告' #定义脚本内容,加u为了防止中文乱码 desc = u'手机JPG登陆模块测试报告详情:' #定义date为日期,time为时间 date=time.strftime("%Y%m%d") time=time.strftime("%Y%m%d%H%M%S") #定义path为文件路径,目录级别,可根据实际情况自定义修改 path= 'D:/Python_test/'+ date +"/login/"+time+"/" #定义报告文件路径和名字,路径为前面定义的path,名字为report(可自定义),格式为.html report_path = path+"report.html" #判断是否定义的路径目录存在,不能存在则创建 if not os.path.exists(path): os.makedirs(path) else: pass #定义一个测试容器 testsuite = unittest.TestSuite() #将测试用例添加到容器 testsuite.addTest(测试类名("测试方法名1")) testsuite.addTest(测试类名("测试方法名2")) #将运行结果保存到report,名字为定义的路径和文件名,运行脚本 with open(report_path, 'wb') as report: runner = HTMLTestRunner(stream=report, title=report_title, description=desc) runner.run(testsuite) #关闭report,脚本结束 report.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值