Skip to content

Commit 511adf8

Browse files
github-actions[bot]Zac-HD
andauthoredJul 8, 2023
[7.4.x] Fix error assertion handling in approx when None in dict comparison (#11180)
Co-authored-by: Zac Hatfield-Dodds <[email protected]>
1 parent c71b5df commit 511adf8

File tree

3 files changed

+31
-12
lines changed

3 files changed

+31
-12
lines changed
 

‎changelog/10702.bugfix.rst

+1
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

+13-12
Original file line numberDiff line numberDiff line change
@@ -266,19 +266,20 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> List[str]:
266266
approx_side_as_map.items(), other_side.values()
267267
):
268268
if approx_value != other_value:
269-
max_abs_diff = max(
270-
max_abs_diff, abs(approx_value.expected - other_value)
271-
)
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-
),
269+
if approx_value.expected is not None and other_value is not None:
270+
max_abs_diff = max(
271+
max_abs_diff, abs(approx_value.expected - other_value)
281272
)
273+
if approx_value.expected == 0.0:
274+
max_rel_diff = math.inf
275+
else:
276+
max_rel_diff = max(
277+
max_rel_diff,
278+
abs(
279+
(approx_value.expected - other_value)
280+
/ approx_value.expected
281+
),
282+
)
282283
different_ids.append(approx_key)
283284

284285
message_data = [

‎testing/python/approx.py

+17
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)
Please sign in to comment.