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