From ca40380e99c2cdaab1d0c041f9f28cff37ef8ff9 Mon Sep 17 00:00:00 2001 From: Jay <43951088+jayendra-patil33@users.noreply.github.com> Date: Tue, 24 Jan 2023 15:37:42 +0530 Subject: [PATCH] Add check for zero denominator in approx (#10624) Closes #10533 --- changelog/10533.bugfix.rst | 1 + src/_pytest/python_api.py | 14 ++++++++++---- testing/python/approx.py | 13 +++++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 changelog/10533.bugfix.rst diff --git a/changelog/10533.bugfix.rst b/changelog/10533.bugfix.rst new file mode 100644 index 000000000..c49e4c3aa --- /dev/null +++ b/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. diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 4bc934861..e1cbce210 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -269,10 +269,16 @@ class ApproxMapping(ApproxBase): 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 = [ diff --git a/testing/python/approx.py b/testing/python/approx.py index 6acb466ff..631e52b56 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -630,6 +630,19 @@ class TestApprox: 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")