Suppress print output in unittests

后端 未结 2 1601
一向
一向 2020-12-10 01:25

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

Say I have the following:

class Foo:
    def bar(self):
        print \'bar\'
         


        
相关标签:
2条回答
  • 2020-12-10 01:28

    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
    
    0 讨论(0)
  • 2020-12-10 01:41

    You can suppress the output by disabling the sys.stdout and enabling it after your test is done:

    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__
    

    Got all of this from:

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

    0 讨论(0)
提交回复
热议问题