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?
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With