How to test print statements?

纵饮孤独 提交于 2019-12-04 00:20:06

print prints to sys.stdout, which you can reassign to your own object if you wish. The only thing your object needs is a write function which takes a single string argument.

Since Python 2.6 you may also change print to be a function rather than a language construct by adding from __future__ import print_function to the top of your script. This way you can override print with your own function.

In Python 3 it's easy to use unittest.mock on the builtin print function:

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()]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!