如何使nosetests打印unicode可读?

时间:2017-06-30 05:53:26

标签: python unicode nose

我正在使用nosetests来运行测试,但我发现它无法打印真正的unicode:

#!/usr/bin/env python
# encoding: utf-8

import unittest

class FooTests(unittest.TestCase):
    def test_str(self):
        print("中国")
        self.assertEqual(1, 0)

    def test_unicode(self):
        print(u"中国")
        self.assertEqual(1, 0)

def main():
    unittest.main()

if __name__ == "__main__":
    main()

其捕获结果如下:

-------------------- >> begin captured stdout << ---------------------
\u4e2d\u56fd

--------------------- >> end captured stdout << ----------------------

我想要的是:

-------------------- >> begin captured stdout << ---------------------
中国

--------------------- >> end captured stdout << ----------------------

2 个答案:

答案 0 :(得分:0)

指定-s--nocapture选项会阻止nosetest捕获标准输出;您将看到所需的字符串,但没有>> beging/end captured stdout<<标记,因为print statemnet将在执行后立即打印字符串:

$ nosetests -s t.py
中国
F中国
F
======================================================================
FAIL: test_str (t.FooTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/t.py", line 9, in test_str
    self.assertEqual(1, 0)
AssertionError: 1 != 0

======================================================================
FAIL: test_unicode (t.FooTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/t.py", line 13, in test_unicode
    self.assertEqual(1, 0)
AssertionError: 1 != 0

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (failures=2)

另一个选择:使用python 3!无需任何选项:

$ python3 -m nose t.py
FF
======================================================================
FAIL: test_str (t.FooTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/t.py", line 9, in test_str
    self.assertEqual(1, 0)
AssertionError: 1 != 0
-------------------- >> begin captured stdout << ---------------------
中国

--------------------- >> end captured stdout << ----------------------

======================================================================
FAIL: test_unicode (t.FooTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/tmp/t.py", line 13, in test_unicode
    self.assertEqual(1, 0)
AssertionError: 1 != 0
-------------------- >> begin captured stdout << ---------------------
中国

--------------------- >> end captured stdout << ----------------------

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=2)

答案 1 :(得分:0)

我有类似的问题,可能是相同的根本原因。如果您使用LC_CTYPE=C nosetests运行测试,则由于区域设置决定C,Python无法使用ASCII编码来编码unicode字符。运行LC_CTYPE=en_US.UTF-8 nosetest应该可以解决该问题。

P.S。我正在寻找解决方案,以便在鼻子测试跑步者的测试中指出这一点。