Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/main.py

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