Testing Warnings with pytest.warns
Sometimes your code emits warnings that you want to verify. pytest provides pytest.warns to capture and assert on warnings.
Basic Usage
Use pytest.warns as a context manager to check that a warning is raised:
import warnings
import pytest
def deprecated_function():
warnings.warn("This function is deprecated", DeprecationWarning)
return 42
def test_deprecated_warning():
with pytest.warns(DeprecationWarning):
deprecated_function()
Checking the Warning Message
You can verify the exact warning message:
def test_warning_message():
with pytest.warns(DeprecationWarning, match="deprecated"):
deprecated_function()
def test_warning_exact_message():
with pytest.warns(DeprecationWarning, match="This function is deprecated"):
deprecated_function()
Accessing Warning Details
Capture the warning list to inspect all warnings raised:
def test_multiple_warnings():
with pytest.warns(DeprecationWarning) as warning_list:
deprecated_function()
assert len(warning_list) == 1
assert "deprecated" in str(warning_list[0].message)
When No Warning Should Be Raised
You can verify that no warning is produced by simply not using pytest.warns:
def test_no_warning():
# If this does NOT raise a warning, the test passes
result = stable_function()
assert result is not None