Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从另一个类获取方法的输出,并在unittest中进行测试_Python_Python 2.7_Python Unittest - Fatal编程技术网

Python 从另一个类获取方法的输出,并在unittest中进行测试

Python 从另一个类获取方法的输出,并在unittest中进行测试,python,python-2.7,python-unittest,Python,Python 2.7,Python Unittest,我正在创建一个unittest,我想测试一个方法的输出。我的代码有点大,所以我将使用一个小例子。假设我的方法是这样的 def foo(): print "hello" def test_code(): firstClass.foo() 现在我转到我的unittest类,在unittest中运行代码,如下所示 def foo(): print "hello" def test_code(): firstClass.foo() 我想测试从控制台获得的输

我正在创建一个unittest,我想测试一个方法的输出。我的代码有点大,所以我将使用一个小例子。假设我的方法是这样的

def foo():
     print "hello"
def test_code():
     firstClass.foo()
现在我转到我的unittest类,在unittest中运行代码,如下所示

def foo():
     print "hello"
def test_code():
     firstClass.foo()

我想测试从控制台获得的输出。我看到一些人在使用
子流程
,但在那里我只能给出参数。因此,我的问题是如何从控制台获取输出,以便在unittest类中对其进行测试

一个简单的解决方案是在单元测试类中对方法执行后的文件进行检查和处理

import sys
sys.stdout = open('result', 'w')

test_code()
# read 'result'
编辑:或者,您可以使用
StringIO
模块操作文件流

import StringIO
output = StringIO.StringIO()
sys.stdout = output
例如:

#!remap.py
import sys
import StringIO

backup_sys = sys.stdout # backup our standard out
output = StringIO.StringIO() # creates file stream for monitoring test result
sys.stdout = output
print 'test' # prints to our IO stream

sys.stdout = backup_sys # remap back to console
print output.getvalue() # prints the entire contents of the IO stream
输出

test

这可能行得通,但我不想创建文件,因为这只是一个测试。我添加了另一种可能对您有用的方法:
StringIO模块
。这将模拟文件写入方法,并允许您轻松地重新映射
打印
功能。