检查功能是否通过鼻子测试发出警告

ast*_*rog 7 python warnings unit-testing nose

我正在使用nose编写单元测试,我想检查函数是否引发警告(函数使用warnings.warn).这是否可以轻松完成?

leo*_*luk 9

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

def your_test():
    with warnings.catch_warnings(record=True) as w:
        your_code()
        assert len(w) > 1
Run Code Online (Sandbox Code Playgroud)

当然,您可以深入检查,而不仅仅是检查长度:

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

在python 2.7或更高版本中,您可以使用上次检查执行此操作:

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