Skip to content Skip to sidebar Skip to footer

Testing Functions Printing Behavior

I have a function foo(..) which prints a lot of messages using 'print'. I want to write unit test to test correctness of printed messages. How can I get printed messages instead of

Solution 1:

You can mock sys.stdout as found in the examples of unittest.mock.patch():

from io import StringIO
from unittest.mock import patch

def foo():
    print('Something')

@patch('sys.stdout', new_callable=StringIO)
def test(mock_stdout):
    foo()
    assert mock_stdout.getvalue() == 'Something\n'

test()

Post a Comment for "Testing Functions Printing Behavior"