Skip to content

Commit 9ef4cd0

Browse files
committed
python_api: improve approx assert message on mappings with only extra elements
Fix #13722
1 parent d2d57e3 commit 9ef4cd0

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

changelog/13722.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixed a misleading assertion failure message when using :func:`pytest.approx` on mappings with differing lengths.

src/_pytest/python_api.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,12 @@ def __repr__(self) -> str:
236236
def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:
237237
import math
238238

239+
if len(self.expected) != len(other_side):
240+
return [
241+
"Impossible to compare mappings with different sizes.",
242+
f"Lengths: {len(self.expected)} and {len(other_side)}",
243+
]
244+
239245
approx_side_as_map = {
240246
k: self._approx_scalar(v) for k, v in self.expected.items()
241247
}

testing/python/approx.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -741,6 +741,17 @@ def test_dict_for_div_by_zero(self, assert_approx_raises_regex):
741741
],
742742
)
743743

744+
def test_dict_differing_lengths(self, assert_approx_raises_regex):
745+
assert_approx_raises_regex(
746+
{"a": 0},
747+
{"a": 0, "b": 1},
748+
[
749+
" ",
750+
r" Impossible to compare mappings with different sizes\.",
751+
r" Lengths: 2 and 1",
752+
],
753+
)
754+
744755
def test_numpy_array(self):
745756
np = pytest.importorskip("numpy")
746757

0 commit comments

Comments
 (0)