通过鼻子测试检查功能是否发出警告 [英] Check that a function raises a warning with nose tests

查看:71
本文介绍了通过鼻子测试检查功能是否发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用鼻子编写单元测试,并且想要检查某个函数是否发出警告(该函数使用warnings.warn).这很容易做到吗?

I'm writing unit tests using nose, and I'd like to check whether a function raises a warning (the function uses warnings.warn). Is this something that can easily be done?

推荐答案

def your_code():
    # ...
    warnings.warn("deprecated", DeprecationWarning)
    # ...

def your_test():
    with warnings.catch_warnings(record=True) as w:
        your_code()
        assert len(w) > 1

当然,您不仅可以检查长度,还可以对其进行深入检查:

Instead of just checking the lenght, you can check it in-depth, of course:

assert str(w.args[0]) == "deprecated"

在python 2.7或更高版本中,您可以使用以下最后一项检查来做到这一点:

In python 2.7 or later, you can do this with the last check as:

assert str(w[0].message[0]) == "deprecated"

这篇关于通过鼻子测试检查功能是否发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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