模拟Python的内置打印函数

2024-06-26 17:37:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过了

from mock import Mock
import __builtin__

__builtin__.print = Mock()

但这引发了一个语法错误。我也试过这样修补

@patch('__builtin__.print')
def test_something_that_performs_lots_of_prints(self, mock_print):

    # assert stuff

有办法吗?


Tags: offromtestimportthatdefmocksomething
2条回答

print是Python2.x中的一个关键字,使用它作为属性会引发语法错误。在文件开头使用from __future__ import print_function可以避免这种情况。

注意:不能简单地使用setattr,因为除非禁用print语句,否则不会调用您修改的打印函数。

编辑:您还需要在希望使用修改后的print函数的每个文件中from __future__ import print_function,否则它将被print语句屏蔽。

这是一个简单得多的Python3解决方案——直接在内置函数上使用unittest.mock比摆弄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()]

相关问题 更多 >