Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide stderr output in unit tests

I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, à la 2> /dev/null?

like image 648
l0b0 Avatar asked Nov 27 '09 17:11

l0b0


2 Answers

I suggest writing a context manager:

import contextlib
import sys

@contextlib.contextmanager
def nostderr():
    savestderr = sys.stderr
    class Devnull(object):
        def write(self, _): pass
        def flush(self): pass
    sys.stderr = Devnull()
    try:
        yield
    finally:
        sys.stderr = savestderr

Now, wrap any code snippet whose stderr you want suppressed in a with nostderr(): and you have the localized, temporary, guaranteed-reversible stderr suppression that you want.

like image 151
Alex Martelli Avatar answered Oct 07 '22 12:10

Alex Martelli


You could create a dummy file object that did nothing with its output, and set stderr to that:

class NullWriter:
    def write(self, s):
        pass

sys.stderr = NullWriter()

If you only want to quiet stderr for a specific duration, you can use a with statement like so:

class Quieter:
    def __enter__(self):
        self.old_stderr = sys.stderr
        sys.stderr = NullWriter()

    def __exit__(self, type, value, traceback):
        sys.stderr = self.old_stderr

with Quieter():
    # Do stuff; stderr will be suppressed, and it will be restored
    # when this block exits

Requires Python 2.6 or higher, or you can use it in Python 2.5 with a from __future__ import with_statement.

like image 44
Adam Rosenfield Avatar answered Oct 07 '22 12:10

Adam Rosenfield