How to assert output with nosetest/unittest in python?

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

    A lot of these answers failed for me because you can't from StringIO import StringIO in Python 3. Here's a minimum working snippet based on @naxa's comment and the Python Cookbook.

    from io import StringIO
    from unittest.mock import patch
    
    with patch('sys.stdout', new=StringIO()) as fakeOutput:
        print('hello world')
        self.assertEqual(fakeOutput.getvalue().strip(), 'hello world')
    

提交回复
热议问题