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
15 changes: 15 additions & 0 deletions changelog/9061.breaking.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Using :func:`pytest.approx` in a boolean context now raises an error hinting at the proper usage.

It is apparently common for users to mistakenly use ``pytest.approx`` like this:

.. code-block:: python

assert pytest.approx(actual, expected)

While the correct usage is:

.. code-block:: python

assert actual == pytest.approx(expected)

The new error message helps catch those mistakes.
5 changes: 5 additions & 0 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ def __eq__(self, actual) -> bool:
a == self._approx_scalar(x) for a, x in self._yield_comparisons(actual)
)

def __bool__(self):
raise AssertionError(
"approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?"
)

# Ignore type because of https://github.com/python/mypy/issues/4266.
__hash__ = None # type: ignore

Expand Down
6 changes: 6 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,12 @@ def test_repr_nd_array(self, value, expected_repr_string):
np_array = np.array(value)
assert repr(approx(np_array)) == expected_repr_string

def test_bool(self):
with pytest.raises(AssertionError) as err:
assert approx(1)

assert err.match(r"approx\(\) is not supported in a boolean context")

def test_operator_overloading(self):
assert 1 == approx(1, rel=1e-6, abs=1e-12)
assert not (1 != approx(1, rel=1e-6, abs=1e-12))
Expand Down