Mock Python's built in print function

前端 未结 11 2017
醉话见心
醉话见心 2020-12-06 09:10

I\'ve tried

from mock import Mock
import __builtin__

__builtin__.print = Mock()

But that raises a syntax error. I\'ve also tried patching

11条回答
  •  渐次进展
    2020-12-06 09:29

    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!

提交回复
热议问题