简体   繁体   English

如何测试打印报表?

[英]How to test print statements?

You want to write unittest -cases for a function like that: 你想为这样的函数编写unittest -cases:

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

At first I thought about just collecting the outputs of do_something in a string and then returning it, to print and test the whole output together. 起初我想过只是在字符串中收集do_something的输出然后返回它,一起打印和测试整个输出。 But it's not always convinient because such loops could cause your buffer string to get very big, depending on the circumstances. 但它并不总是很方便,因为这样的循环可能会导致缓冲区字符串变得非常大,具体取决于具体情况。 So what can you do to test the output, when it is printed and not returned? 那么,在打印并且不返回输出时,您可以做些什么来测试输出?

print prints to sys.stdout , which you can reassign to your own object if you wish. printsys.stdout ,如果您愿意,可以将其重新分配给您自己的对象。 The only thing your object needs is a write function which takes a single string argument. 您的对象唯一需要的是一个带有单个字符串参数的write函数。

Since Python 2.6 you may also change print to be a function rather than a language construct by adding from __future__ import print_function to the top of your script. 从Python 2.6开始,您还可以通过将from __future__ import print_function添加到脚本的顶部来将print更改为函数而不是语言构造。 This way you can override print with your own function. 这样您就可以使用自己的功能覆盖print

In Python 3 it's easy to use unittest.mock on the builtin print function: 在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()]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM