Debian Codegraph @

src/_pytest/warnings.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 from contextlib import contextmanager
6 from contextlib import ExitStack
7 import sys
8 from typing import Literal
9 import warnings
10
11 from _pytest.config import apply_warning_filters
12 from _pytest.config import Config
13 from _pytest.config import parse_warning_filter
14 from _pytest.main import Session
15 from _pytest.nodes import Item
16 from _pytest.terminal import TerminalReporter
17 from _pytest.tracemalloc import tracemalloc_message
18 import pytest
19
20
21 @contextmanager
22 def 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
74 def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:
75 """Convert a warnings.WarningMessage to a string."""
76 return warnings.formatwarning(
77 str(warning_message.message),
78 warning_message.category,
79 warning_message.filename,
80 warning_message.lineno,
81 warning_message.line,
82 ) + tracemalloc_message(warning_message.source)
83
84
85 @pytest.hookimpl(wrapper=True, tryfirst=True)
86 def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
87 with catch_warnings_for_item(
88 config=item.config, ihook=item.ihook, when="runtest", item=item
89 ):
90 return (yield)
91
92
93 @pytest.hookimpl(wrapper=True, tryfirst=True)
94 def pytest_collection(session: Session) -> Generator[None, object, object]:
95 config = session.config
96 with catch_warnings_for_item(
97 config=config, ihook=config.hook, when="collect", item=None
98 ):
99 return (yield)
100
101
102 @pytest.hookimpl(wrapper=True)
103 def pytest_terminal_summary(
104 terminalreporter: TerminalReporter,
105 ) -> Generator[None]:
106 config = terminalreporter.config
107 with catch_warnings_for_item(
108 config=config, ihook=config.hook, when="config", item=None
109 ):
110 return (yield)
111
112
113 @pytest.hookimpl(wrapper=True)
114 def pytest_sessionfinish(session: Session) -> Generator[None]:
115 config = session.config
116 with catch_warnings_for_item(
117 config=config, ihook=config.hook, when="config", item=None
118 ):
119 return (yield)
120
121
122 @pytest.hookimpl(wrapper=True)
123 def pytest_load_initial_conftests(
124 early_config: Config,
125 ) -> Generator[None]:
126 with catch_warnings_for_item(
127 config=early_config, ihook=early_config.hook, when="config", item=None
128 ):
129 return (yield)
130
131
132 def pytest_configure(config: Config) -> None:
133 with ExitStack() as stack:
134 stack.enter_context(
135 catch_warnings_for_item(
136 config=config,
137 ihook=config.hook,
138 when="config",
139 item=None,
140 # this disables recording because the terminalreporter has
141 # finished by the time it comes to reporting logged warnings
142 # from the end of config cleanup. So for now, this is only
143 # useful for setting a warning filter with an 'error' action.
144 record=False,
145 )
146 )
147 config.addinivalue_line(
148 "markers",
149 "filterwarnings(warning): add a warning filter to the given test. "
150 "see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings ",
151 )
152 config.add_cleanup(stack.pop_all().close)