Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/13722.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed a misleading assertion failure message when using :func:`pytest.approx` on mappings with differing lengths.
6 changes: 6 additions & 0 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the bigger length is small (<10) and (or? Calling str might be costly) the Str representation of both is small (fit in max truncation) we might want to show the two mappings directly ?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The full message does include a snippet:

    def test_it():
>       assert pytest.approx({"a": 1, "b": 2}) == {"a": 1, "b": 2, "c": 3}
E       AssertionError: assert approx({'a': ... 2 ± 2.0e-06}) == {'a': 1, 'b': 2, 'c': 3}
E         
E         Impossible to compare mappings with different sizes.
E         Lengths: 2 and 3

x.py:4: AssertionError

]

approx_side_as_map = {
k: self._approx_scalar(v) for k, v in self.expected.items()
}
Expand Down
11 changes: 11 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
Loading