Mock Python's built in print function

前端 未结 11 1955
醉话见心
醉话见心 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:37

    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()]
    

提交回复
热议问题