Turn some print off in python unittest

大憨熊 提交于 2019-12-09 12:01:26

问题


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.


回答1:


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.




回答2:


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.




回答3:


Depending the unittest framework you're using (standard, nose...), you have multiple way to decrease the verbosity:

python -m unittest -h
...
-q, --quiet      Minimal output
...


来源:https://stackoverflow.com/questions/8518043/turn-some-print-off-in-python-unittest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!