Debian Codegraph @

src/_pytest/nodes.py

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