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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
There are (at least) two ways of doing this. You can catch the warning in the
list
ofwarnings.WarningMessage
s in test or usemock
topatch
the importedwarnings
in your module.I think the
patch
version is more general.raise_warning.py:
raise_warning_tests.py:
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"