diff --git a/changelog/12444.bugfix.rst b/changelog/12444.bugfix.rst new file mode 100644 index 00000000000..6b94c887eda --- /dev/null +++ b/changelog/12444.bugfix.rst @@ -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. diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index cbb2ff2b80a..3de6e5cb01f 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -254,9 +254,8 @@ def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]: 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(): + other_value = other_side.get(approx_key, None) if approx_value != other_value: if approx_value.expected is not None and other_value is not None: try: diff --git a/testing/python/approx.py b/testing/python/approx.py index 7eba4755c01..1e2d15d6cde 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -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"""