Debian Codegraph @

src/_pytest/main.py

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