Skip to content

Commit

Permalink
fix pytest-dev#11797: be more lenient on SequenceLike approx
Browse files Browse the repository at this point in the history
this needs a validation as it allows partially implemented sequences
  • Loading branch information
RonnyPfannschmidt committed Jan 15, 2024
1 parent 6e74601 commit 2a16b61
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
1 change: 1 addition & 0 deletions changelog/11797.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Ensure approx for SequenceLike objects doesn't wrap those sequences in a scalar.
18 changes: 12 additions & 6 deletions src/_pytest/python_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,8 @@ def _recursive_sequence_map(f, x):
if isinstance(x, (list, tuple)):
seq_type = type(x)
return seq_type(_recursive_sequence_map(f, xi) for xi in x)
elif _is_sequence_like(x):
return [_recursive_sequence_map(f, xi) for xi in x]
else:
return f(x)

Expand Down Expand Up @@ -721,12 +723,7 @@ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
elif _is_numpy_array(expected):
expected = _as_numpy_array(expected)
cls = ApproxNumpy
elif (
hasattr(expected, "__getitem__")
and isinstance(expected, Sized)
# Type ignored because the error is wrong -- not unreachable.
and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable]
):
elif _is_sequence_like(expected):
cls = ApproxSequenceLike
elif (
isinstance(expected, Collection)
Expand All @@ -741,6 +738,15 @@ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
return cls(expected, rel, abs, nan_ok)


def _is_sequence_like(expected: object) -> bool:
return (
hasattr(expected, "__getitem__")
and isinstance(expected, Sized)
# Type ignored because the error is wrong -- not unreachable.
and not isinstance(expected, STRING_TYPES) # type: ignore[unreachable]
)


def _is_numpy_array(obj: object) -> bool:
"""
Return true if the given object is implicitly convertible to ndarray,
Expand Down

0 comments on commit 2a16b61

Please sign in to comment.