Skip to content
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 AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,7 @@ Raquel Alegre
Ravi Chandra
Reagan Lee
Reilly Brogan
rinopatrick
Rob Arrow
Robert Holt
Roberto Aldera
Expand Down
1 change: 1 addition & 0 deletions changelog/15314.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed :func:`pytest.approx` reporting wrong differences (and wrong equality results) when comparing a list expected value against a NumPy integer array: NumPy scalars are now unboxed before subtraction, avoiding wraparound such as ``0 - np.uint8(1)`` evaluating to ``255``.
5 changes: 4 additions & 1 deletion src/_pytest/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,9 @@ def _repr_compare(self, other_side: Sequence[float]) -> list[str]:
for i, (approx_value, other_value) in enumerate(
zip(approx_side_as_map, other_side, strict=True)
):
# Unbox numpy scalars first: e.g. `0 - np.uint8(1)` wraps around
# to 255 instead of -1 (see #15314).
other_value = _unbox_numpy_scalar(other_value)
if approx_value != other_value:
try:
abs_diff = abs(approx_value.expected - other_value)
Expand Down Expand Up @@ -477,7 +480,7 @@ def __eq__(self, actual) -> bool:
return super().__eq__(actual)

def _yield_comparisons(self, actual):
return zip(actual, self.expected, strict=True)
return zip((_unbox_numpy_scalar(a) for a in actual), self.expected, strict=True)


class ApproxScalar(Approx[ExpectedT]):
Expand Down
10 changes: 10 additions & 0 deletions testing/python/approx.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,16 @@ def test_error_messages_numpy_dtypes(self, assert_approx_raises_regex):
],
)

def test_numpy_integer_actual_against_list_expected(self):
# Numpy integer scalars must be unboxed before comparison, otherwise
# e.g. `0 - np.uint8(1)` wraps around to 255 (see #15314).
np = pytest.importorskip("numpy")

assert np.array([1], dtype=np.uint8) == pytest.approx([0], abs=5)
assert np.array([0], dtype=np.uint8) == pytest.approx([1], abs=5)
assert np.array([255], dtype=np.uint8) != pytest.approx([0])
assert np.array([-128], dtype=np.int8) != pytest.approx([127])

def test_error_messages_invalid_args(self, assert_approx_raises_regex):
np = pytest.importorskip("numpy")
with pytest.raises(AssertionError) as e:
Expand Down
Loading