python_api.py 36 KB

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