main.py 41 KB

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