Python:编写用于控制台打印的单元测试 [英] Python: Write unittest for console print
问题描述
函数 foo
打印到控制台。我想测试控制台打印。
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
我的测试:
def test_foo():
cmdProcess = subprocess.Popen(foo("test"), stdout=subprocess.PIPE)
cmdOut = cmdProcess.communicate()[0]
self.assertEquals("hitest", cmdOut)
推荐答案
通过临时重定向 sys.stdout
到 StringIO
对象,如下所示:
You can easily capture standard output by just temporarily redirecting sys.stdout
to a StringIO
object, as follows:
import StringIO
import sys
def foo(inStr):
print "hi"+inStr
def test_foo():
capturedOutput = StringIO.StringIO() # Create StringIO object
sys.stdout = capturedOutput # and redirect stdout.
foo('test') # Call unchanged function.
sys.stdout = sys.__stdout__ # Reset redirect.
print 'Captured', capturedOutput.getvalue() # Now works as before.
test_foo()
该程序的输出为:
Captured hitest
显示重定向成功捕获了输出,并且您能够将输出流还原到开始捕获之前的状态。
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.
请注意,如问题所示,上面的Python 2.7中的代码。 Python 3稍有不同:
Note that the code above in for Python 2.7, as the question indicates. Python 3 is slightly different:
import io
import sys
def foo(inStr):
print ("hi"+inStr)
def test_foo():
capturedOutput = io.StringIO() # Create StringIO object
sys.stdout = capturedOutput # and redirect stdout.
foo('test') # Call function.
sys.stdout = sys.__stdout__ # Reset redirect.
print ('Captured', capturedOutput.getvalue()) # Now works as before.
test_foo()
这篇关于Python:编写用于控制台打印的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!