How to test print statements?

14,245

Solution 1

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.

Solution 2

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()]
Share:
14,245

Related videos on Youtube

erikbstack
Author by

erikbstack

Updated on September 14, 2022

Comments

  • erikbstack
    erikbstack about 1 year

    You want to write unittest-cases for a function like that:

    def test_me(a):
        for b in c:
            print do_something(a,b)
    

    At first I thought about just collecting the outputs of do_something in a string and then returning it, to print and test the whole output together. But it's not always convinient because such loops could cause your buffer string to get very big, depending on the circumstances. So what can you do to test the output, when it is printed and not returned?

  • sshow
    sshow about 5 years
    Same thing, other syntax: with unittest.mock.patch('builtins.print') as mocked_print: