How to assert output with nosetest/unittest in python?

后端 未结 12 1488
野趣味
野趣味 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:41

    Both n611x007 and Noumenon already suggested using unittest.mock, but this answer adapts Acumenus's to show how you can easily wrap unittest.TestCase methods to interact with a mocked stdout.

    import io
    import unittest
    import unittest.mock
    
    msg = "Hello World!"
    
    
    # function we will be testing
    def foo():
        print(msg, end="")
    
    
    # create a decorator which wraps a TestCase method and pass it a mocked
    # stdout object
    mock_stdout = unittest.mock.patch('sys.stdout', new_callable=io.StringIO)
    
    
    class MyTests(unittest.TestCase):
    
        @mock_stdout
        def test_foo(self, stdout):
            # run the function whose output we want to test
            foo()
            # get its output from the mocked stdout
            actual = stdout.getvalue()
            expected = msg
            self.assertEqual(actual, expected)
    

提交回复
热议问题