views:

28

answers:

1

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?

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

def your_test():
    with warnings.catch_warnings(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"

leoluk