Python unittest - Using the "buffer" option to suppress stdout - how to do this?

In unittest docs [ http://docs.python.org/2/library/unittest.html#unittest.main ] I see the following method signature:

unittest.main([module[, defaultTest[, argv[, testRunner[, testLoader[, exit[, verbosity[, failfast[, catchbreak[, buffer]]]]]]]]]]) 

The last parameter is the "buffer". The docs explain the following about this option:

The failfast, catchbreak, and buffer options have the same effect as the command line options with the same name.

The docs for the command line options [ http://docs.python.org/2/library/unittest.html#command-line-options ] explain the buffer as follows:

-b, --buffer
Standard output and standard error streams are buffered during the test run. The output during the test is discarded. The output is usually repeated when a test error or error is added to the error messages.

I have the following demo code that does not demonstrate the behavior that might be expected:

 import unittest2 class DemoTest(unittest2.TestCase): def test_one(self): self.assertTrue(True) def test_two(self): self.assertTrue(True) if __name__ == '__main__': test_program = unittest2.main(verbosity=0, buffer=True, exit=False) 

The output of this program:

 ---------------------------------------------------------------------- Ran 2 tests in 0.000s OK 

In fact, I get the same result if I change the last line in my program to:

 test_program = unittest2.main(verbosity=0, buffer="hello", exit=False) 

What am I doing wrong? (I tried using unittest instead of unittest2 , but that didn't matter.)

+6
source share
2 answers

The fact is that the buffer option affects the stdout entry inside your tests, ignoring the behavior of unittest2. That is, you will see the difference if you add a line like

 print "Suppress me!" 

for any test method, this expression will appear on stdout if you select buffer=False , while it will be suppressed if you set it to True.

+7
source

As I explained in a comment, buffer simply buffers the output from the test code. This means that you only get the result from unittest2 . It works great. (In your case, it also works trivially - your code does not output anything, so there is no buffer for the buffer, so you will get the same result without it.)

If you also don't want to output from unittest2 , you can always run the script with a shell command line that redirects to /dev/null or imports unittest2 from a script that redirects sys.stdout .

But usually you really want to read this stdout, and not just give it up. Even if you do not want to register it anywhere, you want to check that the last line is "OK" , so you can send an electric shock to your development team or whatever you do in case of a failure. Otherwise, what's the point of running tests via cron ?

+3
source

All Articles