Suppress STDOUT in unittest

13 Jul 2014


You are testing a function in unit test using python. The function emits some text output to sys.stdout, but you want to suppress the output during unit testing (simply because the output is irrelevant during testing).


Using the mock module’s patch() function, it’s pretty simple to mock out sys.stdout for just a single test, and put it back again, without messy temporary variables or leaking mocked-out state between test cases. For example:

from mock import patch
import unittest

def func_to_be_tested():
    print 'some message texts to stdout ...'

class MockDevice():
    """A mock device to temporarily suppress output to stdout
    Similar to UNIX /dev/null.

    def write(self, s): pass

class TestFunctionToBeTested(unittest.TestCase):
    def test_function_to_be_tested():
        # some other setup code
        with patch('sys.stdout', new=MockDevice()) as fake_out:

mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and makes assertions about how they have been used. In the above example, it is used to replace std.stdout temporarily ONLY within the with statement block, and restore it back afterwards.

And of course, the result will be that the text ‘some message texts to stdout …’ simply disappear while running unit test.

The above idea is inspired by the following web resources:

  1. Redirect or Turn Off STDOUT and STDERR
  2. Python Cookbook Chapter 14