warnings.py


Overview

The `warnings.py` file is a core utility module within the pytest testing framework responsible for **capturing, filtering, recording, and reporting Python warnings** during various phases of a test run. It integrates Python's built-in warnings system with pytest's lifecycle hooks, allowing warnings to be reliably intercepted and emitted as pytest events. This ensures that warnings such as deprecations or runtime alerts are surfaced during test collection, execution, and teardown, improving test diagnostics and user awareness.

Key functionalities include:

This module ensures seamless integration of Python warnings into the pytest ecosystem, improving warning visibility and control.


Detailed Explanations

Function: catch_warnings_for_item

@contextmanager
def catch_warnings_for_item(
    config: Config,
    ihook,
    when: Literal["config", "collect", "runtest"],
    item: Item | None,
    *,
    record: bool = True,
) -> Generator[None]:

Purpose

A context manager that captures Python warnings emitted during a block of code executed within pytest. It applies configured warning filters from pytest ini files, command-line options, and test markers, then records warnings if requested and triggers the `pytest_warning_recorded` hook for each captured warning.

Parameters

Returns

Usage Example

with catch_warnings_for_item(config, ihook, "runtest", item):
    # Code executed here will have warnings captured,
    # filtered, and recorded according to configuration
    run_test_function()

Implementation Details


Function: warning_record_to_str

def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:

Purpose

Converts a captured `warnings.WarningMessage` object into a formatted string suitable for terminal output or logging, including traceback memory allocation info if available.

Parameters

Returns

Usage Example

formatted_warning = warning_record_to_str(warning_message)
print(formatted_warning)

Hook Wrapper: pytest_runtest_protocol

@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:

Purpose

Wraps the test execution phase (`runtest`) in the `catch_warnings_for_item` context manager to capture warnings emitted during individual test execution.

Parameters

Returns

Usage

Automatically called by pytest during test execution; test authors do not call this directly.


Hook Wrapper: pytest_collection

@pytest.hookimpl(wrapper=True, tryfirst=True)
def pytest_collection(session: Session) -> Generator[None, object, object]:

Purpose

Wraps the test collection phase in the `catch_warnings_for_item` context manager to capture warnings emitted during test discovery.

Parameters

Returns


Hook Wrappers: pytest_terminal_summary, pytest_sessionfinish, pytest_load_initial_conftests

These hooks similarly wrap their respective pytest phases (`terminal_summary`, `sessionfinish`, `load_initial_conftests`) in the warning capture context, ensuring warnings emitted late in the test lifecycle are captured and reported.


Function: pytest_configure

def pytest_configure(config: Config) -> None:

Purpose

Performs pytest configuration initialization related to warnings:

Parameters


Important Implementation Details and Algorithms


Interaction with Other Parts of the System


Visual Diagram: Class and Function Structure

flowchart TD
    A[catch_warnings_for_item] -->|uses| B[warnings.catch_warnings]
    A --> C[apply_warning_filters]
    A --> D[pytest_warning_recorded hook]

    E[pytest_runtest_protocol] -->|wraps with| A
    F[pytest_collection] -->|wraps with| A
    G[pytest_terminal_summary] -->|wraps with| A
    H[pytest_sessionfinish] -->|wraps with| A
    I[pytest_load_initial_conftests] -->|wraps with| A

    J[pytest_configure] -->|adds filterwarnings marker and sets up non-recording context| A

    K[warning_record_to_str] -->|formats| L[warnings.WarningMessage]

    subgraph Warnings Handling
        A
        K
    end

    subgraph Pytest Hooks Wrappers
        E
        F
        G
        H
        I
        J
    end

Summary

The `warnings.py` file provides pytest with a robust mechanism to **capture, filter, record, and report Python warnings** during test execution. By wrapping core pytest lifecycle hooks with a specialized context manager, it ensures that warnings are not lost but instead processed according to user configuration and test-specific markers. The integration with pytest’s hook system allows flexible reporting and further processing by plugins. Additionally, it enhances warning messages with memory tracing data for improved diagnostics. This module is essential for maintaining high code quality and developer awareness by making runtime warnings visible and actionable within pytest.


Appendix: Example Usage in Tests

Although the functions in this file are mostly internal to pytest, users can benefit from the `filterwarnings` marker added by `pytest_configure`:

import pytest

@pytest.mark.filterwarnings("ignore::DeprecationWarning")
def test_deprecated_usage():
    import warnings
    warnings.warn("deprecated feature used", DeprecationWarning)
    # This warning will be ignored due to the marker

This marker allows per-test customization of which warnings are filtered, complementing global configuration.


End of Documentation for warnings.py