Skip to content

Commit 7ff334e

Browse files
authored
pytest.approx returns a clearer error mesage when comparing mappings with different keys (#13818)
Fixes #13816.
1 parent e3facc0 commit 7ff334e

File tree

4 files changed

+23
-0
lines changed

4 files changed

+23
-0
lines changed

AUTHORS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@ Carlos Jenkins
8383
Ceridwen
8484
Charles Cloud
8585
Charles Machalow
86+
Charles-Meldhine Madi Mnemoi (cmnemoi)
8687
Charnjit SiNGH (CCSJ)
8788
Cheuk Ting Ho
8889
Chris Mahoney

changelog/13816.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed :func:`pytest.approx` which now returns a clearer error message when comparing mappings with different keys.

src/_pytest/python_api.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,12 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:
242242
f"Lengths: {len(self.expected)} and {len(other_side)}",
243243
]
244244

245+
if set(self.expected.keys()) != set(other_side.keys()):
246+
return [
247+
"comparison failed.",
248+
f"Mappings has different keys: expected {self.expected.keys()} but got {other_side.keys()}",
249+
]
250+
245251
approx_side_as_map = {
246252
k: self._approx_scalar(v) for k, v in self.expected.items()
247253
}

testing/python/approx.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import operator
1212
from operator import eq
1313
from operator import ne
14+
import re
1415

1516
from _pytest.pytester import Pytester
1617
from _pytest.python_api import _recursive_sequence_map
@@ -1047,6 +1048,20 @@ def test_strange_sequence(self):
10471048
assert b == pytest.approx(a, abs=2)
10481049
assert b != pytest.approx(a, abs=0.5)
10491050

1051+
def test_approx_dicts_with_mismatch_on_keys(self) -> None:
1052+
"""https://github.com/pytest-dev/pytest/issues/13816"""
1053+
expected = {"a": 1, "b": 3}
1054+
actual = {"a": 1, "c": 3}
1055+
1056+
with pytest.raises(
1057+
AssertionError,
1058+
match=re.escape(
1059+
"comparison failed.\n Mappings has different keys: "
1060+
"expected dict_keys(['a', 'b']) but got dict_keys(['a', 'c'])"
1061+
),
1062+
):
1063+
assert actual == approx(expected)
1064+
10501065

10511066
class MyVec3: # incomplete
10521067
"""sequence like"""

0 commit comments

Comments
 (0)