python_api.py 31 KB

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