抑制单元测试中的打印输出

36 投票
2 回答
22874 浏览
提问于 2025-04-18 09:14

编辑:请注意,我使用的是Python 2.6(如标签所示)

假设我有以下内容:

class Foo:
    def bar(self):
        print 'bar'
        return 7

还有我有以下单元测试:

import unittest
class ut_Foo(unittest.TestCase):
    def test_bar(self):
        obj = Foo()
        res = obj.bar()
        self.assertEqual(res, 7)

所以如果我运行:

unittest.main()

我得到:

bar # <-- I don't want this, but I *do* want the rest
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK
Exit code:  False

我的问题是:有没有办法在运行单元测试时,隐藏被测试对象的输出,同时仍然能看到单元测试框架的输出?

编辑 这个问题并不是重复的标记问题,后者是关于在普通Python脚本中静音某个函数的标准输出。

而这个问题是关于在运行单元测试时,隐藏Python脚本的正常标准输出。我仍然希望显示单元测试的标准输出,而不想禁用我测试脚本的标准输出。

2 个回答

10

你可以通过关闭系统的输出功能来抑制输出,然后在测试完成后再开启它:

import sys
import io
import unittest

class ut_Foo(unittest.TestCase):
    def test_bar(self):

        #You suppress here:
        suppress_text = io.StringIO()
        sys.stdout = suppress_text 
        
        obj = Foo()
        res = obj.bar()
        self.assertEqual(res, 7)
        
        #You release here:
        sys.stdout = sys.__stdout__

这些内容都是从这里得到的:

https://codingdose.info/2018/03/22/supress-print-output-in-python/

49

运行你的单元测试时,加上选项“-b” - 这样可以把标准输出和错误输出都缓存起来。

Foo.py

class Foo:
    def bar(self):
        print "bar"
        return 7

test.py

import unittest
from Foo import Foo

class test_Foo(unittest.TestCase):
    def test_bar(self):
        obj = Foo()
        res = obj.bar()
        self.assertEqual(res, 7)

if __name__ == "__main__":
    unittest.main()

用 -b 选项来运行它

$ python test.py -b
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

另外一种方法:使用 nose

$ pip install nose

这个命令安装了 nosetests

注意,我修改了测试套件,让类和方法前面都加上 test,这样才能符合 nose 默认的测试发现规则。

默认情况下,nosetests 不会显示输出。

$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

如果你想看到输出,可以使用 -s 这个选项:

$ nosetests -s
bar
.
----------------------------------------------------------------------
Ran 1 test in 0.002s

OK

撰写回答