【问题标题】:How to test print statements?如何测试打印语句?
【发布时间】:2012-06-20 15:10:56
【问题描述】:

你想为这样的函数写unittest-cases:

def test_me(a):
    for b in c:
        print do_something(a,b)

起初我想只是将do_something 的输出收集到一个字符串中,然后将其返回,以便一起打印和测试整个输出。但这并不总是很方便,因为这样的循环可能会导致您的缓冲区字符串变得非常大,具体取决于具体情况。那么,当输出被打印并且没有返回时,你可以做些什么来测试输出呢?

【问题讨论】:

标签: python unit-testing stdout


【解决方案1】:

print 打印到 sys.stdout,如果您愿意,您可以将其重新分配给您自己的对象。您的对象唯一需要的是一个 write 函数,它接受一个字符串参数。

从 Python 2.6 开始,您还可以通过在脚本顶部添加 from __future__ import print_functionprint 更改为函数而不是语言结构。这样你就可以用你自己的函数覆盖print

【讨论】:

    【解决方案2】:

    在 Python 3 中,很容易在内置 print 函数上使用 unittest.mock

    from unittest.mock import patch, call
    
    @patch('builtins.print')
    def test_print(mocked_print):
        print('foo')
        print()
    
        assert mocked_print.mock_calls == [call('foo'), call()]
    

    【讨论】:

    • 同样的,其他语法:with unittest.mock.patch('builtins.print') as mocked_print:
    猜你喜欢
    • 2019-05-03
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多