Skip to content

Commit 166ccaa

Browse files
committed
fix(testing): pytest.approx correctly take account Mapping keys order to compare them
1 parent ebcd836 commit 166ccaa

File tree

2 files changed

+13
-3
lines changed

2 files changed

+13
-3
lines changed

src/_pytest/python_api.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -250,9 +250,8 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:
250250
max_abs_diff = -math.inf
251251
max_rel_diff = -math.inf
252252
different_ids = []
253-
for (approx_key, approx_value), other_value in zip(
254-
approx_side_as_map.items(), other_side.values(), strict=True
255-
):
253+
for approx_key, approx_value in approx_side_as_map.items():
254+
other_value = other_side.get(approx_key, None)
256255
if approx_value != other_value:
257256
if approx_value.expected is not None and other_value is not None:
258257
try:

testing/python/approx.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1048,6 +1048,17 @@ def test_strange_sequence(self):
10481048
assert b == pytest.approx(a, abs=2)
10491049
assert b != pytest.approx(a, abs=0.5)
10501050

1051+
def test_approx_on_unordered_mapping_with_mismatch(self) -> None:
1052+
"""https://github.com/pytest-dev/pytest/pull/12445"""
1053+
expected = {"a": 1, "c": 3}
1054+
actual = {"c": 5, "a": 1}
1055+
1056+
with pytest.raises(
1057+
AssertionError,
1058+
match="Mismatched elements: 1 / 2:\n Max absolute difference: 2\n",
1059+
):
1060+
assert expected == approx(actual)
1061+
10511062

10521063
class MyVec3: # incomplete
10531064
"""sequence like"""

0 commit comments

Comments
 (0)