抑制单元测试中的打印输出 [英] Suppress print output in unittests
问题描述
请注意我使用的是 Python 2.6(如标记)
Please notice I'm using Python 2.6 (as tagged)
假设我有以下内容:
class Foo:
def bar(self):
print 'bar'
return 7
假设我有以下单元测试:
And say I have the following unit test:
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
我的问题是:有没有办法抑制被测试对象的输出,同时仍然获得单元测试框架的输出?
My question is: Is there a way to suppress the output of the object being tested while still getting the output of the unittest framework?
编辑这个问题不是 标记的问题 的重复,该问题询问在普通 python 脚本中沉默特定函数的标准输出.
Edit This question is not a duplicate of the flagged question which is asking about silencing stdout of a particular function within a normal python script.
而这个问题询问的是在运行单元测试时隐藏 python 脚本的正常标准输出.我仍然希望显示 unittest 标准输出,并且我不想禁用我的测试脚本的标准输出.
Whereas this question is asking about hiding the normal stdout of a python script while running it's unittests. I still want the unittest stdout to be displayed, and I don't want to disable the stdout of my tested script.
推荐答案
使用选项-b"调用单元测试 - 缓冲标准输出和标准错误
Call your unittest with option "-b" - buffer stdout and stderr
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
默认测试发现规则.
Note, that I have modified test suite to have class and methods prefixed by test
to satisfy nose
default test discovery rules.
nosetests
默认不显示输出
$ nosetests
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
如果要查看输出,请使用 -s
开关:
If you want to see the output, use -s
switch:
$ nosetests -s
bar
.
----------------------------------------------------------------------
Ran 1 test in 0.002s
OK
这篇关于抑制单元测试中的打印输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!