如何在python中使用nosetest/unittest断言输出? [英] How to assert output with nosetest/unittest in python?
问题描述
我正在为下一个函数编写测试:
I'm writing tests for a function like next one:
def foo():
print 'hello world!'
所以当我想测试这个函数时,代码会是这样的:
So when I want to test this function the code will be like this:
import sys
from foomodule import foo
def test_foo():
foo()
output = sys.stdout.getline().strip() # because stdout is an StringIO instance
assert output == 'hello world!'
但是如果我使用 -s 参数运行鼻子测试,测试就会崩溃.如何使用单元测试或鼻子模块捕获输出?
But if I run nosetests with -s parameter the test crashes. How can I catch the output with unittest or nose module?
推荐答案
我用这个 上下文管理器 来捕获输出.它最终通过临时替换 sys.stdout
使用与其他一些答案相同的技术.我更喜欢上下文管理器,因为它将所有簿记包装到一个函数中,因此我不必重新编写任何 try-finally 代码,也不必为此编写设置和拆卸函数.>
I use this context manager to capture output. It ultimately uses the same technique as some of the other answers by temporarily replacing sys.stdout
. I prefer the context manager because it wraps all the bookkeeping into a single function, so I don't have to re-write any try-finally code, and I don't have to write setup and teardown functions just for this.
import sys
from contextlib import contextmanager
from StringIO import StringIO
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
像这样使用它:
with captured_output() as (out, err):
foo()
# This can go inside or outside the `with` block
output = out.getvalue().strip()
self.assertEqual(output, 'hello world!')
此外,由于在退出 with
块时恢复了原始输出状态,我们可以在与第一个捕获块相同的功能中设置第二个捕获块,这是使用 setup 和拆卸功能,并在手动编写 try-finally 块时变得冗长.当测试的目标是比较两个函数的结果而不是某个预先计算的值时,这种能力就派上用场了.
Furthermore, since the original output state is restored upon exiting the with
block, we can set up a second capture block in the same function as the first one, which isn't possible using setup and teardown functions, and gets wordy when writing try-finally blocks manually. That ability came in handy when the goal of a test was to compare the results of two functions relative to each other rather than to some precomputed value.
这篇关于如何在python中使用nosetest/unittest断言输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!