0
0
PyTesttesting~5 mins

Asserting warnings (pytest.warns)

Choose your learning style9 modes available
Introduction

We use pytest.warns to check if our code shows the right warnings. This helps catch small problems early.

When you want to make sure a function warns about deprecated features.
When you expect a warning for unsafe or unusual code use.
When testing that a warning message appears during a specific action.
When you want to confirm your code warns users about upcoming changes.
When you want to catch warnings as part of automated tests.
Syntax
PyTest
with pytest.warns(ExpectedWarningType):
    code_that_warns()

Use the with statement to catch warnings during the code run.

ExpectedWarningType is the type of warning you expect, like DeprecationWarning.

Examples
This test passes if the code inside with raises a DeprecationWarning.
PyTest
import warnings
import pytest

def test_warn():
    with pytest.warns(DeprecationWarning):
        warnings.warn("This is deprecated", DeprecationWarning)
This test checks the warning type and that the message contains "use caution".
PyTest
import warnings
import pytest

def test_warn_message():
    with pytest.warns(UserWarning, match="use caution"):
        warnings.warn("Please use caution", UserWarning)
Sample Program

This test checks that calling old_function() raises a DeprecationWarning with the word "deprecated" in the message.

PyTest
import warnings
import pytest

def old_function():
    warnings.warn("old_function is deprecated", DeprecationWarning)

def test_old_function_warns():
    with pytest.warns(DeprecationWarning, match="deprecated"):
        old_function()
OutputSuccess
Important Notes

If no warning is raised, the test fails.

You can check the warning message text using the match parameter.

Use specific warning types to avoid catching unexpected warnings.

Summary

pytest.warns helps check if code shows expected warnings.

Use it with with to catch warnings during test runs.

Check warning type and message to make tests precise.