python_api.py 37 KB

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