recwarn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """Record warnings during test function execution."""
  2. import re
  3. import warnings
  4. from types import TracebackType
  5. from typing import Any
  6. from typing import Callable
  7. from typing import Generator
  8. from typing import Iterator
  9. from typing import List
  10. from typing import Optional
  11. from typing import overload
  12. from typing import Pattern
  13. from typing import Tuple
  14. from typing import Type
  15. from typing import TypeVar
  16. from typing import Union
  17. from _pytest.compat import final
  18. from _pytest.deprecated import check_ispytest
  19. from _pytest.deprecated import WARNS_NONE_ARG
  20. from _pytest.fixtures import fixture
  21. from _pytest.outcomes import fail
  22. T = TypeVar("T")
  23. @fixture
  24. def recwarn() -> Generator["WarningsRecorder", None, None]:
  25. """Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
  26. See https://docs.python.org/library/how-to/capture-warnings.html for information
  27. on warning categories.
  28. """
  29. wrec = WarningsRecorder(_ispytest=True)
  30. with wrec:
  31. warnings.simplefilter("default")
  32. yield wrec
  33. @overload
  34. def deprecated_call(
  35. *, match: Optional[Union[str, Pattern[str]]] = ...
  36. ) -> "WarningsRecorder":
  37. ...
  38. @overload
  39. def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
  40. ...
  41. def deprecated_call(
  42. func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any
  43. ) -> Union["WarningsRecorder", Any]:
  44. """Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning``.
  45. This function can be used as a context manager::
  46. >>> import warnings
  47. >>> def api_call_v2():
  48. ... warnings.warn('use v3 of this api', DeprecationWarning)
  49. ... return 200
  50. >>> import pytest
  51. >>> with pytest.deprecated_call():
  52. ... assert api_call_v2() == 200
  53. It can also be used by passing a function and ``*args`` and ``**kwargs``,
  54. in which case it will ensure calling ``func(*args, **kwargs)`` produces one of
  55. the warnings types above. The return value is the return value of the function.
  56. In the context manager form you may use the keyword argument ``match`` to assert
  57. that the warning matches a text or regex.
  58. The context manager produces a list of :class:`warnings.WarningMessage` objects,
  59. one for each warning raised.
  60. """
  61. __tracebackhide__ = True
  62. if func is not None:
  63. args = (func,) + args
  64. return warns((DeprecationWarning, PendingDeprecationWarning), *args, **kwargs)
  65. @overload
  66. def warns(
  67. expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ...,
  68. *,
  69. match: Optional[Union[str, Pattern[str]]] = ...,
  70. ) -> "WarningsChecker":
  71. ...
  72. @overload
  73. def warns(
  74. expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]],
  75. func: Callable[..., T],
  76. *args: Any,
  77. **kwargs: Any,
  78. ) -> T:
  79. ...
  80. def warns(
  81. expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
  82. *args: Any,
  83. match: Optional[Union[str, Pattern[str]]] = None,
  84. **kwargs: Any,
  85. ) -> Union["WarningsChecker", Any]:
  86. r"""Assert that code raises a particular class of warning.
  87. Specifically, the parameter ``expected_warning`` can be a warning class or
  88. sequence of warning classes, and the inside the ``with`` block must issue a warning of that class or
  89. classes.
  90. This helper produces a list of :class:`warnings.WarningMessage` objects,
  91. one for each warning raised.
  92. This function can be used as a context manager, or any of the other ways
  93. :func:`pytest.raises` can be used::
  94. >>> import pytest
  95. >>> with pytest.warns(RuntimeWarning):
  96. ... warnings.warn("my warning", RuntimeWarning)
  97. In the context manager form you may use the keyword argument ``match`` to assert
  98. that the warning matches a text or regex::
  99. >>> with pytest.warns(UserWarning, match='must be 0 or None'):
  100. ... warnings.warn("value must be 0 or None", UserWarning)
  101. >>> with pytest.warns(UserWarning, match=r'must be \d+$'):
  102. ... warnings.warn("value must be 42", UserWarning)
  103. >>> with pytest.warns(UserWarning, match=r'must be \d+$'):
  104. ... warnings.warn("this is not here", UserWarning)
  105. Traceback (most recent call last):
  106. ...
  107. Failed: DID NOT WARN. No warnings of type ...UserWarning... were emitted...
  108. """
  109. __tracebackhide__ = True
  110. if not args:
  111. if kwargs:
  112. msg = "Unexpected keyword arguments passed to pytest.warns: "
  113. msg += ", ".join(sorted(kwargs))
  114. msg += "\nUse context-manager form instead?"
  115. raise TypeError(msg)
  116. return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)
  117. else:
  118. func = args[0]
  119. if not callable(func):
  120. raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
  121. with WarningsChecker(expected_warning, _ispytest=True):
  122. return func(*args[1:], **kwargs)
  123. class WarningsRecorder(warnings.catch_warnings):
  124. """A context manager to record raised warnings.
  125. Each recorded warning is an instance of :class:`warnings.WarningMessage`.
  126. Adapted from `warnings.catch_warnings`.
  127. .. note::
  128. ``DeprecationWarning`` and ``PendingDeprecationWarning`` are treated
  129. differently; see :ref:`ensuring_function_triggers`.
  130. """
  131. def __init__(self, *, _ispytest: bool = False) -> None:
  132. check_ispytest(_ispytest)
  133. # Type ignored due to the way typeshed handles warnings.catch_warnings.
  134. super().__init__(record=True) # type: ignore[call-arg]
  135. self._entered = False
  136. self._list: List[warnings.WarningMessage] = []
  137. @property
  138. def list(self) -> List["warnings.WarningMessage"]:
  139. """The list of recorded warnings."""
  140. return self._list
  141. def __getitem__(self, i: int) -> "warnings.WarningMessage":
  142. """Get a recorded warning by index."""
  143. return self._list[i]
  144. def __iter__(self) -> Iterator["warnings.WarningMessage"]:
  145. """Iterate through the recorded warnings."""
  146. return iter(self._list)
  147. def __len__(self) -> int:
  148. """The number of recorded warnings."""
  149. return len(self._list)
  150. def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":
  151. """Pop the first recorded warning, raise exception if not exists."""
  152. for i, w in enumerate(self._list):
  153. if issubclass(w.category, cls):
  154. return self._list.pop(i)
  155. __tracebackhide__ = True
  156. raise AssertionError("%r not found in warning list" % cls)
  157. def clear(self) -> None:
  158. """Clear the list of recorded warnings."""
  159. self._list[:] = []
  160. # Type ignored because it doesn't exactly warnings.catch_warnings.__enter__
  161. # -- it returns a List but we only emulate one.
  162. def __enter__(self) -> "WarningsRecorder": # type: ignore
  163. if self._entered:
  164. __tracebackhide__ = True
  165. raise RuntimeError("Cannot enter %r twice" % self)
  166. _list = super().__enter__()
  167. # record=True means it's None.
  168. assert _list is not None
  169. self._list = _list
  170. warnings.simplefilter("always")
  171. return self
  172. def __exit__(
  173. self,
  174. exc_type: Optional[Type[BaseException]],
  175. exc_val: Optional[BaseException],
  176. exc_tb: Optional[TracebackType],
  177. ) -> None:
  178. if not self._entered:
  179. __tracebackhide__ = True
  180. raise RuntimeError("Cannot exit %r without entering first" % self)
  181. super().__exit__(exc_type, exc_val, exc_tb)
  182. # Built-in catch_warnings does not reset entered state so we do it
  183. # manually here for this context manager to become reusable.
  184. self._entered = False
  185. @final
  186. class WarningsChecker(WarningsRecorder):
  187. def __init__(
  188. self,
  189. expected_warning: Optional[
  190. Union[Type[Warning], Tuple[Type[Warning], ...]]
  191. ] = Warning,
  192. match_expr: Optional[Union[str, Pattern[str]]] = None,
  193. *,
  194. _ispytest: bool = False,
  195. ) -> None:
  196. check_ispytest(_ispytest)
  197. super().__init__(_ispytest=True)
  198. msg = "exceptions must be derived from Warning, not %s"
  199. if expected_warning is None:
  200. warnings.warn(WARNS_NONE_ARG, stacklevel=4)
  201. expected_warning_tup = None
  202. elif isinstance(expected_warning, tuple):
  203. for exc in expected_warning:
  204. if not issubclass(exc, Warning):
  205. raise TypeError(msg % type(exc))
  206. expected_warning_tup = expected_warning
  207. elif issubclass(expected_warning, Warning):
  208. expected_warning_tup = (expected_warning,)
  209. else:
  210. raise TypeError(msg % type(expected_warning))
  211. self.expected_warning = expected_warning_tup
  212. self.match_expr = match_expr
  213. def __exit__(
  214. self,
  215. exc_type: Optional[Type[BaseException]],
  216. exc_val: Optional[BaseException],
  217. exc_tb: Optional[TracebackType],
  218. ) -> None:
  219. super().__exit__(exc_type, exc_val, exc_tb)
  220. __tracebackhide__ = True
  221. # only check if we're not currently handling an exception
  222. if exc_type is None and exc_val is None and exc_tb is None:
  223. if self.expected_warning is not None:
  224. if not any(issubclass(r.category, self.expected_warning) for r in self):
  225. __tracebackhide__ = True
  226. fail(
  227. "DID NOT WARN. No warnings of type {} were emitted. "
  228. "The list of emitted warnings is: {}.".format(
  229. self.expected_warning, [each.message for each in self]
  230. )
  231. )
  232. elif self.match_expr is not None:
  233. for r in self:
  234. if issubclass(r.category, self.expected_warning):
  235. if re.compile(self.match_expr).search(str(r.message)):
  236. break
  237. else:
  238. fail(
  239. "DID NOT WARN. No warnings of type {} matching"
  240. " ('{}') were emitted. The list of emitted warnings"
  241. " is: {}.".format(
  242. self.expected_warning,
  243. self.match_expr,
  244. [each.message for each in self],
  245. )
  246. )