main.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  1. """Core implementation of the testing process: init, session, runtest loop."""
  2. from __future__ import annotations
  3. import argparse
  4. from collections.abc import Callable
  5. from collections.abc import Iterable
  6. from collections.abc import Iterator
  7. from collections.abc import Sequence
  8. from collections.abc import Set as AbstractSet
  9. import dataclasses
  10. import fnmatch
  11. import functools
  12. import importlib
  13. import importlib.util
  14. import os
  15. from pathlib import Path
  16. import sys
  17. from typing import final
  18. from typing import Literal
  19. from typing import overload
  20. from typing import TYPE_CHECKING
  21. import warnings
  22. import pluggy
  23. from _pytest import nodes
  24. import _pytest._code
  25. from _pytest.config import Config
  26. from _pytest.config import directory_arg
  27. from _pytest.config import ExitCode
  28. from _pytest.config import hookimpl
  29. from _pytest.config import PytestPluginManager
  30. from _pytest.config import UsageError
  31. from _pytest.config.argparsing import Parser
  32. from _pytest.config.compat import PathAwareHookProxy
  33. from _pytest.outcomes import exit
  34. from _pytest.pathlib import absolutepath
  35. from _pytest.pathlib import bestrelpath
  36. from _pytest.pathlib import fnmatch_ex
  37. from _pytest.pathlib import safe_exists
  38. from _pytest.pathlib import scandir
  39. from _pytest.reports import CollectReport
  40. from _pytest.reports import TestReport
  41. from _pytest.runner import collect_one_node
  42. from _pytest.runner import SetupState
  43. from _pytest.warning_types import PytestWarning
  44. if TYPE_CHECKING:
  45. from typing_extensions import Self
  46. from _pytest.fixtures import FixtureManager
  47. def pytest_addoption(parser: Parser) -> None:
  48. group = parser.getgroup("general", "Running and selection options")
  49. group._addoption( # private to use reserved lower-case short option
  50. "-x",
  51. "--exitfirst",
  52. action="store_const",
  53. dest="maxfail",
  54. const=1,
  55. help="Exit instantly on first error or failed test",
  56. )
  57. group.addoption(
  58. "--maxfail",
  59. metavar="num",
  60. action="store",
  61. type=int,
  62. dest="maxfail",
  63. default=0,
  64. help="Exit after first num failures or errors",
  65. )
  66. group.addoption(
  67. "--strict-config",
  68. action="store_true",
  69. help="Any warnings encountered while parsing the `pytest` section of the "
  70. "configuration file raise errors",
  71. )
  72. group.addoption(
  73. "--strict-markers",
  74. action="store_true",
  75. help="Markers not registered in the `markers` section of the configuration "
  76. "file raise errors",
  77. )
  78. group.addoption(
  79. "--strict",
  80. action="store_true",
  81. help="(Deprecated) alias to --strict-markers",
  82. )
  83. group = parser.getgroup("pytest-warnings")
  84. group.addoption(
  85. "-W",
  86. "--pythonwarnings",
  87. action="append",
  88. help="Set which warnings to report, see -W option of Python itself",
  89. )
  90. parser.addini(
  91. "filterwarnings",
  92. type="linelist",
  93. help="Each line specifies a pattern for "
  94. "warnings.filterwarnings. "
  95. "Processed after -W/--pythonwarnings.",
  96. )
  97. group = parser.getgroup("collect", "collection")
  98. group.addoption(
  99. "--collectonly",
  100. "--collect-only",
  101. "--co",
  102. action="store_true",
  103. help="Only collect tests, don't execute them",
  104. )
  105. group.addoption(
  106. "--pyargs",
  107. action="store_true",
  108. help="Try to interpret all arguments as Python packages",
  109. )
  110. group.addoption(
  111. "--ignore",
  112. action="append",
  113. metavar="path",
  114. help="Ignore path during collection (multi-allowed)",
  115. )
  116. group.addoption(
  117. "--ignore-glob",
  118. action="append",
  119. metavar="path",
  120. help="Ignore path pattern during collection (multi-allowed)",
  121. )
  122. group.addoption(
  123. "--deselect",
  124. action="append",
  125. metavar="nodeid_prefix",
  126. help="Deselect item (via node id prefix) during collection (multi-allowed)",
  127. )
  128. group.addoption(
  129. "--confcutdir",
  130. dest="confcutdir",
  131. default=None,
  132. metavar="dir",
  133. type=functools.partial(directory_arg, optname="--confcutdir"),
  134. help="Only load conftest.py's relative to specified dir",
  135. )
  136. group.addoption(
  137. "--noconftest",
  138. action="store_true",
  139. dest="noconftest",
  140. default=False,
  141. help="Don't load any conftest.py files",
  142. )
  143. group.addoption(
  144. "--keepduplicates",
  145. "--keep-duplicates",
  146. action="store_true",
  147. dest="keepduplicates",
  148. default=False,
  149. help="Keep duplicate tests",
  150. )
  151. group.addoption(
  152. "--collect-in-virtualenv",
  153. action="store_true",
  154. dest="collect_in_virtualenv",
  155. default=False,
  156. help="Don't ignore tests in a local virtualenv directory",
  157. )
  158. group.addoption(
  159. "--continue-on-collection-errors",
  160. action="store_true",
  161. default=False,
  162. dest="continue_on_collection_errors",
  163. help="Force test execution even if collection errors occur",
  164. )
  165. group.addoption(
  166. "--import-mode",
  167. default="prepend",
  168. choices=["prepend", "append", "importlib"],
  169. dest="importmode",
  170. help="Prepend/append to sys.path when importing test modules and conftest "
  171. "files. Default: prepend.",
  172. )
  173. parser.addini(
  174. "norecursedirs",
  175. "Directory patterns to avoid for recursion",
  176. type="args",
  177. default=[
  178. "*.egg",
  179. ".*",
  180. "_darcs",
  181. "build",
  182. "CVS",
  183. "dist",
  184. "node_modules",
  185. "venv",
  186. "{arch}",
  187. ],
  188. )
  189. parser.addini(
  190. "testpaths",
  191. "Directories to search for tests when no files or directories are given on the "
  192. "command line",
  193. type="args",
  194. default=[],
  195. )
  196. parser.addini(
  197. "collect_imported_tests",
  198. "Whether to collect tests in imported modules outside `testpaths`",
  199. type="bool",
  200. default=True,
  201. )
  202. parser.addini(
  203. "consider_namespace_packages",
  204. type="bool",
  205. default=False,
  206. help="Consider namespace packages when resolving module names during import",
  207. )
  208. group = parser.getgroup("debugconfig", "test session debugging and configuration")
  209. group._addoption( # private to use reserved lower-case short option
  210. "-c",
  211. "--config-file",
  212. metavar="FILE",
  213. type=str,
  214. dest="inifilename",
  215. help="Load configuration from `FILE` instead of trying to locate one of the "
  216. "implicit configuration files.",
  217. )
  218. group.addoption(
  219. "--rootdir",
  220. action="store",
  221. dest="rootdir",
  222. help="Define root directory for tests. Can be relative path: 'root_dir', './root_dir', "
  223. "'root_dir/another_dir/'; absolute path: '/home/user/root_dir'; path with variables: "
  224. "'$HOME/root_dir'.",
  225. )
  226. group.addoption(
  227. "--basetemp",
  228. dest="basetemp",
  229. default=None,
  230. type=validate_basetemp,
  231. metavar="dir",
  232. help=(
  233. "Base temporary directory for this test run. "
  234. "(Warning: this directory is removed if it exists.)"
  235. ),
  236. )
  237. def validate_basetemp(path: str) -> str:
  238. # GH 7119
  239. msg = "basetemp must not be empty, the current working directory or any parent directory of it"
  240. # empty path
  241. if not path:
  242. raise argparse.ArgumentTypeError(msg)
  243. def is_ancestor(base: Path, query: Path) -> bool:
  244. """Return whether query is an ancestor of base."""
  245. if base == query:
  246. return True
  247. return query in base.parents
  248. # check if path is an ancestor of cwd
  249. if is_ancestor(Path.cwd(), Path(path).absolute()):
  250. raise argparse.ArgumentTypeError(msg)
  251. # check symlinks for ancestors
  252. if is_ancestor(Path.cwd().resolve(), Path(path).resolve()):
  253. raise argparse.ArgumentTypeError(msg)
  254. return path
  255. def wrap_session(
  256. config: Config, doit: Callable[[Config, Session], int | ExitCode | None]
  257. ) -> int | ExitCode:
  258. """Skeleton command line program."""
  259. session = Session.from_config(config)
  260. session.exitstatus = ExitCode.OK
  261. initstate = 0
  262. try:
  263. try:
  264. config._do_configure()
  265. initstate = 1
  266. config.hook.pytest_sessionstart(session=session)
  267. initstate = 2
  268. session.exitstatus = doit(config, session) or 0
  269. except UsageError:
  270. session.exitstatus = ExitCode.USAGE_ERROR
  271. raise
  272. except Failed:
  273. session.exitstatus = ExitCode.TESTS_FAILED
  274. except (KeyboardInterrupt, exit.Exception):
  275. excinfo = _pytest._code.ExceptionInfo.from_current()
  276. exitstatus: int | ExitCode = ExitCode.INTERRUPTED
  277. if isinstance(excinfo.value, exit.Exception):
  278. if excinfo.value.returncode is not None:
  279. exitstatus = excinfo.value.returncode
  280. if initstate < 2:
  281. sys.stderr.write(f"{excinfo.typename}: {excinfo.value.msg}\n")
  282. config.hook.pytest_keyboard_interrupt(excinfo=excinfo)
  283. session.exitstatus = exitstatus
  284. except BaseException:
  285. session.exitstatus = ExitCode.INTERNAL_ERROR
  286. excinfo = _pytest._code.ExceptionInfo.from_current()
  287. try:
  288. config.notify_exception(excinfo, config.option)
  289. except exit.Exception as exc:
  290. if exc.returncode is not None:
  291. session.exitstatus = exc.returncode
  292. sys.stderr.write(f"{type(exc).__name__}: {exc}\n")
  293. else:
  294. if isinstance(excinfo.value, SystemExit):
  295. sys.stderr.write("mainloop: caught unexpected SystemExit!\n")
  296. finally:
  297. # Explicitly break reference cycle.
  298. excinfo = None # type: ignore
  299. os.chdir(session.startpath)
  300. if initstate >= 2:
  301. try:
  302. config.hook.pytest_sessionfinish(
  303. session=session, exitstatus=session.exitstatus
  304. )
  305. except exit.Exception as exc:
  306. if exc.returncode is not None:
  307. session.exitstatus = exc.returncode
  308. sys.stderr.write(f"{type(exc).__name__}: {exc}\n")
  309. config._ensure_unconfigure()
  310. return session.exitstatus
  311. def pytest_cmdline_main(config: Config) -> int | ExitCode:
  312. return wrap_session(config, _main)
  313. def _main(config: Config, session: Session) -> int | ExitCode | None:
  314. """Default command line protocol for initialization, session,
  315. running tests and reporting."""
  316. config.hook.pytest_collection(session=session)
  317. config.hook.pytest_runtestloop(session=session)
  318. if session.testsfailed:
  319. return ExitCode.TESTS_FAILED
  320. elif session.testscollected == 0:
  321. return ExitCode.NO_TESTS_COLLECTED
  322. return None
  323. def pytest_collection(session: Session) -> None:
  324. session.perform_collect()
  325. def pytest_runtestloop(session: Session) -> bool:
  326. if session.testsfailed and not session.config.option.continue_on_collection_errors:
  327. raise session.Interrupted(
  328. f"{session.testsfailed} error{'s' if session.testsfailed != 1 else ''} during collection"
  329. )
  330. if session.config.option.collectonly:
  331. return True
  332. for i, item in enumerate(session.items):
  333. nextitem = session.items[i + 1] if i + 1 < len(session.items) else None
  334. item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
  335. if session.shouldfail:
  336. raise session.Failed(session.shouldfail)
  337. if session.shouldstop:
  338. raise session.Interrupted(session.shouldstop)
  339. return True
  340. def _in_venv(path: Path) -> bool:
  341. """Attempt to detect if ``path`` is the root of a Virtual Environment by
  342. checking for the existence of the pyvenv.cfg file.
  343. [https://peps.python.org/pep-0405/]
  344. For regression protection we also check for conda environments that do not include pyenv.cfg yet --
  345. https://github.com/conda/conda/issues/13337 is the conda issue tracking adding pyenv.cfg.
  346. Checking for the `conda-meta/history` file per https://github.com/pytest-dev/pytest/issues/12652#issuecomment-2246336902.
  347. """
  348. try:
  349. return (
  350. path.joinpath("pyvenv.cfg").is_file()
  351. or path.joinpath("conda-meta", "history").is_file()
  352. )
  353. except OSError:
  354. return False
  355. def pytest_ignore_collect(collection_path: Path, config: Config) -> bool | None:
  356. if collection_path.name == "__pycache__":
  357. return True
  358. ignore_paths = config._getconftest_pathlist(
  359. "collect_ignore", path=collection_path.parent
  360. )
  361. ignore_paths = ignore_paths or []
  362. excludeopt = config.getoption("ignore")
  363. if excludeopt:
  364. ignore_paths.extend(absolutepath(x) for x in excludeopt)
  365. if collection_path in ignore_paths:
  366. return True
  367. ignore_globs = config._getconftest_pathlist(
  368. "collect_ignore_glob", path=collection_path.parent
  369. )
  370. ignore_globs = ignore_globs or []
  371. excludeglobopt = config.getoption("ignore_glob")
  372. if excludeglobopt:
  373. ignore_globs.extend(absolutepath(x) for x in excludeglobopt)
  374. if any(fnmatch.fnmatch(str(collection_path), str(glob)) for glob in ignore_globs):
  375. return True
  376. allow_in_venv = config.getoption("collect_in_virtualenv")
  377. if not allow_in_venv and _in_venv(collection_path):
  378. return True
  379. if collection_path.is_dir():
  380. norecursepatterns = config.getini("norecursedirs")
  381. if any(fnmatch_ex(pat, collection_path) for pat in norecursepatterns):
  382. return True
  383. return None
  384. def pytest_collect_directory(
  385. path: Path, parent: nodes.Collector
  386. ) -> nodes.Collector | None:
  387. return Dir.from_parent(parent, path=path)
  388. def pytest_collection_modifyitems(items: list[nodes.Item], config: Config) -> None:
  389. deselect_prefixes = tuple(config.getoption("deselect") or [])
  390. if not deselect_prefixes:
  391. return
  392. remaining = []
  393. deselected = []
  394. for colitem in items:
  395. if colitem.nodeid.startswith(deselect_prefixes):
  396. deselected.append(colitem)
  397. else:
  398. remaining.append(colitem)
  399. if deselected:
  400. config.hook.pytest_deselected(items=deselected)
  401. items[:] = remaining
  402. class FSHookProxy:
  403. def __init__(
  404. self,
  405. pm: PytestPluginManager,
  406. remove_mods: AbstractSet[object],
  407. ) -> None:
  408. self.pm = pm
  409. self.remove_mods = remove_mods
  410. def __getattr__(self, name: str) -> pluggy.HookCaller:
  411. x = self.pm.subset_hook_caller(name, remove_plugins=self.remove_mods)
  412. self.__dict__[name] = x
  413. return x
  414. class Interrupted(KeyboardInterrupt):
  415. """Signals that the test run was interrupted."""
  416. __module__ = "builtins" # For py3.
  417. class Failed(Exception):
  418. """Signals a stop as failed test run."""
  419. @dataclasses.dataclass
  420. class _bestrelpath_cache(dict[Path, str]):
  421. __slots__ = ("path",)
  422. path: Path
  423. def __missing__(self, path: Path) -> str:
  424. r = bestrelpath(self.path, path)
  425. self[path] = r
  426. return r
  427. @final
  428. class Dir(nodes.Directory):
  429. """Collector of files in a file system directory.
  430. .. versionadded:: 8.0
  431. .. note::
  432. Python directories with an `__init__.py` file are instead collected by
  433. :class:`~pytest.Package` by default. Both are :class:`~pytest.Directory`
  434. collectors.
  435. """
  436. @classmethod
  437. def from_parent( # type: ignore[override]
  438. cls,
  439. parent: nodes.Collector,
  440. *,
  441. path: Path,
  442. ) -> Self:
  443. """The public constructor.
  444. :param parent: The parent collector of this Dir.
  445. :param path: The directory's path.
  446. :type path: pathlib.Path
  447. """
  448. return super().from_parent(parent=parent, path=path)
  449. def collect(self) -> Iterable[nodes.Item | nodes.Collector]:
  450. config = self.config
  451. col: nodes.Collector | None
  452. cols: Sequence[nodes.Collector]
  453. ihook = self.ihook
  454. for direntry in scandir(self.path):
  455. if direntry.is_dir():
  456. path = Path(direntry.path)
  457. if not self.session.isinitpath(path, with_parents=True):
  458. if ihook.pytest_ignore_collect(collection_path=path, config=config):
  459. continue
  460. col = ihook.pytest_collect_directory(path=path, parent=self)
  461. if col is not None:
  462. yield col
  463. elif direntry.is_file():
  464. path = Path(direntry.path)
  465. if not self.session.isinitpath(path):
  466. if ihook.pytest_ignore_collect(collection_path=path, config=config):
  467. continue
  468. cols = ihook.pytest_collect_file(file_path=path, parent=self)
  469. yield from cols
  470. @final
  471. class Session(nodes.Collector):
  472. """The root of the collection tree.
  473. ``Session`` collects the initial paths given as arguments to pytest.
  474. """
  475. Interrupted = Interrupted
  476. Failed = Failed
  477. # Set on the session by runner.pytest_sessionstart.
  478. _setupstate: SetupState
  479. # Set on the session by fixtures.pytest_sessionstart.
  480. _fixturemanager: FixtureManager
  481. exitstatus: int | ExitCode
  482. def __init__(self, config: Config) -> None:
  483. super().__init__(
  484. name="",
  485. path=config.rootpath,
  486. fspath=None,
  487. parent=None,
  488. config=config,
  489. session=self,
  490. nodeid="",
  491. )
  492. self.testsfailed = 0
  493. self.testscollected = 0
  494. self._shouldstop: bool | str = False
  495. self._shouldfail: bool | str = False
  496. self.trace = config.trace.root.get("collection")
  497. self._initialpaths: frozenset[Path] = frozenset()
  498. self._initialpaths_with_parents: frozenset[Path] = frozenset()
  499. self._notfound: list[tuple[str, Sequence[nodes.Collector]]] = []
  500. self._initial_parts: list[CollectionArgument] = []
  501. self._collection_cache: dict[nodes.Collector, CollectReport] = {}
  502. self.items: list[nodes.Item] = []
  503. self._bestrelpathcache: dict[Path, str] = _bestrelpath_cache(config.rootpath)
  504. self.config.pluginmanager.register(self, name="session")
  505. @classmethod
  506. def from_config(cls, config: Config) -> Session:
  507. session: Session = cls._create(config=config)
  508. return session
  509. def __repr__(self) -> str:
  510. return (
  511. f"<{self.__class__.__name__} {self.name} "
  512. f"exitstatus=%r "
  513. f"testsfailed={self.testsfailed} "
  514. f"testscollected={self.testscollected}>"
  515. ) % getattr(self, "exitstatus", "<UNSET>")
  516. @property
  517. def shouldstop(self) -> bool | str:
  518. return self._shouldstop
  519. @shouldstop.setter
  520. def shouldstop(self, value: bool | str) -> None:
  521. # The runner checks shouldfail and assumes that if it is set we are
  522. # definitely stopping, so prevent unsetting it.
  523. if value is False and self._shouldstop:
  524. warnings.warn(
  525. PytestWarning(
  526. "session.shouldstop cannot be unset after it has been set; ignoring."
  527. ),
  528. stacklevel=2,
  529. )
  530. return
  531. self._shouldstop = value
  532. @property
  533. def shouldfail(self) -> bool | str:
  534. return self._shouldfail
  535. @shouldfail.setter
  536. def shouldfail(self, value: bool | str) -> None:
  537. # The runner checks shouldfail and assumes that if it is set we are
  538. # definitely stopping, so prevent unsetting it.
  539. if value is False and self._shouldfail:
  540. warnings.warn(
  541. PytestWarning(
  542. "session.shouldfail cannot be unset after it has been set; ignoring."
  543. ),
  544. stacklevel=2,
  545. )
  546. return
  547. self._shouldfail = value
  548. @property
  549. def startpath(self) -> Path:
  550. """The path from which pytest was invoked.
  551. .. versionadded:: 7.0.0
  552. """
  553. return self.config.invocation_params.dir
  554. def _node_location_to_relpath(self, node_path: Path) -> str:
  555. # bestrelpath is a quite slow function.
  556. return self._bestrelpathcache[node_path]
  557. @hookimpl(tryfirst=True)
  558. def pytest_collectstart(self) -> None:
  559. if self.shouldfail:
  560. raise self.Failed(self.shouldfail)
  561. if self.shouldstop:
  562. raise self.Interrupted(self.shouldstop)
  563. @hookimpl(tryfirst=True)
  564. def pytest_runtest_logreport(self, report: TestReport | CollectReport) -> None:
  565. if report.failed and not hasattr(report, "wasxfail"):
  566. self.testsfailed += 1
  567. maxfail = self.config.getvalue("maxfail")
  568. if maxfail and self.testsfailed >= maxfail:
  569. self.shouldfail = f"stopping after {self.testsfailed} failures"
  570. pytest_collectreport = pytest_runtest_logreport
  571. def isinitpath(
  572. self,
  573. path: str | os.PathLike[str],
  574. *,
  575. with_parents: bool = False,
  576. ) -> bool:
  577. """Is path an initial path?
  578. An initial path is a path explicitly given to pytest on the command
  579. line.
  580. :param with_parents:
  581. If set, also return True if the path is a parent of an initial path.
  582. .. versionchanged:: 8.0
  583. Added the ``with_parents`` parameter.
  584. """
  585. # Optimization: Path(Path(...)) is much slower than isinstance.
  586. path_ = path if isinstance(path, Path) else Path(path)
  587. if with_parents:
  588. return path_ in self._initialpaths_with_parents
  589. else:
  590. return path_ in self._initialpaths
  591. def gethookproxy(self, fspath: os.PathLike[str]) -> pluggy.HookRelay:
  592. # Optimization: Path(Path(...)) is much slower than isinstance.
  593. path = fspath if isinstance(fspath, Path) else Path(fspath)
  594. pm = self.config.pluginmanager
  595. # Check if we have the common case of running
  596. # hooks with all conftest.py files.
  597. my_conftestmodules = pm._getconftestmodules(path)
  598. remove_mods = pm._conftest_plugins.difference(my_conftestmodules)
  599. proxy: pluggy.HookRelay
  600. if remove_mods:
  601. # One or more conftests are not in use at this path.
  602. proxy = PathAwareHookProxy(FSHookProxy(pm, remove_mods)) # type: ignore[arg-type,assignment]
  603. else:
  604. # All plugins are active for this fspath.
  605. proxy = self.config.hook
  606. return proxy
  607. def _collect_path(
  608. self,
  609. path: Path,
  610. path_cache: dict[Path, Sequence[nodes.Collector]],
  611. ) -> Sequence[nodes.Collector]:
  612. """Create a Collector for the given path.
  613. `path_cache` makes it so the same Collectors are returned for the same
  614. path.
  615. """
  616. if path in path_cache:
  617. return path_cache[path]
  618. if path.is_dir():
  619. ihook = self.gethookproxy(path.parent)
  620. col: nodes.Collector | None = ihook.pytest_collect_directory(
  621. path=path, parent=self
  622. )
  623. cols: Sequence[nodes.Collector] = (col,) if col is not None else ()
  624. elif path.is_file():
  625. ihook = self.gethookproxy(path)
  626. cols = ihook.pytest_collect_file(file_path=path, parent=self)
  627. else:
  628. # Broken symlink or invalid/missing file.
  629. cols = ()
  630. path_cache[path] = cols
  631. return cols
  632. @overload
  633. def perform_collect(
  634. self, args: Sequence[str] | None = ..., genitems: Literal[True] = ...
  635. ) -> Sequence[nodes.Item]: ...
  636. @overload
  637. def perform_collect(
  638. self, args: Sequence[str] | None = ..., genitems: bool = ...
  639. ) -> Sequence[nodes.Item | nodes.Collector]: ...
  640. def perform_collect(
  641. self, args: Sequence[str] | None = None, genitems: bool = True
  642. ) -> Sequence[nodes.Item | nodes.Collector]:
  643. """Perform the collection phase for this session.
  644. This is called by the default :hook:`pytest_collection` hook
  645. implementation; see the documentation of this hook for more details.
  646. For testing purposes, it may also be called directly on a fresh
  647. ``Session``.
  648. This function normally recursively expands any collectors collected
  649. from the session to their items, and only items are returned. For
  650. testing purposes, this may be suppressed by passing ``genitems=False``,
  651. in which case the return value contains these collectors unexpanded,
  652. and ``session.items`` is empty.
  653. """
  654. if args is None:
  655. args = self.config.args
  656. self.trace("perform_collect", self, args)
  657. self.trace.root.indent += 1
  658. hook = self.config.hook
  659. self._notfound = []
  660. self._initial_parts = []
  661. self._collection_cache = {}
  662. self.items = []
  663. items: Sequence[nodes.Item | nodes.Collector] = self.items
  664. try:
  665. initialpaths: list[Path] = []
  666. initialpaths_with_parents: list[Path] = []
  667. for arg in args:
  668. collection_argument = resolve_collection_argument(
  669. self.config.invocation_params.dir,
  670. arg,
  671. as_pypath=self.config.option.pyargs,
  672. )
  673. self._initial_parts.append(collection_argument)
  674. initialpaths.append(collection_argument.path)
  675. initialpaths_with_parents.append(collection_argument.path)
  676. initialpaths_with_parents.extend(collection_argument.path.parents)
  677. self._initialpaths = frozenset(initialpaths)
  678. self._initialpaths_with_parents = frozenset(initialpaths_with_parents)
  679. rep = collect_one_node(self)
  680. self.ihook.pytest_collectreport(report=rep)
  681. self.trace.root.indent -= 1
  682. if self._notfound:
  683. errors = []
  684. for arg, collectors in self._notfound:
  685. if collectors:
  686. errors.append(
  687. f"not found: {arg}\n(no match in any of {collectors!r})"
  688. )
  689. else:
  690. errors.append(f"found no collectors for {arg}")
  691. raise UsageError(*errors)
  692. if not genitems:
  693. items = rep.result
  694. else:
  695. if rep.passed:
  696. for node in rep.result:
  697. self.items.extend(self.genitems(node))
  698. self.config.pluginmanager.check_pending()
  699. hook.pytest_collection_modifyitems(
  700. session=self, config=self.config, items=items
  701. )
  702. finally:
  703. self._notfound = []
  704. self._initial_parts = []
  705. self._collection_cache = {}
  706. hook.pytest_collection_finish(session=self)
  707. if genitems:
  708. self.testscollected = len(items)
  709. return items
  710. def _collect_one_node(
  711. self,
  712. node: nodes.Collector,
  713. handle_dupes: bool = True,
  714. ) -> tuple[CollectReport, bool]:
  715. if node in self._collection_cache and handle_dupes:
  716. rep = self._collection_cache[node]
  717. return rep, True
  718. else:
  719. rep = collect_one_node(node)
  720. self._collection_cache[node] = rep
  721. return rep, False
  722. def collect(self) -> Iterator[nodes.Item | nodes.Collector]:
  723. # This is a cache for the root directories of the initial paths.
  724. # We can't use collection_cache for Session because of its special
  725. # role as the bootstrapping collector.
  726. path_cache: dict[Path, Sequence[nodes.Collector]] = {}
  727. pm = self.config.pluginmanager
  728. for collection_argument in self._initial_parts:
  729. self.trace("processing argument", collection_argument)
  730. self.trace.root.indent += 1
  731. argpath = collection_argument.path
  732. names = collection_argument.parts
  733. module_name = collection_argument.module_name
  734. # resolve_collection_argument() ensures this.
  735. if argpath.is_dir():
  736. assert not names, f"invalid arg {(argpath, names)!r}"
  737. paths = [argpath]
  738. # Add relevant parents of the path, from the root, e.g.
  739. # /a/b/c.py -> [/, /a, /a/b, /a/b/c.py]
  740. if module_name is None:
  741. # Paths outside of the confcutdir should not be considered.
  742. for path in argpath.parents:
  743. if not pm._is_in_confcutdir(path):
  744. break
  745. paths.insert(0, path)
  746. else:
  747. # For --pyargs arguments, only consider paths matching the module
  748. # name. Paths beyond the package hierarchy are not included.
  749. module_name_parts = module_name.split(".")
  750. for i, path in enumerate(argpath.parents, 2):
  751. if i > len(module_name_parts) or path.stem != module_name_parts[-i]:
  752. break
  753. paths.insert(0, path)
  754. # Start going over the parts from the root, collecting each level
  755. # and discarding all nodes which don't match the level's part.
  756. any_matched_in_initial_part = False
  757. notfound_collectors = []
  758. work: list[tuple[nodes.Collector | nodes.Item, list[Path | str]]] = [
  759. (self, [*paths, *names])
  760. ]
  761. while work:
  762. matchnode, matchparts = work.pop()
  763. # Pop'd all of the parts, this is a match.
  764. if not matchparts:
  765. yield matchnode
  766. any_matched_in_initial_part = True
  767. continue
  768. # Should have been matched by now, discard.
  769. if not isinstance(matchnode, nodes.Collector):
  770. continue
  771. # Collect this level of matching.
  772. # Collecting Session (self) is done directly to avoid endless
  773. # recursion to this function.
  774. subnodes: Sequence[nodes.Collector | nodes.Item]
  775. if isinstance(matchnode, Session):
  776. assert isinstance(matchparts[0], Path)
  777. subnodes = matchnode._collect_path(matchparts[0], path_cache)
  778. else:
  779. # For backward compat, files given directly multiple
  780. # times on the command line should not be deduplicated.
  781. handle_dupes = not (
  782. len(matchparts) == 1
  783. and isinstance(matchparts[0], Path)
  784. and matchparts[0].is_file()
  785. )
  786. rep, duplicate = self._collect_one_node(matchnode, handle_dupes)
  787. if not duplicate and not rep.passed:
  788. # Report collection failures here to avoid failing to
  789. # run some test specified in the command line because
  790. # the module could not be imported (#134).
  791. matchnode.ihook.pytest_collectreport(report=rep)
  792. if not rep.passed:
  793. continue
  794. subnodes = rep.result
  795. # Prune this level.
  796. any_matched_in_collector = False
  797. for node in reversed(subnodes):
  798. # Path part e.g. `/a/b/` in `/a/b/test_file.py::TestIt::test_it`.
  799. if isinstance(matchparts[0], Path):
  800. is_match = node.path == matchparts[0]
  801. if sys.platform == "win32" and not is_match:
  802. # In case the file paths do not match, fallback to samefile() to
  803. # account for short-paths on Windows (#11895).
  804. same_file = os.path.samefile(node.path, matchparts[0])
  805. # We don't want to match links to the current node,
  806. # otherwise we would match the same file more than once (#12039).
  807. is_match = same_file and (
  808. os.path.islink(node.path)
  809. == os.path.islink(matchparts[0])
  810. )
  811. # Name part e.g. `TestIt` in `/a/b/test_file.py::TestIt::test_it`.
  812. else:
  813. # TODO: Remove parametrized workaround once collection structure contains
  814. # parametrization.
  815. is_match = (
  816. node.name == matchparts[0]
  817. or node.name.split("[")[0] == matchparts[0]
  818. )
  819. if is_match:
  820. work.append((node, matchparts[1:]))
  821. any_matched_in_collector = True
  822. if not any_matched_in_collector:
  823. notfound_collectors.append(matchnode)
  824. if not any_matched_in_initial_part:
  825. report_arg = "::".join((str(argpath), *names))
  826. self._notfound.append((report_arg, notfound_collectors))
  827. self.trace.root.indent -= 1
  828. def genitems(self, node: nodes.Item | nodes.Collector) -> Iterator[nodes.Item]:
  829. self.trace("genitems", node)
  830. if isinstance(node, nodes.Item):
  831. node.ihook.pytest_itemcollected(item=node)
  832. yield node
  833. else:
  834. assert isinstance(node, nodes.Collector)
  835. keepduplicates = self.config.getoption("keepduplicates")
  836. # For backward compat, dedup only applies to files.
  837. handle_dupes = not (keepduplicates and isinstance(node, nodes.File))
  838. rep, duplicate = self._collect_one_node(node, handle_dupes)
  839. if duplicate and not keepduplicates:
  840. return
  841. if rep.passed:
  842. for subnode in rep.result:
  843. yield from self.genitems(subnode)
  844. if not duplicate:
  845. node.ihook.pytest_collectreport(report=rep)
  846. def search_pypath(module_name: str) -> str | None:
  847. """Search sys.path for the given a dotted module name, and return its file
  848. system path if found."""
  849. try:
  850. spec = importlib.util.find_spec(module_name)
  851. # AttributeError: looks like package module, but actually filename
  852. # ImportError: module does not exist
  853. # ValueError: not a module name
  854. except (AttributeError, ImportError, ValueError):
  855. return None
  856. if spec is None or spec.origin is None or spec.origin == "namespace":
  857. return None
  858. elif spec.submodule_search_locations:
  859. return os.path.dirname(spec.origin)
  860. else:
  861. return spec.origin
  862. @dataclasses.dataclass(frozen=True)
  863. class CollectionArgument:
  864. """A resolved collection argument."""
  865. path: Path
  866. parts: Sequence[str]
  867. module_name: str | None
  868. def resolve_collection_argument(
  869. invocation_path: Path, arg: str, *, as_pypath: bool = False
  870. ) -> CollectionArgument:
  871. """Parse path arguments optionally containing selection parts and return (fspath, names).
  872. Command-line arguments can point to files and/or directories, and optionally contain
  873. parts for specific tests selection, for example:
  874. "pkg/tests/test_foo.py::TestClass::test_foo"
  875. This function ensures the path exists, and returns a resolved `CollectionArgument`:
  876. CollectionArgument(
  877. path=Path("/full/path/to/pkg/tests/test_foo.py"),
  878. parts=["TestClass", "test_foo"],
  879. module_name=None,
  880. )
  881. When as_pypath is True, expects that the command-line argument actually contains
  882. module paths instead of file-system paths:
  883. "pkg.tests.test_foo::TestClass::test_foo"
  884. In which case we search sys.path for a matching module, and then return the *path* to the
  885. found module, which may look like this:
  886. CollectionArgument(
  887. path=Path("/home/u/myvenv/lib/site-packages/pkg/tests/test_foo.py"),
  888. parts=["TestClass", "test_foo"],
  889. module_name="pkg.tests.test_foo",
  890. )
  891. If the path doesn't exist, raise UsageError.
  892. If the path is a directory and selection parts are present, raise UsageError.
  893. """
  894. base, squacket, rest = str(arg).partition("[")
  895. strpath, *parts = base.split("::")
  896. if parts:
  897. parts[-1] = f"{parts[-1]}{squacket}{rest}"
  898. module_name = None
  899. if as_pypath:
  900. pyarg_strpath = search_pypath(strpath)
  901. if pyarg_strpath is not None:
  902. module_name = strpath
  903. strpath = pyarg_strpath
  904. fspath = invocation_path / strpath
  905. fspath = absolutepath(fspath)
  906. if not safe_exists(fspath):
  907. msg = (
  908. "module or package not found: {arg} (missing __init__.py?)"
  909. if as_pypath
  910. else "file or directory not found: {arg}"
  911. )
  912. raise UsageError(msg.format(arg=arg))
  913. if parts and fspath.is_dir():
  914. msg = (
  915. "package argument cannot contain :: selection parts: {arg}"
  916. if as_pypath
  917. else "directory argument cannot contain :: selection parts: {arg}"
  918. )
  919. raise UsageError(msg.format(arg=arg))
  920. return CollectionArgument(
  921. path=fspath,
  922. parts=parts,
  923. module_name=module_name,
  924. )