mirror of
https://github.com/pre-commit/pre-commit-hooks.git
synced 2026-04-10 13:24:18 +00:00
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
This commit is contained in:
parent
72ad6dc953
commit
f4cd1ba0d6
813 changed files with 66015 additions and 58839 deletions
|
|
@ -1,7 +1,10 @@
|
|||
# mypy: allow-untyped-defs
|
||||
"""Record warnings during test function execution."""
|
||||
from pprint import pformat
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import warnings
|
||||
from pprint import pformat
|
||||
from types import TracebackType
|
||||
from typing import Any
|
||||
from typing import Callable
|
||||
|
|
@ -16,7 +19,6 @@ from typing import Tuple
|
|||
from typing import Type
|
||||
from typing import TypeVar
|
||||
from typing import Union
|
||||
import warnings
|
||||
|
||||
from _pytest.deprecated import check_ispytest
|
||||
from _pytest.fixtures import fixture
|
||||
|
|
@ -24,11 +26,11 @@ from _pytest.outcomes import Exit
|
|||
from _pytest.outcomes import fail
|
||||
|
||||
|
||||
T = TypeVar("T")
|
||||
T = TypeVar('T')
|
||||
|
||||
|
||||
@fixture
|
||||
def recwarn() -> Generator["WarningsRecorder", None, None]:
|
||||
def recwarn() -> Generator[WarningsRecorder, None, None]:
|
||||
"""Return a :class:`WarningsRecorder` instance that records all warnings emitted by test functions.
|
||||
|
||||
See https://docs.pytest.org/en/latest/how-to/capture-warnings.html for information
|
||||
|
|
@ -36,14 +38,14 @@ def recwarn() -> Generator["WarningsRecorder", None, None]:
|
|||
"""
|
||||
wrec = WarningsRecorder(_ispytest=True)
|
||||
with wrec:
|
||||
warnings.simplefilter("default")
|
||||
warnings.simplefilter('default')
|
||||
yield wrec
|
||||
|
||||
|
||||
@overload
|
||||
def deprecated_call(
|
||||
*, match: Optional[Union[str, Pattern[str]]] = ...
|
||||
) -> "WarningsRecorder":
|
||||
*, match: str | Pattern[str] | None = ...,
|
||||
) -> WarningsRecorder:
|
||||
...
|
||||
|
||||
|
||||
|
|
@ -53,8 +55,8 @@ def deprecated_call(func: Callable[..., T], *args: Any, **kwargs: Any) -> T:
|
|||
|
||||
|
||||
def deprecated_call(
|
||||
func: Optional[Callable[..., Any]] = None, *args: Any, **kwargs: Any
|
||||
) -> Union["WarningsRecorder", Any]:
|
||||
func: Callable[..., Any] | None = None, *args: Any, **kwargs: Any,
|
||||
) -> WarningsRecorder | Any:
|
||||
"""Assert that code produces a ``DeprecationWarning`` or ``PendingDeprecationWarning`` or ``FutureWarning``.
|
||||
|
||||
This function can be used as a context manager::
|
||||
|
|
@ -82,22 +84,22 @@ def deprecated_call(
|
|||
if func is not None:
|
||||
args = (func, *args)
|
||||
return warns(
|
||||
(DeprecationWarning, PendingDeprecationWarning, FutureWarning), *args, **kwargs
|
||||
(DeprecationWarning, PendingDeprecationWarning, FutureWarning), *args, **kwargs,
|
||||
)
|
||||
|
||||
|
||||
@overload
|
||||
def warns(
|
||||
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = ...,
|
||||
expected_warning: type[Warning] | tuple[type[Warning], ...] = ...,
|
||||
*,
|
||||
match: Optional[Union[str, Pattern[str]]] = ...,
|
||||
) -> "WarningsChecker":
|
||||
match: str | Pattern[str] | None = ...,
|
||||
) -> WarningsChecker:
|
||||
...
|
||||
|
||||
|
||||
@overload
|
||||
def warns(
|
||||
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]],
|
||||
expected_warning: type[Warning] | tuple[type[Warning], ...],
|
||||
func: Callable[..., T],
|
||||
*args: Any,
|
||||
**kwargs: Any,
|
||||
|
|
@ -106,11 +108,11 @@ def warns(
|
|||
|
||||
|
||||
def warns(
|
||||
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
|
||||
expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,
|
||||
*args: Any,
|
||||
match: Optional[Union[str, Pattern[str]]] = None,
|
||||
match: str | Pattern[str] | None = None,
|
||||
**kwargs: Any,
|
||||
) -> Union["WarningsChecker", Any]:
|
||||
) -> WarningsChecker | Any:
|
||||
r"""Assert that code raises a particular class of warning.
|
||||
|
||||
Specifically, the parameter ``expected_warning`` can be a warning class or tuple
|
||||
|
|
@ -155,16 +157,16 @@ def warns(
|
|||
__tracebackhide__ = True
|
||||
if not args:
|
||||
if kwargs:
|
||||
argnames = ", ".join(sorted(kwargs))
|
||||
argnames = ', '.join(sorted(kwargs))
|
||||
raise TypeError(
|
||||
f"Unexpected keyword arguments passed to pytest.warns: {argnames}"
|
||||
"\nUse context-manager form instead?"
|
||||
f'Unexpected keyword arguments passed to pytest.warns: {argnames}'
|
||||
'\nUse context-manager form instead?',
|
||||
)
|
||||
return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)
|
||||
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')
|
||||
with WarningsChecker(expected_warning, _ispytest=True):
|
||||
return func(*args[1:], **kwargs)
|
||||
|
||||
|
|
@ -187,18 +189,18 @@ class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
|
|||
# Type ignored due to the way typeshed handles warnings.catch_warnings.
|
||||
super().__init__(record=True) # type: ignore[call-arg]
|
||||
self._entered = False
|
||||
self._list: List[warnings.WarningMessage] = []
|
||||
self._list: list[warnings.WarningMessage] = []
|
||||
|
||||
@property
|
||||
def list(self) -> List["warnings.WarningMessage"]:
|
||||
def list(self) -> list[warnings.WarningMessage]:
|
||||
"""The list of recorded warnings."""
|
||||
return self._list
|
||||
|
||||
def __getitem__(self, i: int) -> "warnings.WarningMessage":
|
||||
def __getitem__(self, i: int) -> warnings.WarningMessage:
|
||||
"""Get a recorded warning by index."""
|
||||
return self._list[i]
|
||||
|
||||
def __iter__(self) -> Iterator["warnings.WarningMessage"]:
|
||||
def __iter__(self) -> Iterator[warnings.WarningMessage]:
|
||||
"""Iterate through the recorded warnings."""
|
||||
return iter(self._list)
|
||||
|
||||
|
|
@ -206,24 +208,24 @@ class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
|
|||
"""The number of recorded warnings."""
|
||||
return len(self._list)
|
||||
|
||||
def pop(self, cls: Type[Warning] = Warning) -> "warnings.WarningMessage":
|
||||
def pop(self, cls: type[Warning] = Warning) -> warnings.WarningMessage:
|
||||
"""Pop the first recorded warning which is an instance of ``cls``,
|
||||
but not an instance of a child class of any other match.
|
||||
Raises ``AssertionError`` if there is no match.
|
||||
"""
|
||||
best_idx: Optional[int] = None
|
||||
best_idx: int | None = None
|
||||
for i, w in enumerate(self._list):
|
||||
if w.category == cls:
|
||||
return self._list.pop(i) # exact match, stop looking
|
||||
if issubclass(w.category, cls) and (
|
||||
best_idx is None
|
||||
or not issubclass(w.category, self._list[best_idx].category)
|
||||
best_idx is None or
|
||||
not issubclass(w.category, self._list[best_idx].category)
|
||||
):
|
||||
best_idx = i
|
||||
if best_idx is not None:
|
||||
return self._list.pop(best_idx)
|
||||
__tracebackhide__ = True
|
||||
raise AssertionError(f"{cls!r} not found in warning list")
|
||||
raise AssertionError(f'{cls!r} not found in warning list')
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear the list of recorded warnings."""
|
||||
|
|
@ -231,26 +233,26 @@ class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
|
|||
|
||||
# Type ignored because it doesn't exactly warnings.catch_warnings.__enter__
|
||||
# -- it returns a List but we only emulate one.
|
||||
def __enter__(self) -> "WarningsRecorder": # type: ignore
|
||||
def __enter__(self) -> WarningsRecorder: # type: ignore
|
||||
if self._entered:
|
||||
__tracebackhide__ = True
|
||||
raise RuntimeError(f"Cannot enter {self!r} twice")
|
||||
raise RuntimeError(f'Cannot enter {self!r} twice')
|
||||
_list = super().__enter__()
|
||||
# record=True means it's None.
|
||||
assert _list is not None
|
||||
self._list = _list
|
||||
warnings.simplefilter("always")
|
||||
warnings.simplefilter('always')
|
||||
return self
|
||||
|
||||
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,
|
||||
) -> None:
|
||||
if not self._entered:
|
||||
__tracebackhide__ = True
|
||||
raise RuntimeError(f"Cannot exit {self!r} without entering first")
|
||||
raise RuntimeError(f'Cannot exit {self!r} without entering first')
|
||||
|
||||
super().__exit__(exc_type, exc_val, exc_tb)
|
||||
|
||||
|
|
@ -263,22 +265,22 @@ class WarningsRecorder(warnings.catch_warnings): # type:ignore[type-arg]
|
|||
class WarningsChecker(WarningsRecorder):
|
||||
def __init__(
|
||||
self,
|
||||
expected_warning: Union[Type[Warning], Tuple[Type[Warning], ...]] = Warning,
|
||||
match_expr: Optional[Union[str, Pattern[str]]] = None,
|
||||
expected_warning: type[Warning] | tuple[type[Warning], ...] = Warning,
|
||||
match_expr: str | Pattern[str] | None = None,
|
||||
*,
|
||||
_ispytest: bool = False,
|
||||
) -> None:
|
||||
check_ispytest(_ispytest)
|
||||
super().__init__(_ispytest=True)
|
||||
|
||||
msg = "exceptions must be derived from Warning, not %s"
|
||||
msg = 'exceptions must be derived from Warning, not %s'
|
||||
if isinstance(expected_warning, tuple):
|
||||
for exc in expected_warning:
|
||||
if not issubclass(exc, Warning):
|
||||
raise TypeError(msg % type(exc))
|
||||
expected_warning_tup = expected_warning
|
||||
elif isinstance(expected_warning, type) and issubclass(
|
||||
expected_warning, Warning
|
||||
expected_warning, Warning,
|
||||
):
|
||||
expected_warning_tup = (expected_warning,)
|
||||
else:
|
||||
|
|
@ -290,14 +292,14 @@ class WarningsChecker(WarningsRecorder):
|
|||
def matches(self, warning: warnings.WarningMessage) -> bool:
|
||||
assert self.expected_warning is not None
|
||||
return issubclass(warning.category, self.expected_warning) and bool(
|
||||
self.match_expr is None or re.search(self.match_expr, str(warning.message))
|
||||
self.match_expr is None or re.search(self.match_expr, str(warning.message)),
|
||||
)
|
||||
|
||||
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,
|
||||
) -> None:
|
||||
super().__exit__(exc_type, exc_val, exc_tb)
|
||||
|
||||
|
|
@ -308,9 +310,9 @@ class WarningsChecker(WarningsRecorder):
|
|||
# when the warning doesn't happen. Control-flow exceptions should always
|
||||
# propagate.
|
||||
if exc_val is not None and (
|
||||
not isinstance(exc_val, Exception)
|
||||
not isinstance(exc_val, Exception) or
|
||||
# Exit is an Exception, not a BaseException, for some reason.
|
||||
or isinstance(exc_val, Exit)
|
||||
isinstance(exc_val, Exit)
|
||||
):
|
||||
return
|
||||
|
||||
|
|
@ -320,14 +322,14 @@ class WarningsChecker(WarningsRecorder):
|
|||
try:
|
||||
if not any(issubclass(w.category, self.expected_warning) for w in self):
|
||||
fail(
|
||||
f"DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n"
|
||||
f" Emitted warnings: {found_str()}."
|
||||
f'DID NOT WARN. No warnings of type {self.expected_warning} were emitted.\n'
|
||||
f' Emitted warnings: {found_str()}.',
|
||||
)
|
||||
elif not any(self.matches(w) for w in self):
|
||||
fail(
|
||||
f"DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.\n"
|
||||
f" Regex: {self.match_expr}\n"
|
||||
f" Emitted warnings: {found_str()}."
|
||||
f'DID NOT WARN. No warnings of type {self.expected_warning} matching the regex were emitted.\n'
|
||||
f' Regex: {self.match_expr}\n'
|
||||
f' Emitted warnings: {found_str()}.',
|
||||
)
|
||||
finally:
|
||||
# Whether or not any warnings matched, we want to re-emit all unmatched warnings.
|
||||
|
|
@ -366,5 +368,5 @@ class WarningsChecker(WarningsRecorder):
|
|||
# its first argument was not a string. But that case can't be
|
||||
# distinguished from an invalid type.
|
||||
raise TypeError(
|
||||
f"Warning must be str or Warning, got {msg!r} (type {type(msg).__name__})"
|
||||
f'Warning must be str or Warning, got {msg!r} (type {type(msg).__name__})',
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue