模拟 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

有什么办法吗?

原文由 aychedee 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 582
2 个回答

print 是 python 2.x 中的关键字,将其用作属性会引发 SyntaxError。您可以通过在文件开头使用 from __future__ import print_function 来避免这种情况。

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

编辑:您还需要 from __future__ import print_function 在每个要修改的文件中 print 要使用的函数,否则它将被 print statement.– 屏蔽

原文由 quantum 发布,翻译遵循 CC BY-SA 3.0 许可协议

我知道已经有一个可以接受的答案,但是这个问题有更简单的解决方案——在 python 2.x 中模拟打印。答案在模拟库教程中: http ://www.voidspace.org.uk/python/mock/patch.html 它是:

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

当然你也可以使用下面的断言:

 self.assertEqual("Something\n", mock_stdout.getvalue())

我已经在我的单元测试中检查了这个解决方案,它按预期工作。希望这对某人有帮助。干杯!

原文由 Krzysztof Czeronko 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题