From af9f27a874be2a86621a58a5de6c7cecbbb67168 Mon Sep 17 00:00:00 2001 From: Pierre Mourlanne Date: Sat, 13 Mar 2021 15:01:23 +0100 Subject: [PATCH] Approx decimal sequence mapping (#8422) --- changelog/8421.feature.rst | 1 + src/_pytest/python_api.py | 2 ++ testing/python/approx.py | 14 ++++++++++++++ 3 files changed, 17 insertions(+) create mode 100644 changelog/8421.feature.rst diff --git a/changelog/8421.feature.rst b/changelog/8421.feature.rst new file mode 100644 index 000000000..c729ca395 --- /dev/null +++ b/changelog/8421.feature.rst @@ -0,0 +1 @@ +:func:`pytest.approx` now works on :class:`~decimal.Decimal` within mappings/dicts and sequences/lists. diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 7e0c86479..2285e22a3 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -72,6 +72,8 @@ class ApproxBase: return not (actual == self) def _approx_scalar(self, x) -> "ApproxScalar": + if isinstance(x, Decimal): + return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok) return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok) def _yield_comparisons(self, actual): diff --git a/testing/python/approx.py b/testing/python/approx.py index db6124e39..a0a914842 100644 --- a/testing/python/approx.py +++ b/testing/python/approx.py @@ -313,6 +313,12 @@ class TestApprox: assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual + def test_list_decimal(self): + actual = [Decimal("1.000001"), Decimal("2.000001")] + expected = [Decimal("1"), Decimal("2")] + + assert actual == approx(expected) + def test_list_wrong_len(self): assert [1, 2] != approx([1]) assert [1, 2] != approx([1, 2, 3]) @@ -346,6 +352,14 @@ class TestApprox: assert approx(expected, rel=5e-7, abs=0) == actual assert approx(expected, rel=5e-8, abs=0) != actual + def test_dict_decimal(self): + actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")} + # Dictionaries became ordered in python3.6, so switch up the order here + # to make sure it doesn't matter. + expected = {"b": Decimal("2"), "a": Decimal("1")} + + assert actual == approx(expected) + def test_dict_wrong_len(self): assert {"a": 1, "b": 2} != approx({"a": 1}) assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2})