recwarn.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. Adapted from `warnings.catch_warnings`.
  126. """
  127. def __init__(self, *, _ispytest: bool = False) -> None:
  128. check_ispytest(_ispytest)
  129. # Type ignored due to the way typeshed handles warnings.catch_warnings.
  130. super().__init__(record=True) # type: ignore[call-arg]
  131. self._entered = False
  132. self._list: List[warnings.WarningMessage] = []
  133. @property
  134. def list(self) -> List["warnings.WarningMessage"]:
  135. """The list of recorded warnings."""
  136. return self._list
  137. def __getitem__(self, i: int) -> "warnings.WarningMessage":
  138. """Get a recorded warning by index."""
  139. return self._list[i]
  140. def __iter__(self) -> Iterator["warnings.WarningMessage"]:
  141. """Iterate through the recorded warnings."""
  142. return iter(self._list)
  143. def __len__(self) -> int:
  144. """The number of recorded warnings."""
  145. return len(self._list)
  146. def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":
  147. """Pop the first recorded warning, raise exception if not exists."""
  148. for i, w in enumerate(self._list):
  149. if issubclass(w.category, cls):
  150. return self._list.pop(i)
  151. __tracebackhide__ = True
  152. raise AssertionError("%r not found in warning list" % cls)
  153. def clear(self) -> None:
  154. """Clear the list of recorded warnings."""
  155. self._list[:] = []
  156. # Type ignored because it doesn't exactly warnings.catch_warnings.__enter__
  157. # -- it returns a List but we only emulate one.
  158. def __enter__(self) -> "WarningsRecorder": # type: ignore
  159. if self._entered:
  160. __tracebackhide__ = True
  161. raise RuntimeError("Cannot enter %r twice" % self)
  162. _list = super().__enter__()
  163. # record=True means it's None.
  164. assert _list is not None
  165. self._list = _list
  166. warnings.simplefilter("always")
  167. return self
  168. def __exit__(
  169. self,
  170. exc_type: Optional[Type[BaseException]],
  171. exc_val: Optional[BaseException],
  172. exc_tb: Optional[TracebackType],
  173. ) -> None:
  174. if not self._entered:
  175. __tracebackhide__ = True
  176. raise RuntimeError("Cannot exit %r without entering first" % self)
  177. super().__exit__(exc_type, exc_val, exc_tb)
  178. # Built-in catch_warnings does not reset entered state so we do it
  179. # manually here for this context manager to become reusable.
  180. self._entered = False
  181. @final
  182. class WarningsChecker(WarningsRecorder):
  183. def __init__(
  184. self,
  185. expected_warning: Optional[
  186. Union[Type[Warning], Tuple[Type[Warning], ...]]
  187. ] = Warning,
  188. match_expr: Optional[Union[str, Pattern[str]]] = None,
  189. *,
  190. _ispytest: bool = False,
  191. ) -> None:
  192. check_ispytest(_ispytest)
  193. super().__init__(_ispytest=True)
  194. msg = "exceptions must be derived from Warning, not %s"
  195. if expected_warning is None:
  196. warnings.warn(WARNS_NONE_ARG, stacklevel=4)
  197. expected_warning_tup = None
  198. elif isinstance(expected_warning, tuple):
  199. for exc in expected_warning:
  200. if not issubclass(exc, Warning):
  201. raise TypeError(msg % type(exc))
  202. expected_warning_tup = expected_warning
  203. elif issubclass(expected_warning, Warning):
  204. expected_warning_tup = (expected_warning,)
  205. else:
  206. raise TypeError(msg % type(expected_warning))
  207. self.expected_warning = expected_warning_tup
  208. self.match_expr = match_expr
  209. def __exit__(
  210. self,
  211. exc_type: Optional[Type[BaseException]],
  212. exc_val: Optional[BaseException],
  213. exc_tb: Optional[TracebackType],
  214. ) -> None:
  215. super().__exit__(exc_type, exc_val, exc_tb)
  216. __tracebackhide__ = True
  217. # only check if we're not currently handling an exception
  218. if exc_type is None and exc_val is None and exc_tb is None:
  219. if self.expected_warning is not None:
  220. if not any(issubclass(r.category, self.expected_warning) for r in self):
  221. __tracebackhide__ = True
  222. fail(
  223. "DID NOT WARN. No warnings of type {} were emitted. "
  224. "The list of emitted warnings is: {}.".format(
  225. self.expected_warning, [each.message for each in self]
  226. )
  227. )
  228. elif self.match_expr is not None:
  229. for r in self:
  230. if issubclass(r.category, self.expected_warning):
  231. if re.compile(self.match_expr).search(str(r.message)):
  232. break
  233. else:
  234. fail(
  235. "DID NOT WARN. No warnings of type {} matching"
  236. " ('{}') were emitted. The list of emitted warnings"
  237. " is: {}.".format(
  238. self.expected_warning,
  239. self.match_expr,
  240. [each.message for each in self],
  241. )
  242. )