Mock Python's built in print function

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

    This is a v3 version of @KC's answer.

    I didn't want to mock print because I specifically wanted to see the output as a whole, not check out individual calls so StringIO makes more sense to me.

    from io import StringIO
    from unittest.mock import patch
    
    def foo():
        print ('Something')
    
    def test():
        with patch('sys.stdout', new_callable=StringIO) as buffer:
            foo()
        fake_stdout = buffer.getvalue()
    
        #print() is back!
        print(f"fake_stdout:{fake_stdout}")
        assert fake_stdout == 'Something\n'
    
    test()
    

提交回复
热议问题