Skip to content
Merged
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/14373.improvement.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added type annotations for :func:`pytest.approx`.
7 changes: 6 additions & 1 deletion src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,12 @@ def __repr__(self) -> str:
return f"{self.expected} ± {tol_str}"


def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
def approx(
expected: Any,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this one's extremely dynamic and can accept a huge variety of arguments, e.g.

class MyVec3: # incomplete
"""sequence like"""
_x: int
_y: int
_z: int
def __init__(self, x: int, y: int, z: int):
self._x, self._y, self._z = x, y, z
def __repr__(self) -> str:
return f"<MyVec3 {self._x} {self._y} {self._z}>"
def __len__(self) -> int:
return 3
def __getitem__(self, key: int) -> int:
if key == 0:
return self._x
if key == 1:
return self._y
if key == 2:
return self._z
raise IndexError(key)

Not sure how much it's worth it to list everything, so for now I'm just suggesting Any here and we can start making rel and abs more precise as well as making the function typed

rel: float | Decimal | None = None,
abs: float | Decimal | None = None,
nan_ok: bool = False,
) -> ApproxBase:
"""Assert that two numbers (or two ordered sequences of numbers) are equal to each other
within some tolerance.

Expand Down
2 changes: 2 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,8 @@ def test_decimal(self):
assert a != approx(x, rel=Decimal("5e-7"), abs=0)
assert approx(x, rel=Decimal("5e-6"), abs=0) == a
assert approx(x, rel=Decimal("5e-7"), abs=0) != a
assert approx(x, rel=0, abs=Decimal("5e-3")) == a
assert approx(x, rel=0, abs=Decimal("5e-7")) != a
Comment on lines +619 to +620

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I noticed that there wasn't any test for abs: Decimal, so I added this one


def test_fraction(self):
within_1e6 = [
Expand Down