Skip to content

Commit

Permalink
Add check for zero denominator in approx (#10624)
Browse files Browse the repository at this point in the history
Closes #10533
  • Loading branch information
jayendra-patil33 committed Jan 24, 2023
1 parent 05eee78 commit ca40380
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
1 change: 1 addition & 0 deletions changelog/10533.bugfix.rst
@@ -0,0 +1 @@
Fix :func:`pytest.approx` handling of dictionaries containing one or more values of `0.0` in class ApproxMapping.
14 changes: 10 additions & 4 deletions src/_pytest/python_api.py
Expand Up @@ -269,10 +269,16 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> List[str]:
max_abs_diff = max(
max_abs_diff, abs(approx_value.expected - other_value)
)
max_rel_diff = max(
max_rel_diff,
abs((approx_value.expected - other_value) / approx_value.expected),
)
if approx_value.expected == 0.0:
max_rel_diff = math.inf
else:
max_rel_diff = max(
max_rel_diff,
abs(
(approx_value.expected - other_value)
/ approx_value.expected
),
)
different_ids.append(approx_key)

message_data = [
Expand Down
13 changes: 13 additions & 0 deletions testing/python/approx.py
Expand Up @@ -630,6 +630,19 @@ def test_dict_nonnumeric(self):
def test_dict_vs_other(self):
assert 1 != approx({"a": 0})

def test_dict_for_div_by_zero(self, assert_approx_raises_regex):
assert_approx_raises_regex(
{"foo": 42.0},
{"foo": 0.0},
[
r" comparison failed. Mismatched elements: 1 / 1:",
rf" Max absolute difference: {SOME_FLOAT}",
r" Max relative difference: inf",
r" Index \| Obtained\s+\| Expected ",
rf" foo | {SOME_FLOAT} \| {SOME_FLOAT} ± {SOME_FLOAT}",
],
)

def test_numpy_array(self):
np = pytest.importorskip("numpy")

Expand Down

0 comments on commit ca40380

Please sign in to comment.