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 b
If you really want to do this, you can reassign sys.stdout for the duration of the test.
def test_foo():
import sys
from foomodule import foo
from StringIO import StringIO
saved_stdout = sys.stdout
try:
out = StringIO()
sys.stdout = out
foo()
output = out.getvalue().strip()
assert output == 'hello world!'
finally:
sys.stdout = saved_stdout
If I were writing this code, however, I would prefer to pass an optional out parameter to the foo function.
def foo(out=sys.stdout):
out.write("hello, world!")
Then the test is much simpler:
def test_foo():
from foomodule import foo
from StringIO import StringIO
out = StringIO()
foo(out=out)
output = out.getvalue().strip()
assert output == 'hello world!'