[pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci
This commit is contained in:
pre-commit-ci[bot] 2024-04-13 00:00:18 +00:00
parent 72ad6dc953
commit f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions

View file

@ -1,10 +1,12 @@
# mypy: allow-untyped-defs
from __future__ import annotations
import math
import pprint
from collections.abc import Collection
from collections.abc import Sized
from decimal import Decimal
import math
from numbers import Complex
import pprint
from types import TracebackType
from typing import Any
from typing import Callable
@ -33,25 +35,25 @@ if TYPE_CHECKING:
def _compare_approx(
full_object: object,
message_data: Sequence[Tuple[str, str, str]],
message_data: Sequence[tuple[str, str, str]],
number_of_elements: int,
different_ids: Sequence[object],
max_abs_diff: float,
max_rel_diff: float,
) -> List[str]:
) -> list[str]:
message_list = list(message_data)
message_list.insert(0, ("Index", "Obtained", "Expected"))
message_list.insert(0, ('Index', 'Obtained', 'Expected'))
max_sizes = [0, 0, 0]
for index, obtained, expected in message_list:
max_sizes[0] = max(max_sizes[0], len(index))
max_sizes[1] = max(max_sizes[1], len(obtained))
max_sizes[2] = max(max_sizes[2], len(expected))
explanation = [
f"comparison failed. Mismatched elements: {len(different_ids)} / {number_of_elements}:",
f"Max absolute difference: {max_abs_diff}",
f"Max relative difference: {max_rel_diff}",
f'comparison failed. Mismatched elements: {len(different_ids)} / {number_of_elements}:',
f'Max absolute difference: {max_abs_diff}',
f'Max relative difference: {max_rel_diff}',
] + [
f"{indexes:<{max_sizes[0]}} | {obtained:<{max_sizes[1]}} | {expected:<{max_sizes[2]}}"
f'{indexes:<{max_sizes[0]}} | {obtained:<{max_sizes[1]}} | {expected:<{max_sizes[2]}}'
for indexes, obtained, expected in message_list
]
return explanation
@ -79,11 +81,11 @@ class ApproxBase:
def __repr__(self) -> str:
raise NotImplementedError
def _repr_compare(self, other_side: Any) -> List[str]:
def _repr_compare(self, other_side: Any) -> list[str]:
return [
"comparison failed",
f"Obtained: {other_side}",
f"Expected: {self}",
'comparison failed',
f'Obtained: {other_side}',
f'Expected: {self}',
]
def __eq__(self, actual) -> bool:
@ -94,7 +96,7 @@ class ApproxBase:
def __bool__(self):
__tracebackhide__ = True
raise AssertionError(
"approx() is not supported in a boolean context.\nDid you mean: `assert a == approx(b)`?"
'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.
@ -103,7 +105,7 @@ class ApproxBase:
def __ne__(self, actual) -> bool:
return not (actual == self)
def _approx_scalar(self, x) -> "ApproxScalar":
def _approx_scalar(self, x) -> ApproxScalar:
if isinstance(x, Decimal):
return ApproxDecimal(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
return ApproxScalar(x, rel=self.rel, abs=self.abs, nan_ok=self.nan_ok)
@ -138,16 +140,16 @@ class ApproxNumpy(ApproxBase):
def __repr__(self) -> str:
list_scalars = _recursive_sequence_map(
self._approx_scalar, self.expected.tolist()
self._approx_scalar, self.expected.tolist(),
)
return f"approx({list_scalars!r})"
return f'approx({list_scalars!r})'
def _repr_compare(self, other_side: "ndarray") -> List[str]:
def _repr_compare(self, other_side: ndarray) -> list[str]:
import itertools
import math
def get_value_from_nested_list(
nested_list: List[Any], nd_index: Tuple[Any, ...]
nested_list: list[Any], nd_index: tuple[Any, ...],
) -> Any:
"""
Helper function to get the value out of a nested list, given an n-dimensional index.
@ -160,13 +162,13 @@ class ApproxNumpy(ApproxBase):
np_array_shape = self.expected.shape
approx_side_as_seq = _recursive_sequence_map(
self._approx_scalar, self.expected.tolist()
self._approx_scalar, self.expected.tolist(),
)
if np_array_shape != other_side.shape:
return [
"Impossible to compare arrays with different shapes.",
f"Shapes: {np_array_shape} and {other_side.shape}",
'Impossible to compare arrays with different shapes.',
f'Shapes: {np_array_shape} and {other_side.shape}',
]
number_of_elements = self.expected.size
@ -238,9 +240,9 @@ class ApproxMapping(ApproxBase):
with numeric values (the keys can be anything)."""
def __repr__(self) -> str:
return f"approx({({k: self._approx_scalar(v) for k, v in self.expected.items()})!r})"
return f'approx({({k: self._approx_scalar(v) for k, v in self.expected.items()})!r})'
def _repr_compare(self, other_side: Mapping[object, float]) -> List[str]:
def _repr_compare(self, other_side: Mapping[object, float]) -> list[str]:
import math
approx_side_as_map = {
@ -252,12 +254,12 @@ class ApproxMapping(ApproxBase):
max_rel_diff = -math.inf
different_ids = []
for (approx_key, approx_value), other_value in zip(
approx_side_as_map.items(), other_side.values()
approx_side_as_map.items(), other_side.values(),
):
if approx_value != other_value:
if approx_value.expected is not None and other_value is not None:
max_abs_diff = max(
max_abs_diff, abs(approx_value.expected - other_value)
max_abs_diff, abs(approx_value.expected - other_value),
)
if approx_value.expected == 0.0:
max_rel_diff = math.inf
@ -265,8 +267,8 @@ class ApproxMapping(ApproxBase):
max_rel_diff = max(
max_rel_diff,
abs(
(approx_value.expected - other_value)
/ approx_value.expected
(approx_value.expected - other_value) /
approx_value.expected,
),
)
different_ids.append(approx_key)
@ -302,7 +304,7 @@ class ApproxMapping(ApproxBase):
__tracebackhide__ = True
for key, value in self.expected.items():
if isinstance(value, type(self.expected)):
msg = "pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}"
msg = 'pytest.approx() does not support nested dictionaries: key={!r} value={!r}\n full mapping={}'
raise TypeError(msg.format(key, value, pprint.pformat(self.expected)))
@ -313,15 +315,15 @@ class ApproxSequenceLike(ApproxBase):
seq_type = type(self.expected)
if seq_type not in (tuple, list):
seq_type = list
return f"approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})"
return f'approx({seq_type(self._approx_scalar(x) for x in self.expected)!r})'
def _repr_compare(self, other_side: Sequence[float]) -> List[str]:
def _repr_compare(self, other_side: Sequence[float]) -> list[str]:
import math
if len(self.expected) != len(other_side):
return [
"Impossible to compare lists with different sizes.",
f"Lengths: {len(self.expected)} and {len(other_side)}",
'Impossible to compare lists with different sizes.',
f'Lengths: {len(self.expected)} and {len(other_side)}',
]
approx_side_as_map = _recursive_sequence_map(self._approx_scalar, self.expected)
@ -331,7 +333,7 @@ class ApproxSequenceLike(ApproxBase):
max_rel_diff = -math.inf
different_ids = []
for i, (approx_value, other_value) in enumerate(
zip(approx_side_as_map, other_side)
zip(approx_side_as_map, other_side),
):
if approx_value != other_value:
abs_diff = abs(approx_value.expected - other_value)
@ -371,7 +373,7 @@ class ApproxSequenceLike(ApproxBase):
__tracebackhide__ = True
for index, x in enumerate(self.expected):
if isinstance(x, type(self.expected)):
msg = "pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}"
msg = 'pytest.approx() does not support nested data structures: {!r} at index {}\n full sequence: {}'
raise TypeError(msg.format(x, index, pprint.pformat(self.expected)))
@ -380,8 +382,8 @@ class ApproxScalar(ApproxBase):
# Using Real should be better than this Union, but not possible yet:
# https://github.com/python/typeshed/pull/3108
DEFAULT_ABSOLUTE_TOLERANCE: Union[float, Decimal] = 1e-12
DEFAULT_RELATIVE_TOLERANCE: Union[float, Decimal] = 1e-6
DEFAULT_ABSOLUTE_TOLERANCE: float | Decimal = 1e-12
DEFAULT_RELATIVE_TOLERANCE: float | Decimal = 1e-6
def __repr__(self) -> str:
"""Return a string communicating both the expected value and the
@ -393,24 +395,24 @@ class ApproxScalar(ApproxBase):
# tolerances, i.e. non-numerics and infinities. Need to call abs to
# handle complex numbers, e.g. (inf + 1j).
if (not isinstance(self.expected, (Complex, Decimal))) or math.isinf(
abs(self.expected) # type: ignore[arg-type]
abs(self.expected), # type: ignore[arg-type]
):
return str(self.expected)
# If a sensible tolerance can't be calculated, self.tolerance will
# raise a ValueError. In this case, display '???'.
try:
vetted_tolerance = f"{self.tolerance:.1e}"
vetted_tolerance = f'{self.tolerance:.1e}'
if (
isinstance(self.expected, Complex)
and self.expected.imag
and not math.isinf(self.tolerance)
isinstance(self.expected, Complex) and
self.expected.imag and
not math.isinf(self.tolerance)
):
vetted_tolerance += " ∠ ±180°"
vetted_tolerance += ' ∠ ±180°'
except ValueError:
vetted_tolerance = "???"
vetted_tolerance = '???'
return f"{self.expected} ± {vetted_tolerance}"
return f'{self.expected} ± {vetted_tolerance}'
def __eq__(self, actual) -> bool:
"""Return whether the given value is equal to the expected value
@ -429,8 +431,8 @@ class ApproxScalar(ApproxBase):
# NB: we need Complex, rather than just Number, to ensure that __abs__,
# __sub__, and __float__ are defined.
if not (
isinstance(self.expected, (Complex, Decimal))
and isinstance(actual, (Complex, Decimal))
isinstance(self.expected, (Complex, Decimal)) and
isinstance(actual, (Complex, Decimal))
):
return False
@ -473,7 +475,7 @@ class ApproxScalar(ApproxBase):
if absolute_tolerance < 0:
raise ValueError(
f"absolute tolerance can't be negative: {absolute_tolerance}"
f"absolute tolerance can't be negative: {absolute_tolerance}",
)
if math.isnan(absolute_tolerance):
raise ValueError("absolute tolerance can't be NaN.")
@ -490,12 +492,12 @@ class ApproxScalar(ApproxBase):
# because we don't want to raise errors about the relative tolerance if
# we aren't even going to use it.
relative_tolerance = set_default(
self.rel, self.DEFAULT_RELATIVE_TOLERANCE
self.rel, self.DEFAULT_RELATIVE_TOLERANCE,
) * abs(self.expected)
if relative_tolerance < 0:
raise ValueError(
f"relative tolerance can't be negative: {relative_tolerance}"
f"relative tolerance can't be negative: {relative_tolerance}",
)
if math.isnan(relative_tolerance):
raise ValueError("relative tolerance can't be NaN.")
@ -507,8 +509,8 @@ class ApproxScalar(ApproxBase):
class ApproxDecimal(ApproxScalar):
"""Perform approximate comparisons where the expected value is a Decimal."""
DEFAULT_ABSOLUTE_TOLERANCE = Decimal("1e-12")
DEFAULT_RELATIVE_TOLERANCE = Decimal("1e-6")
DEFAULT_ABSOLUTE_TOLERANCE = Decimal('1e-12')
DEFAULT_RELATIVE_TOLERANCE = Decimal('1e-6')
def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
@ -711,20 +713,20 @@ def approx(expected, rel=None, abs=None, nan_ok: bool = False) -> ApproxBase:
__tracebackhide__ = True
if isinstance(expected, Decimal):
cls: Type[ApproxBase] = ApproxDecimal
cls: type[ApproxBase] = ApproxDecimal
elif isinstance(expected, Mapping):
cls = ApproxMapping
elif _is_numpy_array(expected):
expected = _as_numpy_array(expected)
cls = ApproxNumpy
elif (
hasattr(expected, "__getitem__")
and isinstance(expected, Sized)
and not isinstance(expected, (str, bytes))
hasattr(expected, '__getitem__') and
isinstance(expected, Sized) and
not isinstance(expected, (str, bytes))
):
cls = ApproxSequenceLike
elif isinstance(expected, Collection) and not isinstance(expected, (str, bytes)):
msg = f"pytest.approx() only supports ordered sequences, but got: {expected!r}"
msg = f'pytest.approx() only supports ordered sequences, but got: {expected!r}'
raise TypeError(msg)
else:
cls = ApproxScalar
@ -740,42 +742,42 @@ def _is_numpy_array(obj: object) -> bool:
return _as_numpy_array(obj) is not None
def _as_numpy_array(obj: object) -> Optional["ndarray"]:
def _as_numpy_array(obj: object) -> ndarray | None:
"""
Return an ndarray if the given object is implicitly convertible to ndarray,
and numpy is already imported, otherwise None.
"""
import sys
np: Any = sys.modules.get("numpy")
np: Any = sys.modules.get('numpy')
if np is not None:
# avoid infinite recursion on numpy scalars, which have __array__
if np.isscalar(obj):
return None
elif isinstance(obj, np.ndarray):
return obj
elif hasattr(obj, "__array__") or hasattr("obj", "__array_interface__"):
elif hasattr(obj, '__array__') or hasattr('obj', '__array_interface__'):
return np.asarray(obj)
return None
# builtin pytest.raises helper
E = TypeVar("E", bound=BaseException)
E = TypeVar('E', bound=BaseException)
@overload
def raises(
expected_exception: Union[Type[E], Tuple[Type[E], ...]],
expected_exception: type[E] | tuple[type[E], ...],
*,
match: Optional[Union[str, Pattern[str]]] = ...,
) -> "RaisesContext[E]":
match: str | Pattern[str] | None = ...,
) -> RaisesContext[E]:
...
@overload
def raises(
expected_exception: Union[Type[E], Tuple[Type[E], ...]],
expected_exception: type[E] | tuple[type[E], ...],
func: Callable[..., Any],
*args: Any,
**kwargs: Any,
@ -784,8 +786,8 @@ def raises(
def raises(
expected_exception: Union[Type[E], Tuple[Type[E], ...]], *args: Any, **kwargs: Any
) -> Union["RaisesContext[E]", _pytest._code.ExceptionInfo[E]]:
expected_exception: type[E] | tuple[type[E], ...], *args: Any, **kwargs: Any,
) -> RaisesContext[E] | _pytest._code.ExceptionInfo[E]:
r"""Assert that a code block/function call raises an exception type, or one of its subclasses.
:param expected_exception:
@ -928,34 +930,34 @@ def raises(
if not expected_exception:
raise ValueError(
f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
f'Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. '
f"Raising exceptions is already understood as failing the test, so you don't need "
f"any special code to say 'this should never raise an exception'."
f"any special code to say 'this should never raise an exception'.",
)
if isinstance(expected_exception, type):
expected_exceptions: Tuple[Type[E], ...] = (expected_exception,)
expected_exceptions: tuple[type[E], ...] = (expected_exception,)
else:
expected_exceptions = expected_exception
for exc in expected_exceptions:
if not isinstance(exc, type) or not issubclass(exc, BaseException):
msg = "expected exception must be a BaseException type, not {}" # type: ignore[unreachable]
msg = 'expected exception must be a BaseException type, not {}' # type: ignore[unreachable]
not_a = exc.__name__ if isinstance(exc, type) else type(exc).__name__
raise TypeError(msg.format(not_a))
message = f"DID NOT RAISE {expected_exception}"
message = f'DID NOT RAISE {expected_exception}'
if not args:
match: Optional[Union[str, Pattern[str]]] = kwargs.pop("match", None)
match: str | Pattern[str] | None = kwargs.pop('match', None)
if kwargs:
msg = "Unexpected keyword arguments passed to pytest.raises: "
msg += ", ".join(sorted(kwargs))
msg += "\nUse context-manager form instead?"
msg = 'Unexpected keyword arguments passed to pytest.raises: '
msg += ', '.join(sorted(kwargs))
msg += '\nUse context-manager form instead?'
raise TypeError(msg)
return RaisesContext(expected_exception, message, match)
else:
func = args[0]
if not callable(func):
raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
raise TypeError(f'{func!r} object (type: {type(func)}) must be callable')
try:
func(*args[1:], **kwargs)
except expected_exception as e:
@ -971,14 +973,14 @@ raises.Exception = fail.Exception # type: ignore
class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]):
def __init__(
self,
expected_exception: Union[Type[E], Tuple[Type[E], ...]],
expected_exception: type[E] | tuple[type[E], ...],
message: str,
match_expr: Optional[Union[str, Pattern[str]]] = None,
match_expr: str | Pattern[str] | None = None,
) -> None:
self.expected_exception = expected_exception
self.message = message
self.match_expr = match_expr
self.excinfo: Optional[_pytest._code.ExceptionInfo[E]] = None
self.excinfo: _pytest._code.ExceptionInfo[E] | None = None
def __enter__(self) -> _pytest._code.ExceptionInfo[E]:
self.excinfo = _pytest._code.ExceptionInfo.for_later()
@ -986,9 +988,9 @@ class RaisesContext(ContextManager[_pytest._code.ExceptionInfo[E]]):
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
exc_type: type[BaseException] | None,
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> bool:
__tracebackhide__ = True
if exc_type is None: