Skip to content

Commit 76bef68

Browse files
[7.2.x] Add check for zero denominator in approx (#10689)
Co-authored-by: Jay <[email protected]>
1 parent af22d34 commit 76bef68

File tree

3 files changed

+24
-4
lines changed

3 files changed

+24
-4
lines changed

changelog/10533.bugfix.rst

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :func:`pytest.approx` handling of dictionaries containing one or more values of `0.0` in class ApproxMapping.

src/_pytest/python_api.py

+10-4
Original file line numberDiff line numberDiff line change
@@ -269,10 +269,16 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> List[str]:
269269
max_abs_diff = max(
270270
max_abs_diff, abs(approx_value.expected - other_value)
271271
)
272-
max_rel_diff = max(
273-
max_rel_diff,
274-
abs((approx_value.expected - other_value) / approx_value.expected),
275-
)
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+
)
276282
different_ids.append(approx_key)
277283

278284
message_data = [

testing/python/approx.py

+13
Original file line numberDiff line numberDiff line change
@@ -630,6 +630,19 @@ def test_dict_nonnumeric(self):
630630
def test_dict_vs_other(self):
631631
assert 1 != approx({"a": 0})
632632

633+
def test_dict_for_div_by_zero(self, assert_approx_raises_regex):
634+
assert_approx_raises_regex(
635+
{"foo": 42.0},
636+
{"foo": 0.0},
637+
[
638+
r" comparison failed. Mismatched elements: 1 / 1:",
639+
rf" Max absolute difference: {SOME_FLOAT}",
640+
r" Max relative difference: inf",
641+
r" Index \| Obtained\s+\| Expected ",
642+
rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
643+
],
644+
)
645+
633646
def test_numpy_array(self):
634647
np = pytest.importorskip("numpy")
635648

0 commit comments

Comments
 (0)