I am using pytest to run tests in a Python package, and I would like to know if any of the code that is executed as part of the tests is raising deprecation warnings (when all tests are passing). Does anyone know of a way to do this?
Both recwarn and pytest. warns() return the same interface for recorded warnings: a WarningsRecorder instance. To view the recorded warnings, you can iterate over this instance, call len on it to get the number of recorded warnings, or index into it to get a particular recorded warning.
To warn about deprecation, you need to set Python's builtin DeprecationWarning as category. To let the warning refer to the caller, so you know exactly where you use deprecated code, you have to set stacklevel=2 .
Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.
Using pytest.Deprecated since version 7.0. pytest. warns(None) is now deprecated because it was frequently misused.
The code
import warnings
warnings.simplefilter("error")
will turn (all) warnings into errors, which may help.
Alternatively, you can get a list of generated warnings with
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.warn("deprecated", DeprecationWarning)
print(w)
#>>> [<warnings.WarningMessage object at 0x7fee80484f50>]
and then assert on that list.
Starting with pytest 3.1, warnings are automatically displayed at the end of the session: see https://docs.pytest.org/en/latest/warnings.html
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