Search code examples
pythonunit-testingwarningsnose

Check that a function raises a warning with nose tests


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?


Solution

  • 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"

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

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