Skip to content

Commit 06c9d7d

Browse files
committed
fix(testing): pytest.approx correctly take account Mapping keys order to compare them
1 parent 3e1a5a7 commit 06c9d7d

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
@@ -256,9 +256,8 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:
256256
max_abs_diff = -math.inf
257257
max_rel_diff = -math.inf
258258
different_ids = []
259-
for (approx_key, approx_value), other_value in zip(
260-
approx_side_as_map.items(), other_side.values(), strict=True
261-
):
259+
for approx_key, approx_value in approx_side_as_map.items():
260+
other_value = other_side.get(approx_key, None)
262261
if approx_value != other_value:
263262
if approx_value.expected is not None and other_value is not None:
264263
try:

testing/python/approx.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,6 +1059,17 @@ def test_approx_dicts_with_mismatch_on_keys(self) -> None:
10591059
):
10601060
assert actual == approx(expected)
10611061

1062+
def test_approx_on_unordered_mapping_with_mismatch(self) -> None:
1063+
"""https://github.com/pytest-dev/pytest/pull/12445"""
1064+
expected = {"a": 1, "c": 3}
1065+
actual = {"c": 5, "a": 1}
1066+
1067+
with pytest.raises(
1068+
AssertionError,
1069+
match="Mismatched elements: 1 / 2:\n Max absolute difference: 2\n",
1070+
):
1071+
assert expected == approx(actual)
1072+
10621073

10631074
class MyVec3: # incomplete
10641075
"""sequence like"""

0 commit comments

Comments
 (0)