python_api.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  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. if len(self.expected) != len(other_side):
  194. return [
  195. "Impossible to compare mappings with different sizes.",
  196. f"Lengths: {len(self.expected)} and {len(other_side)}",
  197. ]
  198. if set(self.expected.keys()) != set(other_side.keys()):
  199. return [
  200. "comparison failed.",
  201. f"Mappings has different keys: expected {self.expected.keys()} but got {other_side.keys()}",
  202. ]
  203. approx_side_as_map = {
  204. k: self._approx_scalar(v) for k, v in self.expected.items()
  205. }
  206. number_of_elements = len(approx_side_as_map)
  207. max_abs_diff = -math.inf
  208. max_rel_diff = -math.inf
  209. different_ids = []
  210. for (approx_key, approx_value), other_value in zip(
  211. approx_side_as_map.items(), other_side.values(), strict=True
  212. ):
  213. if approx_value != other_value:
  214. if approx_value.expected is not None and other_value is not None:
  215. try:
  216. max_abs_diff = max(
  217. max_abs_diff, abs(approx_value.expected - other_value)
  218. )
  219. if approx_value.expected == 0.0:
  220. max_rel_diff = math.inf
  221. else:
  222. max_rel_diff = max(
  223. max_rel_diff,
  224. abs(
  225. (approx_value.expected - other_value)
  226. / approx_value.expected
  227. ),
  228. )
  229. except ZeroDivisionError:
  230. pass
  231. different_ids.append(approx_key)
  232. message_data = [
  233. (str(key), str(other_side[key]), str(approx_side_as_map[key]))
  234. for key in different_ids
  235. ]
  236. return _compare_approx(
  237. self.expected,
  238. message_data,
  239. number_of_elements,
  240. different_ids,
  241. max_abs_diff,
  242. max_rel_diff,
  243. )
  244. def __eq__(self, actual) -> bool:
  245. try:
  246. if set(actual.keys()) != set(self.expected.keys()):
  247. return False
  248. except AttributeError:
  249. return False
  250. return super().__eq__(actual)
  251. def _yield_comparisons(self, actual):
  252. for k in self.expected.keys():
  253. yield actual[k], self.expected[k]
  254. def _check_type(self) -> None:
  255. __tracebackhide__ = True
  256. for key, value in self.expected.items():
  257. if isinstance(value, type(self.expected)):
  258. msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}"
  259. raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))
  260. class ApproxSequenceLike(ApproxBase):
  261. """Perform approximate comparisons where the expected value is a sequence of numbers."""
  262. def __repr__(self) -> str:
  263. seq_type = type(self.expected)
  264. if seq_type not in (tuple, list):
  265. seq_type = list
  266. return f"approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})"
  267. def _repr_compare(self, other_side: Sequence[float]) -> list[str]:
  268. import math
  269. if len(self.expected) != len(other_side):
  270. return [
  271. "Impossible to compare lists with different sizes.",
  272. f"Lengths: {len(self.expected)} and {len(other_side)}",
  273. ]
  274. approx_side_as_map = _recursive_sequence_map(self._approx_scalar, self.expected)
  275. number_of_elements = len(approx_side_as_map)
  276. max_abs_diff = -math.inf
  277. max_rel_diff = -math.inf
  278. different_ids = []
  279. for i, (approx_value, other_value) in enumerate(
  280. zip(approx_side_as_map, other_side, strict=True)
  281. ):
  282. if approx_value != other_value:
  283. try:
  284. abs_diff = abs(approx_value.expected - other_value)
  285. max_abs_diff = max(max_abs_diff, abs_diff)
  286. # Ignore non-numbers for the diff calculations (#13012).
  287. except TypeError:
  288. pass
  289. else:
  290. if other_value == 0.0:
  291. max_rel_diff = math.inf
  292. else:
  293. max_rel_diff = max(max_rel_diff, abs_diff / abs(other_value))
  294. different_ids.append(i)
  295. message_data = [
  296. (str(i), str(other_side[i]), str(approx_side_as_map[i]))
  297. for i in different_ids
  298. ]
  299. return _compare_approx(
  300. self.expected,
  301. message_data,
  302. number_of_elements,
  303. different_ids,
  304. max_abs_diff,
  305. max_rel_diff,
  306. )
  307. def __eq__(self, actual) -> bool:
  308. try:
  309. if len(actual) != len(self.expected):
  310. return False
  311. except TypeError:
  312. return False
  313. return super().__eq__(actual)
  314. def _yield_comparisons(self, actual):
  315. return zip(actual, self.expected, strict=True)
  316. def _check_type(self) -> None:
  317. __tracebackhide__ = True
  318. for index, x in enumerate(self.expected):
  319. if isinstance(x, type(self.expected)):
  320. msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}"
  321. raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))
  322. class ApproxScalar(ApproxBase):
  323. """Perform approximate comparisons where the expected value is a single number."""
  324. # Using Real should be better than this Union, but not possible yet:
  325. # https://github.com/python/typeshed/pull/3108
  326. DEFAULT_ABSOLUTE_TOLERANCE: float | Decimal = 1e-12
  327. DEFAULT_RELATIVE_TOLERANCE: float | Decimal = 1e-6
  328. def __repr__(self) -> str:
  329. """Return a string communicating both the expected value and the
  330. tolerance for the comparison being made.
  331. For example, ``1.0 ± 1e-6``, ``(3+4j) ± 5e-6 ∠ ±180°``.
  332. """
  333. # Don't show a tolerance for values that aren't compared using
  334. # tolerances, i.e. non-numerics and infinities. Need to call abs to
  335. # handle complex numbers, e.g. (inf + 1j).
  336. if (
  337. isinstance(self.expected, bool)
  338. or (not isinstance(self.expected, Complex | Decimal))
  339. or math.isinf(abs(self.expected) or isinstance(self.expected, bool))
  340. ):
  341. return str(self.expected)
  342. # If a sensible tolerance can't be calculated, self.tolerance will
  343. # raise a ValueError. In this case, display '???'.
  344. try:
  345. if 1e-3 <= self.tolerance < 1e3:
  346. vetted_tolerance = f"{self.tolerance:n}"
  347. else:
  348. vetted_tolerance = f"{self.tolerance:.1e}"
  349. if (
  350. isinstance(self.expected, Complex)
  351. and self.expected.imag
  352. and not math.isinf(self.tolerance)
  353. ):
  354. vetted_tolerance += " ∠ ±180°"
  355. except ValueError:
  356. vetted_tolerance = "???"
  357. return f"{self.expected} ± {vetted_tolerance}"
  358. def __eq__(self, actual) -> bool:
  359. """Return whether the given value is equal to the expected value
  360. within the pre-specified tolerance."""
  361. def is_bool(val: Any) -> bool:
  362. # Check if `val` is a native bool or numpy bool.
  363. if isinstance(val, bool):
  364. return True
  365. if np := sys.modules.get("numpy"):
  366. return isinstance(val, np.bool_)
  367. return False
  368. asarray = _as_numpy_array(actual)
  369. if asarray is not None:
  370. # Call ``__eq__()`` manually to prevent infinite-recursion with
  371. # numpy<1.13. See #3748.
  372. return all(self.__eq__(a) for a in asarray.flat)
  373. # Short-circuit exact equality, except for bool and np.bool_
  374. if is_bool(self.expected) and not is_bool(actual):
  375. return False
  376. elif actual == self.expected:
  377. return True
  378. # If either type is non-numeric, fall back to strict equality.
  379. # NB: we need Complex, rather than just Number, to ensure that __abs__,
  380. # __sub__, and __float__ are defined. Also, consider bool to be
  381. # non-numeric, even though it has the required arithmetic.
  382. if is_bool(self.expected) or not (
  383. isinstance(self.expected, Complex | Decimal)
  384. and isinstance(actual, Complex | Decimal)
  385. ):
  386. return False
  387. # Allow the user to control whether NaNs are considered equal to each
  388. # other or not. The abs() calls are for compatibility with complex
  389. # numbers.
  390. if math.isnan(abs(self.expected)):
  391. return self.nan_ok and math.isnan(abs(actual))
  392. # Infinity shouldn't be approximately equal to anything but itself, but
  393. # if there's a relative tolerance, it will be infinite and infinity
  394. # will seem approximately equal to everything. The equal-to-itself
  395. # case would have been short circuited above, so here we can just
  396. # return false if the expected value is infinite. The abs() call is
  397. # for compatibility with complex numbers.
  398. if math.isinf(abs(self.expected)):
  399. return False
  400. # Return true if the two numbers are within the tolerance.
  401. result: bool = abs(self.expected - actual) <= self.tolerance
  402. return result
  403. __hash__ = None
  404. @property
  405. def tolerance(self):
  406. """Return the tolerance for the comparison.
  407. This could be either an absolute tolerance or a relative tolerance,
  408. depending on what the user specified or which would be larger.
  409. """
  410. def set_default(x, default):
  411. return x if x is not None else default
  412. # Figure out what the absolute tolerance should be. ``self.abs`` is
  413. # either None or a value specified by the user.
  414. absolute_tolerance = set_default(self.abs, self.DEFAULT_ABSOLUTE_TOLERANCE)
  415. if absolute_tolerance < 0:
  416. raise ValueError(
  417. f"absolute tolerance can't be negative: {absolute_tolerance}"
  418. )
  419. if math.isnan(absolute_tolerance):
  420. raise ValueError("absolute tolerance can't be NaN.")
  421. # If the user specified an absolute tolerance but not a relative one,
  422. # just return the absolute tolerance.
  423. if self.rel is None:
  424. if self.abs is not None:
  425. return absolute_tolerance
  426. # Figure out what the relative tolerance should be. ``self.rel`` is
  427. # either None or a value specified by the user. This is done after
  428. # we've made sure the user didn't ask for an absolute tolerance only,
  429. # because we don't want to raise errors about the relative tolerance if
  430. # we aren't even going to use it.
  431. relative_tolerance = set_default(
  432. self.rel, self.DEFAULT_RELATIVE_TOLERANCE
  433. ) * abs(self.expected)
  434. if relative_tolerance < 0:
  435. raise ValueError(
  436. f"relative tolerance can't be negative: {relative_tolerance}"
  437. )
  438. if math.isnan(relative_tolerance):
  439. raise ValueError("relative tolerance can't be NaN.")
  440. # Return the larger of the relative and absolute tolerances.
  441. return max(relative_tolerance, absolute_tolerance)
  442. class ApproxDecimal(ApproxScalar):
  443. """Perform approximate comparisons where the expected value is a Decimal."""
  444. DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
  445. DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
  446. def __repr__(self) -> str:
  447. if isinstance(self.rel, float):
  448. rel = Decimal.from_float(self.rel)
  449. else:
  450. rel = self.rel
  451. if isinstance(self.abs, float):
  452. abs_ = Decimal.from_float(self.abs)
  453. else:
  454. abs_ = self.abs
  455. tol_str = "???"
  456. if rel is not None and Decimal("1e-3") <= rel <= Decimal("1e3"):
  457. tol_str = f"{rel:.1e}"
  458. elif abs_ is not None:
  459. tol_str = f"{abs_:.1e}"
  460. return f"{self.expected} ± {tol_str}"
  461. def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
  462. """Assert that two numbers (or two ordered sequences of numbers) are equal to each other
  463. within some tolerance.
  464. Due to the :doc:`python:tutorial/floatingpoint`, numbers that we
  465. would intuitively expect to be equal are not always so::
  466. >>> 0.1 + 0.2 == 0.3
  467. False
  468. This problem is commonly encountered when writing tests, e.g. when making
  469. sure that floating-point values are what you expect them to be. One way to
  470. deal with this problem is to assert that two floating-point numbers are
  471. equal to within some appropriate tolerance::
  472. >>> abs((0.1 + 0.2) - 0.3) < 1e-6
  473. True
  474. However, comparisons like this are tedious to write and difficult to
  475. understand. Furthermore, absolute comparisons like the one above are
  476. usually discouraged because there's no tolerance that works well for all
  477. situations. ``1e-6`` is good for numbers around ``1``, but too small for
  478. very big numbers and too big for very small ones. It's better to express
  479. the tolerance as a fraction of the expected value, but relative comparisons
  480. like that are even more difficult to write correctly and concisely.
  481. The ``approx`` class performs floating-point comparisons using a syntax
  482. that's as intuitive as possible::
  483. >>> from pytest import approx
  484. >>> 0.1 + 0.2 == approx(0.3)
  485. True
  486. The same syntax also works for ordered sequences of numbers::
  487. >>> (0.1 + 0.2, 0.2 + 0.4) == approx((0.3, 0.6))
  488. True
  489. ``numpy`` arrays::
  490. >>> import numpy as np # doctest: +SKIP
  491. >>> np.array([0.1, 0.2]) + np.array([0.2, 0.4]) == approx(np.array([0.3, 0.6])) # doctest: +SKIP
  492. True
  493. And for a ``numpy`` array against a scalar::
  494. >>> import numpy as np # doctest: +SKIP
  495. >>> np.array([0.1, 0.2]) + np.array([0.2, 0.1]) == approx(0.3) # doctest: +SKIP
  496. True
  497. Only ordered sequences are supported, because ``approx`` needs
  498. to infer the relative position of the sequences without ambiguity. This means
  499. ``sets`` and other unordered sequences are not supported.
  500. Finally, dictionary *values* can also be compared::
  501. >>> {'a': 0.1 + 0.2, 'b': 0.2 + 0.4} == approx({'a': 0.3, 'b': 0.6})
  502. True
  503. The comparison will be true if both mappings have the same keys and their
  504. respective values match the expected tolerances.
  505. **Tolerances**
  506. By default, ``approx`` considers numbers within a relative tolerance of
  507. ``1e-6`` (i.e. one part in a million) of its expected value to be equal.
  508. This treatment would lead to surprising results if the expected value was
  509. ``0.0``, because nothing but ``0.0`` itself is relatively close to ``0.0``.
  510. To handle this case less surprisingly, ``approx`` also considers numbers
  511. within an absolute tolerance of ``1e-12`` of its expected value to be
  512. equal. Infinity and NaN are special cases. Infinity is only considered
  513. equal to itself, regardless of the relative tolerance. NaN is not
  514. considered equal to anything by default, but you can make it be equal to
  515. itself by setting the ``nan_ok`` argument to True. (This is meant to
  516. facilitate comparing arrays that use NaN to mean "no data".)
  517. Both the relative and absolute tolerances can be changed by passing
  518. arguments to the ``approx`` constructor::
  519. >>> 1.0001 == approx(1)
  520. False
  521. >>> 1.0001 == approx(1, rel=1e-3)
  522. True
  523. >>> 1.0001 == approx(1, abs=1e-3)
  524. True
  525. If you specify ``abs`` but not ``rel``, the comparison will not consider
  526. the relative tolerance at all. In other words, two numbers that are within
  527. the default relative tolerance of ``1e-6`` will still be considered unequal
  528. if they exceed the specified absolute tolerance. If you specify both
  529. ``abs`` and ``rel``, the numbers will be considered equal if either
  530. tolerance is met::
  531. >>> 1 + 1e-8 == approx(1)
  532. True
  533. >>> 1 + 1e-8 == approx(1, abs=1e-12)
  534. False
  535. >>> 1 + 1e-8 == approx(1, rel=1e-6, abs=1e-12)
  536. True
  537. **Non-numeric types**
  538. You can also use ``approx`` to compare non-numeric types, or dicts and
  539. sequences containing non-numeric types, in which case it falls back to
  540. strict equality. This can be useful for comparing dicts and sequences that
  541. can contain optional values::
  542. >>> {"required": 1.0000005, "optional": None} == approx({"required": 1, "optional": None})
  543. True
  544. >>> [None, 1.0000005] == approx([None,1])
  545. True
  546. >>> ["foo", 1.0000005] == approx([None,1])
  547. False
  548. If you're thinking about using ``approx``, then you might want to know how
  549. it compares to other good ways of comparing floating-point numbers. All of
  550. these algorithms are based on relative and absolute tolerances and should
  551. agree for the most part, but they do have meaningful differences:
  552. - ``math.isclose(a, b, rel_tol=1e-9, abs_tol=0.0)``: True if the relative
  553. tolerance is met w.r.t. either ``a`` or ``b`` or if the absolute
  554. tolerance is met. Because the relative tolerance is calculated w.r.t.
  555. both ``a`` and ``b``, this test is symmetric (i.e. neither ``a`` nor
  556. ``b`` is a "reference value"). You have to specify an absolute tolerance
  557. if you want to compare to ``0.0`` because there is no tolerance by
  558. default. More information: :py:func:`math.isclose`.
  559. - ``numpy.isclose(a, b, rtol=1e-5, atol=1e-8)``: True if the difference
  560. between ``a`` and ``b`` is less that the sum of the relative tolerance
  561. w.r.t. ``b`` and the absolute tolerance. Because the relative tolerance
  562. is only calculated w.r.t. ``b``, this test is asymmetric and you can
  563. think of ``b`` as the reference value. Support for comparing sequences
  564. is provided by :py:func:`numpy.allclose`. More information:
  565. :std:doc:`numpy:reference/generated/numpy.isclose`.
  566. - ``unittest.TestCase.assertAlmostEqual(a, b)``: True if ``a`` and ``b``
  567. are within an absolute tolerance of ``1e-7``. No relative tolerance is
  568. considered , so this function is not appropriate for very large or very
  569. small numbers. Also, it's only available in subclasses of ``unittest.TestCase``
  570. and it's ugly because it doesn't follow PEP8. More information:
  571. :py:meth:`unittest.TestCase.assertAlmostEqual`.
  572. - ``a == pytest.approx(b, rel=1e-6, abs=1e-12)``: True if the relative
  573. tolerance is met w.r.t. ``b`` or if the absolute tolerance is met.
  574. Because the relative tolerance is only calculated w.r.t. ``b``, this test
  575. is asymmetric and you can think of ``b`` as the reference value. In the
  576. special case that you explicitly specify an absolute tolerance but not a
  577. relative tolerance, only the absolute tolerance is considered.
  578. .. note::
  579. ``approx`` can handle numpy arrays, but we recommend the
  580. specialised test helpers in :std:doc:`numpy:reference/routines.testing`
  581. if you need support for comparisons, NaNs, or ULP-based tolerances.
  582. To match strings using regex, you can use
  583. `Matches <https://github.com/asottile/re-assert#re_assertmatchespattern-str-args-kwargs>`_
  584. from the
  585. `re_assert package <https://github.com/asottile/re-assert>`_.
  586. .. note::
  587. Unlike built-in equality, this function considers
  588. booleans unequal to numeric zero or one. For example::
  589. >>> 1 == approx(True)
  590. False
  591. .. warning::
  592. .. versionchanged:: 3.2
  593. In order to avoid inconsistent behavior, :py:exc:`TypeError` is
  594. raised for ``>``, ``>=``, ``<`` and ``<=`` comparisons.
  595. The example below illustrates the problem::
  596. assert approx(0.1) > 0.1 + 1e-10 # calls approx(0.1).__gt__(0.1 + 1e-10)
  597. assert 0.1 + 1e-10 > approx(0.1) # calls approx(0.1).__lt__(0.1 + 1e-10)
  598. In the second example one expects ``approx(0.1).__le__(0.1 + 1e-10)``
  599. to be called. But instead, ``approx(0.1).__lt__(0.1 + 1e-10)`` is used to
  600. comparison. This is because the call hierarchy of rich comparisons
  601. follows a fixed behavior. More information: :py:meth:`object.__ge__`
  602. .. versionchanged:: 3.7.1
  603. ``approx`` raises ``TypeError`` when it encounters a dict value or
  604. sequence element of non-numeric type.
  605. .. versionchanged:: 6.1.0
  606. ``approx`` falls back to strict equality for non-numeric types instead
  607. of raising ``TypeError``.
  608. """
  609. # Delegate the comparison to a class that knows how to deal with the type
  610. # of the expected value (e.g. int, float, list, dict, numpy.array, etc).
  611. #
  612. # The primary responsibility of these classes is to implement ``__eq__()``
  613. # and ``__repr__()``. The former is used to actually check if some
  614. # "actual" value is equivalent to the given expected value within the
  615. # allowed tolerance. The latter is used to show the user the expected
  616. # value and tolerance, in the case that a test failed.
  617. #
  618. # The actual logic for making approximate comparisons can be found in
  619. # ApproxScalar, which is used to compare individual numbers. All of the
  620. # other Approx classes eventually delegate to this class. The ApproxBase
  621. # class provides some convenient methods and overloads, but isn't really
  622. # essential.
  623. __tracebackhide__ = True
  624. if isinstance(expected, Decimal):
  625. cls: type[ApproxBase] = ApproxDecimal
  626. elif isinstance(expected, Mapping):
  627. cls = ApproxMapping
  628. elif _is_numpy_array(expected):
  629. expected = _as_numpy_array(expected)
  630. cls = ApproxNumpy
  631. elif _is_sequence_like(expected):
  632. cls = ApproxSequenceLike
  633. elif isinstance(expected, Collection) and not isinstance(expected, str | bytes):
  634. msg = f"pytest.approx() only supports ordered sequences, but got: {expected!r}"
  635. raise TypeError(msg)
  636. else:
  637. cls = ApproxScalar
  638. return cls(expected, rel, abs, nan_ok)
  639. def _is_sequence_like(expected: object) -> bool:
  640. return (
  641. hasattr(expected, "__getitem__")
  642. and isinstance(expected, Sized)
  643. and not isinstance(expected, str | bytes)
  644. )
  645. def _is_numpy_array(obj: object) -> bool:
  646. """
  647. Return true if the given object is implicitly convertible to ndarray,
  648. and numpy is already imported.
  649. """
  650. return _as_numpy_array(obj) is not None
  651. def _as_numpy_array(obj: object) -> ndarray | None:
  652. """
  653. Return an ndarray if the given object is implicitly convertible to ndarray,
  654. and numpy is already imported, otherwise None.
  655. """
  656. np: Any = sys.modules.get("numpy")
  657. if np is not None:
  658. # avoid infinite recursion on numpy scalars, which have __array__
  659. if np.isscalar(obj):
  660. return None
  661. elif isinstance(obj, np.ndarray):
  662. return obj
  663. elif hasattr(obj, "__array__") or hasattr("obj", "__array_interface__"):
  664. return np.asarray(obj)
  665. return None