从 python unittest 获取 unicode 输出

Getting unicode output from python unittest

我有以下测试:

# -*- coding: utf-8 -*-
import unittest

class Tests(unittest.TestCase):
    #pylint:disable=invalid-name
    def test_string_matches(self):
        self.assertEqual(u'你好', u'好')

这在 shell 中给出了以下输出:

======================================================================
FAIL: test_string_matches (test.Tests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 7, in test_string_matches
    self.assertEqual(u'你好', u'好')
AssertionError: u'\u4f60\u597d' != u'\u597d'
- \u4f60\u597d
? -
+ \u597d

但是如果我 运行:

print '你好'

在终端中,我得到了预期的输出:你好

有没有办法让 python unittest 输出实际的 unicode 字符?

您仍在使用 Python 2.x 有什么原因吗?如果您切换到 Python 3.x 那么异常将以您期望的方式显示。

$ python3 t.py
F
======================================================================
FAIL: test_string_matches (__main__.Tests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "t.py", line 7, in test_string_matches
    self.assertEqual(u'你好', u'好')
AssertionError: '你好' != '好'
- 你好
? -
+ 好


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)

如果您需要在 Python2 上实现此功能,我发现解决该问题的唯一方法是强制系统编码为 utf-8:

reload(sys)
sys.setdefaultencoding('utf-8')