Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 631
astrofrog Avatar asked Aug 27 '10 19:08

astrofrog


People also ask

How do you check if a function raises an error in Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

Which command is used to run nose tests?

nose can be integrated with DocTest by using with-doctest option in athe bove command line. The result will be true if the test run is successful, or false if it fails or raises an uncaught exception. nose supports fixtures (setup and teardown methods) at the package, module, class, and test level.


1 Answers

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"

like image 167
leoluk Avatar answered Sep 22 '22 06:09

leoluk