[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
from __future__ import annotations
import abc
from functools import cached_property
from inspect import signature
import os
import pathlib
import warnings
from functools import cached_property
from inspect import signature
from pathlib import Path
from typing import Any
from typing import Callable
@ -21,11 +24,9 @@ from typing import Type
from typing import TYPE_CHECKING
from typing import TypeVar
from typing import Union
import warnings
import pluggy
import _pytest._code
import pluggy
from _pytest._code import getfslineno
from _pytest._code.code import ExceptionInfo
from _pytest._code.code import TerminalRepr
@ -53,18 +54,18 @@ if TYPE_CHECKING:
from _pytest.main import Session
SEP = "/"
SEP = '/'
tracebackcutdir = Path(_pytest.__file__).parent
_T = TypeVar("_T")
_T = TypeVar('_T')
def _imply_path(
node_type: Type["Node"],
path: Optional[Path],
fspath: Optional[LEGACY_PATH],
node_type: type[Node],
path: Path | None,
fspath: LEGACY_PATH | None,
) -> Path:
if fspath is not None:
warnings.warn(
@ -82,7 +83,7 @@ def _imply_path(
return Path(fspath)
_NodeType = TypeVar("_NodeType", bound="Node")
_NodeType = TypeVar('_NodeType', bound='Node')
class NodeMeta(abc.ABCMeta):
@ -102,28 +103,28 @@ class NodeMeta(abc.ABCMeta):
def __call__(cls, *k, **kw) -> NoReturn:
msg = (
"Direct construction of {name} has been deprecated, please use {name}.from_parent.\n"
"See "
"https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent"
" for more details."
).format(name=f"{cls.__module__}.{cls.__name__}")
'Direct construction of {name} has been deprecated, please use {name}.from_parent.\n'
'See '
'https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent'
' for more details.'
).format(name=f'{cls.__module__}.{cls.__name__}')
fail(msg, pytrace=False)
def _create(cls: Type[_T], *k, **kw) -> _T:
def _create(cls: type[_T], *k, **kw) -> _T:
try:
return super().__call__(*k, **kw) # type: ignore[no-any-return,misc]
except TypeError:
sig = signature(getattr(cls, "__init__"))
sig = signature(getattr(cls, '__init__'))
known_kw = {k: v for k, v in kw.items() if k in sig.parameters}
from .warning_types import PytestDeprecationWarning
warnings.warn(
PytestDeprecationWarning(
f"{cls} is not using a cooperative constructor and only takes {set(known_kw)}.\n"
"See https://docs.pytest.org/en/stable/deprecations.html"
"#constructors-of-custom-pytest-node-subclasses-should-take-kwargs "
"for more details."
)
f'{cls} is not using a cooperative constructor and only takes {set(known_kw)}.\n'
'See https://docs.pytest.org/en/stable/deprecations.html'
'#constructors-of-custom-pytest-node-subclasses-should-take-kwargs '
'for more details.',
),
)
return super().__call__(*k, **known_kw) # type: ignore[no-any-return,misc]
@ -147,25 +148,25 @@ class Node(abc.ABC, metaclass=NodeMeta):
# Use __slots__ to make attribute access faster.
# Note that __dict__ is still available.
__slots__ = (
"name",
"parent",
"config",
"session",
"path",
"_nodeid",
"_store",
"__dict__",
'name',
'parent',
'config',
'session',
'path',
'_nodeid',
'_store',
'__dict__',
)
def __init__(
self,
name: str,
parent: "Optional[Node]" = None,
config: Optional[Config] = None,
session: "Optional[Session]" = None,
fspath: Optional[LEGACY_PATH] = None,
path: Optional[Path] = None,
nodeid: Optional[str] = None,
parent: Optional[Node] = None,
config: Config | None = None,
session: Optional[Session] = None,
fspath: LEGACY_PATH | None = None,
path: Path | None = None,
nodeid: str | None = None,
) -> None:
#: A unique name within the scope of the parent node.
self.name: str = name
@ -178,7 +179,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
self.config: Config = config
else:
if not parent:
raise TypeError("config or parent must be provided")
raise TypeError('config or parent must be provided')
self.config = parent.config
if session:
@ -186,11 +187,11 @@ class Node(abc.ABC, metaclass=NodeMeta):
self.session: Session = session
else:
if not parent:
raise TypeError("session or parent must be provided")
raise TypeError('session or parent must be provided')
self.session = parent.session
if path is None and fspath is None:
path = getattr(parent, "path", None)
path = getattr(parent, 'path', None)
#: Filesystem path where this node was collected from (can be None).
self.path: pathlib.Path = _imply_path(type(self), path, fspath=fspath)
@ -199,18 +200,18 @@ class Node(abc.ABC, metaclass=NodeMeta):
self.keywords: MutableMapping[str, Any] = NodeKeywords(self)
#: The marker objects belonging to this node.
self.own_markers: List[Mark] = []
self.own_markers: list[Mark] = []
#: Allow adding of extra keywords to use for matching.
self.extra_keyword_matches: Set[str] = set()
self.extra_keyword_matches: set[str] = set()
if nodeid is not None:
assert "::()" not in nodeid
assert '::()' not in nodeid
self._nodeid = nodeid
else:
if not self.parent:
raise TypeError("nodeid or parent must be provided")
self._nodeid = self.parent.nodeid + "::" + self.name
raise TypeError('nodeid or parent must be provided')
self._nodeid = self.parent.nodeid + '::' + self.name
#: A place where plugins can store information on the node for their
#: own use.
@ -219,7 +220,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
self._store = self.stash
@classmethod
def from_parent(cls, parent: "Node", **kw) -> "Self":
def from_parent(cls, parent: Node, **kw) -> Self:
"""Public constructor for Nodes.
This indirection got introduced in order to enable removing
@ -230,10 +231,10 @@ class Node(abc.ABC, metaclass=NodeMeta):
:param parent: The parent node of this Node.
"""
if "config" in kw:
raise TypeError("config is not a valid argument for from_parent")
if "session" in kw:
raise TypeError("session is not a valid argument for from_parent")
if 'config' in kw:
raise TypeError('config is not a valid argument for from_parent')
if 'session' in kw:
raise TypeError('session is not a valid argument for from_parent')
return cls._create(parent=parent, **kw)
@property
@ -242,7 +243,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
return self.session.gethookproxy(self.path)
def __repr__(self) -> str:
return "<{} {}>".format(self.__class__.__name__, getattr(self, "name", None))
return '<{} {}>'.format(self.__class__.__name__, getattr(self, 'name', None))
def warn(self, warning: Warning) -> None:
"""Issue a warning for this Node.
@ -268,7 +269,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
# enforce type checks here to avoid getting a generic type error later otherwise.
if not isinstance(warning, Warning):
raise ValueError(
f"warning must be an instance of Warning or subclass, got {warning!r}"
f'warning must be an instance of Warning or subclass, got {warning!r}',
)
path, lineno = get_fslocation_from_item(self)
assert lineno is not None
@ -295,22 +296,22 @@ class Node(abc.ABC, metaclass=NodeMeta):
def teardown(self) -> None:
pass
def iter_parents(self) -> Iterator["Node"]:
def iter_parents(self) -> Iterator[Node]:
"""Iterate over all parent collectors starting from and including self
up to the root of the collection tree.
.. versionadded:: 8.1
"""
parent: Optional[Node] = self
parent: Node | None = self
while parent is not None:
yield parent
parent = parent.parent
def listchain(self) -> List["Node"]:
def listchain(self) -> list[Node]:
"""Return a list of all parent collectors starting from the root of the
collection tree down to and including self."""
chain = []
item: Optional[Node] = self
item: Node | None = self
while item is not None:
chain.append(item)
item = item.parent
@ -318,7 +319,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
return chain
def add_marker(
self, marker: Union[str, MarkDecorator], append: bool = True
self, marker: str | MarkDecorator, append: bool = True,
) -> None:
"""Dynamically add a marker object to the node.
@ -334,14 +335,14 @@ class Node(abc.ABC, metaclass=NodeMeta):
elif isinstance(marker, str):
marker_ = getattr(MARK_GEN, marker)
else:
raise ValueError("is not a string or pytest.mark.* Marker")
raise ValueError('is not a string or pytest.mark.* Marker')
self.keywords[marker_.name] = marker_
if append:
self.own_markers.append(marker_.mark)
else:
self.own_markers.insert(0, marker_.mark)
def iter_markers(self, name: Optional[str] = None) -> Iterator[Mark]:
def iter_markers(self, name: str | None = None) -> Iterator[Mark]:
"""Iterate over all markers of the node.
:param name: If given, filter the results by the name attribute.
@ -350,8 +351,8 @@ class Node(abc.ABC, metaclass=NodeMeta):
return (x[1] for x in self.iter_markers_with_node(name=name))
def iter_markers_with_node(
self, name: Optional[str] = None
) -> Iterator[Tuple["Node", Mark]]:
self, name: str | None = None,
) -> Iterator[tuple[Node, Mark]]:
"""Iterate over all markers of the node.
:param name: If given, filter the results by the name attribute.
@ -359,11 +360,11 @@ class Node(abc.ABC, metaclass=NodeMeta):
"""
for node in self.iter_parents():
for mark in node.own_markers:
if name is None or getattr(mark, "name", None) == name:
if name is None or getattr(mark, 'name', None) == name:
yield node, mark
@overload
def get_closest_marker(self, name: str) -> Optional[Mark]:
def get_closest_marker(self, name: str) -> Mark | None:
...
@overload
@ -371,8 +372,8 @@ class Node(abc.ABC, metaclass=NodeMeta):
...
def get_closest_marker(
self, name: str, default: Optional[Mark] = None
) -> Optional[Mark]:
self, name: str, default: Mark | None = None,
) -> Mark | None:
"""Return the first marker matching the name, from closest (for
example function) to farther level (for example module level).
@ -381,14 +382,14 @@ class Node(abc.ABC, metaclass=NodeMeta):
"""
return next(self.iter_markers(name=name), default)
def listextrakeywords(self) -> Set[str]:
def listextrakeywords(self) -> set[str]:
"""Return a set of all extra keywords in self and any parents."""
extra_keywords: Set[str] = set()
extra_keywords: set[str] = set()
for item in self.listchain():
extra_keywords.update(item.extra_keyword_matches)
return extra_keywords
def listnames(self) -> List[str]:
def listnames(self) -> list[str]:
return [x.name for x in self.listchain()]
def addfinalizer(self, fin: Callable[[], object]) -> None:
@ -400,7 +401,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
"""
self.session._setupstate.addfinalizer(fin, self)
def getparent(self, cls: Type[_NodeType]) -> Optional[_NodeType]:
def getparent(self, cls: type[_NodeType]) -> _NodeType | None:
"""Get the closest parent node (including self) which is an instance of
the given class.
@ -418,7 +419,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
def _repr_failure_py(
self,
excinfo: ExceptionInfo[BaseException],
style: "Optional[_TracebackStyle]" = None,
style: Optional[_TracebackStyle] = None,
) -> TerminalRepr:
from _pytest.fixtures import FixtureLookupError
@ -426,26 +427,26 @@ class Node(abc.ABC, metaclass=NodeMeta):
excinfo = ExceptionInfo.from_exception(excinfo.value.cause)
if isinstance(excinfo.value, fail.Exception):
if not excinfo.value.pytrace:
style = "value"
style = 'value'
if isinstance(excinfo.value, FixtureLookupError):
return excinfo.value.formatrepr()
tbfilter: Union[bool, Callable[[ExceptionInfo[BaseException]], Traceback]]
if self.config.getoption("fulltrace", False):
style = "long"
tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback]
if self.config.getoption('fulltrace', False):
style = 'long'
tbfilter = False
else:
tbfilter = self._traceback_filter
if style == "auto":
style = "long"
if style == 'auto':
style = 'long'
# XXX should excinfo.getrepr record all data and toterminal() process it?
if style is None:
if self.config.getoption("tbstyle", "auto") == "short":
style = "short"
if self.config.getoption('tbstyle', 'auto') == 'short':
style = 'short'
else:
style = "long"
style = 'long'
if self.config.getoption("verbose", 0) > 1:
if self.config.getoption('verbose', 0) > 1:
truncate_locals = False
else:
truncate_locals = True
@ -464,7 +465,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
return excinfo.getrepr(
funcargs=True,
abspath=abspath,
showlocals=self.config.getoption("showlocals", False),
showlocals=self.config.getoption('showlocals', False),
style=style,
tbfilter=tbfilter,
truncate_locals=truncate_locals,
@ -473,8 +474,8 @@ class Node(abc.ABC, metaclass=NodeMeta):
def repr_failure(
self,
excinfo: ExceptionInfo[BaseException],
style: "Optional[_TracebackStyle]" = None,
) -> Union[str, TerminalRepr]:
style: Optional[_TracebackStyle] = None,
) -> str | TerminalRepr:
"""Return a representation of a collection or test failure.
.. seealso:: :ref:`non-python tests`
@ -484,7 +485,7 @@ class Node(abc.ABC, metaclass=NodeMeta):
return self._repr_failure_py(excinfo, style)
def get_fslocation_from_item(node: "Node") -> Tuple[Union[str, Path], Optional[int]]:
def get_fslocation_from_item(node: Node) -> tuple[str | Path, int | None]:
"""Try to extract the actual location from a node, depending on available attributes:
* "location": a pair (path, lineno)
@ -494,13 +495,13 @@ def get_fslocation_from_item(node: "Node") -> Tuple[Union[str, Path], Optional[i
:rtype: A tuple of (str|Path, int) with filename and 0-based line number.
"""
# See Item.location.
location: Optional[Tuple[str, Optional[int], str]] = getattr(node, "location", None)
location: tuple[str, int | None, str] | None = getattr(node, 'location', None)
if location is not None:
return location[:2]
obj = getattr(node, "obj", None)
obj = getattr(node, 'obj', None)
if obj is not None:
return getfslineno(obj)
return getattr(node, "path", "unknown location"), -1
return getattr(node, 'path', 'unknown location'), -1
class Collector(Node, abc.ABC):
@ -514,34 +515,34 @@ class Collector(Node, abc.ABC):
"""An error during collection, contains a custom message."""
@abc.abstractmethod
def collect(self) -> Iterable[Union["Item", "Collector"]]:
def collect(self) -> Iterable[Item | Collector]:
"""Collect children (items and collectors) for this collector."""
raise NotImplementedError("abstract")
raise NotImplementedError('abstract')
# TODO: This omits the style= parameter which breaks Liskov Substitution.
def repr_failure( # type: ignore[override]
self, excinfo: ExceptionInfo[BaseException]
) -> Union[str, TerminalRepr]:
self, excinfo: ExceptionInfo[BaseException],
) -> str | TerminalRepr:
"""Return a representation of a collection failure.
:param excinfo: Exception information for the failure.
"""
if isinstance(excinfo.value, self.CollectError) and not self.config.getoption(
"fulltrace", False
'fulltrace', False,
):
exc = excinfo.value
return str(exc.args[0])
# Respect explicit tbstyle option, but default to "short"
# (_repr_failure_py uses "long" with "fulltrace" option always).
tbstyle = self.config.getoption("tbstyle", "auto")
if tbstyle == "auto":
tbstyle = "short"
tbstyle = self.config.getoption('tbstyle', 'auto')
if tbstyle == 'auto':
tbstyle = 'short'
return self._repr_failure_py(excinfo, style=tbstyle)
def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback:
if hasattr(self, "path"):
if hasattr(self, 'path'):
traceback = excinfo.traceback
ntraceback = traceback.cut(path=self.path)
if ntraceback == traceback:
@ -550,11 +551,11 @@ class Collector(Node, abc.ABC):
return excinfo.traceback
def _check_initialpaths_for_relpath(session: "Session", path: Path) -> Optional[str]:
def _check_initialpaths_for_relpath(session: Session, path: Path) -> str | None:
for initial_path in session._initialpaths:
if commonpath(path, initial_path) == initial_path:
rel = str(path.relative_to(initial_path))
return "" if rel == "." else rel
return '' if rel == '.' else rel
return None
@ -563,14 +564,14 @@ class FSCollector(Collector, abc.ABC):
def __init__(
self,
fspath: Optional[LEGACY_PATH] = None,
path_or_parent: Optional[Union[Path, Node]] = None,
path: Optional[Path] = None,
name: Optional[str] = None,
parent: Optional[Node] = None,
config: Optional[Config] = None,
session: Optional["Session"] = None,
nodeid: Optional[str] = None,
fspath: LEGACY_PATH | None = None,
path_or_parent: Path | Node | None = None,
path: Path | None = None,
name: str | None = None,
parent: Node | None = None,
config: Config | None = None,
session: Session | None = None,
nodeid: str | None = None,
) -> None:
if path_or_parent:
if isinstance(path_or_parent, Node):
@ -620,10 +621,10 @@ class FSCollector(Collector, abc.ABC):
cls,
parent,
*,
fspath: Optional[LEGACY_PATH] = None,
path: Optional[Path] = None,
fspath: LEGACY_PATH | None = None,
path: Path | None = None,
**kw,
) -> "Self":
) -> Self:
"""The public constructor."""
return super().from_parent(parent=parent, fspath=fspath, path=path, **kw)
@ -665,9 +666,9 @@ class Item(Node, abc.ABC):
self,
name,
parent=None,
config: Optional[Config] = None,
session: Optional["Session"] = None,
nodeid: Optional[str] = None,
config: Config | None = None,
session: Session | None = None,
nodeid: str | None = None,
**kw,
) -> None:
# The first two arguments are intentionally passed positionally,
@ -682,11 +683,11 @@ class Item(Node, abc.ABC):
nodeid=nodeid,
**kw,
)
self._report_sections: List[Tuple[str, str, str]] = []
self._report_sections: list[tuple[str, str, str]] = []
#: A list of tuples (name, value) that holds user defined properties
#: for this test.
self.user_properties: List[Tuple[str, object]] = []
self.user_properties: list[tuple[str, object]] = []
self._check_item_and_collector_diamond_inheritance()
@ -701,21 +702,21 @@ class Item(Node, abc.ABC):
# for the same class more than once, which is not helpful.
# It is a hack, but was deemed acceptable in order to avoid
# flooding the user in the common case.
attr_name = "_pytest_diamond_inheritance_warning_shown"
attr_name = '_pytest_diamond_inheritance_warning_shown'
if getattr(cls, attr_name, False):
return
setattr(cls, attr_name, True)
problems = ", ".join(
problems = ', '.join(
base.__name__ for base in cls.__bases__ if issubclass(base, Collector)
)
if problems:
warnings.warn(
f"{cls.__name__} is an Item subclass and should not be a collector, "
f"however its bases {problems} are collectors.\n"
"Please split the Collectors and the Item into separate node types.\n"
"Pytest Doc example: https://docs.pytest.org/en/latest/example/nonpython.html\n"
"example pull request on a plugin: https://github.com/asmeurer/pytest-flakes/pull/40/",
f'{cls.__name__} is an Item subclass and should not be a collector, '
f'however its bases {problems} are collectors.\n'
'Please split the Collectors and the Item into separate node types.\n'
'Pytest Doc example: https://docs.pytest.org/en/latest/example/nonpython.html\n'
'example pull request on a plugin: https://github.com/asmeurer/pytest-flakes/pull/40/',
PytestWarning,
)
@ -727,7 +728,7 @@ class Item(Node, abc.ABC):
.. seealso:: :ref:`non-python tests`
"""
raise NotImplementedError("runtest must be implemented by Item subclass")
raise NotImplementedError('runtest must be implemented by Item subclass')
def add_report_section(self, when: str, key: str, content: str) -> None:
"""Add a new report section, similar to what's done internally to add
@ -746,7 +747,7 @@ class Item(Node, abc.ABC):
if content:
self._report_sections.append((when, key, content))
def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]:
def reportinfo(self) -> tuple[os.PathLike[str] | str, int | None, str]:
"""Get location information for this item for test reports.
Returns a tuple with three elements:
@ -757,10 +758,10 @@ class Item(Node, abc.ABC):
.. seealso:: :ref:`non-python tests`
"""
return self.path, None, ""
return self.path, None, ''
@cached_property
def location(self) -> Tuple[str, Optional[int], str]:
def location(self) -> tuple[str, int | None, str]:
"""
Returns a tuple of ``(relfspath, lineno, testname)`` for this item
where ``relfspath`` is file path relative to ``config.rootpath``