Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix for approx on mismatched dictionaries #13046

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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/12444.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
In :pr:`13046`, fixes a bug where the .approx method incorrectly reported all key-value pairs as mismatched when only one was incorrect in unordered dictionaries.
5 changes: 2 additions & 3 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,9 +254,8 @@
max_abs_diff = -math.inf
max_rel_diff = -math.inf
different_ids = []
for (approx_key, approx_value), other_value in zip(
approx_side_as_map.items(), other_side.values()
):
for approx_key, approx_value in approx_side_as_map.items():
Copy link
Member

Choose a reason for hiding this comment

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

I just noted that the fix ignores additional keys in the other side

other_value = other_side.get(approx_key, None)

Check warning on line 258 in src/_pytest/python_api.py

View check run for this annotation

Codecov / codecov/patch

src/_pytest/python_api.py#L258

Added line #L258 was not covered by tests
if approx_value != other_value:
if approx_value.expected is not None and other_value is not None:
try:
Expand Down
11 changes: 11 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1022,6 +1022,17 @@ def test_strange_sequence(self):
assert b == pytest.approx(a, abs=2)
assert b != pytest.approx(a, abs=0.5)

def test_approx_unordered_dicts_with_mismatch(self):
"""https://github.com/pytest-dev/pytest/pull/12445"""
dict1 = {"a": 1.0, "b": 1.0, "c": 3.1}
dict2 = {"b": 2.0, "a": 1.0, "c": 3.1} # 'b' has a different value

with pytest.raises(
AssertionError,
match="Mismatched elements: 1 / 3:\n Max absolute difference: 1.0\n",
):
assert dict1 == pytest.approx(dict2)


class MyVec3: # incomplete
"""sequence like"""
Expand Down
Loading