python_api.py 38 KB

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