[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,9 +1,12 @@
# mypy: allow-untyped-defs
"""Monkeypatching and mocking functionality."""
from contextlib import contextmanager
from __future__ import annotations
import os
import re
import sys
import warnings
from contextlib import contextmanager
from typing import Any
from typing import final
from typing import Generator
@ -15,21 +18,20 @@ from typing import overload
from typing import Tuple
from typing import TypeVar
from typing import Union
import warnings
from _pytest.fixtures import fixture
from _pytest.warning_types import PytestWarning
RE_IMPORT_ERROR_NAME = re.compile(r"^No module named (.*)$")
RE_IMPORT_ERROR_NAME = re.compile(r'^No module named (.*)$')
K = TypeVar("K")
V = TypeVar("V")
K = TypeVar('K')
V = TypeVar('V')
@fixture
def monkeypatch() -> Generator["MonkeyPatch", None, None]:
def monkeypatch() -> Generator[MonkeyPatch, None, None]:
"""A convenient fixture for monkey-patching.
The fixture provides these methods to modify objects, dictionaries, or
@ -60,12 +62,12 @@ def monkeypatch() -> Generator["MonkeyPatch", None, None]:
def resolve(name: str) -> object:
# Simplified from zope.dottedname.
parts = name.split(".")
parts = name.split('.')
used = parts.pop(0)
found: object = __import__(used)
for part in parts:
used += "." + part
used += '.' + part
try:
found = getattr(found, part)
except AttributeError:
@ -81,7 +83,7 @@ def resolve(name: str) -> object:
if expected == used:
raise
else:
raise ImportError(f"import error in {used}: {ex}") from ex
raise ImportError(f'import error in {used}: {ex}') from ex
found = annotated_getattr(found, part, used)
return found
@ -91,15 +93,15 @@ def annotated_getattr(obj: object, name: str, ann: str) -> object:
obj = getattr(obj, name)
except AttributeError as e:
raise AttributeError(
f"{type(obj).__name__!r} object at {ann} has no attribute {name!r}"
f'{type(obj).__name__!r} object at {ann} has no attribute {name!r}',
) from e
return obj
def derive_importpath(import_path: str, raising: bool) -> Tuple[str, object]:
if not isinstance(import_path, str) or "." not in import_path:
raise TypeError(f"must be absolute import path string, not {import_path!r}")
module, attr = import_path.rsplit(".", 1)
def derive_importpath(import_path: str, raising: bool) -> tuple[str, object]:
if not isinstance(import_path, str) or '.' not in import_path:
raise TypeError(f'must be absolute import path string, not {import_path!r}')
module, attr = import_path.rsplit('.', 1)
target = resolve(module)
if raising:
annotated_getattr(target, attr, ann=module)
@ -108,7 +110,7 @@ def derive_importpath(import_path: str, raising: bool) -> Tuple[str, object]:
class Notset:
def __repr__(self) -> str:
return "<notset>"
return '<notset>'
notset = Notset()
@ -129,14 +131,14 @@ class MonkeyPatch:
"""
def __init__(self) -> None:
self._setattr: List[Tuple[object, str, object]] = []
self._setitem: List[Tuple[Mapping[Any, Any], object, object]] = []
self._cwd: Optional[str] = None
self._savesyspath: Optional[List[str]] = None
self._setattr: list[tuple[object, str, object]] = []
self._setitem: list[tuple[Mapping[Any, Any], object, object]] = []
self._cwd: str | None = None
self._savesyspath: list[str] | None = None
@classmethod
@contextmanager
def context(cls) -> Generator["MonkeyPatch", None, None]:
def context(cls) -> Generator[MonkeyPatch, None, None]:
"""Context manager that returns a new :class:`MonkeyPatch` object
which undoes any patching done inside the ``with`` block upon exit.
@ -182,8 +184,8 @@ class MonkeyPatch:
def setattr(
self,
target: Union[str, object],
name: Union[object, str],
target: str | object,
name: object | str,
value: object = notset,
raising: bool = True,
) -> None:
@ -228,23 +230,23 @@ class MonkeyPatch:
if isinstance(value, Notset):
if not isinstance(target, str):
raise TypeError(
"use setattr(target, name, value) or "
"setattr(target, value) with target being a dotted "
"import string"
'use setattr(target, name, value) or '
'setattr(target, value) with target being a dotted '
'import string',
)
value = name
name, target = derive_importpath(target, raising)
else:
if not isinstance(name, str):
raise TypeError(
"use setattr(target, name, value) with name being a string or "
"setattr(target, value) with target being a dotted "
"import string"
'use setattr(target, name, value) with name being a string or '
'setattr(target, value) with target being a dotted '
'import string',
)
oldval = getattr(target, name, notset)
if raising and oldval is notset:
raise AttributeError(f"{target!r} has no attribute {name!r}")
raise AttributeError(f'{target!r} has no attribute {name!r}')
# avoid class descriptors like staticmethod/classmethod
if inspect.isclass(target):
@ -254,8 +256,8 @@ class MonkeyPatch:
def delattr(
self,
target: Union[object, str],
name: Union[str, Notset] = notset,
target: object | str,
name: str | Notset = notset,
raising: bool = True,
) -> None:
"""Delete attribute ``name`` from ``target``.
@ -273,9 +275,9 @@ class MonkeyPatch:
if isinstance(name, Notset):
if not isinstance(target, str):
raise TypeError(
"use delattr(target, name) or "
"delattr(target) with target being a dotted "
"import string"
'use delattr(target, name) or '
'delattr(target) with target being a dotted '
'import string',
)
name, target = derive_importpath(target, raising)
@ -310,7 +312,7 @@ class MonkeyPatch:
# Not all Mapping types support indexing, but MutableMapping doesn't support TypedDict
del dic[name] # type: ignore[attr-defined]
def setenv(self, name: str, value: str, prepend: Optional[str] = None) -> None:
def setenv(self, name: str, value: str, prepend: str | None = None) -> None:
"""Set environment variable ``name`` to ``value``.
If ``prepend`` is a character, read the current environment variable
@ -320,8 +322,8 @@ class MonkeyPatch:
if not isinstance(value, str):
warnings.warn( # type: ignore[unreachable]
PytestWarning(
f"Value of environment variable {name} type should be str, but got "
f"{value!r} (type: {type(value).__name__}); converted to str implicitly"
f'Value of environment variable {name} type should be str, but got '
f'{value!r} (type: {type(value).__name__}); converted to str implicitly',
),
stacklevel=2,
)
@ -347,7 +349,7 @@ class MonkeyPatch:
# https://github.com/pypa/setuptools/blob/d8b901bc/docs/pkg_resources.txt#L162-L171
# this is only needed when pkg_resources was already loaded by the namespace package
if "pkg_resources" in sys.modules:
if 'pkg_resources' in sys.modules:
from pkg_resources import fixup_namespace_packages
fixup_namespace_packages(str(path))
@ -363,7 +365,7 @@ class MonkeyPatch:
invalidate_caches()
def chdir(self, path: Union[str, "os.PathLike[str]"]) -> None:
def chdir(self, path: str | os.PathLike[str]) -> None:
"""Change the current working directory to the specified path.
:param path: