Python:为控制台打印编写单元测试

标签 python python-2.7 unit-testing console python-unittest

函数 foo 打印到控制台。我想测试控制台打印。如何在 python 中实现这一点?

需要测试这个功能,没有返回语句:

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 对象来轻松捕获标准输出,如下所示:

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

显示重定向成功捕获了输出,并且您能够将输出流恢复到开始捕获之前的状态。


请注意,如问题所示,上述代码适用于 Python 2.7。 Python 3 略有不同:

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:为控制台打印编写单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767627/

相关文章:

c# - 包含从 Request.Form 中挑选的数据的单元测试方法。新手问题

selenium - 针对跨多个浏览器的 Selenium 测试的自动化测试套件包结构的建议

python - Python 3 中的动态导入 + 相对导入

Python请求参数未通过

python - 基于约束的Dataframe列生成

python - 在 Python 2.7 中保存/加载大型列表的最快方法是什么?

python-2.7 - 在类的一个函数中获取用户输入并在 Python 中的另一个函数中使用它

python - 使用 Python 打印 PDF 文件时如何选择纸张格式?

python - 如何在不同的数据源之间切换?

javascript - 如何在 JavaScript 中使用 Math.random 进行测试?