Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to temporary hide stdout or stderr while running a unittest in Python

Tags:

python

I have a faulty third party python module that is outputing to stdout or stderr while it is imported and this is breaking the output of my unittests.

How can I temporary redirect the stdout in order to hide its output.

Limit to Python 2.5 syntax :)

Update, I forgot to mention that sys.stdout and sys.__stderr__ methods do not work in this case. As far as I know this faulty module is using native code.

like image 210
sorin Avatar asked Dec 15 '11 15:12

sorin


People also ask

Does python print go to stdout or stderr?

In Python, whenever we use print() the text is written to Python's sys. stdout, whenever input() is used, it comes from sys. stdin, and whenever exceptions occur it is written to sys. stderr.

How do you record stdout output from a Python function call?

To capture stdout output from a Python function call, we can use the redirect_stdout function. to call redirect_stdout with the f StringIO object. Then we call do_something which prints stuff to stdout. And then we get the value printed to stdout with f.


1 Answers

You can also use mock to let you patch sys.stdout and sys.stderr for you when the module is imported. An example of a testing module that using this strategy would be:

import os
devnull = open(os.devnull, 'w')

from mock import patch
with patch('sys.stdout', devnull):
    with patch('sys.stderr', devnull):
        import bad_module

# Test cases writen here

where bad_module is the third party module that is printing to sys.stdout and sys.stderr when is being imported.

like image 173
jcollado Avatar answered Oct 23 '22 12:10

jcollado