Disable print in python unittest

Im uses unittest and it prints ".", "E" or "F" for "ok", "error" and "fail" after each test. How to disable it? Im using Python 2.7, and this print comes from the runner class, which is inline. It sounds very difficult to redefine classes because they are all nested.

edit: I only want to remove the characters E. and F because they do not appear at the same time as any other protocol of my tests.

+6
source share
3 answers

The unittest output unittest written to the standard error stream, which you can plug in somewhere else. In the * nix field, this will be possible as follows:

 python -m unittest some_module 2> /dev/null 

In windows it should look like this (thanks to Karl Knechtel):

 python -m unittest some_module 2> NUL 

If you run tests from python, you can simply replace the stderr stream as follows:

 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 disable updates for characters., F, E, you can also create your own TestResult class by overriding the default value. In my case (Python 2.6), it 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 disables character printing, but supports default functionality.

Now we also need a new _makeResult 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 testing without registering.

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

+9
source

A bit late answer, but someone might find this helpful. You can turn. E and F, setting the level of detail to 0:

 testRunner = unittest.TextTestRunner( verbosity = 0 ) 

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

Tested in Python 2.4 and 2.7.

+5
source

Depending on the unittest framework used (standard, nose ...) you have several ways to reduce verbosity:

 python -m unittest -h ... -q, --quiet Minimal output ... 
+1
source

Source: https://habr.com/ru/post/903827/


All Articles