Debian Codegraph @

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

raw
1 # mypy: allow-untyped-defs
2 """Record warnings during test function execution."""
3
4 from pprint import pformat
5 import re
6 from types import TracebackType
7 from typing import Any
8 from typing import Callable
9 from typing import final
10 from typing import Generator
11 from typing import Iterator
12 from typing import List
13 from typing import Optional
14 from typing import overload
15 from typing import Pattern
16 from typing import Tuple
17 from typing import Type
18 from typing import TypeVar
19 from typing import Union
20 import warnings
21
22 from _pytest.deprecated import check_ispytest
23 from _pytest.fixtures import fixture
24 from _pytest.outcomes import Exit
25 from _pytest.outcomes import fail
26
27
28 T = TypeVar("T")
29
30
31 @fixture
32 def recwarn() -> Generator["WarningsRecorder", None, None]:
33 """Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
34
35 See https://docs.pytest.org/en/latest/how-to/capture-warnings.html for information
36 on warning categories.
37 """
38 wrec = WarningsRecorder(_ispytest=True)
39 with wrec:
40 warnings.simplefilter("default")
41 yield wrec
42
43
44 @overload
45 def deprecated_call(
46 *, match: Optional[Union[str, Pattern[str]]] = ...
47 ) -> "WarningsRecorder": ...
48
49
50 @overload
51 def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T: ...
52
53
54 def deprecated_call(
55 func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any
56 ) -> Union["WarningsRecorder", Any]:
57 """Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``.
58
59 This function can be used as a context manager::
60
61 >>> import warnings
62 >>> def api_call_v2():
63 ... warnings.warn('use v3 of this api', DeprecationWarning)
64 ... return 200
65
66 >>> import pytest
67 >>> with pytest.deprecated_call():
68 ... assert api_call_v2() == 200
69
70 It can also be used by passing a function and ``*args`` and ``**kwargs``,
71 in which case it will ensure calling ``func(*args, **kwargs)`` produces one of
72 the warnings types above. The return value is the return value of the function.
73
74 In the context manager form you may use the keyword argument ``match`` to assert
75 that the warning matches a text or regex.
76
77 The context manager produces a list of :class:`warnings.WarningMessage` objects,
78 one for each warning raised.
79 """
80 __tracebackhide__ = True
81 if func is not None:
82 args = (func, *args)
83 return warns(
84 (DeprecationWarning, PendingDeprecationWarning, FutureWarning), *args, **kwargs
85 )
86
87
88 @overload
89 def warns(
90 expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ...,
91 *,
92 match: Optional[Union[str, Pattern[str]]] = ...,
93 ) -> "WarningsChecker": ...
94
95
96 @overload
97 def warns(
98 expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]],
99 func: Callable[..., T],
100 *args: Any,
101 **kwargs: Any,
102 ) -> T: ...
103
104
105 def warns(
106 expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
107 *args: Any,
108 match: Optional[Union[str, Pattern[str]]] = None,
109 **kwargs: Any,
110 ) -> Union["WarningsChecker", Any]:
111 r"""Assert that code raises a particular class of warning.
112
113 Specifically, the parameter ``expected_warning`` can be a warning class or tuple
114 of warning classes, and the code inside the ``with`` block must issue at least one
115 warning of that class or classes.
116
117 This helper produces a list of :class:`warnings.WarningMessage` objects, one for
118 each warning emitted (regardless of whether it is an ``expected_warning`` or not).
119 Since pytest 8.0, unmatched warnings are also re-emitted when the context closes.
120
121 This function can be used as a context manager::
122
123 >>> import pytest
124 >>> with pytest.warns(RuntimeWarning):
125 ... warnings.warn("my warning", RuntimeWarning)
126
127 In the context manager form you may use the keyword argument ``match`` to assert
128 that the warning matches a text or regex::
129
130 >>> with pytest.warns(UserWarning, match='must be 0 or None'):
131 ... warnings.warn("value must be 0 or None", UserWarning)
132
133 >>> with pytest.warns(UserWarning, match=r'must be \d+$'):
134 ... warnings.warn("value must be 42", UserWarning)
135
136 >>> with pytest.warns(UserWarning): # catch re-emitted warning
137 ... with pytest.warns(UserWarning, match=r'must be \d+$'):
138 ... warnings.warn("this is not here", UserWarning)
139 Traceback (most recent call last):
140 ...
141 Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
142
143 **Using with** ``pytest.mark.parametrize``
144
145 When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests
146 such that some runs raise a warning and others do not.
147
148 This could be achieved in the same way as with exceptions, see
149 :ref:`parametrizing_conditional_raising` for an example.
150
151 """
152 __tracebackhide__ = True
153 if not args:
154 if kwargs:
155 argnames = ", ".join(sorted(kwargs))
156 raise TypeError(
157 f"Unexpected keyword arguments passed to pytest.warns: {argnames}"
158 "\nUse context-manager form instead?"
159 )
160 return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)
161 else:
162 func = args[0]
163 if not callable(func):
164 raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
165 with WarningsChecker(expected_warning, _ispytest=True):
166 return func(*args[1:], **kwargs)
167
168
169 class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
170 """A context manager to record raised warnings.
171
172 Each recorded warning is an instance of :class:`warnings.WarningMessage`.
173
174 Adapted from `warnings.catch_warnings`.
175
176 .. note::
177 ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated
178 differently; see :ref:`ensuring_function_triggers`.
179
180 """
181
182 def __init__(self, *, _ispytest: bool = False) -> None:
183 check_ispytest(_ispytest)
184 super().__init__(record=True)
185 self._entered = False
186 self._list: List[warnings.WarningMessage] = []
187
188 @property
189 def list(self) -> List["warnings.WarningMessage"]:
190 """The list of recorded warnings."""
191 return self._list
192
193 def __getitem__(self, i: int) -> "warnings.WarningMessage":
194 """Get a recorded warning by index."""
195 return self._list[i]
196
197 def __iter__(self) -> Iterator["warnings.WarningMessage"]:
198 """Iterate through the recorded warnings."""
199 return iter(self._list)
200
201 def __len__(self) -> int:
202 """The number of recorded warnings."""
203 return len(self._list)
204
205 def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":
206 """Pop the first recorded warning which is an instance of ``cls``,
207 but not an instance of a child class of any other match.
208 Raises ``AssertionError`` if there is no match.
209 """
210 best_idx: Optional[int] = None
211 for i, w in enumerate(self._list):
212 if w.category == cls:
213 return self._list.pop(i) # exact match, stop looking
214 if issubclass(w.category, cls) and (
215 best_idx is None
216 or not issubclass(w.category, self._list[best_idx].category)
217 ):
218 best_idx = i
219 if best_idx is not None:
220 return self._list.pop(best_idx)
221 __tracebackhide__ = True
222 raise AssertionError(f"{cls!r} not found in warning list")
223
224 def clear(self) -> None:
225 """Clear the list of recorded warnings."""
226 self._list[:] = []
227
228 # Type ignored because it doesn't exactly warnings.catch_warnings.__enter__
229 # -- it returns a List but we only emulate one.
230 def __enter__(self) -> "WarningsRecorder": # type: ignore
231 if self._entered:
232 __tracebackhide__ = True
233 raise RuntimeError(f"Cannot enter {self!r} twice")
234 _list = super().__enter__()
235 # record=True means it's None.
236 assert _list is not None
237 self._list = _list
238 warnings.simplefilter("always")
239 return self
240
241 def __exit__(
242 self,
243 exc_type: Optional[Type[BaseException]],
244 exc_val: Optional[BaseException],
245 exc_tb: Optional[TracebackType],
246 ) -> None:
247 if not self._entered:
248 __tracebackhide__ = True
249 raise RuntimeError(f"Cannot exit {self!r} without entering first")
250
251 super().__exit__(exc_type, exc_val, exc_tb)
252
253 # Built-in catch_warnings does not reset entered state so we do it
254 # manually here for this context manager to become reusable.
255 self._entered = False
256
257
258 @final
259 class WarningsChecker(WarningsRecorder):
260 def __init__(
261 self,
262 expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
263 match_expr: Optional[Union[str, Pattern[str]]] = None,
264 *,
265 _ispytest: bool = False,
266 ) -> None:
267 check_ispytest(_ispytest)
268 super().__init__(_ispytest=True)
269
270 msg = "exceptions must be derived from Warning, not %s"
271 if isinstance(expected_warning, tuple):
272 for exc in expected_warning:
273 if not issubclass(exc, Warning):
274 raise TypeError(msg % type(exc))
275 expected_warning_tup = expected_warning
276 elif isinstance(expected_warning, type) and issubclass(
277 expected_warning, Warning
278 ):
279 expected_warning_tup = (expected_warning,)
280 else:
281 raise TypeError(msg % type(expected_warning))
282
283 self.expected_warning = expected_warning_tup
284 self.match_expr = match_expr
285
286 def matches(self, warning: warnings.WarningMessage) -> bool:
287 assert self.expected_warning is not None
288 return issubclass(warning.category, self.expected_warning) and bool(
289 self.match_expr is None or re.search(self.match_expr, str(warning.message))
290 )
291
292 def __exit__(
293 self,
294 exc_type: Optional[Type[BaseException]],
295 exc_val: Optional[BaseException],
296 exc_tb: Optional[TracebackType],
297 ) -> None:
298 super().__exit__(exc_type, exc_val, exc_tb)
299
300 __tracebackhide__ = True
301
302 # BaseExceptions like pytest.{skip,fail,xfail,exit} or Ctrl-C within
303 # pytest.warns should *not* trigger "DID NOT WARN" and get suppressed
304 # when the warning doesn't happen. Control-flow exceptions should always
305 # propagate.
306 if exc_val is not None and (
307 not isinstance(exc_val, Exception)
308 # Exit is an Exception, not a BaseException, for some reason.
309 or isinstance(exc_val, Exit)
310 ):
311 return
312
313 def found_str() -> str:
314 return pformat([record.message for record in self], indent=2)
315
316 try:
317 if not any(issubclass(w.category, self.expected_warning) for w in self):
318 fail(
319 f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
320 f" Emitted warnings: {found_str()}."
321 )
322 elif not any(self.matches(w) for w in self):
323 fail(
324 f"DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.\n"
325 f" Regex: {self.match_expr}\n"
326 f" Emitted warnings: {found_str()}."
327 )
328 finally:
329 # Whether or not any warnings matched, we want to re-emit all unmatched warnings.
330 for w in self:
331 if not self.matches(w):
332 warnings.warn_explicit(
333 message=w.message,
334 category=w.category,
335 filename=w.filename,
336 lineno=w.lineno,
337 module=w.__module__,
338 source=w.source,
339 )
340
341 # Currently in Python it is possible to pass other types than an
342 # `str` message when creating `Warning` instances, however this
343 # causes an exception when :func:`warnings.filterwarnings` is used
344 # to filter those warnings. See
345 # https://github.com/python/cpython/issues/103577 for a discussion.
346 # While this can be considered a bug in CPython, we put guards in
347 # pytest as the error message produced without this check in place
348 # is confusing (#10865).
349 for w in self:
350 if type(w.message) is not UserWarning:
351 # If the warning was of an incorrect type then `warnings.warn()`
352 # creates a UserWarning. Any other warning must have been specified
353 # explicitly.
354 continue
355 if not w.message.args:
356 # UserWarning() without arguments must have been specified explicitly.
357 continue
358 msg = w.message.args[0]
359 if isinstance(msg, str):
360 continue
361 # It's possible that UserWarning was explicitly specified, and
362 # its first argument was not a string. But that case can't be
363 # distinguished from an invalid type.
364 raise TypeError(
365 f"Warning must be str or Warning, got {msg!r} (type {type(msg).__name__})"
366 )