Skip to content

Commit c5b1309

Browse files
committed
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
1 parent f5a9aa0 commit c5b1309

File tree

3 files changed

+31
-12
lines changed

3 files changed

+31
-12
lines changed

changelog/10702.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed error assertion handling in :func:`pytest.approx` when ``None`` is an expected or received value when comparing dictionaries.

src/_pytest/python_api.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -265,19 +265,20 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> List[str]:
265265
approx_side_as_map.items(), other_side.values()
266266
):
267267
if approx_value != other_value:
268-
max_abs_diff = max(
269-
max_abs_diff, abs(approx_value.expected - other_value)
270-
)
271-
if approx_value.expected == 0.0:
272-
max_rel_diff = math.inf
273-
else:
274-
max_rel_diff = max(
275-
max_rel_diff,
276-
abs(
277-
(approx_value.expected - other_value)
278-
/ approx_value.expected
279-
),
268+
if not any((approx_value.expected is None, other_value is None)):
269+
max_abs_diff = max(
270+
max_abs_diff, abs(approx_value.expected - other_value)
280271
)
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+
)
281282
different_ids.append(approx_key)
282283

283284
message_data = [

testing/python/approx.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,23 @@ def test_error_messages_native_dtypes(self, assert_approx_raises_regex):
122122
],
123123
)
124124

125+
assert_approx_raises_regex(
126+
{"a": 1.0, "b": None, "c": None},
127+
{
128+
"a": None,
129+
"b": 1000.0,
130+
"c": None,
131+
},
132+
[
133+
r" comparison failed. Mismatched elements: 2 / 3:",
134+
r" Max absolute difference: -inf",
135+
r" Max relative difference: -inf",
136+
r" Index \| Obtained\s+\| Expected\s+",
137+
rf" a \| {SOME_FLOAT} \| None",
138+
rf" b \| None\s+\| {SOME_FLOAT} ± {SOME_FLOAT}",
139+
],
140+
)
141+
125142
assert_approx_raises_regex(
126143
[1.0, 2.0, 3.0, 4.0],
127144
[1.0, 3.0, 3.0, 5.0],

0 commit comments

Comments
 (0)