Python:为控制台打印编写单元测试 [英] Python: Write unittest for console print

查看:26
本文介绍了Python:为控制台打印编写单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆