You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

787 lines
30KB

  1. import math
  2. import pprint
  3. from collections.abc import Iterable
  4. from collections.abc import Mapping
  5. from collections.abc import Sized
  6. from decimal import Decimal
  7. from numbers import Complex
  8. from types import TracebackType
  9. from typing import Any
  10. from typing import Callable
  11. from typing import cast
  12. from typing import Generic
  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 TYPE_CHECKING
  19. from typing import TypeVar
  20. from typing import Union
  21. if TYPE_CHECKING:
  22. from numpy import ndarray
  23. import _pytest._code
  24. from _pytest.compat import final
  25. from _pytest.compat import STRING_TYPES
  26. from _pytest.outcomes import fail
  27. def _non_numeric_type_error(value, at: Optional[str]) -> TypeError:
  28. at_str = f" at {at}" if at else ""
  29. return TypeError(
  30. "cannot make approximate comparisons to non-numeric values: {!r} {}".format(
  31. value, at_str
  32. )
  33. )
  34. # builtin pytest.approx helper
  35. class ApproxBase:
  36. """Provide shared utilities for making approximate comparisons between
  37. numbers or sequences of numbers."""
  38. # Tell numpy to use our `__eq__` operator instead of its.
  39. __array_ufunc__ = None
  40. __array_priority__ = 100
  41. def __init__(self, expected, rel=None, abs=None, nan_ok: bool = False) -> None:
  42. __tracebackhide__ = True
  43. self.expected = expected
  44. self.abs = abs
  45. self.rel = rel
  46. self.nan_ok = nan_ok
  47. self._check_type()
  48. def __repr__(self) -> str:
  49. raise NotImplementedError
  50. def __eq__(self, actual) -> bool:
  51. return all(
  52. a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
  53. )
  54. # Ignore type because of https://github.com/python/mypy/issues/4266.
  55. __hash__ = None # type: ignore
  56. def __ne__(self, actual) -> bool:
  57. return not (actual == self)
  58. def _approx_scalar(self, x) -> "ApproxScalar":
  59. return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
  60. def _yield_comparisons(self, actual):
  61. """Yield all the pairs of numbers to be compared.
  62. This is used to implement the `__eq__` method.
  63. """
  64. raise NotImplementedError
  65. def _check_type(self) -> None:
  66. """Raise a TypeError if the expected value is not a valid type."""
  67. # This is only a concern if the expected value is a sequence. In every
  68. # other case, the approx() function ensures that the expected value has
  69. # a numeric type. For this reason, the default is to do nothing. The
  70. # classes that deal with sequences should reimplement this method to
  71. # raise if there are any non-numeric elements in the sequence.
  72. pass
  73. def _recursive_list_map(f, x):
  74. if isinstance(x, list):
  75. return list(_recursive_list_map(f, xi) for xi in x)
  76. else:
  77. return f(x)
  78. class ApproxNumpy(ApproxBase):
  79. """Perform approximate comparisons where the expected value is numpy array."""
  80. def __repr__(self) -> str:
  81. list_scalars = _recursive_list_map(self._approx_scalar, self.expected.tolist())
  82. return f"approx({list_scalars!r})"
  83. def __eq__(self, actual) -> bool:
  84. import numpy as np
  85. # self.expected is supposed to always be an array here.
  86. if not np.isscalar(actual):
  87. try:
  88. actual = np.asarray(actual)
  89. except Exception as e:
  90. raise TypeError(f"cannot compare '{actual}' to numpy.ndarray") from e
  91. if not np.isscalar(actual) and actual.shape != self.expected.shape:
  92. return False
  93. return ApproxBase.__eq__(self, actual)
  94. def _yield_comparisons(self, actual):
  95. import numpy as np
  96. # `actual` can either be a numpy array or a scalar, it is treated in
  97. # `__eq__` before being passed to `ApproxBase.__eq__`, which is the
  98. # only method that calls this one.
  99. if np.isscalar(actual):
  100. for i in np.ndindex(self.expected.shape):
  101. yield actual, self.expected[i].item()
  102. else:
  103. for i in np.ndindex(self.expected.shape):
  104. yield actual[i].item(), self.expected[i].item()
  105. class ApproxMapping(ApproxBase):
  106. """Perform approximate comparisons where the expected value is a mapping
  107. with numeric values (the keys can be anything)."""
  108. def __repr__(self) -> str:
  109. return "approx({!r})".format(
  110. {k: self._approx_scalar(v) for k, v in self.expected.items()}
  111. )
  112. def __eq__(self, actual) -> bool:
  113. try:
  114. if set(actual.keys()) != set(self.expected.keys()):
  115. return False
  116. except AttributeError:
  117. return False
  118. return ApproxBase.__eq__(self, actual)
  119. def _yield_comparisons(self, actual):
  120. for k in self.expected.keys():
  121. yield actual[k], self.expected[k]
  122. def _check_type(self) -> None:
  123. __tracebackhide__ = True
  124. for key, value in self.expected.items():
  125. if isinstance(value, type(self.expected)):
  126. msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}"
  127. raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))
  128. class ApproxSequencelike(ApproxBase):
  129. """Perform approximate comparisons where the expected value is a sequence of numbers."""
  130. def __repr__(self) -> str:
  131. seq_type = type(self.expected)
  132. if seq_type not in (tuple, list, set):
  133. seq_type = list
  134. return "approx({!r})".format(
  135. seq_type(self._approx_scalar(x) for x in self.expected)
  136. )
  137. def __eq__(self, actual) -> bool:
  138. try:
  139. if len(actual) != len(self.expected):
  140. return False
  141. except TypeError:
  142. return False
  143. return ApproxBase.__eq__(self, actual)
  144. def _yield_comparisons(self, actual):
  145. return zip(actual, self.expected)
  146. def _check_type(self) -> None:
  147. __tracebackhide__ = True
  148. for index, x in enumerate(self.expected):
  149. if isinstance(x, type(self.expected)):
  150. msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}"
  151. raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))
  152. class ApproxScalar(ApproxBase):
  153. """Perform approximate comparisons where the expected value is a single number."""
  154. # Using Real should be better than this Union, but not possible yet:
  155. # https://github.com/python/typeshed/pull/3108
  156. DEFAULT_ABSOLUTE_TOLERANCE: Union[float, Decimal] = 1e-12
  157. DEFAULT_RELATIVE_TOLERANCE: Union[float, Decimal] = 1e-6
  158. def __repr__(self) -> str:
  159. """Return a string communicating both the expected value and the
  160. tolerance for the comparison being made.
  161. For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.
  162. """
  163. # Don't show a tolerance for values that aren't compared using
  164. # tolerances, i.e. non-numerics and infinities. Need to call abs to
  165. # handle complex numbers, e.g. (inf + 1j).
  166. if (not isinstance(self.expected, (Complex, Decimal))) or math.isinf(
  167. abs(self.expected) # type: ignore[arg-type]
  168. ):
  169. return str(self.expected)
  170. # If a sensible tolerance can't be calculated, self.tolerance will
  171. # raise a ValueError. In this case, display '???'.
  172. try:
  173. vetted_tolerance = f"{self.tolerance:.1e}"
  174. if (
  175. isinstance(self.expected, Complex)
  176. and self.expected.imag
  177. and not math.isinf(self.tolerance)
  178. ):
  179. vetted_tolerance += " ∠ ±180°"
  180. except ValueError:
  181. vetted_tolerance = "???"
  182. return f"{self.expected} ± {vetted_tolerance}"
  183. def __eq__(self, actual) -> bool:
  184. """Return whether the given value is equal to the expected value
  185. within the pre-specified tolerance."""
  186. asarray = _as_numpy_array(actual)
  187. if asarray is not None:
  188. # Call ``__eq__()`` manually to prevent infinite-recursion with
  189. # numpy<1.13. See #3748.
  190. return all(self.__eq__(a) for a in asarray.flat)
  191. # Short-circuit exact equality.
  192. if actual == self.expected:
  193. return True
  194. # If either type is non-numeric, fall back to strict equality.
  195. # NB: we need Complex, rather than just Number, to ensure that __abs__,
  196. # __sub__, and __float__ are defined.
  197. if not (
  198. isinstance(self.expected, (Complex, Decimal))
  199. and isinstance(actual, (Complex, Decimal))
  200. ):
  201. return False
  202. # Allow the user to control whether NaNs are considered equal to each
  203. # other or not. The abs() calls are for compatibility with complex
  204. # numbers.
  205. if math.isnan(abs(self.expected)): # type: ignore[arg-type]
  206. return self.nan_ok and math.isnan(abs(actual)) # type: ignore[arg-type]
  207. # Infinity shouldn't be approximately equal to anything but itself, but
  208. # if there's a relative tolerance, it will be infinite and infinity
  209. # will seem approximately equal to everything. The equal-to-itself
  210. # case would have been short circuited above, so here we can just
  211. # return false if the expected value is infinite. The abs() call is
  212. # for compatibility with complex numbers.
  213. if math.isinf(abs(self.expected)): # type: ignore[arg-type]
  214. return False
  215. # Return true if the two numbers are within the tolerance.
  216. result: bool = abs(self.expected - actual) <= self.tolerance
  217. return result
  218. # Ignore type because of https://github.com/python/mypy/issues/4266.
  219. __hash__ = None # type: ignore
  220. @property
  221. def tolerance(self):
  222. """Return the tolerance for the comparison.
  223. This could be either an absolute tolerance or a relative tolerance,
  224. depending on what the user specified or which would be larger.
  225. """
  226. def set_default(x, default):
  227. return x if x is not None else default
  228. # Figure out what the absolute tolerance should be. ``self.abs`` is
  229. # either None or a value specified by the user.
  230. absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)
  231. if absolute_tolerance < 0:
  232. raise ValueError(
  233. f"absolute tolerance can't be negative: {absolute_tolerance}"
  234. )
  235. if math.isnan(absolute_tolerance):
  236. raise ValueError("absolute tolerance can't be NaN.")
  237. # If the user specified an absolute tolerance but not a relative one,
  238. # just return the absolute tolerance.
  239. if self.rel is None:
  240. if self.abs is not None:
  241. return absolute_tolerance
  242. # Figure out what the relative tolerance should be. ``self.rel`` is
  243. # either None or a value specified by the user. This is done after
  244. # we've made sure the user didn't ask for an absolute tolerance only,
  245. # because we don't want to raise errors about the relative tolerance if
  246. # we aren't even going to use it.
  247. relative_tolerance = set_default(
  248. self.rel, self.DEFAULT_RELATIVE_TOLERANCE
  249. ) * abs(self.expected)
  250. if relative_tolerance < 0:
  251. raise ValueError(
  252. f"relative tolerance can't be negative: {absolute_tolerance}"
  253. )
  254. if math.isnan(relative_tolerance):
  255. raise ValueError("relative tolerance can't be NaN.")
  256. # Return the larger of the relative and absolute tolerances.
  257. return max(relative_tolerance, absolute_tolerance)
  258. class ApproxDecimal(ApproxScalar):
  259. """Perform approximate comparisons where the expected value is a Decimal."""
  260. DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
  261. DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
  262. def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
  263. """Assert that two numbers (or two sets of numbers) are equal to each other
  264. within some tolerance.
  265. Due to the `intricacies of floating-point arithmetic`__, numbers that we
  266. would intuitively expect to be equal are not always so::
  267. >>> 0.1 + 0.2 == 0.3
  268. False
  269. __ https://docs.python.org/3/tutorial/floatingpoint.html
  270. This problem is commonly encountered when writing tests, e.g. when making
  271. sure that floating-point values are what you expect them to be. One way to
  272. deal with this problem is to assert that two floating-point numbers are
  273. equal to within some appropriate tolerance::
  274. >>> abs((0.1 + 0.2) - 0.3) < 1e-6
  275. True
  276. However, comparisons like this are tedious to write and difficult to
  277. understand. Furthermore, absolute comparisons like the one above are
  278. usually discouraged because there's no tolerance that works well for all
  279. situations. ``1e-6`` is good for numbers around ``1``, but too small for
  280. very big numbers and too big for very small ones. It's better to express
  281. the tolerance as a fraction of the expected value, but relative comparisons
  282. like that are even more difficult to write correctly and concisely.
  283. The ``approx`` class performs floating-point comparisons using a syntax
  284. that's as intuitive as possible::
  285. >>> from pytest import approx
  286. >>> 0.1 + 0.2 == approx(0.3)
  287. True
  288. The same syntax also works for sequences of numbers::
  289. >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
  290. True
  291. Dictionary *values*::
  292. >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
  293. True
  294. ``numpy`` arrays::
  295. >>> import numpy as np # doctest: +SKIP
  296. >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
  297. True
  298. And for a ``numpy`` array against a scalar::
  299. >>> import numpy as np # doctest: +SKIP
  300. >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
  301. True
  302. By default, ``approx`` considers numbers within a relative tolerance of
  303. ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
  304. This treatment would lead to surprising results if the expected value was
  305. ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
  306. To handle this case less surprisingly, ``approx`` also considers numbers
  307. within an absolute tolerance of ``1e-12`` of its expected value to be
  308. equal. Infinity and NaN are special cases. Infinity is only considered
  309. equal to itself, regardless of the relative tolerance. NaN is not
  310. considered equal to anything by default, but you can make it be equal to
  311. itself by setting the ``nan_ok`` argument to True. (This is meant to
  312. facilitate comparing arrays that use NaN to mean "no data".)
  313. Both the relative and absolute tolerances can be changed by passing
  314. arguments to the ``approx`` constructor::
  315. >>> 1.0001 == approx(1)
  316. False
  317. >>> 1.0001 == approx(1, rel=1e-3)
  318. True
  319. >>> 1.0001 == approx(1, abs=1e-3)
  320. True
  321. If you specify ``abs`` but not ``rel``, the comparison will not consider
  322. the relative tolerance at all. In other words, two numbers that are within
  323. the default relative tolerance of ``1e-6`` will still be considered unequal
  324. if they exceed the specified absolute tolerance. If you specify both
  325. ``abs`` and ``rel``, the numbers will be considered equal if either
  326. tolerance is met::
  327. >>> 1 + 1e-8 == approx(1)
  328. True
  329. >>> 1 + 1e-8 == approx(1, abs=1e-12)
  330. False
  331. >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
  332. True
  333. You can also use ``approx`` to compare nonnumeric types, or dicts and
  334. sequences containing nonnumeric types, in which case it falls back to
  335. strict equality. This can be useful for comparing dicts and sequences that
  336. can contain optional values::
  337. >>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
  338. True
  339. >>> [None, 1.0000005] == approx([None,1])
  340. True
  341. >>> ["foo", 1.0000005] == approx([None,1])
  342. False
  343. If you're thinking about using ``approx``, then you might want to know how
  344. it compares to other good ways of comparing floating-point numbers. All of
  345. these algorithms are based on relative and absolute tolerances and should
  346. agree for the most part, but they do have meaningful differences:
  347. - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative
  348. tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
  349. tolerance is met. Because the relative tolerance is calculated w.r.t.
  350. both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor
  351. ``b`` is a "reference value"). You have to specify an absolute tolerance
  352. if you want to compare to ``0.0`` because there is no tolerance by
  353. default. `More information...`__
  354. __ https://docs.python.org/3/library/math.html#math.isclose
  355. - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
  356. between ``a`` and ``b`` is less that the sum of the relative tolerance
  357. w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance
  358. is only calculated w.r.t. ``b``, this test is asymmetric and you can
  359. think of ``b`` as the reference value. Support for comparing sequences
  360. is provided by ``numpy.allclose``. `More information...`__
  361. __ https://numpy.org/doc/stable/reference/generated/numpy.isclose.html
  362. - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
  363. are within an absolute tolerance of ``1e-7``. No relative tolerance is
  364. considered and the absolute tolerance cannot be changed, so this function
  365. is not appropriate for very large or very small numbers. Also, it's only
  366. available in subclasses of ``unittest.TestCase`` and it's ugly because it
  367. doesn't follow PEP8. `More information...`__
  368. __ https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertAlmostEqual
  369. - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
  370. tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
  371. Because the relative tolerance is only calculated w.r.t. ``b``, this test
  372. is asymmetric and you can think of ``b`` as the reference value. In the
  373. special case that you explicitly specify an absolute tolerance but not a
  374. relative tolerance, only the absolute tolerance is considered.
  375. .. warning::
  376. .. versionchanged:: 3.2
  377. In order to avoid inconsistent behavior, ``TypeError`` is
  378. raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
  379. The example below illustrates the problem::
  380. assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)
  381. assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)
  382. In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
  383. to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
  384. comparison. This is because the call hierarchy of rich comparisons
  385. follows a fixed behavior. `More information...`__
  386. __ https://docs.python.org/3/reference/datamodel.html#object.__ge__
  387. .. versionchanged:: 3.7.1
  388. ``approx`` raises ``TypeError`` when it encounters a dict value or
  389. sequence element of nonnumeric type.
  390. .. versionchanged:: 6.1.0
  391. ``approx`` falls back to strict equality for nonnumeric types instead
  392. of raising ``TypeError``.
  393. """
  394. # Delegate the comparison to a class that knows how to deal with the type
  395. # of the expected value (e.g. int, float, list, dict, numpy.array, etc).
  396. #
  397. # The primary responsibility of these classes is to implement ``__eq__()``
  398. # and ``__repr__()``. The former is used to actually check if some
  399. # "actual" value is equivalent to the given expected value within the
  400. # allowed tolerance. The latter is used to show the user the expected
  401. # value and tolerance, in the case that a test failed.
  402. #
  403. # The actual logic for making approximate comparisons can be found in
  404. # ApproxScalar, which is used to compare individual numbers. All of the
  405. # other Approx classes eventually delegate to this class. The ApproxBase
  406. # class provides some convenient methods and overloads, but isn't really
  407. # essential.
  408. __tracebackhide__ = True
  409. if isinstance(expected, Decimal):
  410. cls: Type[ApproxBase] = ApproxDecimal
  411. elif isinstance(expected, Mapping):
  412. cls = ApproxMapping
  413. elif _is_numpy_array(expected):
  414. expected = _as_numpy_array(expected)
  415. cls = ApproxNumpy
  416. elif (
  417. isinstance(expected, Iterable)
  418. and isinstance(expected, Sized)
  419. # Type ignored because the error is wrong -- not unreachable.
  420. and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable]
  421. ):
  422. cls = ApproxSequencelike
  423. else:
  424. cls = ApproxScalar
  425. return cls(expected, rel, abs, nan_ok)
  426. def _is_numpy_array(obj: object) -> bool:
  427. """
  428. Return true if the given object is implicitly convertible to ndarray,
  429. and numpy is already imported.
  430. """
  431. return _as_numpy_array(obj) is not None
  432. def _as_numpy_array(obj: object) -> Optional["ndarray"]:
  433. """
  434. Return an ndarray if the given object is implicitly convertible to ndarray,
  435. and numpy is already imported, otherwise None.
  436. """
  437. import sys
  438. np: Any = sys.modules.get("numpy")
  439. if np is not None:
  440. # avoid infinite recursion on numpy scalars, which have __array__
  441. if np.isscalar(obj):
  442. return None
  443. elif isinstance(obj, np.ndarray):
  444. return obj
  445. elif hasattr(obj, "__array__") or hasattr("obj", "__array_interface__"):
  446. return np.asarray(obj)
  447. return None
  448. # builtin pytest.raises helper
  449. _E = TypeVar("_E", bound=BaseException)
  450. @overload
  451. def raises(
  452. expected_exception: Union[Type[_E], Tuple[Type[_E], ...]],
  453. *,
  454. match: Optional[Union[str, Pattern[str]]] = ...,
  455. ) -> "RaisesContext[_E]":
  456. ...
  457. @overload
  458. def raises(
  459. expected_exception: Union[Type[_E], Tuple[Type[_E], ...]],
  460. func: Callable[..., Any],
  461. *args: Any,
  462. **kwargs: Any,
  463. ) -> _pytest._code.ExceptionInfo[_E]:
  464. ...
  465. def raises(
  466. expected_exception: Union[Type[_E], Tuple[Type[_E], ...]], *args: Any, **kwargs: Any
  467. ) -> Union["RaisesContext[_E]", _pytest._code.ExceptionInfo[_E]]:
  468. r"""Assert that a code block/function call raises ``expected_exception``
  469. or raise a failure exception otherwise.
  470. :kwparam match:
  471. If specified, a string containing a regular expression,
  472. or a regular expression object, that is tested against the string
  473. representation of the exception using ``re.search``. To match a literal
  474. string that may contain `special characters`__, the pattern can
  475. first be escaped with ``re.escape``.
  476. (This is only used when ``pytest.raises`` is used as a context manager,
  477. and passed through to the function otherwise.
  478. When using ``pytest.raises`` as a function, you can use:
  479. ``pytest.raises(Exc, func, match="passed on").match("my pattern")``.)
  480. __ https://docs.python.org/3/library/re.html#regular-expression-syntax
  481. .. currentmodule:: _pytest._code
  482. Use ``pytest.raises`` as a context manager, which will capture the exception of the given
  483. type::
  484. >>> import pytest
  485. >>> with pytest.raises(ZeroDivisionError):
  486. ... 1/0
  487. If the code block does not raise the expected exception (``ZeroDivisionError`` in the example
  488. above), or no exception at all, the check will fail instead.
  489. You can also use the keyword argument ``match`` to assert that the
  490. exception matches a text or regex::
  491. >>> with pytest.raises(ValueError, match='must be 0 or None'):
  492. ... raise ValueError("value must be 0 or None")
  493. >>> with pytest.raises(ValueError, match=r'must be \d+$'):
  494. ... raise ValueError("value must be 42")
  495. The context manager produces an :class:`ExceptionInfo` object which can be used to inspect the
  496. details of the captured exception::
  497. >>> with pytest.raises(ValueError) as exc_info:
  498. ... raise ValueError("value must be 42")
  499. >>> assert exc_info.type is ValueError
  500. >>> assert exc_info.value.args[0] == "value must be 42"
  501. .. note::
  502. When using ``pytest.raises`` as a context manager, it's worthwhile to
  503. note that normal context manager rules apply and that the exception
  504. raised *must* be the final line in the scope of the context manager.
  505. Lines of code after that, within the scope of the context manager will
  506. not be executed. For example::
  507. >>> value = 15
  508. >>> with pytest.raises(ValueError) as exc_info:
  509. ... if value > 10:
  510. ... raise ValueError("value must be <= 10")
  511. ... assert exc_info.type is ValueError # this will not execute
  512. Instead, the following approach must be taken (note the difference in
  513. scope)::
  514. >>> with pytest.raises(ValueError) as exc_info:
  515. ... if value > 10:
  516. ... raise ValueError("value must be <= 10")
  517. ...
  518. >>> assert exc_info.type is ValueError
  519. **Using with** ``pytest.mark.parametrize``
  520. When using :ref:`pytest.mark.parametrize ref`
  521. it is possible to parametrize tests such that
  522. some runs raise an exception and others do not.
  523. See :ref:`parametrizing_conditional_raising` for an example.
  524. **Legacy form**
  525. It is possible to specify a callable by passing a to-be-called lambda::
  526. >>> raises(ZeroDivisionError, lambda: 1/0)
  527. <ExceptionInfo ...>
  528. or you can specify an arbitrary callable with arguments::
  529. >>> def f(x): return 1/x
  530. ...
  531. >>> raises(ZeroDivisionError, f, 0)
  532. <ExceptionInfo ...>
  533. >>> raises(ZeroDivisionError, f, x=0)
  534. <ExceptionInfo ...>
  535. The form above is fully supported but discouraged for new code because the
  536. context manager form is regarded as more readable and less error-prone.
  537. .. note::
  538. Similar to caught exception objects in Python, explicitly clearing
  539. local references to returned ``ExceptionInfo`` objects can
  540. help the Python interpreter speed up its garbage collection.
  541. Clearing those references breaks a reference cycle
  542. (``ExceptionInfo`` --> caught exception --> frame stack raising
  543. the exception --> current frame stack --> local variables -->
  544. ``ExceptionInfo``) which makes Python keep all objects referenced
  545. from that cycle (including all local variables in the current
  546. frame) alive until the next cyclic garbage collection run.
  547. More detailed information can be found in the official Python
  548. documentation for :ref:`the try statement <python:try>`.
  549. """
  550. __tracebackhide__ = True
  551. if isinstance(expected_exception, type):
  552. excepted_exceptions: Tuple[Type[_E], ...] = (expected_exception,)
  553. else:
  554. excepted_exceptions = expected_exception
  555. for exc in excepted_exceptions:
  556. if not isinstance(exc, type) or not issubclass(exc, BaseException): # type: ignore[unreachable]
  557. msg = "expected exception must be a BaseException type, not {}" # type: ignore[unreachable]
  558. not_a = exc.__name__ if isinstance(exc, type) else type(exc).__name__
  559. raise TypeError(msg.format(not_a))
  560. message = f"DID NOT RAISE {expected_exception}"
  561. if not args:
  562. match: Optional[Union[str, Pattern[str]]] = kwargs.pop("match", None)
  563. if kwargs:
  564. msg = "Unexpected keyword arguments passed to pytest.raises: "
  565. msg += ", ".join(sorted(kwargs))
  566. msg += "\nUse context-manager form instead?"
  567. raise TypeError(msg)
  568. return RaisesContext(expected_exception, message, match)
  569. else:
  570. func = args[0]
  571. if not callable(func):
  572. raise TypeError(
  573. "{!r} object (type: {}) must be callable".format(func, type(func))
  574. )
  575. try:
  576. func(*args[1:], **kwargs)
  577. except expected_exception as e:
  578. # We just caught the exception - there is a traceback.
  579. assert e.__traceback__ is not None
  580. return _pytest._code.ExceptionInfo.from_exc_info(
  581. (type(e), e, e.__traceback__)
  582. )
  583. fail(message)
  584. # This doesn't work with mypy for now. Use fail.Exception instead.
  585. raises.Exception = fail.Exception # type: ignore
  586. @final
  587. class RaisesContext(Generic[_E]):
  588. def __init__(
  589. self,
  590. expected_exception: Union[Type[_E], Tuple[Type[_E], ...]],
  591. message: str,
  592. match_expr: Optional[Union[str, Pattern[str]]] = None,
  593. ) -> None:
  594. self.expected_exception = expected_exception
  595. self.message = message
  596. self.match_expr = match_expr
  597. self.excinfo: Optional[_pytest._code.ExceptionInfo[_E]] = None
  598. def __enter__(self) -> _pytest._code.ExceptionInfo[_E]:
  599. self.excinfo = _pytest._code.ExceptionInfo.for_later()
  600. return self.excinfo
  601. def __exit__(
  602. self,
  603. exc_type: Optional[Type[BaseException]],
  604. exc_val: Optional[BaseException],
  605. exc_tb: Optional[TracebackType],
  606. ) -> bool:
  607. __tracebackhide__ = True
  608. if exc_type is None:
  609. fail(self.message)
  610. assert self.excinfo is not None
  611. if not issubclass(exc_type, self.expected_exception):
  612. return False
  613. # Cast to narrow the exception type now that it's verified.
  614. exc_info = cast(Tuple[Type[_E], _E, TracebackType], (exc_type, exc_val, exc_tb))
  615. self.excinfo.fill_unfilled(exc_info)
  616. if self.match_expr is not None:
  617. self.excinfo.match(self.match_expr)
  618. return True