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!


This is a much simpler Python 3 solution -- it's easier to use unittest.mock directly on the builtin print function, rather than fiddling around with sys.stdout:

from unittest.mock import patch, call

@patch('builtins.print')
def test_print(mocked_print):
    print('foo')
    print()

    assert mocked_print.mock_calls == [call('foo'), call()]

print is a keyword in python 2.x, using it as attribute raises a SyntaxError. You can avoid that by using from __future__ import print_function in the beginning of the file.

Note: you can't simply use setattr, because the print function you modified doesn't get invoked unless the print statement is disabled.

Edit: you also need to from __future__ import print_function in every file you want your modified print function to be used, or it will be masked by the print statement.