MCPcopy
hub / github.com/pytest-dev/pytest / catch_warnings_for_item

Function catch_warnings_for_item

src/_pytest/warnings.py:22–71  ·  view source on GitHub ↗

Context manager that catches warnings generated in the contained execution block. ``item`` can be None if we are not in the context of an item execution. Each warning captured triggers the ``pytest_warning_recorded`` hook.

(
    config: Config,
    ihook,
    when: Literal["config", "collect", "runtest"],
    item: Item | None,
    *,
    record: bool = True,
)

Source from the content-addressed store, hash-verified

20
21@contextmanager
22def catch_warnings_for_item(
23 config: Config,
24 ihook,
25 when: Literal["config", "collect", "runtest"],
26 item: Item | None,
27 *,
28 record: bool = True,
29) -> Generator[None]:
30 """Context manager that catches warnings generated in the contained execution block.
31
32 ``item`` can be None if we are not in the context of an item execution.
33
34 Each warning captured triggers the ``pytest_warning_recorded`` hook.
35 """
36 config_filters = config.getini("filterwarnings")
37 cmdline_filters = config.known_args_namespace.pythonwarnings or []
38 with warnings.catch_warnings(record=record) as log:
39 if not sys.warnoptions:
40 # If user is not explicitly configuring warning filters, show deprecation warnings by default (#2908).
41 warnings.filterwarnings("always", category=DeprecationWarning)
42 warnings.filterwarnings("always", category=PendingDeprecationWarning)
43
44 # To be enabled in pytest 10.0.0.
45 # warnings.filterwarnings("error", category=pytest.PytestRemovedIn10Warning)
46
47 apply_warning_filters(config_filters, cmdline_filters)
48
49 # apply filters from "filterwarnings" marks
50 nodeid = "" if item is None else item.nodeid
51 if item is not None:
52 for mark in item.iter_markers(name="filterwarnings"):
53 for arg in mark.args:
54 warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
55
56 try:
57 yield
58 finally:
59 if record:
60 # mypy can't infer that record=True means log is not None; help it.
61 assert log is not None
62
63 for warning_message in log:
64 ihook.pytest_warning_recorded.call_historic(
65 kwargs=dict(
66 warning_message=warning_message,
67 nodeid=nodeid,
68 when=when,
69 location=None,
70 )
71 )
72
73
74def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:

Callers 6

pytest_runtest_protocolFunction · 0.85
pytest_collectionFunction · 0.85
pytest_terminal_summaryFunction · 0.85
pytest_sessionfinishFunction · 0.85
pytest_configureFunction · 0.85

Calls 4

apply_warning_filtersFunction · 0.90
parse_warning_filterFunction · 0.90
iter_markersMethod · 0.80
getiniMethod · 0.45

Tested by

no test coverage detected