Mock Python's built in print function

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

    As lcq says, print is a keyword. So, think about what it would mean if you were actually successful in patching/mocking print under Python 2.7.3. You would have code like this:

    print "Hi."
    

    turning into:

     "Hi."
    

    MagicMock objects cannot be accessed this way, so you would get a syntax error.

    So... Yeah. You can only mock the Python3 print function or sys.stdout.

提交回复
热议问题