nodes.py 26 KB

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