Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if any tests raise a deprecation warning with pytest

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?

like image 262
astrofrog Avatar asked Sep 20 '13 15:09

astrofrog


People also ask

How do I check my Pytest warnings?

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.

How do you raise a deprecation warning in Python?

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 .

How do you filter warnings in Python?

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.

Is Pytest deprecated?

Using pytest.Deprecated since version 7.0. pytest. warns(None) is now deprecated because it was frequently misused.


2 Answers

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.

like image 110
Veedrac Avatar answered Oct 10 '22 09:10

Veedrac


Starting with pytest 3.1, warnings are automatically displayed at the end of the session: see https://docs.pytest.org/en/latest/warnings.html

like image 35
Wolfgang Ulmer Avatar answered Oct 10 '22 11:10

Wolfgang Ulmer