Function foo
prints to console. I want to test the console print. How can I achieve this in python?
Need to test this function, has NO return statement :
def foo(inStr):
print "hi"+inStr
My test :
def test_foo():
cmdProcess = subprocess.Popen(foo("test"), stdout=subprocess.PIPE)
cmdOut = cmdProcess.communicate()[0]
self.assertEquals("hitest", cmdOut)
This Python 3 example builds upon the one by paxdiablo. It uses
unittest.mock
. It uses a reusable helper method for making the assertion.A general-purpose
TestStdout
class, possibly a mixin, can in principle be derived from the above.You can easily capture standard output by just temporarily redirecting
sys.stdout
to aStringIO
object, as follows:The output of this program is:
showing that the redirection successfully captured the output and that you were able to restore the output stream to what it was before you began the capture.
Note that the code above in for Python 2.7, as the question indicates. Python 3 is slightly different: