Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

python - Suppress print output in unittests

Edit: Please notice I'm using Python 2.6 (as tagged)

Say I have the following:

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)

So if I run:

unittest.main()

I get:

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?

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Call your unittest with option "-b" - buffer stdout and stderr

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()

Run it with -b option

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

OK

Alternative: use nose

$ pip install nose

what installs command nosetests

Note, that I have modified test suite to have class and methods prefixed by test to satisfy nose default test discovery rules.

nosetests by default does not show output

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

OK

If you want to see the output, use -s switch:

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

OK

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...