Debian Codegraph @

testing/python/approx.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from contextlib import contextmanager
5 import decimal
6 from decimal import Decimal
7 from fractions import Fraction
8 from math import inf
9 from math import nan
10 from math import sqrt
11 import operator
12 from operator import eq
13 from operator import ne
14 import re
15
16 from _pytest.pytester import Pytester
17 from _pytest.python_api import _recursive_sequence_map
18 import pytest
19 from pytest import approx
20
21
22 @pytest.fixture
23 def mocked_doctest_runner(monkeypatch):
24 import doctest
25
26 class MockedPdb:
27 def __init__(self, out):
28 pass
29
30 def set_trace(self):
31 raise NotImplementedError("not used")
32
33 def reset(self):
34 pass
35
36 def set_continue(self):
37 pass
38
39 monkeypatch.setattr("doctest._OutputRedirectingPdb", MockedPdb)
40
41 class MyDocTestRunner(doctest.DocTestRunner):
42 def report_failure(self, out, test, example, got):
43 raise AssertionError(
44 f"'{example.source.strip()}' evaluates to '{got.strip()}', not '{example.want.strip()}'"
45 )
46
47 return MyDocTestRunner()
48
49
50 @contextmanager
51 def temporary_verbosity(config, verbosity=0):
52 original_verbosity = config.getoption("verbose")
53 config.option.verbose = verbosity
54 try:
55 yield
56 finally:
57 config.option.verbose = original_verbosity
58
59
60 @pytest.fixture
61 def assert_approx_raises_regex(pytestconfig):
62 def do_assert(lhs, rhs, expected_message, verbosity_level=0):
63 import re
64
65 with temporary_verbosity(pytestconfig, verbosity_level):
66 with pytest.raises(AssertionError) as e:
67 assert lhs == approx(rhs)
68
69 nl = "\n"
70 obtained_message = str(e.value).splitlines()[1:]
71 assert len(obtained_message) == len(expected_message), (
72 "Regex message length doesn't match obtained.\n"
73 "Obtained:\n"
74 f"{nl.join(obtained_message)}\n\n"
75 "Expected regex:\n"
76 f"{nl.join(expected_message)}\n\n"
77 )
78
79 for i, (obtained_line, expected_line) in enumerate(
80 zip(obtained_message, expected_message, strict=True)
81 ):
82 regex = re.compile(expected_line)
83 assert regex.match(obtained_line) is not None, (
84 "Unexpected error message:\n"
85 f"{nl.join(obtained_message)}\n\n"
86 "Did not match regex:\n"
87 f"{nl.join(expected_message)}\n\n"
88 f"With verbosity level = {verbosity_level}, on line {i}"
89 )
90
91 return do_assert
92
93
94 SOME_FLOAT = r"[+-]?((?:([0-9]*[.])?[0-9]+(e-?[0-9]+)?)|inf|nan)\s*"
95 SOME_INT = r"[0-9]+\s*"
96 SOME_TOLERANCE = rf"({SOME_FLOAT}|[+-]?[0-9]+(\.[0-9]+)?[eE][+-]?[0-9]+\s*)"
97
98
99 class TestApprox:
100 def test_error_messages_native_dtypes(self, assert_approx_raises_regex):
101 # Treat bool exactly.
102 assert_approx_raises_regex(
103 {"a": 1.0, "b": True},
104 {"a": 1.0, "b": False},
105 [
106 "",
107 " comparison failed. Mismatched elements: 1 / 2:",
108 f" Max absolute difference: {SOME_FLOAT}",
109 f" Max relative difference: {SOME_FLOAT}",
110 r" Index\s+\| Obtained\s+\| Expected",
111 r".*(True|False)\s+",
112 ],
113 )
114 assert_approx_raises_regex(
115 2.0,
116 1.0,
117 [
118 "",
119 " comparison failed",
120 f" Obtained: {SOME_FLOAT}",
121 f" Expected: {SOME_FLOAT} ± {SOME_TOLERANCE}",
122 ],
123 )
124
125 assert_approx_raises_regex(
126 {"a": 1.0, "b": 1000.0, "c": 1000000.0},
127 {
128 "a": 2.0,
129 "b": 1000.0,
130 "c": 3000000.0,
131 },
132 [
133 r"",
134 r" comparison failed. Mismatched elements: 2 / 3:",
135 rf" Max absolute difference: {SOME_FLOAT}",
136 rf" Max relative difference: {SOME_FLOAT}",
137 r" Index \| Obtained\s+\| Expected\s+",
138 rf" a \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}",
139 rf" c \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_TOLERANCE}",
140 ],
141 )
142
143 assert_approx_raises_regex(
144 {"a": 1.0, "b": None, "c": None},
145 {
146 "a": None,
147 "b": 1000.0,
148 "c": None,
149 },
150 [
151 r"",
152 r" comparison failed. Mismatched elements: 2 / 3:",
153 r" Max absolute difference: -inf",
154 r" Max relative difference: -inf",
155 r" Index \| Obtained\s+\| Expected\s+",
156 rf" a \| {SOME_FLOAT} \| None",
157 rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}",
158 ],
159 )
160
161 assert_approx_raises_regex(
162 [1.0, 2.0, 3.0, 4.0],
163 [1.0, 3.0, 3.0, 5.0],
164 [
165 r"",
166 r" comparison failed. Mismatched elements: 2 / 4:",
167 rf" Max absolute difference: {SOME_FLOAT}",
168 rf" Max relative difference: {SOME_FLOAT}",
169 r" Index \| Obtained\s+\| Expected ",
170 rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
171 rf" 3 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
172 ],
173 )
174
175 assert_approx_raises_regex(
176 (1, 2.2, 4),
177 (1, 3.2, 4),
178 [
179 r"",
180 r" comparison failed. Mismatched elements: 1 / 3:",
181 rf" Max absolute difference: {SOME_FLOAT}",
182 rf" Max relative difference: {SOME_FLOAT}",
183 r" Index \| Obtained\s+\| Expected ",
184 rf" 1 \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
185 ],
186 )
187
188 # Specific test for comparison with 0.0 (relative diff will be 'inf')
189 assert_approx_raises_regex(
190 [0.0],
191 [1.0],
192 [
193 r"",
194 r" comparison failed. Mismatched elements: 1 / 1:",
195 rf" Max absolute difference: {SOME_FLOAT}",
196 r" Max relative difference: inf",
197 r" Index \| Obtained\s+\| Expected ",
198 rf"\s*0\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
199 ],
200 )
201
202 def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex):
203 np = pytest.importorskip("numpy")
204
205 a = np.linspace(0, 100, 20)
206 b = np.linspace(0, 100, 20)
207 a[10] += 0.5
208 assert_approx_raises_regex(
209 a,
210 b,
211 [
212 r"",
213 r" comparison failed. Mismatched elements: 1 / 20:",
214 rf" Max absolute difference: {SOME_FLOAT}",
215 rf" Max relative difference: {SOME_FLOAT}",
216 r" Index \| Obtained\s+\| Expected",
217 rf" \(10,\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
218 ],
219 )
220
221 assert_approx_raises_regex(
222 np.array(
223 [
224 [[1.1987311, 12412342.3], [3.214143244, 1423412423415.677]],
225 [[1, 2], [3, 219371297321973]],
226 ]
227 ),
228 np.array(
229 [
230 [[1.12313, 12412342.3], [3.214143244, 534523542345.677]],
231 [[1, 2], [3, 7]],
232 ]
233 ),
234 [
235 r"",
236 r" comparison failed. Mismatched elements: 3 / 8:",
237 rf" Max absolute difference: {SOME_FLOAT}",
238 rf" Max relative difference: {SOME_FLOAT}",
239 r" Index\s+\| Obtained\s+\| Expected\s+",
240 rf" \(0, 0, 0\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
241 rf" \(0, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
242 rf" \(1, 1, 1\) \| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
243 ],
244 )
245
246 # Specific test for comparison with 0.0 (relative diff will be 'inf')
247 assert_approx_raises_regex(
248 np.array([0.0]),
249 np.array([1.0]),
250 [
251 r"",
252 r" comparison failed. Mismatched elements: 1 / 1:",
253 rf" Max absolute difference: {SOME_FLOAT}",
254 r" Max relative difference: inf",
255 r" Index \| Obtained\s+\| Expected ",
256 rf"\s*\(0,\)\s*\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
257 ],
258 )
259
260 def test_error_messages_invalid_args(self, assert_approx_raises_regex):
261 np = pytest.importorskip("numpy")
262 with pytest.raises(AssertionError) as e:
263 assert np.array([[1.2, 3.4], [4.0, 5.0]]) == pytest.approx(
264 np.array([[4.0], [5.0]])
265 )
266 message = "\n".join(str(e.value).split("\n")[1:])
267 assert message == "\n".join(
268 [
269 " ",
270 " Impossible to compare arrays with different shapes.",
271 " Shapes: (2, 1) and (2, 2)",
272 ]
273 )
274
275 with pytest.raises(AssertionError) as e:
276 assert [1.0, 2.0, 3.0] == pytest.approx([4.0, 5.0])
277 message = "\n".join(str(e.value).split("\n")[1:])
278 assert message == "\n".join(
279 [
280 " ",
281 " Impossible to compare lists with different sizes.",
282 " Lengths: 2 and 3",
283 ]
284 )
285
286 def test_error_messages_with_different_verbosity(self, assert_approx_raises_regex):
287 np = pytest.importorskip("numpy")
288 for v in [0, 1, 2]:
289 # Verbosity level doesn't affect the error message for scalars
290 assert_approx_raises_regex(
291 2.0,
292 1.0,
293 [
294 "",
295 " comparison failed",
296 f" Obtained: {SOME_FLOAT}",
297 f" Expected: {SOME_FLOAT} ± {SOME_FLOAT}",
298 ],
299 verbosity_level=v,
300 )
301
302 a = np.linspace(1, 101, 20)
303 b = np.linspace(2, 102, 20)
304 assert_approx_raises_regex(
305 a,
306 b,
307 [
308 r"^ $",
309 r"^ comparison failed. Mismatched elements: 20 / 20:$",
310 rf"^ Max absolute difference: {SOME_FLOAT}$",
311 rf"^ Max relative difference: {SOME_FLOAT}$",
312 r"^ Index \| Obtained\s+\| Expected\s+$",
313 rf"^ \(0,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}$",
314 rf"^ \(1,\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}e-{SOME_INT}\.\.\.$",
315 "^ $",
316 rf"^ ...Full output truncated \({SOME_INT} lines hidden\), use '-vv' to show$",
317 ],
318 verbosity_level=0,
319 )
320
321 assert_approx_raises_regex(
322 a,
323 b,
324 [
325 r" ",
326 r" comparison failed. Mismatched elements: 20 / 20:",
327 rf" Max absolute difference: {SOME_FLOAT}",
328 rf" Max relative difference: {SOME_FLOAT}",
329 r" Index \| Obtained\s+\| Expected",
330 ]
331 + [
332 rf" \({i},\)\s+\| {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}"
333 for i in range(20)
334 ],
335 verbosity_level=2,
336 )
337
338 def test_repr_string(self):
339 assert repr(approx(1.0)) == "1.0 ± 1.0e-06"
340 assert repr(approx([1.0, 2.0])) == "approx([1.0 ± 1.0e-06, 2.0 ± 2.0e-06])"
341 assert repr(approx((1.0, 2.0))) == "approx((1.0 ± 1.0e-06, 2.0 ± 2.0e-06))"
342 assert repr(approx(inf)) == "inf"
343 assert repr(approx(1.0, rel=nan)) == "1.0 ± ???"
344 assert repr(approx(1.0, rel=inf)) == "1.0 ± inf"
345
346 # Dictionaries aren't ordered, so we need to check both orders.
347 assert repr(approx({"a": 1.0, "b": 2.0})) in (
348 "approx({'a': 1.0 ± 1.0e-06, 'b': 2.0 ± 2.0e-06})",
349 "approx({'b': 2.0 ± 2.0e-06, 'a': 1.0 ± 1.0e-06})",
350 )
351
352 assert repr(approx(42, abs=1)) == "42 ± 1"
353 assert repr(approx(5, rel=0.01)) == "5 ± 0.05"
354 assert repr(approx(24000, abs=500)) == "24000 ± 500"
355 assert repr(approx(1500, abs=555)) == "1500 ± 555"
356
357 def test_repr_complex_numbers(self):
358 assert repr(approx(inf + 1j)) == "(inf+1j)"
359 assert repr(approx(1.0j, rel=inf)) == "1j ± inf"
360
361 # can't compute a sensible tolerance
362 assert repr(approx(nan + 1j)) == "(nan+1j) ± ???"
363
364 assert repr(approx(1.0j)) == "1j ± 1.0e-06 ∠ ±180°"
365
366 # relative tolerance is scaled to |3+4j| = 5
367 assert repr(approx(3 + 4 * 1j)) == "(3+4j) ± 5.0e-06 ∠ ±180°"
368
369 # absolute tolerance is not scaled
370 assert repr(approx(3.3 + 4.4 * 1j, abs=0.02)) == "(3.3+4.4j) ± 0.02 ∠ ±180°"
371
372 @pytest.mark.parametrize(
373 "value, expected_repr_string",
374 [
375 (5.0, "approx(5.0 ± 5.0e-06)"),
376 ([5.0], "approx([5.0 ± 5.0e-06])"),
377 ([[5.0]], "approx([[5.0 ± 5.0e-06]])"),
378 ([[5.0, 6.0]], "approx([[5.0 ± 5.0e-06, 6.0 ± 6.0e-06]])"),
379 ([[5.0], [6.0]], "approx([[5.0 ± 5.0e-06], [6.0 ± 6.0e-06]])"),
380 ],
381 )
382 def test_repr_nd_array(self, value, expected_repr_string):
383 """Make sure that arrays of all different dimensions are repr'd correctly."""
384 np = pytest.importorskip("numpy")
385 np_array = np.array(value)
386 assert repr(approx(np_array)) == expected_repr_string
387
388 def test_bool(self):
389 with pytest.raises(AssertionError) as err:
390 assert approx(1)
391
392 assert err.match(r"approx\(\) is not supported in a boolean context")
393
394 def test_mixed_sequence(self, assert_approx_raises_regex) -> None:
395 """Approx should work on sequences that also contain non-numbers (#13010)."""
396 assert_approx_raises_regex(
397 [1.1, 2, "word"],
398 [1.0, 2, "different"],
399 [
400 "",
401 r" comparison failed. Mismatched elements: 2 / 3:",
402 rf" Max absolute difference: {SOME_FLOAT}",
403 rf" Max relative difference: {SOME_FLOAT}",
404 r" Index \| Obtained\s+\| Expected\s+",
405 r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*",
406 r"\s*2\s*\|\s*word\s*\|\s*different\s*",
407 ],
408 verbosity_level=2,
409 )
410 assert_approx_raises_regex(
411 [1.1, 2, "word"],
412 [1.0, 2, "word"],
413 [
414 "",
415 r" comparison failed. Mismatched elements: 1 / 3:",
416 rf" Max absolute difference: {SOME_FLOAT}",
417 rf" Max relative difference: {SOME_FLOAT}",
418 r" Index \| Obtained\s+\| Expected\s+",
419 r"\s*0\s*\|\s*1\.1\s*\|\s*1\.0\s*±\s*1\.0e\-06\s*",
420 ],
421 verbosity_level=2,
422 )
423 assert [1.1, 2, "word"] == pytest.approx([1.1, 2, "word"])
424
425 def test_operator_overloading(self):
426 assert 1 == approx(1, rel=1e-6, abs=1e-12)
427 assert not (1 != approx(1, rel=1e-6, abs=1e-12))
428 assert 10 != approx(1, rel=1e-6, abs=1e-12)
429 assert not (10 == approx(1, rel=1e-6, abs=1e-12))
430
431 def test_exactly_equal(self):
432 examples = [
433 (2.0, 2.0),
434 (0.1e200, 0.1e200),
435 (1.123e-300, 1.123e-300),
436 (12345, 12345.0),
437 (0.0, -0.0),
438 (345678, 345678),
439 (Decimal("1.0001"), Decimal("1.0001")),
440 (Fraction(1, 3), Fraction(-1, -3)),
441 ]
442 for a, x in examples:
443 assert a == approx(x)
444
445 def test_opposite_sign(self):
446 examples = [(eq, 1e-100, -1e-100), (ne, 1e100, -1e100)]
447 for op, a, x in examples:
448 assert op(a, approx(x))
449
450 def test_zero_tolerance(self):
451 within_1e10 = [(1.1e-100, 1e-100), (-1.1e-100, -1e-100)]
452 for a, x in within_1e10:
453 assert x == approx(x, rel=0.0, abs=0.0)
454 assert a != approx(x, rel=0.0, abs=0.0)
455 assert a == approx(x, rel=0.0, abs=5e-101)
456 assert a != approx(x, rel=0.0, abs=5e-102)
457 assert a == approx(x, rel=5e-1, abs=0.0)
458 assert a != approx(x, rel=5e-2, abs=0.0)
459
460 @pytest.mark.parametrize(
461 ("rel", "abs"),
462 [
463 (-1e100, None),
464 (None, -1e100),
465 (1e100, -1e100),
466 (-1e100, 1e100),
467 (-1e100, -1e100),
468 ],
469 )
470 def test_negative_tolerance(self, rel: float | None, abs: float | None) -> None:
471 # Negative tolerances are not allowed.
472 with pytest.raises(ValueError):
473 1.1 == approx(1, rel, abs)
474
475 def test_negative_tolerance_message(self):
476 # Error message for negative tolerance should include the value.
477 with pytest.raises(ValueError, match="-3"):
478 0 == approx(1, abs=-3)
479 with pytest.raises(ValueError, match="-3"):
480 0 == approx(1, rel=-3)
481
482 def test_inf_tolerance(self):
483 # Everything should be equal if the tolerance is infinite.
484 large_diffs = [(1, 1000), (1e-50, 1e50), (-1.0, -1e300), (0.0, 10)]
485 for a, x in large_diffs:
486 assert a != approx(x, rel=0.0, abs=0.0)
487 assert a == approx(x, rel=inf, abs=0.0)
488 assert a == approx(x, rel=0.0, abs=inf)
489 assert a == approx(x, rel=inf, abs=inf)
490
491 def test_inf_tolerance_expecting_zero(self) -> None:
492 # If the relative tolerance is zero but the expected value is infinite,
493 # the actual tolerance is a NaN, which should be an error.
494 with pytest.raises(ValueError):
495 1 == approx(0, rel=inf, abs=0.0)
496 with pytest.raises(ValueError):
497 1 == approx(0, rel=inf, abs=inf)
498
499 def test_nan_tolerance(self) -> None:
500 with pytest.raises(ValueError):
501 1.1 == approx(1, rel=nan)
502 with pytest.raises(ValueError):
503 1.1 == approx(1, abs=nan)
504 with pytest.raises(ValueError):
505 1.1 == approx(1, rel=nan, abs=nan)
506
507 def test_reasonable_defaults(self):
508 # Whatever the defaults are, they should work for numbers close to 1
509 # than have a small amount of floating-point error.
510 assert 0.1 + 0.2 == approx(0.3)
511
512 def test_default_tolerances(self):
513 # This tests the defaults as they are currently set. If you change the
514 # defaults, this test will fail but you should feel free to change it.
515 # None of the other tests (except the doctests) should be affected by
516 # the choice of defaults.
517 examples = [
518 # Relative tolerance used.
519 (eq, 1e100 + 1e94, 1e100),
520 (ne, 1e100 + 2e94, 1e100),
521 (eq, 1e0 + 1e-6, 1e0),
522 (ne, 1e0 + 2e-6, 1e0),
523 # Absolute tolerance used.
524 (eq, 1e-100, +1e-106),
525 (eq, 1e-100, +2e-106),
526 (eq, 1e-100, 0),
527 ]
528 for op, a, x in examples:
529 assert op(a, approx(x))
530
531 def test_custom_tolerances(self):
532 assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e0)
533 assert 1e8 + 1e0 == approx(1e8, rel=5e-9, abs=5e0)
534 assert 1e8 + 1e0 == approx(1e8, rel=5e-8, abs=5e-1)
535 assert 1e8 + 1e0 != approx(1e8, rel=5e-9, abs=5e-1)
536
537 assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-8)
538 assert 1e0 + 1e-8 == approx(1e0, rel=5e-9, abs=5e-8)
539 assert 1e0 + 1e-8 == approx(1e0, rel=5e-8, abs=5e-9)
540 assert 1e0 + 1e-8 != approx(1e0, rel=5e-9, abs=5e-9)
541
542 assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-16)
543 assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-9, abs=5e-16)
544 assert 1e-8 + 1e-16 == approx(1e-8, rel=5e-8, abs=5e-17)
545 assert 1e-8 + 1e-16 != approx(1e-8, rel=5e-9, abs=5e-17)
546
547 def test_relative_tolerance(self):
548 within_1e8_rel = [(1e8 + 1e0, 1e8), (1e0 + 1e-8, 1e0), (1e-8 + 1e-16, 1e-8)]
549 for a, x in within_1e8_rel:
550 assert a == approx(x, rel=5e-8, abs=0.0)
551 assert a != approx(x, rel=5e-9, abs=0.0)
552
553 def test_absolute_tolerance(self):
554 within_1e8_abs = [(1e8 + 9e-9, 1e8), (1e0 + 9e-9, 1e0), (1e-8 + 9e-9, 1e-8)]
555 for a, x in within_1e8_abs:
556 assert a == approx(x, rel=0, abs=5e-8)
557 assert a != approx(x, rel=0, abs=5e-9)
558
559 def test_expecting_zero(self):
560 examples = [
561 (ne, 1e-6, 0.0),
562 (ne, -1e-6, 0.0),
563 (eq, 1e-12, 0.0),
564 (eq, -1e-12, 0.0),
565 (ne, 2e-12, 0.0),
566 (ne, -2e-12, 0.0),
567 (ne, inf, 0.0),
568 (ne, nan, 0.0),
569 ]
570 for op, a, x in examples:
571 assert op(a, approx(x, rel=0.0, abs=1e-12))
572 assert op(a, approx(x, rel=1e-6, abs=1e-12))
573
574 def test_expecting_inf(self):
575 examples = [
576 (eq, inf, inf),
577 (eq, -inf, -inf),
578 (ne, inf, -inf),
579 (ne, 0.0, inf),
580 (ne, nan, inf),
581 ]
582 for op, a, x in examples:
583 assert op(a, approx(x))
584
585 def test_expecting_nan(self):
586 examples = [
587 (eq, nan, nan),
588 (eq, -nan, -nan),
589 (eq, nan, -nan),
590 (ne, 0.0, nan),
591 (ne, inf, nan),
592 ]
593 for op, a, x in examples:
594 # Nothing is equal to NaN by default.
595 assert a != approx(x)
596
597 # If ``nan_ok=True``, then NaN is equal to NaN.
598 assert op(a, approx(x, nan_ok=True))
599
600 def test_int(self):
601 within_1e6 = [(1000001, 1000000), (-1000001, -1000000)]
602 for a, x in within_1e6:
603 assert a == approx(x, rel=5e-6, abs=0)
604 assert a != approx(x, rel=5e-7, abs=0)
605 assert approx(x, rel=5e-6, abs=0) == a
606 assert approx(x, rel=5e-7, abs=0) != a
607
608 def test_decimal(self):
609 within_1e6 = [
610 (Decimal("1.000001"), Decimal("1.0")),
611 (Decimal("-1.000001"), Decimal("-1.0")),
612 ]
613 for a, x in within_1e6:
614 assert a == approx(x)
615 assert a == approx(x, rel=Decimal("5e-6"), abs=0)
616 assert a != approx(x, rel=Decimal("5e-7"), abs=0)
617 assert approx(x, rel=Decimal("5e-6"), abs=0) == a
618 assert approx(x, rel=Decimal("5e-7"), abs=0) != a
619 assert approx(x, rel=0, abs=Decimal("5e-3")) == a
620 assert approx(x, rel=0, abs=Decimal("5e-7")) != a
621
622 def test_fraction(self):
623 within_1e6 = [
624 (1 + Fraction(1, 1000000), Fraction(1)),
625 (-1 - Fraction(-1, 1000000), Fraction(-1)),
626 ]
627 for a, x in within_1e6:
628 assert a == approx(x, rel=5e-6, abs=0)
629 assert a != approx(x, rel=5e-7, abs=0)
630 assert approx(x, rel=5e-6, abs=0) == a
631 assert approx(x, rel=5e-7, abs=0) != a
632
633 def test_complex(self):
634 within_1e6 = [
635 (1.000001 + 1.0j, 1.0 + 1.0j),
636 (1.0 + 1.000001j, 1.0 + 1.0j),
637 (-1.000001 + 1.0j, -1.0 + 1.0j),
638 (1.0 - 1.000001j, 1.0 - 1.0j),
639 ]
640 for a, x in within_1e6:
641 assert a == approx(x, rel=5e-6, abs=0)
642 assert a != approx(x, rel=5e-7, abs=0)
643 assert approx(x, rel=5e-6, abs=0) == a
644 assert approx(x, rel=5e-7, abs=0) != a
645
646 def test_expecting_bool(self) -> None:
647 assert True == approx(True) # noqa: E712
648 assert False == approx(False) # noqa: E712
649 assert True != approx(False) # noqa: E712
650 assert True != approx(False, abs=2) # noqa: E712
651 assert 1 != approx(True)
652
653 def test_expecting_bool_numpy(self) -> None:
654 """Check approx comparing with numpy.bool (#13047)."""
655 np = pytest.importorskip("numpy")
656 assert np.False_ != approx(True)
657 assert np.True_ != approx(False)
658 assert np.True_ == approx(True)
659 assert np.False_ == approx(False)
660 assert np.True_ != approx(False, abs=2)
661
662 def test_list(self):
663 actual = [1 + 1e-7, 2 + 1e-8]
664 expected = [1, 2]
665
666 # Return false if any element is outside the tolerance.
667 assert actual == approx(expected, rel=5e-7, abs=0)
668 assert actual != approx(expected, rel=5e-8, abs=0)
669 assert approx(expected, rel=5e-7, abs=0) == actual
670 assert approx(expected, rel=5e-8, abs=0) != actual
671
672 def test_list_decimal(self):
673 actual = [Decimal("1.000001"), Decimal("2.000001")]
674 expected = [Decimal("1"), Decimal("2")]
675
676 assert actual == approx(expected)
677
678 def test_list_wrong_len(self):
679 assert [1, 2] != approx([1])
680 assert [1, 2] != approx([1, 2, 3])
681
682 def test_tuple(self):
683 actual = (1 + 1e-7, 2 + 1e-8)
684 expected = (1, 2)
685
686 # Return false if any element is outside the tolerance.
687 assert actual == approx(expected, rel=5e-7, abs=0)
688 assert actual != approx(expected, rel=5e-8, abs=0)
689 assert approx(expected, rel=5e-7, abs=0) == actual
690 assert approx(expected, rel=5e-8, abs=0) != actual
691
692 def test_tuple_wrong_len(self):
693 assert (1, 2) != approx((1,))
694 assert (1, 2) != approx((1, 2, 3))
695
696 def test_tuple_vs_other(self):
697 assert 1 != approx((1,))
698
699 def test_dict(self):
700 actual = {"a": 1 + 1e-7, "b": 2 + 1e-8}
701 # Dictionaries became ordered in python3.6, so switch up the order here
702 # to make sure it doesn't matter.
703 expected = {"b": 2, "a": 1}
704
705 # Return false if any element is outside the tolerance.
706 assert actual == approx(expected, rel=5e-7, abs=0)
707 assert actual != approx(expected, rel=5e-8, abs=0)
708 assert approx(expected, rel=5e-7, abs=0) == actual
709 assert approx(expected, rel=5e-8, abs=0) != actual
710
711 def test_dict_decimal(self):
712 actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")}
713 # Dictionaries became ordered in python3.6, so switch up the order here
714 # to make sure it doesn't matter.
715 expected = {"b": Decimal("2"), "a": Decimal("1")}
716
717 assert actual == approx(expected)
718
719 def test_dict_wrong_len(self):
720 assert {"a": 1, "b": 2} != approx({"a": 1})
721 assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2})
722 assert {"a": 1, "b": 2} != approx({"a": 1, "b": 2, "c": 3})
723
724 def test_dict_nonnumeric(self):
725 assert {"a": 1.0, "b": None} == pytest.approx({"a": 1.0, "b": None})
726 assert {"a": 1.0, "b": 1} != pytest.approx({"a": 1.0, "b": None})
727 assert {"a": 1.0, "b": True} != pytest.approx({"a": 1.0, "b": False}, abs=2)
728
729 def test_dict_vs_other(self):
730 assert 1 != approx({"a": 0})
731
732 def test_dict_for_div_by_zero(self, assert_approx_raises_regex):
733 assert_approx_raises_regex(
734 {"foo": 42.0},
735 {"foo": 0.0},
736 [
737 r"",
738 r" comparison failed. Mismatched elements: 1 / 1:",
739 rf" Max absolute difference: {SOME_FLOAT}",
740 r" Max relative difference: inf",
741 r" Index \| Obtained\s+\| Expected ",
742 rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
743 ],
744 )
745
746 def test_dict_differing_lengths(self, assert_approx_raises_regex):
747 assert_approx_raises_regex(
748 {"a": 0},
749 {"a": 0, "b": 1},
750 [
751 " ",
752 r" Impossible to compare mappings with different sizes\.",
753 r" Lengths: 2 and 1",
754 ],
755 )
756
757 def test_numpy_array(self):
758 np = pytest.importorskip("numpy")
759
760 actual = np.array([1 + 1e-7, 2 + 1e-8])
761 expected = np.array([1, 2])
762
763 # Return false if any element is outside the tolerance.
764 assert actual == approx(expected, rel=5e-7, abs=0)
765 assert actual != approx(expected, rel=5e-8, abs=0)
766 assert approx(expected, rel=5e-7, abs=0) == expected
767 assert approx(expected, rel=5e-8, abs=0) != actual
768
769 # Should be able to compare lists with numpy arrays.
770 assert list(actual) == approx(expected, rel=5e-7, abs=0)
771 assert list(actual) != approx(expected, rel=5e-8, abs=0)
772 assert actual == approx(list(expected), rel=5e-7, abs=0)
773 assert actual != approx(list(expected), rel=5e-8, abs=0)
774
775 def test_numpy_tolerance_args(self):
776 """
777 Check that numpy rel/abs args are handled correctly
778 for comparison against an np.array
779 Check both sides of the operator, hopefully it doesn't impact things.
780 Test all permutations of where the approx and np.array() can show up
781 """
782 np = pytest.importorskip("numpy")
783 expected = 100.0
784 actual = 99.0
785 abs_diff = expected - actual
786 rel_diff = (expected - actual) / expected
787
788 tests = [
789 (eq, abs_diff, 0),
790 (eq, 0, rel_diff),
791 (ne, 0, rel_diff / 2.0), # rel diff fail
792 (ne, abs_diff / 2.0, 0), # abs diff fail
793 ]
794
795 for op, _abs, _rel in tests:
796 assert op(np.array(actual), approx(expected, abs=_abs, rel=_rel)) # a, b
797 assert op(approx(expected, abs=_abs, rel=_rel), np.array(actual)) # b, a
798
799 assert op(actual, approx(np.array(expected), abs=_abs, rel=_rel)) # a, b
800 assert op(approx(np.array(expected), abs=_abs, rel=_rel), actual) # b, a
801
802 assert op(np.array(actual), approx(np.array(expected), abs=_abs, rel=_rel))
803 assert op(approx(np.array(expected), abs=_abs, rel=_rel), np.array(actual))
804
805 def test_numpy_expecting_nan(self):
806 np = pytest.importorskip("numpy")
807 examples = [
808 (eq, nan, nan),
809 (eq, -nan, -nan),
810 (eq, nan, -nan),
811 (ne, 0.0, nan),
812 (ne, inf, nan),
813 ]
814 for op, a, x in examples:
815 # Nothing is equal to NaN by default.
816 assert np.array(a) != approx(x)
817 assert a != approx(np.array(x))
818
819 # If ``nan_ok=True``, then NaN is equal to NaN.
820 assert op(np.array(a), approx(x, nan_ok=True))
821 assert op(a, approx(np.array(x), nan_ok=True))
822
823 def test_numpy_expecting_inf(self):
824 np = pytest.importorskip("numpy")
825 examples = [
826 (eq, inf, inf),
827 (eq, -inf, -inf),
828 (ne, inf, -inf),
829 (ne, 0.0, inf),
830 (ne, nan, inf),
831 ]
832 for op, a, x in examples:
833 assert op(np.array(a), approx(x))
834 assert op(a, approx(np.array(x)))
835 assert op(np.array(a), approx(np.array(x)))
836
837 def test_numpy_array_wrong_shape(self):
838 np = pytest.importorskip("numpy")
839
840 a12 = np.array([[1, 2]])
841 a21 = np.array([[1], [2]])
842
843 assert a12 != approx(a21)
844 assert a21 != approx(a12)
845
846 def test_numpy_array_implicit_conversion(self):
847 np = pytest.importorskip("numpy")
848
849 class ImplicitArray:
850 """Type which is implicitly convertible to a numpy array."""
851
852 def __init__(self, vals):
853 self.vals = vals
854
855 def __array__(self, dtype=None, copy=None):
856 return np.array(self.vals)
857
858 vec1 = ImplicitArray([1.0, 2.0, 3.0])
859 vec2 = ImplicitArray([1.0, 2.0, 4.0])
860 # see issue #12114 for test case
861 assert vec1 != approx(vec2)
862
863 def test_numpy_array_protocol(self):
864 """
865 array-like objects such as tensorflow's DeviceArray are handled like ndarray.
866 See issue #8132
867 """
868 np = pytest.importorskip("numpy")
869
870 class DeviceArray:
871 def __init__(self, value, size):
872 self.value = value
873 self.size = size
874
875 def __array__(self):
876 return self.value * np.ones(self.size)
877
878 class DeviceScalar:
879 def __init__(self, value):
880 self.value = value
881
882 def __array__(self):
883 return np.array(self.value)
884
885 expected = 1
886 actual = 1 + 1e-6
887 assert approx(expected) == DeviceArray(actual, size=1)
888 assert approx(expected) == DeviceArray(actual, size=2)
889 assert approx(expected) == DeviceScalar(actual)
890 assert approx(DeviceScalar(expected)) == actual
891 assert approx(DeviceScalar(expected)) == DeviceScalar(actual)
892
893 def test_doctests(self, mocked_doctest_runner) -> None:
894 import doctest
895
896 parser = doctest.DocTestParser()
897 assert approx.__doc__ is not None
898 test = parser.get_doctest(
899 approx.__doc__, {"approx": approx}, approx.__name__, None, None
900 )
901 mocked_doctest_runner.run(test)
902
903 def test_unicode_plus_minus(self, pytester: Pytester) -> None:
904 """
905 Comparing approx instances inside lists should not produce an error in the detailed diff.
906 Integration test for issue #2111.
907 """
908 pytester.makepyfile(
909 """
910 import pytest
911 def test_foo():
912 assert [3] == [pytest.approx(4)]
913 """
914 )
915 expected = "4.0e-06"
916 result = pytester.runpytest()
917 result.stdout.fnmatch_lines(
918 [f"*At index 0 diff: 3 != 4 ± {expected}", "=* 1 failed in *="]
919 )
920
921 @pytest.mark.parametrize(
922 "x, name",
923 [
924 pytest.param([[1]], "data structures", id="nested-list"),
925 pytest.param({"key": {"key": 1}}, "dictionaries", id="nested-dict"),
926 ],
927 )
928 def test_expected_value_type_error(self, x, name):
929 with pytest.raises(
930 TypeError,
931 match=rf"pytest.approx\(\) does not support nested {name}:",
932 ):
933 approx(x)
934
935 @pytest.mark.parametrize(
936 "x",
937 [
938 pytest.param(None),
939 pytest.param("string"),
940 pytest.param(["string"], id="nested-str"),
941 pytest.param({"key": "string"}, id="dict-with-string"),
942 ],
943 )
944 def test_nonnumeric_okay_if_equal(self, x):
945 assert x == approx(x)
946
947 @pytest.mark.parametrize(
948 "x",
949 [
950 pytest.param("string"),
951 pytest.param(["string"], id="nested-str"),
952 pytest.param({"key": "string"}, id="dict-with-string"),
953 ],
954 )
955 def test_nonnumeric_false_if_unequal(self, x):
956 """For non-numeric types, x != pytest.approx(y) reduces to x != y"""
957 assert "ab" != approx("abc")
958 assert ["ab"] != approx(["abc"])
959 # in particular, both of these should return False
960 assert {"a": 1.0} != approx({"a": None})
961 assert {"a": None} != approx({"a": 1.0})
962
963 assert 1.0 != approx(None)
964 assert None != approx(1.0) # noqa: E711
965
966 assert 1.0 != approx([None])
967 assert None != approx([1.0]) # noqa: E711
968
969 def test_nonnumeric_dict_repr(self):
970 """Dicts with non-numerics and infinites have no tolerances"""
971 x1 = {"foo": 1.0000005, "bar": None, "foobar": inf}
972 assert (
973 repr(approx(x1))
974 == "approx({'foo': 1.0000005 ± 1.0e-06, 'bar': None, 'foobar': inf})"
975 )
976
977 def test_nonnumeric_list_repr(self):
978 """Lists with non-numerics and infinites have no tolerances"""
979 x1 = [1.0000005, None, inf]
980 assert repr(approx(x1)) == "approx([1.0000005 ± 1.0e-06, None, inf])"
981
982 @pytest.mark.parametrize(
983 "op",
984 [
985 pytest.param(operator.le, id="<="),
986 pytest.param(operator.lt, id="<"),
987 pytest.param(operator.ge, id=">="),
988 pytest.param(operator.gt, id=">"),
989 ],
990 )
991 def test_comparison_operator_type_error(self, op):
992 """pytest.approx should raise TypeError for operators other than == and != (#2003)."""
993 with pytest.raises(TypeError):
994 op(1, approx(1, rel=1e-6, abs=1e-12))
995
996 def test_numpy_array_with_scalar(self):
997 np = pytest.importorskip("numpy")
998
999 actual = np.array([1 + 1e-7, 1 - 1e-8])
1000 expected = 1.0
1001
1002 assert actual == approx(expected, rel=5e-7, abs=0)
1003 assert actual != approx(expected, rel=5e-8, abs=0)
1004 assert approx(expected, rel=5e-7, abs=0) == actual
1005 assert approx(expected, rel=5e-8, abs=0) != actual
1006
1007 def test_numpy_scalar_with_array(self):
1008 np = pytest.importorskip("numpy")
1009
1010 actual = 1.0
1011 expected = np.array([1 + 1e-7, 1 - 1e-8])
1012
1013 assert actual == approx(expected, rel=5e-7, abs=0)
1014 assert actual != approx(expected, rel=5e-8, abs=0)
1015 assert approx(expected, rel=5e-7, abs=0) == actual
1016 assert approx(expected, rel=5e-8, abs=0) != actual
1017
1018 def test_generic_ordered_sequence(self):
1019 class MySequence:
1020 def __getitem__(self, i):
1021 return [1, 2, 3, 4][i]
1022
1023 def __len__(self):
1024 return 4
1025
1026 expected = MySequence()
1027 assert [1, 2, 3, 4] == approx(expected, abs=1e-4)
1028
1029 expected_repr = "approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])"
1030 assert repr(approx(expected)) == expected_repr
1031
1032 def test_decimal_approx_repr(self, monkeypatch) -> None:
1033 monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True)
1034 approx_obj = pytest.approx(decimal.Decimal("2.60"))
1035 assert decimal.Decimal("2.600001") == approx_obj
1036
1037 def test_allow_ordered_sequences_only(self) -> None:
1038 """pytest.approx() should raise an error on unordered sequences (#9692)."""
1039 with pytest.raises(TypeError, match="only supports ordered sequences"):
1040 assert {1, 2, 3} == approx({1, 2, 3})
1041
1042 def test_strange_sequence(self):
1043 """https://github.com/pytest-dev/pytest/issues/11797"""
1044 a = MyVec3(1, 2, 3)
1045 b = MyVec3(0, 1, 2)
1046
1047 # this would trigger the error inside the test
1048 pytest.approx(a, abs=0.5)._repr_compare(b)
1049
1050 assert b == pytest.approx(a, abs=2)
1051 assert b != pytest.approx(a, abs=0.5)
1052
1053 def test_approx_dicts_with_mismatch_on_keys(self) -> None:
1054 """https://github.com/pytest-dev/pytest/issues/13816"""
1055 expected = {"a": 1, "b": 3}
1056 actual = {"a": 1, "c": 3}
1057
1058 with pytest.raises(
1059 AssertionError,
1060 match=re.escape(
1061 "comparison failed.\n Mappings has different keys: "
1062 "expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])"
1063 ),
1064 ):
1065 assert actual == approx(expected)
1066
1067 def test_approx_on_unordered_mapping_with_mismatch(
1068 self, pytester: Pytester
1069 ) -> None:
1070 """https://github.com/pytest-dev/pytest/issues/12444"""
1071 pytester.makepyfile(
1072 """
1073 import pytest
1074
1075 def test_approx_on_unordered_mapping_with_mismatch():
1076 expected = {"a": 1, "b": 2, "c": 3, "d": 4}
1077 actual = {"d": 4, "c": 5, "a": 8, "b": 2}
1078 assert actual == pytest.approx(expected)
1079 """
1080 )
1081 result = pytester.runpytest()
1082 result.assert_outcomes(failed=1)
1083 result.stdout.fnmatch_lines(
1084 [
1085 "*comparison failed.**Mismatched elements: 2 / 4:*",
1086 "*Max absolute difference: 7*",
1087 "*Index | Obtained | Expected *",
1088 "* a * | 8 * | 1 *",
1089 "* c * | 5 * | 3 *",
1090 ]
1091 )
1092
1093 def test_approx_on_unordered_mapping_matching(self, pytester: Pytester) -> None:
1094 """https://github.com/pytest-dev/pytest/issues/12444"""
1095 pytester.makepyfile(
1096 """
1097 import pytest
1098 def test_approx_on_unordered_mapping_matching():
1099 expected = {"a": 1, "b": 2, "c": 3, "d": 4}
1100 actual = {"d": 4, "c": 3, "a": 1, "b": 2}
1101 assert actual == pytest.approx(expected)
1102 """
1103 )
1104 result = pytester.runpytest()
1105 result.assert_outcomes(passed=1)
1106
1107 def test_assertion_rewriting_works_with_approx_on_lhs(
1108 self, pytestconfig: pytest.Config
1109 ) -> None:
1110 """Assertion rewriting works also when approx() is on the left-hand side."""
1111 with temporary_verbosity(pytestconfig, verbosity=0):
1112 with pytest.raises(AssertionError) as e:
1113 assert pytest.approx(1) == 2
1114 obtained_message = str(e.value).splitlines()[-2:]
1115 assert obtained_message == [
1116 " Obtained: 2",
1117 " Expected: 1 ± 1.0e-06",
1118 ]
1119
1120
1121 class TestApproxDatetime:
1122 """Tests for datetime/timedelta support in approx (issue #8395)."""
1123
1124 def test_datetime_exactly_equal(self):
1125 from datetime import datetime
1126 from datetime import timedelta
1127
1128 dt = datetime(2024, 1, 1, 12, 0, 0)
1129 assert dt == approx(dt, abs=timedelta(seconds=1))
1130
1131 def test_datetime_within_tolerance(self):
1132 from datetime import datetime
1133 from datetime import timedelta
1134
1135 dt1 = datetime(2024, 1, 1, 12, 0, 0)
1136 dt2 = datetime(2024, 1, 1, 12, 0, 0, 500000) # +0.5s
1137 assert dt1 == approx(dt2, abs=timedelta(seconds=1))
1138
1139 def test_datetime_outside_tolerance(self):
1140 from datetime import datetime
1141 from datetime import timedelta
1142
1143 dt1 = datetime(2024, 1, 1, 12, 0, 0)
1144 dt2 = datetime(2024, 1, 1, 12, 0, 2) # +2s
1145 assert dt1 != approx(dt2, abs=timedelta(seconds=1))
1146
1147 def test_datetime_negative_difference(self):
1148 from datetime import datetime
1149 from datetime import timedelta
1150
1151 dt1 = datetime(2024, 1, 1, 12, 0, 1)
1152 dt2 = datetime(2024, 1, 1, 12, 0, 0) # dt2 < dt1
1153 assert dt1 == approx(dt2, abs=timedelta(seconds=2))
1154 assert dt1 != approx(dt2, abs=timedelta(milliseconds=500))
1155
1156 def test_timedelta_within_tolerance(self):
1157 from datetime import timedelta
1158
1159 td1 = timedelta(seconds=100)
1160 td2 = timedelta(seconds=100.5)
1161 assert td1 == approx(td2, abs=timedelta(seconds=1))
1162
1163 def test_timedelta_outside_tolerance(self):
1164 from datetime import timedelta
1165
1166 td1 = timedelta(seconds=100)
1167 td2 = timedelta(seconds=102)
1168 assert td1 != approx(td2, abs=timedelta(seconds=1))
1169
1170 def test_timedelta_rel_within_tolerance(self):
1171 from datetime import timedelta
1172
1173 td1 = timedelta(seconds=100)
1174 td2 = timedelta(seconds=100.5)
1175 assert td1 == approx(td2, rel=0.01)
1176
1177 def test_timedelta_rel_outside_tolerance(self):
1178 from datetime import timedelta
1179
1180 td1 = timedelta(seconds=100)
1181 td2 = timedelta(seconds=102)
1182 assert td1 != approx(td2, rel=0.01)
1183
1184 def test_requires_tolerance(self):
1185 from datetime import datetime
1186
1187 with pytest.raises(TypeError, match="requires an explicit tolerance"):
1188 approx(datetime(2024, 1, 1))
1189
1190 def test_datetime_rejects_rel(self):
1191 from datetime import datetime
1192 from datetime import timedelta
1193
1194 with pytest.raises(TypeError, match="does not support relative tolerance"):
1195 approx(datetime(2024, 1, 1), rel=0.1, abs=timedelta(seconds=1))
1196
1197 with pytest.raises(TypeError, match="does not support relative tolerance"):
1198 approx(datetime(2024, 1, 1), rel=timedelta(seconds=1))
1199
1200 def test_abs_must_be_timedelta(self):
1201 from datetime import datetime
1202
1203 with pytest.raises(TypeError, match="must be a timedelta"):
1204 approx(datetime(2024, 1, 1), abs=1.0)
1205
1206 def test_timedelta_rel_must_be_number(self):
1207 from datetime import timedelta
1208
1209 with pytest.raises(TypeError, match="must be a number"):
1210 approx(timedelta(seconds=1), rel=timedelta(seconds=1))
1211
1212 def test_timedelta_rel_must_be_non_negative(self):
1213 from datetime import timedelta
1214
1215 with pytest.raises(ValueError, match="relative tolerance can't be negative"):
1216 approx(timedelta(seconds=1), rel=-0.1)
1217
1218 def test_timedelta_rel_must_not_be_nan(self):
1219 from datetime import timedelta
1220
1221 with pytest.raises(ValueError, match="relative tolerance can't be NaN"):
1222 approx(timedelta(seconds=1), rel=float("nan"))
1223
1224 def test_timedelta_abs_must_be_non_negative(self):
1225 from datetime import timedelta
1226
1227 with pytest.raises(ValueError, match="absolute tolerance can't be negative"):
1228 approx(timedelta(seconds=1), abs=timedelta(seconds=-1))
1229
1230 def test_timedelta_rel_with_abs(self):
1231 from datetime import timedelta
1232
1233 # rel=0.05 gives 5s tolerance, abs=timedelta(seconds=1) gives 1s.
1234 # max(1s, 5s) = 5s tolerance.
1235 td1 = timedelta(seconds=100)
1236 td2 = timedelta(seconds=104)
1237 assert td1 == approx(td2, rel=0.05, abs=timedelta(seconds=1))
1238
1239 def test_timedelta_rel_zero(self):
1240 from datetime import timedelta
1241
1242 # rel=0 means exact match required (0 * expected = 0)
1243 td1 = timedelta(seconds=100)
1244 assert td1 == approx(td1, rel=0.0, abs=timedelta(seconds=0))
1245 assert td1 != approx(timedelta(seconds=101), rel=0.0, abs=timedelta(seconds=0))
1246
1247 def test_timedelta_rel_scales_with_expected(self):
1248 from datetime import timedelta
1249
1250 # Same rel=0.1, but different expected values.
1251 # 10% of 100s = 10s, 10% of 200s = 20s.
1252 assert timedelta(seconds=109) == approx(timedelta(seconds=100), rel=0.1)
1253 assert timedelta(seconds=218) == approx(timedelta(seconds=200), rel=0.1)
1254 # 11s is > 10% of 100s, but < 10% of 200s
1255 assert timedelta(seconds=111) != approx(timedelta(seconds=100), rel=0.1)
1256 assert timedelta(seconds=211) == approx(timedelta(seconds=200), rel=0.1)
1257
1258 def test_rejects_nan_ok(self):
1259 from datetime import datetime
1260 from datetime import timedelta
1261
1262 with pytest.raises(TypeError, match="does not support nan_ok"):
1263 approx(datetime(2024, 1, 1), abs=timedelta(seconds=1), nan_ok=True)
1264
1265 def test_datetime_repr(self):
1266 from datetime import datetime
1267 from datetime import timedelta
1268
1269 dt = datetime(2024, 1, 1, 12, 0, 0)
1270 result = repr(approx(dt, abs=timedelta(seconds=1)))
1271 assert "2024-01-01 12:00:00" in result
1272 assert "0:00:01" in result
1273
1274 def test_timedelta_repr(self):
1275 from datetime import timedelta
1276
1277 td = timedelta(seconds=100)
1278 result = repr(approx(td, abs=timedelta(seconds=1)))
1279 assert "0:01:40" in result # 100 seconds
1280 assert "0:00:01" in result # 1 second tolerance
1281
1282 def test_datetime_symmetry(self):
1283 """Approx comparison should work on both sides of ==."""
1284 from datetime import datetime
1285 from datetime import timedelta
1286
1287 dt1 = datetime(2024, 1, 1, 12, 0, 0)
1288 dt2 = datetime(2024, 1, 1, 12, 0, 0, 500000)
1289 tol = timedelta(seconds=1)
1290 assert dt1 == approx(dt2, abs=tol)
1291 assert approx(dt2, abs=tol) == dt1
1292
1293 def test_datetime_ne_operator(self):
1294 from datetime import datetime
1295 from datetime import timedelta
1296
1297 dt1 = datetime(2024, 1, 1, 12, 0, 0)
1298 dt2 = datetime(2024, 1, 1, 12, 0, 5)
1299 tol = timedelta(seconds=1)
1300 assert dt1 != approx(dt2, abs=tol)
1301 assert not (dt1 == approx(dt2, abs=tol))
1302
1303 def test_datetime_with_timezone(self):
1304 from datetime import datetime
1305 from datetime import timedelta
1306 from datetime import timezone
1307
1308 tz = timezone.utc
1309 dt1 = datetime(2024, 1, 1, 12, 0, 0, tzinfo=tz)
1310 dt2 = datetime(2024, 1, 1, 12, 0, 0, 500000, tzinfo=tz)
1311 assert dt1 == approx(dt2, abs=timedelta(seconds=1))
1312
1313 def test_datetime_error_message(self):
1314 from datetime import datetime
1315 from datetime import timedelta
1316
1317 dt1 = datetime(2024, 1, 1, 12, 0, 0)
1318 dt2 = datetime(2024, 1, 1, 12, 0, 5) # 5 seconds off
1319 with pytest.raises(AssertionError, match="comparison failed"):
1320 assert dt1 == approx(dt2, abs=timedelta(seconds=1))
1321
1322 def test_timedelta_zero(self):
1323 from datetime import timedelta
1324
1325 td1 = timedelta(seconds=0)
1326 td2 = timedelta(seconds=0)
1327 assert td1 == approx(td2, abs=timedelta(seconds=1))
1328
1329 def test_datetime_boundary_exact(self):
1330 """Test that values exactly at the tolerance boundary are equal."""
1331 from datetime import datetime
1332 from datetime import timedelta
1333
1334 dt1 = datetime(2024, 1, 1, 12, 0, 0)
1335 dt2 = datetime(2024, 1, 1, 12, 0, 1) # exactly 1 second
1336 assert dt1 == approx(dt2, abs=timedelta(seconds=1))
1337
1338 def test_datetime_microsecond_tolerance(self):
1339 from datetime import datetime
1340 from datetime import timedelta
1341
1342 dt1 = datetime(2024, 1, 1, 12, 0, 0, 0)
1343 dt2 = datetime(2024, 1, 1, 12, 0, 0, 100) # +100 microseconds
1344 assert dt1 == approx(dt2, abs=timedelta(microseconds=200))
1345 assert dt1 != approx(dt2, abs=timedelta(microseconds=50))
1346
1347 def test_bool_context_raises(self):
1348 from datetime import datetime
1349 from datetime import timedelta
1350
1351 with pytest.raises(AssertionError, match="boolean context"):
1352 bool(approx(datetime(2024, 1, 1), abs=timedelta(seconds=1)))
1353
1354 def test_wrong_type_comparison(self):
1355 """Comparing a datetime approx with a non-datetime should return False."""
1356 from datetime import datetime
1357 from datetime import timedelta
1358
1359 assert 42 != approx(datetime(2024, 1, 1), abs=timedelta(seconds=1))
1360 assert "string" != approx(datetime(2024, 1, 1), abs=timedelta(seconds=1))
1361
1362 def test_yield_comparisons(self):
1363 """Test that _yield_comparisons yields (actual, expected) pairs."""
1364 from datetime import datetime
1365 from datetime import timedelta
1366
1367 dt = datetime(2024, 1, 1, 12, 0, 0)
1368 a = approx(dt, abs=timedelta(seconds=1))
1369 actual = datetime(2024, 1, 1, 12, 0, 0, 500000)
1370 pairs = list(a._yield_comparisons(actual))
1371 assert pairs == [(actual, dt)]
1372
1373 def test_repr_compare_with_incompatible_type(self):
1374 """_repr_compare handles TypeError when actual is not a datetime."""
1375 from datetime import datetime
1376 from datetime import timedelta
1377
1378 a = approx(datetime(2024, 1, 1), abs=timedelta(seconds=1))
1379 result = a._repr_compare("not a datetime")
1380 assert "comparison failed" in result[0]
1381 assert "N/A" in result[3]
1382
1383 def test_timedelta_in_sequence(self):
1384 from datetime import timedelta
1385
1386 assert [timedelta(seconds=105)] == approx([timedelta(seconds=100)], rel=0.05)
1387 assert [timedelta(seconds=110)] != approx([timedelta(seconds=100)], rel=0.05)
1388 assert [timedelta(seconds=105)] == approx(
1389 [timedelta(seconds=100)], abs=timedelta(seconds=10)
1390 )
1391
1392 def test_timedelta_in_mapping(self):
1393 from datetime import timedelta
1394
1395 assert {"x": timedelta(seconds=105)} == approx(
1396 {"x": timedelta(seconds=100)}, rel=0.05
1397 )
1398 assert {"x": timedelta(seconds=110)} != approx(
1399 {"x": timedelta(seconds=100)}, rel=0.05
1400 )
1401 assert {"x": timedelta(seconds=105)} == approx(
1402 {"x": timedelta(seconds=100)}, abs=timedelta(seconds=10)
1403 )
1404
1405 def test_datetime_in_sequence(self):
1406 from datetime import datetime
1407 from datetime import timedelta
1408
1409 assert [datetime(2024, 1, 1, 12, 0, 0, 500_000)] == approx(
1410 [datetime(2024, 1, 1, 12, 0, 0)], abs=timedelta(seconds=1)
1411 )
1412 assert [datetime(2024, 1, 1, 12, 0, 5)] != approx(
1413 [datetime(2024, 1, 1, 12, 0, 0)], abs=timedelta(seconds=1)
1414 )
1415
1416 def test_datetime_in_mapping(self):
1417 from datetime import datetime
1418 from datetime import timedelta
1419
1420 assert {"t": datetime(2024, 1, 1, 12, 0, 0, 500_000)} == approx(
1421 {"t": datetime(2024, 1, 1, 12, 0, 0)}, abs=timedelta(seconds=1)
1422 )
1423 assert {"t": datetime(2024, 1, 1, 12, 0, 5)} != approx(
1424 {"t": datetime(2024, 1, 1, 12, 0, 0)}, abs=timedelta(seconds=1)
1425 )
1426
1427
1428 class MyVec3: # incomplete
1429 """sequence like"""
1430
1431 _x: int
1432 _y: int
1433 _z: int
1434
1435 def __init__(self, x: int, y: int, z: int):
1436 self._x, self._y, self._z = x, y, z
1437
1438 def __repr__(self) -> str:
1439 return f"<MyVec3 {self._x} {self._y} {self._z}>"
1440
1441 def __len__(self) -> int:
1442 return 3
1443
1444 def __getitem__(self, key: int) -> int:
1445 if key == 0:
1446 return self._x
1447 if key == 1:
1448 return self._y
1449 if key == 2:
1450 return self._z
1451 raise IndexError(key)
1452
1453
1454 class TestRecursiveSequenceMap:
1455 def test_map_over_scalar(self):
1456 assert _recursive_sequence_map(sqrt, 16) == 4
1457
1458 def test_map_over_empty_list(self):
1459 assert _recursive_sequence_map(sqrt, []) == []
1460
1461 def test_map_over_list(self):
1462 assert _recursive_sequence_map(sqrt, [4, 16, 25, 676]) == [2, 4, 5, 26]
1463
1464 def test_map_over_tuple(self):
1465 assert _recursive_sequence_map(sqrt, (4, 16, 25, 676)) == (2, 4, 5, 26)
1466
1467 def test_map_over_nested_lists(self):
1468 assert _recursive_sequence_map(sqrt, [4, [25, 64], [[49]]]) == [
1469 2,
1470 [5, 8],
1471 [[7]],
1472 ]
1473
1474 def test_map_over_mixed_sequence(self):
1475 assert _recursive_sequence_map(sqrt, [4, (25, 64), [49]]) == [
1476 2,
1477 (5, 8),
1478 [7],
1479 ]
1480
1481 def test_map_over_sequence_like(self):
1482 assert _recursive_sequence_map(int, MyVec3(1, 2, 3)) == [1, 2, 3]