From 166ccaab07af06bafd61ad7feb3977d58662c7bc Mon Sep 17 00:00:00 2001 From: Charles-Meldhine Madi Mnemoi Date: Wed, 15 Oct 2025 13:02:39 +0200 Subject: [PATCH 1/3] fix(testing): `pytest.approx` correctly take account Mapping keys order to compare them --- src/_pytest/python_api.py | 5 ++--- testing/python/approx.py | 11 +++++++++++ 2 files changed, 13 insertions(+), 3 deletions(-) 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""" From 8fd32a3b8be58ea3aa143763a660e6bd0b17c33e Mon Sep 17 00:00:00 2001 From: Charles-Meldhine Madi Mnemoi Date: Wed, 15 Oct 2025 13:06:44 +0200 Subject: [PATCH 2/3] doc(changelog): add entry for fixing `pytest.approx` to account for Mapping keys order --- changelog/12444.bugfix.rst | 1 + 1 file changed, 1 insertion(+) create mode 100644 changelog/12444.bugfix.rst 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. From 23b8c8ea3f5c65be5bc52f19e50a72275e4c2cc4 Mon Sep 17 00:00:00 2001 From: Charles-Meldhine Madi Mnemoi Date: Wed, 15 Oct 2025 13:07:43 +0200 Subject: [PATCH 3/3] doc(authors): add Charles-Meldhine Madi Mnemoi (cmnemoi) to the contributors list --- AUTHORS | 1 + 1 file changed, 1 insertion(+) diff --git a/AUTHORS b/AUTHORS index b28f49776d6..5849228200b 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