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