From 9ef4cd0797940815fd4a5ced64e5e25961a73a95 Mon Sep 17 00:00:00 2001 From: Ran Benita Date: Fri, 12 Sep 2025 23:59:31 +0300 Subject: [PATCH] python_api: improve approx assert message on mappings with only extra elements Fix #13722 --- changelog/13722.bugfix.rst | 1 + src/_pytest/python_api.py | 6 ++++++ testing/python/approx.py | 11 +++++++++++ 3 files changed, 18 insertions(+) create mode 100644 changelog/13722.bugfix.rst diff --git a/changelog/13722.bugfix.rst b/changelog/13722.bugfix.rst new file mode 100644 index 00000000000..ec36f466815 --- /dev/null +++ b/changelog/13722.bugfix.rst @@ -0,0 +1 @@ +Fixed a misleading assertion failure message when using :func:`pytest.approx` on mappings with differing lengths. diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 52e564bd809..958a3bd9b25 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -236,6 +236,12 @@ def __repr__(self) -> str: def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]: import math + if len(self.expected) != len(other_side): + return [ + "Impossible to compare mappings with different sizes.", + f"Lengths: {len(self.expected)} and {len(other_side)}", + ] + approx_side_as_map = { k: self._approx_scalar(v) for k, v in self.expected.items() } diff --git a/testing/python/approx.py b/testing/python/approx.py index 06633b544ec..2707b3638e8 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -741,6 +741,17 @@ def test_dict_for_div_by_zero(self, assert_approx_raises_regex): ], ) + def test_dict_differing_lengths(self, assert_approx_raises_regex): + assert_approx_raises_regex( + {"a": 0}, + {"a": 0, "b": 1}, + [ + " ", + r" Impossible to compare mappings with different sizes\.", + r" Lengths: 2 and 1", + ], + ) + def test_numpy_array(self): np = pytest.importorskip("numpy")