nodes.py 25 KB

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