| 1 |
# mypy: allow-untyped-defs |
| 2 |
import abc |
| 3 |
from functools import cached_property |
| 4 |
from inspect import signature |
| 5 |
import os |
| 6 |
import pathlib |
| 7 |
from pathlib import Path |
| 8 |
from typing import Any |
| 9 |
from typing import Callable |
| 10 |
from typing import cast |
| 11 |
from typing import Iterable |
| 12 |
from typing import Iterator |
| 13 |
from typing import List |
| 14 |
from typing import MutableMapping |
| 15 |
from typing import NoReturn |
| 16 |
from typing import Optional |
| 17 |
from typing import overload |
| 18 |
from typing import Set |
| 19 |
from typing import Tuple |
| 20 |
from typing import Type |
| 21 |
from typing import TYPE_CHECKING |
| 22 |
from typing import TypeVar |
| 23 |
from typing import Union |
| 24 |
import warnings |
| 25 |
|
| 26 |
import pluggy |
| 27 |
|
| 28 |
import _pytest._code |
| 29 |
from _pytest._code import getfslineno |
| 30 |
from _pytest._code.code import ExceptionInfo |
| 31 |
from _pytest._code.code import TerminalRepr |
| 32 |
from _pytest._code.code import Traceback |
| 33 |
from _pytest.compat import LEGACY_PATH |
| 34 |
from _pytest.config import Config |
| 35 |
from _pytest.config import ConftestImportFailure |
| 36 |
from _pytest.config.compat import _check_path |
| 37 |
from _pytest.deprecated import NODE_CTOR_FSPATH_ARG |
| 38 |
from _pytest.mark.structures import Mark |
| 39 |
from _pytest.mark.structures import MarkDecorator |
| 40 |
from _pytest.mark.structures import NodeKeywords |
| 41 |
from _pytest.outcomes import fail |
| 42 |
from _pytest.pathlib import absolutepath |
| 43 |
from _pytest.pathlib import commonpath |
| 44 |
from _pytest.stash import Stash |
| 45 |
from _pytest.warning_types import PytestWarning |
| 46 |
|
| 47 |
|
| 48 |
if TYPE_CHECKING: |
| 49 |
from typing import Self |
| 50 |
|
| 51 |
# Imported here due to circular import. |
| 52 |
from _pytest._code.code import _TracebackStyle |
| 53 |
from _pytest.main import Session |
| 54 |
|
| 55 |
|
| 56 |
SEP = "/" |
| 57 |
|
| 58 |
tracebackcutdir = Path(_pytest.__file__).parent |
| 59 |
|
| 60 |
|
| 61 |
_T = TypeVar("_T") |
| 62 |
|
| 63 |
|
| 64 |
def _imply_path( |
| 65 |
node_type: Type["Node"], |
| 66 |
path: Optional[Path], |
| 67 |
fspath: Optional[LEGACY_PATH], |
| 68 |
) -> Path: |
| 69 |
if fspath is not None: |
| 70 |
warnings.warn( |
| 71 |
NODE_CTOR_FSPATH_ARG.format( |
| 72 |
node_type_name=node_type.__name__, |
| 73 |
), |
| 74 |
stacklevel=6, |
| 75 |
) |
| 76 |
if path is not None: |
| 77 |
if fspath is not None: |
| 78 |
_check_path(path, fspath) |
| 79 |
return path |
| 80 |
else: |
| 81 |
assert fspath is not None |
| 82 |
return Path(fspath) |
| 83 |
|
| 84 |
|
| 85 |
_NodeType = TypeVar("_NodeType", bound="Node") |
| 86 |
|
| 87 |
|
| 88 |
class NodeMeta(abc.ABCMeta): |
| 89 |
"""Metaclass used by :class:`Node` to enforce that direct construction raises |
| 90 |
:class:`Failed`. |
| 91 |
|
| 92 |
This behaviour supports the indirection introduced with :meth:`Node.from_parent`, |
| 93 |
the named constructor to be used instead of direct construction. The design |
| 94 |
decision to enforce indirection with :class:`NodeMeta` was made as a |
| 95 |
temporary aid for refactoring the collection tree, which was diagnosed to |
| 96 |
have :class:`Node` objects whose creational patterns were overly entangled. |
| 97 |
Once the refactoring is complete, this metaclass can be removed. |
| 98 |
|
| 99 |
See https://github.com/pytest-dev/pytest/projects/3 for an overview of the |
| 100 |
progress on detangling the :class:`Node` classes. |
| 101 |
""" |
| 102 |
|
| 103 |
def __call__(cls, *k, **kw) -> NoReturn: |
| 104 |
msg = ( |
| 105 |
"Direct construction of {name} has been deprecated, please use {name}.from_parent.\n" |
| 106 |
"See " |
| 107 |
"https://docs.pytest.org/en/stable/deprecations.html#node-construction-changed-to-node-from-parent" |
| 108 |
" for more details." |
| 109 |
).format(name=f"{cls.__module__}.{cls.__name__}") |
| 110 |
fail(msg, pytrace=False) |
| 111 |
|
| 112 |
def _create(cls: Type[_T], *k, **kw) -> _T: |
| 113 |
try: |
| 114 |
return super().__call__(*k, **kw) # type: ignore[no-any-return,misc] |
| 115 |
except TypeError: |
| 116 |
sig = signature(getattr(cls, "__init__")) |
| 117 |
known_kw = {k: v for k, v in kw.items() if k in sig.parameters} |
| 118 |
from .warning_types import PytestDeprecationWarning |
| 119 |
|
| 120 |
warnings.warn( |
| 121 |
PytestDeprecationWarning( |
| 122 |
f"{cls} is not using a cooperative constructor and only takes {set(known_kw)}.\n" |
| 123 |
"See https://docs.pytest.org/en/stable/deprecations.html" |
| 124 |
"#constructors-of-custom-pytest-node-subclasses-should-take-kwargs " |
| 125 |
"for more details." |
| 126 |
) |
| 127 |
) |
| 128 |
|
| 129 |
return super().__call__(*k, **known_kw) # type: ignore[no-any-return,misc] |
| 130 |
|
| 131 |
|
| 132 |
class Node(abc.ABC, metaclass=NodeMeta): |
| 133 |
r"""Base class of :class:`Collector` and :class:`Item`, the components of |
| 134 |
the test collection tree. |
| 135 |
|
| 136 |
``Collector``\'s are the internal nodes of the tree, and ``Item``\'s are the |
| 137 |
leaf nodes. |
| 138 |
""" |
| 139 |
|
| 140 |
# Implemented in the legacypath plugin. |
| 141 |
#: A ``LEGACY_PATH`` copy of the :attr:`path` attribute. Intended for usage |
| 142 |
#: for methods not migrated to ``pathlib.Path`` yet, such as |
| 143 |
#: :meth:`Item.reportinfo <pytest.Item.reportinfo>`. Will be deprecated in |
| 144 |
#: a future release, prefer using :attr:`path` instead. |
| 145 |
fspath: LEGACY_PATH |
| 146 |
|
| 147 |
# Use __slots__ to make attribute access faster. |
| 148 |
# Note that __dict__ is still available. |
| 149 |
__slots__ = ( |
| 150 |
"name", |
| 151 |
"parent", |
| 152 |
"config", |
| 153 |
"session", |
| 154 |
"path", |
| 155 |
"_nodeid", |
| 156 |
"_store", |
| 157 |
"__dict__", |
| 158 |
) |
| 159 |
|
| 160 |
def __init__( |
| 161 |
self, |
| 162 |
name: str, |
| 163 |
parent: "Optional[Node]" = None, |
| 164 |
config: Optional[Config] = None, |
| 165 |
session: "Optional[Session]" = None, |
| 166 |
fspath: Optional[LEGACY_PATH] = None, |
| 167 |
path: Optional[Path] = None, |
| 168 |
nodeid: Optional[str] = None, |
| 169 |
) -> None: |
| 170 |
#: A unique name within the scope of the parent node. |
| 171 |
self.name: str = name |
| 172 |
|
| 173 |
#: The parent collector node. |
| 174 |
self.parent = parent |
| 175 |
|
| 176 |
if config: |
| 177 |
#: The pytest config object. |
| 178 |
self.config: Config = config |
| 179 |
else: |
| 180 |
if not parent: |
| 181 |
raise TypeError("config or parent must be provided") |
| 182 |
self.config = parent.config |
| 183 |
|
| 184 |
if session: |
| 185 |
#: The pytest session this node is part of. |
| 186 |
self.session: Session = session |
| 187 |
else: |
| 188 |
if not parent: |
| 189 |
raise TypeError("session or parent must be provided") |
| 190 |
self.session = parent.session |
| 191 |
|
| 192 |
if path is None and fspath is None: |
| 193 |
path = getattr(parent, "path", None) |
| 194 |
#: Filesystem path where this node was collected from (can be None). |
| 195 |
self.path: pathlib.Path = _imply_path(type(self), path, fspath=fspath) |
| 196 |
|
| 197 |
# The explicit annotation is to avoid publicly exposing NodeKeywords. |
| 198 |
#: Keywords/markers collected from all scopes. |
| 199 |
self.keywords: MutableMapping[str, Any] = NodeKeywords(self) |
| 200 |
|
| 201 |
#: The marker objects belonging to this node. |
| 202 |
self.own_markers: List[Mark] = [] |
| 203 |
|
| 204 |
#: Allow adding of extra keywords to use for matching. |
| 205 |
self.extra_keyword_matches: Set[str] = set() |
| 206 |
|
| 207 |
if nodeid is not None: |
| 208 |
assert "::()" not in nodeid |
| 209 |
self._nodeid = nodeid |
| 210 |
else: |
| 211 |
if not self.parent: |
| 212 |
raise TypeError("nodeid or parent must be provided") |
| 213 |
self._nodeid = self.parent.nodeid + "::" + self.name |
| 214 |
|
| 215 |
#: A place where plugins can store information on the node for their |
| 216 |
#: own use. |
| 217 |
self.stash: Stash = Stash() |
| 218 |
# Deprecated alias. Was never public. Can be removed in a few releases. |
| 219 |
self._store = self.stash |
| 220 |
|
| 221 |
@classmethod |
| 222 |
def from_parent(cls, parent: "Node", **kw) -> "Self": |
| 223 |
"""Public constructor for Nodes. |
| 224 |
|
| 225 |
This indirection got introduced in order to enable removing |
| 226 |
the fragile logic from the node constructors. |
| 227 |
|
| 228 |
Subclasses can use ``super().from_parent(...)`` when overriding the |
| 229 |
construction. |
| 230 |
|
| 231 |
:param parent: The parent node of this Node. |
| 232 |
""" |
| 233 |
if "config" in kw: |
| 234 |
raise TypeError("config is not a valid argument for from_parent") |
| 235 |
if "session" in kw: |
| 236 |
raise TypeError("session is not a valid argument for from_parent") |
| 237 |
return cls._create(parent=parent, **kw) |
| 238 |
|
| 239 |
@property |
| 240 |
def ihook(self) -> pluggy.HookRelay: |
| 241 |
"""fspath-sensitive hook proxy used to call pytest hooks.""" |
| 242 |
return self.session.gethookproxy(self.path) |
| 243 |
|
| 244 |
def __repr__(self) -> str: |
| 245 |
return "<{} {}>".format(self.__class__.__name__, getattr(self, "name", None)) |
| 246 |
|
| 247 |
def warn(self, warning: Warning) -> None: |
| 248 |
"""Issue a warning for this Node. |
| 249 |
|
| 250 |
Warnings will be displayed after the test session, unless explicitly suppressed. |
| 251 |
|
| 252 |
:param Warning warning: |
| 253 |
The warning instance to issue. |
| 254 |
|
| 255 |
:raises ValueError: If ``warning`` instance is not a subclass of Warning. |
| 256 |
|
| 257 |
Example usage: |
| 258 |
|
| 259 |
.. code-block:: python |
| 260 |
|
| 261 |
node.warn(PytestWarning("some message")) |
| 262 |
node.warn(UserWarning("some message")) |
| 263 |
|
| 264 |
.. versionchanged:: 6.2 |
| 265 |
Any subclass of :class:`Warning` is now accepted, rather than only |
| 266 |
:class:`PytestWarning <pytest.PytestWarning>` subclasses. |
| 267 |
""" |
| 268 |
# enforce type checks here to avoid getting a generic type error later otherwise. |
| 269 |
if not isinstance(warning, Warning): |
| 270 |
raise ValueError( |
| 271 |
f"warning must be an instance of Warning or subclass, got {warning!r}" |
| 272 |
) |
| 273 |
path, lineno = get_fslocation_from_item(self) |
| 274 |
assert lineno is not None |
| 275 |
warnings.warn_explicit( |
| 276 |
warning, |
| 277 |
category=None, |
| 278 |
filename=str(path), |
| 279 |
lineno=lineno + 1, |
| 280 |
) |
| 281 |
|
| 282 |
# Methods for ordering nodes. |
| 283 |
|
| 284 |
@property |
| 285 |
def nodeid(self) -> str: |
| 286 |
"""A ::-separated string denoting its collection tree address.""" |
| 287 |
return self._nodeid |
| 288 |
|
| 289 |
def __hash__(self) -> int: |
| 290 |
return hash(self._nodeid) |
| 291 |
|
| 292 |
def setup(self) -> None: |
| 293 |
pass |
| 294 |
|
| 295 |
def teardown(self) -> None: |
| 296 |
pass |
| 297 |
|
| 298 |
def iter_parents(self) -> Iterator["Node"]: |
| 299 |
"""Iterate over all parent collectors starting from and including self |
| 300 |
up to the root of the collection tree. |
| 301 |
|
| 302 |
.. versionadded:: 8.1 |
| 303 |
""" |
| 304 |
parent: Optional[Node] = self |
| 305 |
while parent is not None: |
| 306 |
yield parent |
| 307 |
parent = parent.parent |
| 308 |
|
| 309 |
def listchain(self) -> List["Node"]: |
| 310 |
"""Return a list of all parent collectors starting from the root of the |
| 311 |
collection tree down to and including self.""" |
| 312 |
chain = [] |
| 313 |
item: Optional[Node] = self |
| 314 |
while item is not None: |
| 315 |
chain.append(item) |
| 316 |
item = item.parent |
| 317 |
chain.reverse() |
| 318 |
return chain |
| 319 |
|
| 320 |
def add_marker( |
| 321 |
self, marker: Union[str, MarkDecorator], append: bool = True |
| 322 |
) -> None: |
| 323 |
"""Dynamically add a marker object to the node. |
| 324 |
|
| 325 |
:param marker: |
| 326 |
The marker. |
| 327 |
:param append: |
| 328 |
Whether to append the marker, or prepend it. |
| 329 |
""" |
| 330 |
from _pytest.mark import MARK_GEN |
| 331 |
|
| 332 |
if isinstance(marker, MarkDecorator): |
| 333 |
marker_ = marker |
| 334 |
elif isinstance(marker, str): |
| 335 |
marker_ = getattr(MARK_GEN, marker) |
| 336 |
else: |
| 337 |
raise ValueError("is not a string or pytest.mark.* Marker") |
| 338 |
self.keywords[marker_.name] = marker_ |
| 339 |
if append: |
| 340 |
self.own_markers.append(marker_.mark) |
| 341 |
else: |
| 342 |
self.own_markers.insert(0, marker_.mark) |
| 343 |
|
| 344 |
def iter_markers(self, name: Optional[str] = None) -> Iterator[Mark]: |
| 345 |
"""Iterate over all markers of the node. |
| 346 |
|
| 347 |
:param name: If given, filter the results by the name attribute. |
| 348 |
:returns: An iterator of the markers of the node. |
| 349 |
""" |
| 350 |
return (x[1] for x in self.iter_markers_with_node(name=name)) |
| 351 |
|
| 352 |
def iter_markers_with_node( |
| 353 |
self, name: Optional[str] = None |
| 354 |
) -> Iterator[Tuple["Node", Mark]]: |
| 355 |
"""Iterate over all markers of the node. |
| 356 |
|
| 357 |
:param name: If given, filter the results by the name attribute. |
| 358 |
:returns: An iterator of (node, mark) tuples. |
| 359 |
""" |
| 360 |
for node in self.iter_parents(): |
| 361 |
for mark in node.own_markers: |
| 362 |
if name is None or getattr(mark, "name", None) == name: |
| 363 |
yield node, mark |
| 364 |
|
| 365 |
@overload |
| 366 |
def get_closest_marker(self, name: str) -> Optional[Mark]: ... |
| 367 |
|
| 368 |
@overload |
| 369 |
def get_closest_marker(self, name: str, default: Mark) -> Mark: ... |
| 370 |
|
| 371 |
def get_closest_marker( |
| 372 |
self, name: str, default: Optional[Mark] = None |
| 373 |
) -> Optional[Mark]: |
| 374 |
"""Return the first marker matching the name, from closest (for |
| 375 |
example function) to farther level (for example module level). |
| 376 |
|
| 377 |
:param default: Fallback return value if no marker was found. |
| 378 |
:param name: Name to filter by. |
| 379 |
""" |
| 380 |
return next(self.iter_markers(name=name), default) |
| 381 |
|
| 382 |
def listextrakeywords(self) -> Set[str]: |
| 383 |
"""Return a set of all extra keywords in self and any parents.""" |
| 384 |
extra_keywords: Set[str] = set() |
| 385 |
for item in self.listchain(): |
| 386 |
extra_keywords.update(item.extra_keyword_matches) |
| 387 |
return extra_keywords |
| 388 |
|
| 389 |
def listnames(self) -> List[str]: |
| 390 |
return [x.name for x in self.listchain()] |
| 391 |
|
| 392 |
def addfinalizer(self, fin: Callable[[], object]) -> None: |
| 393 |
"""Register a function to be called without arguments when this node is |
| 394 |
finalized. |
| 395 |
|
| 396 |
This method can only be called when this node is active |
| 397 |
in a setup chain, for example during self.setup(). |
| 398 |
""" |
| 399 |
self.session._setupstate.addfinalizer(fin, self) |
| 400 |
|
| 401 |
def getparent(self, cls: Type[_NodeType]) -> Optional[_NodeType]: |
| 402 |
"""Get the closest parent node (including self) which is an instance of |
| 403 |
the given class. |
| 404 |
|
| 405 |
:param cls: The node class to search for. |
| 406 |
:returns: The node, if found. |
| 407 |
""" |
| 408 |
for node in self.iter_parents(): |
| 409 |
if isinstance(node, cls): |
| 410 |
return node |
| 411 |
return None |
| 412 |
|
| 413 |
def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback: |
| 414 |
return excinfo.traceback |
| 415 |
|
| 416 |
def _repr_failure_py( |
| 417 |
self, |
| 418 |
excinfo: ExceptionInfo[BaseException], |
| 419 |
style: "Optional[_TracebackStyle]" = None, |
| 420 |
) -> TerminalRepr: |
| 421 |
from _pytest.fixtures import FixtureLookupError |
| 422 |
|
| 423 |
if isinstance(excinfo.value, ConftestImportFailure): |
| 424 |
excinfo = ExceptionInfo.from_exception(excinfo.value.cause) |
| 425 |
if isinstance(excinfo.value, fail.Exception): |
| 426 |
if not excinfo.value.pytrace: |
| 427 |
style = "value" |
| 428 |
if isinstance(excinfo.value, FixtureLookupError): |
| 429 |
return excinfo.value.formatrepr() |
| 430 |
|
| 431 |
tbfilter: Union[bool, Callable[[ExceptionInfo[BaseException]], Traceback]] |
| 432 |
if self.config.getoption("fulltrace", False): |
| 433 |
style = "long" |
| 434 |
tbfilter = False |
| 435 |
else: |
| 436 |
tbfilter = self._traceback_filter |
| 437 |
if style == "auto": |
| 438 |
style = "long" |
| 439 |
# XXX should excinfo.getrepr record all data and toterminal() process it? |
| 440 |
if style is None: |
| 441 |
if self.config.getoption("tbstyle", "auto") == "short": |
| 442 |
style = "short" |
| 443 |
else: |
| 444 |
style = "long" |
| 445 |
|
| 446 |
if self.config.getoption("verbose", 0) > 1: |
| 447 |
truncate_locals = False |
| 448 |
else: |
| 449 |
truncate_locals = True |
| 450 |
|
| 451 |
# excinfo.getrepr() formats paths relative to the CWD if `abspath` is False. |
| 452 |
# It is possible for a fixture/test to change the CWD while this code runs, which |
| 453 |
# would then result in the user seeing confusing paths in the failure message. |
| 454 |
# To fix this, if the CWD changed, always display the full absolute path. |
| 455 |
# It will be better to just always display paths relative to invocation_dir, but |
| 456 |
# this requires a lot of plumbing (#6428). |
| 457 |
try: |
| 458 |
abspath = Path(os.getcwd()) != self.config.invocation_params.dir |
| 459 |
except OSError: |
| 460 |
abspath = True |
| 461 |
|
| 462 |
return excinfo.getrepr( |
| 463 |
funcargs=True, |
| 464 |
abspath=abspath, |
| 465 |
showlocals=self.config.getoption("showlocals", False), |
| 466 |
style=style, |
| 467 |
tbfilter=tbfilter, |
| 468 |
truncate_locals=truncate_locals, |
| 469 |
) |
| 470 |
|
| 471 |
def repr_failure( |
| 472 |
self, |
| 473 |
excinfo: ExceptionInfo[BaseException], |
| 474 |
style: "Optional[_TracebackStyle]" = None, |
| 475 |
) -> Union[str, TerminalRepr]: |
| 476 |
"""Return a representation of a collection or test failure. |
| 477 |
|
| 478 |
.. seealso:: :ref:`non-python tests` |
| 479 |
|
| 480 |
:param excinfo: Exception information for the failure. |
| 481 |
""" |
| 482 |
return self._repr_failure_py(excinfo, style) |
| 483 |
|
| 484 |
|
| 485 |
def get_fslocation_from_item(node: "Node") -> Tuple[Union[str, Path], Optional[int]]: |
| 486 |
"""Try to extract the actual location from a node, depending on available attributes: |
| 487 |
|
| 488 |
* "location": a pair (path, lineno) |
| 489 |
* "obj": a Python object that the node wraps. |
| 490 |
* "path": just a path |
| 491 |
|
| 492 |
:rtype: A tuple of (str|Path, int) with filename and 0-based line number. |
| 493 |
""" |
| 494 |
# See Item.location. |
| 495 |
location: Optional[Tuple[str, Optional[int], str]] = getattr(node, "location", None) |
| 496 |
if location is not None: |
| 497 |
return location[:2] |
| 498 |
obj = getattr(node, "obj", None) |
| 499 |
if obj is not None: |
| 500 |
return getfslineno(obj) |
| 501 |
return getattr(node, "path", "unknown location"), -1 |
| 502 |
|
| 503 |
|
| 504 |
class Collector(Node, abc.ABC): |
| 505 |
"""Base class of all collectors. |
| 506 |
|
| 507 |
Collector create children through `collect()` and thus iteratively build |
| 508 |
the collection tree. |
| 509 |
""" |
| 510 |
|
| 511 |
class CollectError(Exception): |
| 512 |
"""An error during collection, contains a custom message.""" |
| 513 |
|
| 514 |
@abc.abstractmethod |
| 515 |
def collect(self) -> Iterable[Union["Item", "Collector"]]: |
| 516 |
"""Collect children (items and collectors) for this collector.""" |
| 517 |
raise NotImplementedError("abstract") |
| 518 |
|
| 519 |
# TODO: This omits the style= parameter which breaks Liskov Substitution. |
| 520 |
def repr_failure( # type: ignore[override] |
| 521 |
self, excinfo: ExceptionInfo[BaseException] |
| 522 |
) -> Union[str, TerminalRepr]: |
| 523 |
"""Return a representation of a collection failure. |
| 524 |
|
| 525 |
:param excinfo: Exception information for the failure. |
| 526 |
""" |
| 527 |
if isinstance(excinfo.value, self.CollectError) and not self.config.getoption( |
| 528 |
"fulltrace", False |
| 529 |
): |
| 530 |
exc = excinfo.value |
| 531 |
return str(exc.args[0]) |
| 532 |
|
| 533 |
# Respect explicit tbstyle option, but default to "short" |
| 534 |
# (_repr_failure_py uses "long" with "fulltrace" option always). |
| 535 |
tbstyle = self.config.getoption("tbstyle", "auto") |
| 536 |
if tbstyle == "auto": |
| 537 |
tbstyle = "short" |
| 538 |
|
| 539 |
return self._repr_failure_py(excinfo, style=tbstyle) |
| 540 |
|
| 541 |
def _traceback_filter(self, excinfo: ExceptionInfo[BaseException]) -> Traceback: |
| 542 |
if hasattr(self, "path"): |
| 543 |
traceback = excinfo.traceback |
| 544 |
ntraceback = traceback.cut(path=self.path) |
| 545 |
if ntraceback == traceback: |
| 546 |
ntraceback = ntraceback.cut(excludepath=tracebackcutdir) |
| 547 |
return ntraceback.filter(excinfo) |
| 548 |
return excinfo.traceback |
| 549 |
|
| 550 |
|
| 551 |
def _check_initialpaths_for_relpath(session: "Session", path: Path) -> Optional[str]: |
| 552 |
for initial_path in session._initialpaths: |
| 553 |
if commonpath(path, initial_path) == initial_path: |
| 554 |
rel = str(path.relative_to(initial_path)) |
| 555 |
return "" if rel == "." else rel |
| 556 |
return None |
| 557 |
|
| 558 |
|
| 559 |
class FSCollector(Collector, abc.ABC): |
| 560 |
"""Base class for filesystem collectors.""" |
| 561 |
|
| 562 |
def __init__( |
| 563 |
self, |
| 564 |
fspath: Optional[LEGACY_PATH] = None, |
| 565 |
path_or_parent: Optional[Union[Path, Node]] = None, |
| 566 |
path: Optional[Path] = None, |
| 567 |
name: Optional[str] = None, |
| 568 |
parent: Optional[Node] = None, |
| 569 |
config: Optional[Config] = None, |
| 570 |
session: Optional["Session"] = None, |
| 571 |
nodeid: Optional[str] = None, |
| 572 |
) -> None: |
| 573 |
if path_or_parent: |
| 574 |
if isinstance(path_or_parent, Node): |
| 575 |
assert parent is None |
| 576 |
parent = cast(FSCollector, path_or_parent) |
| 577 |
elif isinstance(path_or_parent, Path): |
| 578 |
assert path is None |
| 579 |
path = path_or_parent |
| 580 |
|
| 581 |
path = _imply_path(type(self), path, fspath=fspath) |
| 582 |
if name is None: |
| 583 |
name = path.name |
| 584 |
if parent is not None and parent.path != path: |
| 585 |
try: |
| 586 |
rel = path.relative_to(parent.path) |
| 587 |
except ValueError: |
| 588 |
pass |
| 589 |
else: |
| 590 |
name = str(rel) |
| 591 |
name = name.replace(os.sep, SEP) |
| 592 |
self.path = path |
| 593 |
|
| 594 |
if session is None: |
| 595 |
assert parent is not None |
| 596 |
session = parent.session |
| 597 |
|
| 598 |
if nodeid is None: |
| 599 |
try: |
| 600 |
nodeid = str(self.path.relative_to(session.config.rootpath)) |
| 601 |
except ValueError: |
| 602 |
nodeid = _check_initialpaths_for_relpath(session, path) |
| 603 |
|
| 604 |
if nodeid and os.sep != SEP: |
| 605 |
nodeid = nodeid.replace(os.sep, SEP) |
| 606 |
|
| 607 |
super().__init__( |
| 608 |
name=name, |
| 609 |
parent=parent, |
| 610 |
config=config, |
| 611 |
session=session, |
| 612 |
nodeid=nodeid, |
| 613 |
path=path, |
| 614 |
) |
| 615 |
|
| 616 |
@classmethod |
| 617 |
def from_parent( |
| 618 |
cls, |
| 619 |
parent, |
| 620 |
*, |
| 621 |
fspath: Optional[LEGACY_PATH] = None, |
| 622 |
path: Optional[Path] = None, |
| 623 |
**kw, |
| 624 |
) -> "Self": |
| 625 |
"""The public constructor.""" |
| 626 |
return super().from_parent(parent=parent, fspath=fspath, path=path, **kw) |
| 627 |
|
| 628 |
|
| 629 |
class File(FSCollector, abc.ABC): |
| 630 |
"""Base class for collecting tests from a file. |
| 631 |
|
| 632 |
:ref:`non-python tests`. |
| 633 |
""" |
| 634 |
|
| 635 |
|
| 636 |
class Directory(FSCollector, abc.ABC): |
| 637 |
"""Base class for collecting files from a directory. |
| 638 |
|
| 639 |
A basic directory collector does the following: goes over the files and |
| 640 |
sub-directories in the directory and creates collectors for them by calling |
| 641 |
the hooks :hook:`pytest_collect_directory` and :hook:`pytest_collect_file`, |
| 642 |
after checking that they are not ignored using |
| 643 |
:hook:`pytest_ignore_collect`. |
| 644 |
|
| 645 |
The default directory collectors are :class:`~pytest.Dir` and |
| 646 |
:class:`~pytest.Package`. |
| 647 |
|
| 648 |
.. versionadded:: 8.0 |
| 649 |
|
| 650 |
:ref:`custom directory collectors`. |
| 651 |
""" |
| 652 |
|
| 653 |
|
| 654 |
class Item(Node, abc.ABC): |
| 655 |
"""Base class of all test invocation items. |
| 656 |
|
| 657 |
Note that for a single function there might be multiple test invocation items. |
| 658 |
""" |
| 659 |
|
| 660 |
nextitem = None |
| 661 |
|
| 662 |
def __init__( |
| 663 |
self, |
| 664 |
name, |
| 665 |
parent=None, |
| 666 |
config: Optional[Config] = None, |
| 667 |
session: Optional["Session"] = None, |
| 668 |
nodeid: Optional[str] = None, |
| 669 |
**kw, |
| 670 |
) -> None: |
| 671 |
# The first two arguments are intentionally passed positionally, |
| 672 |
# to keep plugins who define a node type which inherits from |
| 673 |
# (pytest.Item, pytest.File) working (see issue #8435). |
| 674 |
# They can be made kwargs when the deprecation above is done. |
| 675 |
super().__init__( |
| 676 |
name, |
| 677 |
parent, |
| 678 |
config=config, |
| 679 |
session=session, |
| 680 |
nodeid=nodeid, |
| 681 |
**kw, |
| 682 |
) |
| 683 |
self._report_sections: List[Tuple[str, str, str]] = [] |
| 684 |
|
| 685 |
#: A list of tuples (name, value) that holds user defined properties |
| 686 |
#: for this test. |
| 687 |
self.user_properties: List[Tuple[str, object]] = [] |
| 688 |
|
| 689 |
self._check_item_and_collector_diamond_inheritance() |
| 690 |
|
| 691 |
def _check_item_and_collector_diamond_inheritance(self) -> None: |
| 692 |
""" |
| 693 |
Check if the current type inherits from both File and Collector |
| 694 |
at the same time, emitting a warning accordingly (#8447). |
| 695 |
""" |
| 696 |
cls = type(self) |
| 697 |
|
| 698 |
# We inject an attribute in the type to avoid issuing this warning |
| 699 |
# for the same class more than once, which is not helpful. |
| 700 |
# It is a hack, but was deemed acceptable in order to avoid |
| 701 |
# flooding the user in the common case. |
| 702 |
attr_name = "_pytest_diamond_inheritance_warning_shown" |
| 703 |
if getattr(cls, attr_name, False): |
| 704 |
return |
| 705 |
setattr(cls, attr_name, True) |
| 706 |
|
| 707 |
problems = ", ".join( |
| 708 |
base.__name__ for base in cls.__bases__ if issubclass(base, Collector) |
| 709 |
) |
| 710 |
if problems: |
| 711 |
warnings.warn( |
| 712 |
f"{cls.__name__} is an Item subclass and should not be a collector, " |
| 713 |
f"however its bases {problems} are collectors.\n" |
| 714 |
"Please split the Collectors and the Item into separate node types.\n" |
| 715 |
"Pytest Doc example: https://docs.pytest.org/en/latest/example/nonpython.html\n" |
| 716 |
"example pull request on a plugin: https://github.com/asmeurer/pytest-flakes/pull/40/", |
| 717 |
PytestWarning, |
| 718 |
) |
| 719 |
|
| 720 |
@abc.abstractmethod |
| 721 |
def runtest(self) -> None: |
| 722 |
"""Run the test case for this item. |
| 723 |
|
| 724 |
Must be implemented by subclasses. |
| 725 |
|
| 726 |
.. seealso:: :ref:`non-python tests` |
| 727 |
""" |
| 728 |
raise NotImplementedError("runtest must be implemented by Item subclass") |
| 729 |
|
| 730 |
def add_report_section(self, when: str, key: str, content: str) -> None: |
| 731 |
"""Add a new report section, similar to what's done internally to add |
| 732 |
stdout and stderr captured output:: |
| 733 |
|
| 734 |
item.add_report_section("call", "stdout", "report section contents") |
| 735 |
|
| 736 |
:param str when: |
| 737 |
One of the possible capture states, ``"setup"``, ``"call"``, ``"teardown"``. |
| 738 |
:param str key: |
| 739 |
Name of the section, can be customized at will. Pytest uses ``"stdout"`` and |
| 740 |
``"stderr"`` internally. |
| 741 |
:param str content: |
| 742 |
The full contents as a string. |
| 743 |
""" |
| 744 |
if content: |
| 745 |
self._report_sections.append((when, key, content)) |
| 746 |
|
| 747 |
def reportinfo(self) -> Tuple[Union["os.PathLike[str]", str], Optional[int], str]: |
| 748 |
"""Get location information for this item for test reports. |
| 749 |
|
| 750 |
Returns a tuple with three elements: |
| 751 |
|
| 752 |
- The path of the test (default ``self.path``) |
| 753 |
- The 0-based line number of the test (default ``None``) |
| 754 |
- A name of the test to be shown (default ``""``) |
| 755 |
|
| 756 |
.. seealso:: :ref:`non-python tests` |
| 757 |
""" |
| 758 |
return self.path, None, "" |
| 759 |
|
| 760 |
@cached_property |
| 761 |
def location(self) -> Tuple[str, Optional[int], str]: |
| 762 |
""" |
| 763 |
Returns a tuple of ``(relfspath, lineno, testname)`` for this item |
| 764 |
where ``relfspath`` is file path relative to ``config.rootpath`` |
| 765 |
and lineno is a 0-based line number. |
| 766 |
""" |
| 767 |
location = self.reportinfo() |
| 768 |
path = absolutepath(location[0]) |
| 769 |
relfspath = self.session._node_location_to_relpath(path) |
| 770 |
assert type(location[2]) is str |
| 771 |
return (relfspath, location[1], location[2]) |