Skip to content

Commit af9f27a

Browse files
authored
Approx decimal sequence mapping (#8422)
1 parent 146eda9 commit af9f27a

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

changelog/8421.feature.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
:func:`pytest.approx` now works on :class:`~decimal.Decimal` within mappings/dicts and sequences/lists.

src/_pytest/python_api.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,8 @@ def __ne__(self, actual) -> bool:
7272
return not (actual == self)
7373

7474
def _approx_scalar(self, x) -> "ApproxScalar":
75+
if isinstance(x, Decimal):
76+
return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
7577
return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
7678

7779
def _yield_comparisons(self, actual):

testing/python/approx.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,12 @@ def test_list(self):
313313
assert approx(expected, rel=5e-7, abs=0) == actual
314314
assert approx(expected, rel=5e-8, abs=0) != actual
315315

316+
def test_list_decimal(self):
317+
actual = [Decimal("1.000001"), Decimal("2.000001")]
318+
expected = [Decimal("1"), Decimal("2")]
319+
320+
assert actual == approx(expected)
321+
316322
def test_list_wrong_len(self):
317323
assert [1, 2] != approx([1])
318324
assert [1, 2] != approx([1, 2, 3])
@@ -346,6 +352,14 @@ def test_dict(self):
346352
assert approx(expected, rel=5e-7, abs=0) == actual
347353
assert approx(expected, rel=5e-8, abs=0) != actual
348354

355+
def test_dict_decimal(self):
356+
actual = {"a": Decimal("1.000001"), "b": Decimal("2.000001")}
357+
# Dictionaries became ordered in python3.6, so switch up the order here
358+
# to make sure it doesn't matter.
359+
expected = {"b": Decimal("2"), "a": Decimal("1")}
360+
361+
assert actual == approx(expected)
362+
349363
def test_dict_wrong_len(self):
350364
assert {"a": 1, "b": 2} != approx({"a": 1})
351365
assert {"a": 1, "b": 2} != approx({"a": 1, "c": 2})

0 commit comments

Comments
 (0)