0

我有以下测试:

# -*- 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 字符?

4

2 回答 2

1

您仍在使用 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)
于 2018-10-04T09:55:21.170 回答
0

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

reload(sys)
sys.setdefaultencoding('utf-8')
于 2019-01-28T18:19:19.210 回答