recwarn.py


Overview

The `recwarn.py` module provides utilities for **recording, asserting, and managing Python warnings during test execution** within the pytest framework. It offers a fixture and context managers that enable test functions to capture warnings emitted by the code under test, verify that expected warnings occur, optionally match warning messages using patterns, and fail tests when warnings are missing or unexpected.

Warnings recorded are instances of Python’s `warnings.WarningMessage` and include the warning category, message, source location, and other metadata. This module enhances test reliability and clarity by integrating warnings into pytest’s assertion and reporting mechanisms.


Classes, Functions, and Methods

Fixture: recwarn

@fixture
def recwarn() -> Generator[WarningsRecorder]:

Function: deprecated_call

def deprecated_call(
    func: Callable[..., Any] | None = None,
    *,
    match: str | re.Pattern[str] | None = None,
    **kwargs: Any
) -> WarningsRecorder | Any:

Function: warns

def warns(
    expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,
    *args: Any,
    match: str | re.Pattern[str] | None = None,
    **kwargs: Any,
) -> WarningsChecker | Any:

Class: WarningsRecorder

class WarningsRecorder(warnings.catch_warnings):

Class: WarningsChecker

@final
class WarningsChecker(WarningsRecorder):

Important Implementation Details and Algorithms


Interactions with Other Parts of the System


Visual Diagram: Class Structure of recwarn.py

classDiagram
    class WarningsRecorder {
        - _list: list[WarningMessage]
        - _entered: bool
        + list: list[WarningMessage]
        + __getitem__(int) : WarningMessage
        + __iter__() : Iterator[WarningMessage]
        + __len__() : int
        + pop(cls: type) : WarningMessage
        + clear() : None
        + __enter__() : Self
        + __exit__(exc_type, exc_val, exc_tb) : None
    }
    class WarningsChecker {
        - expected_warning: tuple[type]
        - match_expr: str | re.Pattern | None
        + __init__(expected_warning, match_expr, _ispytest=False)
        + matches(warning: WarningMessage) : bool
        + __exit__(exc_type, exc_val, exc_tb) : None
    }

    WarningsChecker --|> WarningsRecorder

Summary

The `recwarn.py` module is a crucial component of pytest's warning management system. It provides:

This module ensures that Python warnings are first-class citizens in pytest test suites, allowing developers to write precise tests that verify the presence or absence of warnings related to deprecated features, future compatibility, and other runtime conditions.


Example Usage Snippets

Using recwarn fixture

def test_deprecated_api(recwarn):
    import warnings
    warnings.warn("deprecated!", DeprecationWarning)
    w = recwarn.pop(DeprecationWarning)
    assert "deprecated" in str(w.message)

Using warns as context manager

with warns(UserWarning, match="value is deprecated"):
    warnings.warn("value is deprecated", UserWarning)

Using deprecated_call as function wrapper

def old_function():
    warnings.warn("use new_function instead", DeprecationWarning)
    return 42

result = deprecated_call(old_function)
assert result == 42

End of Documentation for recwarn.py