Mock Python’s built in print function

I know that there is already an accepted answer but there is simpler solution for that problem – mocking the print in python 2.x. Answer is in the mock library tutorial: http://www.voidspace.org.uk/python/mock/patch.html and it is:

>>> from StringIO import StringIO
>>> def foo():
...     print 'Something'
...
>>> @patch('sys.stdout', new_callable=StringIO)
... def test(mock_stdout):
...     foo()
...     assert mock_stdout.getvalue() == 'Something\n'
...
>>> test()

Of course you can use also following assertion:

self.assertEqual("Something\n", mock_stdout.getvalue())

I have checked this solution in my unittests and it is working as expected. Hope this helps somebody. Cheers!

Leave a Comment