Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turn some print off in python unittest

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.

like image 598
swan Avatar asked Dec 15 '11 09:12

swan


2 Answers

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.

like image 71
Constantinius Avatar answered Oct 16 '22 17:10

Constantinius


A bit late response, but someone may find it useful. You can turn . E and F off by setting verbosity level to 0:

testRunner = unittest.TextTestRunner( verbosity = 0 )

You will still have the final result and possible errors/exceptions at the end of tests in the stderr.

Tested in Python 2.4 and 2.7.

like image 32
Karadur Avatar answered Oct 16 '22 15:10

Karadur