Turn some print off in python unittest

swan picture swan · Dec 15, 2011 · Viewed 9.2k times · Source

Im using unittest and it prints ".", "E" or "F" for "ok", "error" and "fail" after each test it does. How do I switch it off ? Im using Python 2.7 and these print come from the runner class which is built in. It sounds very tough to override the classes because it's all nested.

edit: I only want to take off the characters E . and F because they don't appear at the same time as some other log in my tests.

Answer

Constantinius picture Constantinius · Dec 15, 2011

The output of unittest is written to the standard error stream, which you can pipe somewhere else. On a *nix box this would be possible like this:

python -m unittest some_module 2> /dev/null

On windows, this should look like this (thanks Karl Knechtel):

python -m unittest some_module 2> NUL

If you run the tests from python, you can simply replace the stderr stream like that:

import sys, os

sys.stderr = open(os.devnull, 'w')

... # do your testing here

sys.stderr = sys.__stderr__ # if you still need the stderr stream

Since you just want to turn off the updates for the ., F, E symbols, you could also create your own TestResult class by overriding the default one. In my case (Python 2.6) this would look like this:

import unittest

class MyTestResult(unittest._TextTestResult):
    def addSuccess(self, test):
        TestResult.addSuccess(self, test)
    def addError(self, test, err):
        TestResult.addError(self, test, err)
    def addFailure(self, test, err):
        TestResult.addFailure(self, test, err)

This effectively turns off the printing of the characters, but maintaining the default functionality.

Now we also need a new TestRunner class and override the _makeResult method:

class MyTestRunner(unittest.TextTestRunner):
    def _makeResult(self):
        return MyTestResult(self.stream, self.descriptions, self.verbosity)

With this runner you can now enjoy a log free testing.

Just a note: this is not possible from the command line, unfortunately.