From c5b13099e6e121e6e9991855136371dbad53fbad Mon Sep 17 00:00:00 2001 From: Kenny Y <24802984+kenny-y-dev@users.noreply.github.com> Date: Fri, 7 Jul 2023 14:42:59 -0400 Subject: [PATCH] Fix error assertion handling in approx when None in dict comparison Dict comparsion in the ApproxMapping class did not check if values were None before attempting to subtract for max_abs_diff stat, which was throwing an TypeError instead of being handled by pytest error assertion. Check for None has been added before these calculations, so that None will properly show as Obtained/Expected in pytest assert message --- changelog/10702.bugfix.rst | 1 + src/_pytest/python_api.py | 25 +++++++++++++------------ testing/python/approx.py | 17 +++++++++++++++++ 3 files changed, 31 insertions(+), 12 deletions(-) create mode 100644 changelog/10702.bugfix.rst diff --git a/changelog/10702.bugfix.rst b/changelog/10702.bugfix.rst new file mode 100644 index 000000000..4008cc882 --- /dev/null +++ b/changelog/10702.bugfix.rst @@ -0,0 +1 @@ +Fixed error assertion handling in :func:`pytest.approx` when ``None`` is an expected or received value when comparing dictionaries. diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 0967ae8ec..35560f168 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -265,19 +265,20 @@ class ApproxMapping(ApproxBase): approx_side_as_map.items(), other_side.values() ): if approx_value != other_value: - max_abs_diff = max( - max_abs_diff, abs(approx_value.expected - other_value) - ) - 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 - ), + if not any((approx_value.expected is None, other_value is None)): + max_abs_diff = max( + max_abs_diff, abs(approx_value.expected - other_value) ) + 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 631e52b56..6ad411a3e 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -122,6 +122,23 @@ class TestApprox: ], ) + assert_approx_raises_regex( + {"a": 1.0, "b": None, "c": None}, + { + "a": None, + "b": 1000.0, + "c": None, + }, + [ + r" comparison failed. Mismatched elements: 2 / 3:", + r" Max absolute difference: -inf", + r" Max relative difference: -inf", + r" Index \| Obtained\s+\| Expected\s+", + rf" a \| {SOME_FLOAT} \| None", + rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}", + ], + ) + assert_approx_raises_regex( [1.0, 2.0, 3.0, 4.0], [1.0, 3.0, 3.0, 5.0],