参考网上的方法,在 HTMLTestRunner 源码乱码设置为 utf-8 编码格式,测试报告的标题可以写中文,但是用例断言失败后打印的依然是乱码,求解。怎样才能让断言异常也能输入中文
用的是 python2.7,运行脚本如下:
这个需要修改HTMLTestRunner.py
里面错误输出进行转码:
773 行左右
if isinstance(o, str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# uo = unicode(o.encode('string_escape'))
uo = o.decode('utf-8')
else:
uo = o
if isinstance(e, str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# ue = unicode(e.encode('string_escape'))
ue = e.decode('utf-8')
else:
ue = e
简单的方法是错误原因不加 u...
def test_112(self):
'''testdesc2'''
print u'测试一下2'
self.assertTrue(False, '错误信息')
加了 u 之后错误信息转码忒复杂,没搞粗来
if isinstance(e, str):
# TODO: some problem with 'string_escape': it escape \n and mess up formating
# ue = unicode(e.encode('string_escape'))
ue = e.decode('gbk', 'ignore')
个人觉得这个不是乱码,而是你的文字是以 unicode 编码值的形式显示出来了。乱码一般是说用了错误的解码器解码,例如用 gbk 解码 utf-8 ,一般特征是长得像火星文,各种未见过的生僻字。你可以在 http://tool.chinaz.com/tools/unicode.aspx 做一下转换,就会发现实际上显示的就是你想用的中文,只是显示形式不对。
我目前了解的会出现这种情况的场景,是用了 repr 方法解析 unicode 字符串:
unicode_str = u'中文'
# 这样就会显示 u'\u4e2d\u6587'
print repr(unicode_str)
建议可以在 if isinstance(e,str):
和 if isinstance(o,str):
加个断点,看下此时中文是否已经变成了 unicode 编码值?
用 py3.x 吧。2.7 已经是历史的遗迹了
如果文件头使用的 utf-8,建议修改 Python 的默认 encoding 为 utf-8,应该能解决问题。
import sys
reload(sys)
sys.setdefaultencoding('utf8')