Skip to content

Commit e112226

Browse files
committed
fix(testing): pytest.approx correctly take account Mapping keys order to compare them
1 parent 10c83c5 commit e112226

File tree

2 files changed

+19
-12
lines changed

2 files changed

+19
-12
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: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,18 @@
11
# mypy: allow-untyped-defs
22
from __future__ import annotations
33

4-
from contextlib import contextmanager
54
import decimal
6-
from decimal import Decimal
7-
from fractions import Fraction
8-
from math import inf
9-
from math import nan
10-
from math import sqrt
115
import operator
12-
from operator import eq
13-
from operator import ne
146
import re
7+
from contextlib import contextmanager
8+
from decimal import Decimal
9+
from fractions import Fraction
10+
from math import inf, nan, sqrt
11+
from operator import eq, ne
1512

13+
import pytest
1614
from _pytest.pytester import Pytester
1715
from _pytest.python_api import _recursive_sequence_map
18-
import pytest
1916
from pytest import approx
2017

2118

@@ -1062,6 +1059,17 @@ def test_approx_dicts_with_mismatch_on_keys(self) -> None:
10621059
):
10631060
assert actual == approx(expected)
10641061

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

10661074
class MyVec3: # incomplete
10671075
"""sequence like"""

0 commit comments

Comments
 (0)