How to assert output with nosetest/unittest in python?

后端 未结 12 1454
野趣味
野趣味 2020-11-28 02:56

I\'m writing tests for a function like next one:

def foo():
    print \'hello world!\'

So when I want to test this function the code will b

12条回答
  •  旧巷少年郎
    2020-11-28 03:32

    Since version 2.7, you do not need anymore to reassign sys.stdout, this is provided through buffer flag. Moreover, it is the default behavior of nosetest.

    Here is a sample failing in non buffered context:

    import sys
    import unittest
    
    def foo():
        print 'hello world!'
    
    class Case(unittest.TestCase):
        def test_foo(self):
            foo()
            if not hasattr(sys.stdout, "getvalue"):
                self.fail("need to run in buffered mode")
            output = sys.stdout.getvalue().strip() # because stdout is an StringIO instance
            self.assertEquals(output,'hello world!')
    

    You can set buffer through unit2 command line flag -b, --buffer or in unittest.main options. The opposite is achieved through nosetest flag --nocapture.

    if __name__=="__main__":   
        assert not hasattr(sys.stdout, "getvalue")
        unittest.main(module=__name__, buffer=True, exit=False)
        #.
        #----------------------------------------------------------------------
        #Ran 1 test in 0.000s
        #
        #OK
        assert not hasattr(sys.stdout, "getvalue")
    
        unittest.main(module=__name__, buffer=False)
        #hello world!
        #F
        #======================================================================
        #FAIL: test_foo (__main__.Case)
        #----------------------------------------------------------------------
        #Traceback (most recent call last):
        #  File "test_stdout.py", line 15, in test_foo
        #    self.fail("need to run in buffered mode")
        #AssertionError: need to run in buffered mode
        #
        #----------------------------------------------------------------------
        #Ran 1 test in 0.002s
        #
        #FAILED (failures=1)
    

提交回复
热议问题