diff --git a/AUTHORS b/AUTHORS index 9539e8dc4f4..8e4265cbbe0 100644 --- a/AUTHORS +++ b/AUTHORS @@ -83,6 +83,7 @@ Carlos Jenkins Ceridwen Charles Cloud Charles Machalow +Charles-Meldhine Madi Mnemoi (cmnemoi) Charnjit SiNGH (CCSJ) Cheuk Ting Ho Chris Mahoney diff --git a/changelog/12444.bugfix.rst b/changelog/12444.bugfix.rst new file mode 100644 index 00000000000..146cfc7ab24 --- /dev/null +++ b/changelog/12444.bugfix.rst @@ -0,0 +1 @@ +Fixed :func:`pytest.approx` which now correctly takes account Mapping keys order to compare them. diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index c64587bb219..9f6c696d2b5 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -250,9 +250,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(), strict=True - ): + 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 dc10a954839..ac3b8adc11b 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -1048,6 +1048,17 @@ def test_strange_sequence(self): assert b == pytest.approx(a, abs=2) assert b != pytest.approx(a, abs=0.5) + def test_approx_on_unordered_mapping_with_mismatch(self) -> None: + """https://github.com/pytest-dev/pytest/pull/12445""" + expected = {"a": 1, "c": 3} + actual = {"c": 5, "a": 1} + + with pytest.raises( + AssertionError, + match="Mismatched elements: 1 / 2:\n Max absolute difference: 2\n", + ): + assert expected == approx(actual) + class MyVec3: # incomplete """sequence like"""