如何测试打印语句? [英] How to test print statements?

查看:25
本文介绍了如何测试打印语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

You want to write unittest-cases for a function like that:

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

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

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. 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 打印到 sys.stdout,您可以重新分配如果你愿意,你自己的对象.你的对象唯一需要的是一个 write 函数,它接受一个字符串参数.

print prints to sys.stdout, which you can reassign to your own object if you wish. The only thing your object needs is a write function which takes a single string argument.

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

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. This way you can override print with your own function.

这篇关于如何测试打印语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆