Skip to content

Fix decimal.FloatOperation error in pytest.approx Decimal __repr__ #13543

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/13530.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed a crash when using :func:`pytest.approx` and :class:`decimal.Decimal` instances with the :class:`decimal.FloatOperation` trap set.
20 changes: 20 additions & 0 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,26 @@ class ApproxDecimal(ApproxScalar):
DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")

def __repr__(self) -> str:
if isinstance(self.rel, float):
rel = Decimal.from_float(self.rel)
else:
rel = self.rel

if isinstance(self.abs, float):
abs_ = Decimal.from_float(self.abs)
else:
abs_ = self.abs

if rel is not None and Decimal("1e-3") <= rel <= Decimal("1e3"):
tol_str = f"{rel:.1e}"
elif abs_ is not None:
tol_str = f"{abs_:.1e}"
else:
tol_str = "???"

return f"{self.expected} ± {tol_str}"


def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
"""Assert that two numbers (or two ordered sequences of numbers) are equal to each other
Expand Down
5 changes: 5 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -1015,6 +1015,11 @@ def __len__(self):
expected_repr = "approx([1 ± 1.0e-06, 2 ± 2.0e-06, 3 ± 3.0e-06, 4 ± 4.0e-06])"
assert repr(approx(expected)) == expected_repr

def test_decimal_approx_repr(self, monkeypatch) -> None:
monkeypatch.setitem(decimal.getcontext().traps, decimal.FloatOperation, True)
approx_obj = pytest.approx(decimal.Decimal("2.60"))
assert decimal.Decimal("2.600001") == approx_obj

def test_allow_ordered_sequences_only(self) -> None:
"""pytest.approx() should raise an error on unordered sequences (#9692)."""
with pytest.raises(TypeError, match="only supports ordered sequences"):
Expand Down
Loading