python - python - 如何在python中使用nosetest/unittest断言输出?

标签 python unit-testing nose

我正在为类似下一个的函数编写测试:

def foo():
    print 'hello world!'

所以当我想测试这个功能时,代码会是这样的:

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 参数运行 Nose 测试,测试会崩溃。如何使用 unittest 或 nose 模块捕获输出?

最佳答案

我用这个context manager捕获输出。它最终通过临时替换 sys.stdout 使用与其他一些答案相同的技术。我更喜欢上下文管理器,因为它将所有簿记包装到一个函数中,因此我不必重新编写任何 try-finally 代码,也不必为此编写 setup 和 teardown 函数。

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 block 时会恢复原始输出状态,因此我们可以在与第一个函数相同的函数中设置第二个捕获 block ,而使用 setup 和拆解函数,并且在手动编写 try-finally block 时变得冗长。当测试的目标是比较两个函数的结果,而不是与某个预先计算的值进行比较时,这种能力就派上用场了。

关于python - python - 如何在python中使用nosetest/unittest断言输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4219717/

相关文章:

Python根据给定的键组合2个列表

objective-c - 更好地控制 SenTesting Kit/OCUnit 中的测试套件

python - 并行单元测试

python - Nose 不从导入的模块运行 doctests

python - 如果我想迭代附加值,在迭代期间附加到列表是否安全?

python - 如何使用 Python 发送没有 'Host Header' 的请求?

python - Python中if语句的最佳结构

c# - Mock 的基类是什么?

xml - 如何结合两个不同 Nose 测试的测试结果?

python - 运行 nose --with-coverage 获取所有包文件,但不获取其他依赖项和库