Turn some print off in python unittest

前端 未结 2 1227
你的背包
你的背包 2021-02-15 21:59

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 co

相关标签:
2条回答
  • 2021-02-15 22:14

    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.

    0 讨论(0)
  • 2021-02-15 22:25

    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.

    0 讨论(0)
提交回复
热议问题