I'm writing tests for a function like next one:
def foo():
print 'hello world!'
So when I want to test this function the code will be like this:
import sys
from foomodule import foo
def test_foo():
foo()
output = sys.stdout.getline().strip() # because stdout is an StringIO instance
assert output == 'hello world!'
But if I run nosetests with -s parameter the test crashes. How can I catch the output with unittest or nose module?
If you really want to do this, you can reassign sys.stdout for the duration of the test.
If I were writing this code, however, I would prefer to pass an optional
out
parameter to thefoo
function.Then the test is much simpler:
Since version 2.7, you do not need anymore to reassign
sys.stdout
, this is provided throughbuffer
flag. Moreover, it is the default behavior of nosetest.Here is a sample failing in non buffered context:
You can set buffer through
unit2
command line flag-b
,--buffer
or inunittest.main
options. The opposite is achieved throughnosetest
flag--nocapture
.In python 3.5 you can use
contextlib.redirect_stdout()
andStringIO()
. Here's the modification to your code