Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/warnings.py

raw
1 # mypy: allow-untyped-defs
2 from contextlib import contextmanager
3 import sys
4 from typing import Generator
5 from typing import Literal
6 from typing import Optional
7 import warnings
8
9 from _pytest.config import apply_warning_filters
10 from _pytest.config import Config
11 from _pytest.config import parse_warning_filter
12 from _pytest.main import Session
13 from _pytest.nodes import Item
14 from _pytest.terminal import TerminalReporter
15 import pytest
16
17
18 def pytest_configure(config: Config) -> None:
19 config.addinivalue_line(
20 "markers",
21 "filterwarnings(warning): add a warning filter to the given test. "
22 "see https://docs.pytest.org/en/stable/how-to/capture-warnings.html#pytest-mark-filterwarnings ",
23 )
24
25
26 @contextmanager
27 def catch_warnings_for_item(
28 config: Config,
29 ihook,
30 when: Literal["config", "collect", "runtest"],
31 item: Optional[Item],
32 ) -> Generator[None, None, None]:
33 """Context manager that catches warnings generated in the contained execution block.
34
35 ``item`` can be None if we are not in the context of an item execution.
36
37 Each warning captured triggers the ``pytest_warning_recorded`` hook.
38 """
39 config_filters = config.getini("filterwarnings")
40 cmdline_filters = config.known_args_namespace.pythonwarnings or []
41 with warnings.catch_warnings(record=True) as log:
42 # mypy can't infer that record=True means log is not None; help it.
43 assert log is not None
44
45 if not sys.warnoptions:
46 # If user is not explicitly configuring warning filters, show deprecation warnings by default (#2908).
47 warnings.filterwarnings("always", category=DeprecationWarning)
48 warnings.filterwarnings("always", category=PendingDeprecationWarning)
49
50 # To be enabled in pytest 9.0.0.
51 # warnings.filterwarnings("error", category=pytest.PytestRemovedIn9Warning)
52
53 apply_warning_filters(config_filters, cmdline_filters)
54
55 # apply filters from "filterwarnings" marks
56 nodeid = "" if item is None else item.nodeid
57 if item is not None:
58 for mark in item.iter_markers(name="filterwarnings"):
59 for arg in mark.args:
60 warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
61
62 try:
63 yield
64 finally:
65 for warning_message in log:
66 ihook.pytest_warning_recorded.call_historic(
67 kwargs=dict(
68 warning_message=warning_message,
69 nodeid=nodeid,
70 when=when,
71 location=None,
72 )
73 )
74
75
76 def warning_record_to_str(warning_message: warnings.WarningMessage) -> str:
77 """Convert a warnings.WarningMessage to a string."""
78 warn_msg = warning_message.message
79 msg = warnings.formatwarning(
80 str(warn_msg),
81 warning_message.category,
82 warning_message.filename,
83 warning_message.lineno,
84 warning_message.line,
85 )
86 if warning_message.source is not None:
87 try:
88 import tracemalloc
89 except ImportError:
90 pass
91 else:
92 tb = tracemalloc.get_object_traceback(warning_message.source)
93 if tb is not None:
94 formatted_tb = "\n".join(tb.format())
95 # Use a leading new line to better separate the (large) output
96 # from the traceback to the previous warning text.
97 msg += f"\nObject allocated at:\n{formatted_tb}"
98 else:
99 # No need for a leading new line.
100 url = "https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings"
101 msg += "Enable tracemalloc to get traceback where the object was allocated.\n"
102 msg += f"See {url} for more info."
103 return msg
104
105
106 @pytest.hookimpl(wrapper=True, tryfirst=True)
107 def pytest_runtest_protocol(item: Item) -> Generator[None, object, object]:
108 with catch_warnings_for_item(
109 config=item.config, ihook=item.ihook, when="runtest", item=item
110 ):
111 return (yield)
112
113
114 @pytest.hookimpl(wrapper=True, tryfirst=True)
115 def pytest_collection(session: Session) -> Generator[None, object, object]:
116 config = session.config
117 with catch_warnings_for_item(
118 config=config, ihook=config.hook, when="collect", item=None
119 ):
120 return (yield)
121
122
123 @pytest.hookimpl(wrapper=True)
124 def pytest_terminal_summary(
125 terminalreporter: TerminalReporter,
126 ) -> Generator[None, None, None]:
127 config = terminalreporter.config
128 with catch_warnings_for_item(
129 config=config, ihook=config.hook, when="config", item=None
130 ):
131 return (yield)
132
133
134 @pytest.hookimpl(wrapper=True)
135 def pytest_sessionfinish(session: Session) -> Generator[None, None, None]:
136 config = session.config
137 with catch_warnings_for_item(
138 config=config, ihook=config.hook, when="config", item=None
139 ):
140 return (yield)
141
142
143 @pytest.hookimpl(wrapper=True)
144 def pytest_load_initial_conftests(
145 early_config: "Config",
146 ) -> Generator[None, None, None]:
147 with catch_warnings_for_item(
148 config=early_config, ihook=early_config.hook, when="config", item=None
149 ):
150 return (yield)