Skip to content

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

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

Closed
Closed
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
11 changes: 11 additions & 0 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,17 @@ class ApproxDecimal(ApproxScalar):
DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")

def __repr__(self):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def __repr__(self):
def __repr__(self) -> str:

rel = Decimal(str(self.rel)) if isinstance(self.rel, float) else self.rel
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to verify if using Decimal.from_float is more correct here

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also we might need to generally ensure that rel is not a float

abs_ = Decimal(str(self.abs)) if isinstance(self.abs, float) else 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
16 changes: 16 additions & 0 deletions testing/test_decimal_approx.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from __future__ import annotations

import decimal

import pytest


def test_decimal_approx_repr_issue() -> None:
trap = decimal.getcontext().traps[decimal.FloatOperation]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use momkeypatch.setitem to ensure undo happens even on failures (not that i expect a failure)

decimal.getcontext().traps[decimal.FloatOperation] = False

approx_obj = pytest.approx(decimal.Decimal("2.60"))
print(f"Attempting to represent pytest.approx(Decimal): {approx_obj}")
assert decimal.Decimal("2.600001") == approx_obj

decimal.getcontext().traps[decimal.FloatOperation] = trap