Debian Codegraph @

src/_pytest/config/__init__.py

raw
1 # mypy: allow-untyped-defs
2 """Command line options, config-file and conftest.py processing."""
3
4 from __future__ import annotations
5
6 import argparse
7 import builtins
8 import collections.abc
9 from collections.abc import Callable
10 from collections.abc import Generator
11 from collections.abc import Iterable
12 from collections.abc import Iterator
13 from collections.abc import Mapping
14 from collections.abc import MutableMapping
15 from collections.abc import Sequence
16 import contextlib
17 import copy
18 import dataclasses
19 import enum
20 from functools import lru_cache
21 import glob
22 import importlib
23 import importlib.metadata
24 import inspect
25 import os
26 import pathlib
27 import re
28 import shlex
29 import sys
30 from textwrap import dedent
31 import types
32 from types import FunctionType
33 from typing import Any
34 from typing import cast
35 from typing import Final
36 from typing import final
37 from typing import IO
38 from typing import TextIO
39 from typing import TYPE_CHECKING
40 import warnings
41
42 from pluggy import HookimplMarker
43 from pluggy import HookimplOpts
44 from pluggy import HookspecMarker
45 from pluggy import HookspecOpts
46 from pluggy import PluginManager
47
48 from .exceptions import PrintHelp as PrintHelp
49 from .exceptions import UsageError as UsageError
50 from .findpaths import ConfigDict
51 from .findpaths import ConfigValue
52 from .findpaths import determine_setup
53 from .findpaths import parse_override_ini
54 from _pytest import __version__
55 import _pytest._code
56 from _pytest._code import ExceptionInfo
57 from _pytest._code import filter_traceback
58 from _pytest._code.code import TracebackStyle
59 from _pytest._io import TerminalWriter
60 from _pytest.compat import assert_never
61 from _pytest.compat import deprecated
62 from _pytest.compat import NOTSET
63 from _pytest.config.argparsing import Argument
64 from _pytest.config.argparsing import FILE_OR_DIR
65 from _pytest.config.argparsing import Parser
66 import _pytest.deprecated
67 import _pytest.hookspec
68 from _pytest.outcomes import fail
69 from _pytest.outcomes import Skipped
70 from _pytest.pathlib import absolutepath
71 from _pytest.pathlib import bestrelpath
72 from _pytest.pathlib import import_path
73 from _pytest.pathlib import ImportMode
74 from _pytest.pathlib import resolve_package_path
75 from _pytest.pathlib import safe_exists
76 from _pytest.stash import Stash
77 from _pytest.warning_types import PytestConfigWarning
78 from _pytest.warning_types import warn_explicit_for
79
80
81 if TYPE_CHECKING:
82 from _pytest.assertion.rewrite import AssertionRewritingHook
83 from _pytest.cacheprovider import Cache
84 from _pytest.terminal import TerminalReporter
85
86 _PluggyPlugin = object
87 """A type to represent plugin objects.
88
89 Plugins can be any namespace, so we can't narrow it down much, but we use an
90 alias to make the intent clear.
91
92 Ideally this type would be provided by pluggy itself.
93 """
94
95
96 hookimpl = HookimplMarker("pytest")
97 hookspec = HookspecMarker("pytest")
98
99
100 @final
101 class ExitCode(enum.IntEnum):
102 """Encodes the valid exit codes by pytest.
103
104 Currently users and plugins may supply other exit codes as well.
105
106 .. versionadded:: 5.0
107 """
108
109 #: Tests passed.
110 OK = 0
111 #: Tests failed.
112 TESTS_FAILED = 1
113 #: pytest was interrupted.
114 INTERRUPTED = 2
115 #: An internal error got in the way.
116 INTERNAL_ERROR = 3
117 #: pytest was misused.
118 USAGE_ERROR = 4
119 #: pytest couldn't find tests.
120 NO_TESTS_COLLECTED = 5
121 #: All tests pass, but maximum number of warnings exceeded.
122 MAX_WARNINGS_ERROR = 6
123
124 __module__ = "pytest"
125
126
127 class ConftestImportFailure(Exception):
128 def __init__(
129 self,
130 path: pathlib.Path,
131 *,
132 cause: Exception,
133 ) -> None:
134 self.path = path
135 self.cause = cause
136
137 def __str__(self) -> str:
138 return f"{type(self.cause).__name__}: {self.cause} (from {self.path})"
139
140
141 def filter_traceback_for_conftest_import_failure(
142 entry: _pytest._code.TracebackEntry,
143 ) -> bool:
144 """Filter tracebacks entries which point to pytest internals or importlib.
145
146 Make a special case for importlib because we use it to import test modules and conftest files
147 in _pytest.pathlib.import_path.
148 """
149 return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep)
150
151
152 def print_conftest_import_error(e: ConftestImportFailure, file: TextIO) -> None:
153 exc_info = ExceptionInfo.from_exception(e.cause)
154 tw = TerminalWriter(file)
155 tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
156 exc_info.traceback = exc_info.traceback.filter(
157 filter_traceback_for_conftest_import_failure
158 )
159 exc_repr = (
160 exc_info.getrepr(style="short", chain=False)
161 if exc_info.traceback
162 else exc_info.exconly()
163 )
164 formatted_tb = str(exc_repr)
165 for line in formatted_tb.splitlines():
166 tw.line(line.rstrip(), red=True)
167
168
169 def print_usage_error(e: UsageError, file: TextIO) -> None:
170 tw = TerminalWriter(file)
171 for msg in e.args:
172 tw.line(f"ERROR: {msg}\n", red=True)
173
174
175 def _get_prog_name(argv: Sequence[str]) -> str:
176 """Determine the CLI program name from the argument vector.
177
178 :param argv: The argument vector (typically ``sys.argv``).
179 :returns: ``"python -m pytest"`` when invoked via ``python -m``,
180 ``"pytest"`` otherwise.
181 """
182 argv0 = argv[0] if argv else ""
183 if os.path.basename(argv0) == "__main__.py":
184 return "python -m pytest"
185 return "pytest"
186
187
188 def main(
189 args: list[str] | os.PathLike[str] | None = None,
190 plugins: Sequence[str | _PluggyPlugin] | None = None,
191 ) -> int | ExitCode:
192 """Perform an in-process test run.
193
194 :param args:
195 List of command line arguments. If `None` or not given, defaults to reading
196 arguments directly from the process command line (:data:`sys.argv`).
197 :param plugins: List of plugin objects to be auto-registered during initialization.
198
199 :returns: An exit code.
200 """
201 return _main(args=args, plugins=plugins, prog="pytest.main()")
202
203
204 def _main(
205 *,
206 args: list[str] | os.PathLike[str] | None = None,
207 plugins: Sequence[str | _PluggyPlugin] | None = None,
208 prog: str,
209 ) -> int | ExitCode:
210 # Handle a single `--version`/`-V` argument early to avoid starting up the entire pytest infrastructure.
211 new_args = sys.argv[1:] if args is None else args
212 if (
213 isinstance(new_args, Sequence)
214 and (new_args.count("--version") + new_args.count("-V")) == 1
215 ):
216 sys.stdout.write(f"pytest {__version__}\n")
217 return ExitCode.OK
218
219 old_pytest_version = os.environ.get("PYTEST_VERSION")
220 try:
221 os.environ["PYTEST_VERSION"] = __version__
222 try:
223 config = _prepareconfig(new_args, plugins, prog=prog)
224 except ConftestImportFailure as e:
225 print_conftest_import_error(e, file=sys.stderr)
226 return ExitCode.USAGE_ERROR
227
228 try:
229 ret: ExitCode | int = config.hook.pytest_cmdline_main(config=config)
230 try:
231 return ExitCode(ret)
232 except ValueError:
233 return ret
234 finally:
235 config._ensure_unconfigure()
236 except UsageError as e:
237 print_usage_error(e, file=sys.stderr)
238 return ExitCode.USAGE_ERROR
239 finally:
240 if old_pytest_version is None:
241 os.environ.pop("PYTEST_VERSION", None)
242 else:
243 os.environ["PYTEST_VERSION"] = old_pytest_version
244
245
246 def _console_main() -> int:
247 """The CLI entry point of pytest (internal).
248
249 This is the real implementation used by entry points and ``__main__.py``.
250 """
251 # https://docs.python.org/3/library/signal.html#note-on-sigpipe
252 try:
253 code = _main(prog=_get_prog_name(sys.argv))
254 sys.stdout.flush()
255 return code
256 except BrokenPipeError:
257 # Python flushes standard streams on exit; redirect remaining output
258 # to devnull to avoid another BrokenPipeError at shutdown
259 devnull = os.open(os.devnull, os.O_WRONLY)
260 os.dup2(devnull, sys.stdout.fileno())
261 return 1 # Python exits with error code 1 on EPIPE
262
263
264 def console_main() -> int:
265 """The CLI entry point of pytest.
266
267 .. deprecated:: 9.1
268 This function is slated for removal in pytest 10.
269 It is not meant for programmable use; use :func:`pytest.main` instead.
270 """
271 import warnings
272
273 from _pytest.deprecated import CONSOLE_MAIN
274
275 warnings.warn(CONSOLE_MAIN, stacklevel=2)
276 return _console_main()
277
278
279 class cmdline: # compatibility namespace
280 main = staticmethod(main)
281
282
283 def filename_arg(path: str, optname: str) -> str:
284 """Argparse type validator for filename arguments.
285
286 :path: Path of filename.
287 :optname: Name of the option.
288 """
289 if os.path.isdir(path):
290 raise UsageError(f"{optname} must be a filename, given: {path}")
291 return path
292
293
294 def directory_arg(path: str, optname: str) -> str:
295 """Argparse type validator for directory arguments.
296
297 :path: Path of directory.
298 :optname: Name of the option.
299 """
300 if not os.path.isdir(path):
301 raise UsageError(f"{optname} must be a directory, given: {path}")
302 return path
303
304
305 # Plugins that cannot be disabled via "-p no:X" currently.
306 essential_plugins = (
307 "mark",
308 "main",
309 "runner",
310 "fixtures",
311 "helpconfig", # Provides -p.
312 )
313
314 default_plugins = (
315 *essential_plugins,
316 "python",
317 "terminal",
318 "debugging",
319 "unittest",
320 "capture",
321 "skipping",
322 "legacypath",
323 "tmpdir",
324 "monkeypatch",
325 "recwarn",
326 "pastebin",
327 "assertion",
328 "junitxml",
329 "doctest",
330 "cacheprovider",
331 "setuponly",
332 "setupplan",
333 "stepwise",
334 "unraisableexception",
335 "threadexception",
336 "warnings",
337 "logging",
338 "reports",
339 "faulthandler",
340 "subtests",
341 )
342
343 builtin_plugins = {
344 *default_plugins,
345 "pytester",
346 "pytester_assertions",
347 "terminalprogress",
348 }
349
350
351 def get_config(
352 args: Iterable[str] | None = None,
353 plugins: Sequence[str | _PluggyPlugin] | None = None,
354 *,
355 prog: str | None = None,
356 ) -> Config:
357 # Subsequent calls to main will create a fresh instance.
358 pluginmanager = PytestPluginManager()
359 invocation_params = Config.InvocationParams(
360 args=args or (),
361 plugins=plugins,
362 dir=pathlib.Path.cwd(),
363 )
364 config = Config(pluginmanager, invocation_params=invocation_params, prog=prog)
365
366 if invocation_params.args:
367 # Handle any "-p no:plugin" args.
368 pluginmanager.consider_preparse(invocation_params.args, exclude_only=True)
369
370 for spec in default_plugins:
371 pluginmanager.import_plugin(spec)
372
373 return config
374
375
376 def get_plugin_manager() -> PytestPluginManager:
377 """Obtain a new instance of the
378 :py:class:`pytest.PytestPluginManager`, with default plugins
379 already loaded.
380
381 This function can be used by integration with other tools, like hooking
382 into pytest to run tests into an IDE.
383 """
384 return get_config().pluginmanager
385
386
387 def _prepareconfig(
388 args: list[str] | os.PathLike[str],
389 plugins: Sequence[str | _PluggyPlugin] | None = None,
390 *,
391 prog: str | None = None,
392 ) -> Config:
393 if isinstance(args, os.PathLike):
394 args = [os.fspath(args)]
395 elif not isinstance(args, list):
396 msg = ( # type:ignore[unreachable]
397 "`args` parameter expected to be a list of strings, got: {!r} (type: {})"
398 )
399 raise TypeError(msg.format(args, type(args)))
400
401 initial_config = get_config(args, plugins, prog=prog)
402 pluginmanager = initial_config.pluginmanager
403 try:
404 if plugins:
405 for plugin in plugins:
406 if isinstance(plugin, str):
407 pluginmanager.consider_pluginarg(plugin)
408 else:
409 pluginmanager.register(plugin)
410 config: Config = pluginmanager.hook.pytest_cmdline_parse(
411 pluginmanager=pluginmanager, args=args
412 )
413 return config
414 except BaseException:
415 initial_config._ensure_unconfigure()
416 raise
417
418
419 def _get_directory(path: pathlib.Path) -> pathlib.Path:
420 """Get the directory of a path - itself if already a directory."""
421 if path.is_file():
422 return path.parent
423 else:
424 return path
425
426
427 def _get_legacy_hook_marks(
428 method: Any,
429 hook_type: str,
430 opt_names: tuple[str, ...],
431 ) -> dict[str, bool]:
432 if TYPE_CHECKING:
433 # abuse typeguard from importlib to avoid massive method type union that's lacking an alias
434 assert inspect.isroutine(method)
435 known_marks: set[str] = {m.name for m in getattr(method, "pytestmark", [])}
436 must_warn: list[str] = []
437 opts: dict[str, bool] = {}
438 for opt_name in opt_names:
439 opt_attr = getattr(method, opt_name, AttributeError)
440 if opt_attr is not AttributeError:
441 must_warn.append(f"{opt_name}={opt_attr}")
442 opts[opt_name] = True
443 elif opt_name in known_marks:
444 must_warn.append(f"{opt_name}=True")
445 opts[opt_name] = True
446 else:
447 opts[opt_name] = False
448 if must_warn:
449 hook_opts = ", ".join(must_warn)
450 message = _pytest.deprecated.HOOK_LEGACY_MARKING.format(
451 type=hook_type,
452 fullname=method.__qualname__,
453 hook_opts=hook_opts,
454 )
455 warn_explicit_for(cast(FunctionType, method), message)
456 return opts
457
458
459 @final
460 class PytestPluginManager(PluginManager):
461 """A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with
462 additional pytest-specific functionality:
463
464 * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and
465 ``pytest_plugins`` global variables found in plugins being loaded.
466 * ``conftest.py`` loading during start-up.
467 """
468
469 def __init__(self) -> None:
470 from _pytest.assertion import DummyRewriteHook
471 from _pytest.assertion import RewriteHook
472
473 super().__init__("pytest")
474
475 # -- State related to local conftest plugins.
476 # All loaded conftest modules.
477 self._conftest_plugins: set[types.ModuleType] = set()
478 # All conftest modules applicable for a directory.
479 # This includes the directory's own conftest modules as well
480 # as those of its parent directories.
481 self._dirpath2confmods: dict[pathlib.Path, list[types.ModuleType]] = {}
482 # Cutoff directory above which conftests are no longer discovered.
483 self._confcutdir: pathlib.Path | None = None
484 # If set, conftest loading is skipped.
485 self._noconftest = False
486
487 # _getconftestmodules()'s call to _get_directory() causes a stat
488 # storm when it's called potentially thousands of times in a test
489 # session (#9478), often with the same path, so cache it.
490 self._get_directory = lru_cache(256)(_get_directory)
491
492 # plugins that were explicitly skipped with pytest.skip
493 # list of (module name, skip reason)
494 # previously we would issue a warning when a plugin was skipped, but
495 # since we refactored warnings as first citizens of Config, they are
496 # just stored here to be used later.
497 self.skipped_plugins: list[tuple[str, str]] = []
498
499 self.add_hookspecs(_pytest.hookspec)
500 self.register(self)
501 if os.environ.get("PYTEST_DEBUG"):
502 err: IO[str] = sys.stderr
503 encoding: str = getattr(err, "encoding", "utf8")
504 try:
505 err = open(
506 os.dup(err.fileno()),
507 mode=err.mode,
508 buffering=1,
509 encoding=encoding,
510 )
511 except Exception:
512 pass
513 self.trace.root.setwriter(err.write)
514 self.enable_tracing()
515
516 # Config._consider_importhook will set a real object if required.
517 self.rewrite_hook: RewriteHook = DummyRewriteHook()
518 # Used to know when we are importing conftests after the pytest_configure stage.
519 self._configured = False
520
521 def parse_hookimpl_opts(
522 self, plugin: _PluggyPlugin, name: str
523 ) -> HookimplOpts | None:
524 """:meta private:"""
525 # pytest hooks are always prefixed with "pytest_",
526 # so we avoid accessing possibly non-readable attributes
527 # (see issue #1073).
528 if not name.startswith("pytest_"):
529 return None
530 # Ignore names which cannot be hooks.
531 if name == "pytest_plugins":
532 return None
533
534 opts = super().parse_hookimpl_opts(plugin, name)
535 if opts is not None:
536 return opts
537
538 method = getattr(plugin, name)
539 # Consider only actual functions for hooks (#3775).
540 if not inspect.isroutine(method):
541 return None
542 # Collect unmarked hooks as long as they have the `pytest_' prefix.
543 legacy = _get_legacy_hook_marks(
544 method, "impl", ("tryfirst", "trylast", "optionalhook", "hookwrapper")
545 )
546 return cast(HookimplOpts, legacy)
547
548 def parse_hookspec_opts(self, module_or_class, name: str) -> HookspecOpts | None:
549 """:meta private:"""
550 opts = super().parse_hookspec_opts(module_or_class, name)
551 if opts is None:
552 method = getattr(module_or_class, name)
553 if name.startswith("pytest_"):
554 legacy = _get_legacy_hook_marks(
555 method, "spec", ("firstresult", "historic")
556 )
557 opts = cast(HookspecOpts, legacy)
558 return opts
559
560 def register(self, plugin: _PluggyPlugin, name: str | None = None) -> str | None:
561 if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS:
562 warnings.warn(
563 PytestConfigWarning(
564 "{} plugin has been merged into the core, "
565 "please remove it from your requirements.".format(
566 name.replace("_", "-")
567 )
568 )
569 )
570 return None
571 plugin_name = super().register(plugin, name)
572 if plugin_name is not None:
573 self.hook.pytest_plugin_registered.call_historic(
574 kwargs=dict(
575 plugin=plugin,
576 plugin_name=plugin_name,
577 manager=self,
578 )
579 )
580
581 if isinstance(plugin, types.ModuleType):
582 self.consider_module(plugin)
583 return plugin_name
584
585 def getplugin(self, name: str):
586 # Support deprecated naming because plugins (xdist e.g.) use it.
587 plugin: _PluggyPlugin | None = self.get_plugin(name)
588 return plugin
589
590 def hasplugin(self, name: str) -> bool:
591 """Return whether a plugin with the given name is registered."""
592 return bool(self.get_plugin(name))
593
594 def pytest_configure(self, config: Config) -> None:
595 """:meta private:"""
596 # XXX now that the pluginmanager exposes hookimpl(tryfirst...)
597 # we should remove tryfirst/trylast as markers.
598 config.addinivalue_line(
599 "markers",
600 "tryfirst: mark a hook implementation function such that the "
601 "plugin machinery will try to call it first/as early as possible. "
602 "DEPRECATED, use @pytest.hookimpl(tryfirst=True) instead.",
603 )
604 config.addinivalue_line(
605 "markers",
606 "trylast: mark a hook implementation function such that the "
607 "plugin machinery will try to call it last/as late as possible. "
608 "DEPRECATED, use @pytest.hookimpl(trylast=True) instead.",
609 )
610 self._configured = True
611
612 #
613 # Internal API for local conftest plugin handling.
614 #
615 def _set_initial_conftests(
616 self,
617 args: Sequence[str | pathlib.Path],
618 pyargs: bool,
619 noconftest: bool,
620 rootpath: pathlib.Path,
621 confcutdir: pathlib.Path | None,
622 invocation_dir: pathlib.Path,
623 importmode: ImportMode | str,
624 *,
625 consider_namespace_packages: bool,
626 ) -> None:
627 """Load initial conftest files given a preparsed "namespace".
628
629 As conftest files may add their own command line options which have
630 arguments ('--my-opt somepath') we might get some false positives.
631 All builtin and 3rd party plugins will have been loaded, however, so
632 common options will not confuse our logic here.
633 """
634 self._confcutdir = (
635 absolutepath(invocation_dir / confcutdir) if confcutdir else None
636 )
637 self._noconftest = noconftest
638 self._using_pyargs = pyargs
639
640 anchors = []
641 for initial_path in args:
642 path = str(initial_path)
643 # remove node-id syntax
644 i = path.find("::")
645 if i != -1:
646 path = path[:i]
647 anchor = absolutepath(invocation_dir / path)
648 # Ensure we do not break if what appears to be an anchor
649 # is in fact a very long option (#10169, #11394).
650 if not safe_exists(anchor):
651 continue
652
653 anchors.append(anchor)
654 # Let's also consider test* subdirs.
655 if anchor.is_dir():
656 anchors.extend(x for x in anchor.glob("test*") if x.is_dir())
657 if not anchors:
658 anchors.append(invocation_dir)
659 anchors.extend(x for x in invocation_dir.glob("test*") if x.is_dir())
660
661 for anchor in anchors:
662 self._loadconftestmodules(
663 anchor,
664 importmode,
665 rootpath,
666 consider_namespace_packages=consider_namespace_packages,
667 )
668
669 def _is_in_confcutdir(self, path: pathlib.Path) -> bool:
670 """Whether to consider the given path to load conftests from."""
671 if self._confcutdir is None:
672 return True
673 # The semantics here are literally:
674 # Do not load a conftest if it is found upwards from confcut dir.
675 # But this is *not* the same as:
676 # Load only conftests from confcutdir or below.
677 # At first glance they might seem the same thing, however we do support use cases where
678 # we want to load conftests that are not found in confcutdir or below, but are found
679 # in completely different directory hierarchies like packages installed
680 # in out-of-source trees.
681 # (see #9767 for a regression where the logic was inverted).
682 return path not in self._confcutdir.parents
683
684 def _loadconftestmodules(
685 self,
686 path: pathlib.Path,
687 importmode: str | ImportMode,
688 rootpath: pathlib.Path,
689 *,
690 consider_namespace_packages: bool,
691 ) -> None:
692 if self._noconftest:
693 return
694
695 directory = self._get_directory(path)
696
697 # Optimization: avoid repeated searches in the same directory.
698 # Assumes always called with same importmode and rootpath.
699 if directory in self._dirpath2confmods:
700 return
701
702 clist = []
703 for parent in reversed((directory, *directory.parents)):
704 if self._is_in_confcutdir(parent):
705 conftestpath = parent / "conftest.py"
706 if conftestpath.is_file():
707 mod = self._importconftest(
708 conftestpath,
709 importmode,
710 rootpath,
711 consider_namespace_packages=consider_namespace_packages,
712 )
713 clist.append(mod)
714 self._dirpath2confmods[directory] = clist
715
716 def _getconftestmodules(self, path: pathlib.Path) -> Sequence[types.ModuleType]:
717 directory = self._get_directory(path)
718 return self._dirpath2confmods.get(directory, ())
719
720 def _rget_with_confmod(
721 self,
722 name: str,
723 path: pathlib.Path,
724 ) -> tuple[types.ModuleType, Any]:
725 modules = self._getconftestmodules(path)
726 for mod in reversed(modules):
727 try:
728 return mod, getattr(mod, name)
729 except AttributeError:
730 continue
731 raise KeyError(name)
732
733 def _importconftest(
734 self,
735 conftestpath: pathlib.Path,
736 importmode: str | ImportMode,
737 rootpath: pathlib.Path,
738 *,
739 consider_namespace_packages: bool,
740 ) -> types.ModuleType:
741 conftestpath_plugin_name = str(conftestpath)
742 existing = self.get_plugin(conftestpath_plugin_name)
743 if existing is not None:
744 return cast(types.ModuleType, existing)
745
746 # conftest.py files there are not in a Python package all have module
747 # name "conftest", and thus conflict with each other. Clear the existing
748 # before loading the new one, otherwise the existing one will be
749 # returned from the module cache.
750 pkgpath = resolve_package_path(conftestpath)
751 if pkgpath is None:
752 try:
753 del sys.modules[conftestpath.stem]
754 except KeyError:
755 pass
756
757 try:
758 mod = import_path(
759 conftestpath,
760 mode=importmode,
761 root=rootpath,
762 consider_namespace_packages=consider_namespace_packages,
763 )
764 except Exception as e:
765 assert e.__traceback__ is not None
766 raise ConftestImportFailure(conftestpath, cause=e) from e
767
768 self._check_non_top_pytest_plugins(mod, conftestpath)
769
770 self._conftest_plugins.add(mod)
771 dirpath = conftestpath.parent
772 if dirpath in self._dirpath2confmods:
773 for path, mods in self._dirpath2confmods.items():
774 if dirpath in path.parents or path == dirpath:
775 if mod in mods:
776 raise AssertionError(
777 f"While trying to load conftest path {conftestpath!s}, "
778 f"found that the module {mod} is already loaded with path {mod.__file__}. "
779 "This is not supposed to happen. Please report this issue to pytest."
780 )
781 mods.append(mod)
782 self.trace(f"loading conftestmodule {mod!r}")
783 self.consider_conftest(mod, registration_name=conftestpath_plugin_name)
784 return mod
785
786 def _check_non_top_pytest_plugins(
787 self,
788 mod: types.ModuleType,
789 conftestpath: pathlib.Path,
790 ) -> None:
791 if (
792 hasattr(mod, "pytest_plugins")
793 and self._configured
794 and not self._using_pyargs
795 ):
796 msg = (
797 "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\n"
798 "It affects the entire test suite instead of just below the conftest as expected.\n"
799 " {}\n"
800 "Please move it to a top level conftest file at the rootdir:\n"
801 " {}\n"
802 "For more information, visit:\n"
803 " https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files"
804 )
805 fail(msg.format(conftestpath, self._confcutdir), pytrace=False)
806
807 #
808 # API for bootstrapping plugin loading
809 #
810 #
811
812 def consider_preparse(
813 self, args: Sequence[str], *, exclude_only: bool = False
814 ) -> None:
815 """:meta private:"""
816 i = 0
817 n = len(args)
818 while i < n:
819 opt = args[i]
820 i += 1
821 if isinstance(opt, str):
822 if opt == "-p":
823 try:
824 parg = args[i]
825 except IndexError:
826 return
827 i += 1
828 elif opt.startswith("-p"):
829 parg = opt[2:]
830 else:
831 continue
832 parg = parg.strip()
833 if exclude_only and not parg.startswith("no:"):
834 continue
835 self.consider_pluginarg(parg)
836
837 def consider_pluginarg(self, arg: str) -> None:
838 """:meta private:"""
839 if arg.startswith("no:"):
840 name = arg[3:]
841 if name in essential_plugins:
842 raise UsageError(f"plugin {name} cannot be disabled")
843
844 if name.endswith("conftest.py"):
845 raise UsageError(
846 f"Blocking conftest files using -p is not supported: -p no:{name}\n"
847 "conftest.py files are not plugins and cannot be disabled via -p.\n"
848 )
849
850 # PR #4304: remove stepwise if cacheprovider is blocked.
851 if name == "cacheprovider":
852 self.set_blocked("stepwise")
853 self.set_blocked("pytest_stepwise")
854
855 self.set_blocked(name)
856 if not name.startswith("pytest_"):
857 self.set_blocked("pytest_" + name)
858 else:
859 name = arg
860 # Unblock the plugin.
861 self.unblock(name)
862 if not name.startswith("pytest_"):
863 self.unblock("pytest_" + name)
864 self.import_plugin(arg, consider_entry_points=True)
865
866 def consider_conftest(
867 self, conftestmodule: types.ModuleType, registration_name: str
868 ) -> None:
869 """:meta private:"""
870 self.register(conftestmodule, name=registration_name)
871
872 def consider_env(self) -> None:
873 """:meta private:"""
874 self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
875
876 def consider_module(self, mod: types.ModuleType) -> None:
877 """:meta private:"""
878 self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
879
880 def _import_plugin_specs(
881 self, spec: None | types.ModuleType | str | Sequence[str]
882 ) -> None:
883 plugins = _get_plugin_specs_as_list(spec)
884 for import_spec in plugins:
885 self.import_plugin(import_spec)
886
887 def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None:
888 """Import a plugin with ``modname``.
889
890 If ``consider_entry_points`` is True, entry point names are also
891 considered to find a plugin.
892 """
893 # Most often modname refers to builtin modules, e.g. "pytester",
894 # "terminal" or "capture". Those plugins are registered under their
895 # basename for historic purposes but must be imported with the
896 # _pytest prefix.
897 assert isinstance(modname, str), (
898 f"module name as text required, got {modname!r}"
899 )
900 if self.is_blocked(modname) or self.get_plugin(modname) is not None:
901 return
902
903 importspec = "_pytest." + modname if modname in builtin_plugins else modname
904 self.rewrite_hook.mark_rewrite(importspec)
905
906 if consider_entry_points:
907 loaded = self.load_setuptools_entrypoints("pytest11", name=modname)
908 if loaded:
909 return
910
911 try:
912 if sys.version_info >= (3, 11):
913 mod = importlib.import_module(importspec)
914 else:
915 # On Python 3.10, import_module breaks
916 # testing/test_config.py::test_disable_plugin_autoload.
917 __import__(importspec)
918 mod = sys.modules[importspec]
919 except ImportError as e:
920 raise ImportError(
921 f'Error importing plugin "{modname}": {e.args[0]}'
922 ).with_traceback(e.__traceback__) from e
923
924 except Skipped as e:
925 self.skipped_plugins.append((modname, e.msg or ""))
926 else:
927 self.register(mod, modname)
928
929
930 def _get_plugin_specs_as_list(
931 specs: None | types.ModuleType | str | Sequence[str],
932 ) -> list[str]:
933 """Parse a plugins specification into a list of plugin names."""
934 # None means empty.
935 if specs is None:
936 return []
937 # Workaround for #3899 - a submodule which happens to be called "pytest_plugins".
938 if isinstance(specs, types.ModuleType):
939 return []
940 # Comma-separated list.
941 if isinstance(specs, str):
942 return specs.split(",") if specs else []
943 # Direct specification.
944 if isinstance(specs, collections.abc.Sequence):
945 return list(specs)
946 raise UsageError(
947 f"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: {specs!r}"
948 )
949
950
951 def _iter_rewritable_modules(package_files: Iterable[str]) -> Iterator[str]:
952 """Given an iterable of file names in a source distribution, return the "names" that should
953 be marked for assertion rewrite.
954
955 For example the package "pytest_mock/__init__.py" should be added as "pytest_mock" in
956 the assertion rewrite mechanism.
957
958 This function has to deal with dist-info based distributions and egg based distributions
959 (which are still very much in use for "editable" installs).
960
961 Here are the file names as seen in a dist-info based distribution:
962
963 pytest_mock/__init__.py
964 pytest_mock/_version.py
965 pytest_mock/plugin.py
966 pytest_mock.egg-info/PKG-INFO
967
968 Here are the file names as seen in an egg based distribution:
969
970 src/pytest_mock/__init__.py
971 src/pytest_mock/_version.py
972 src/pytest_mock/plugin.py
973 src/pytest_mock.egg-info/PKG-INFO
974 LICENSE
975 setup.py
976
977 We have to take in account those two distribution flavors in order to determine which
978 names should be considered for assertion rewriting.
979
980 More information:
981 https://github.com/pytest-dev/pytest-mock/issues/167
982 """
983 package_files = list(package_files)
984 seen_some = False
985 for fn in package_files:
986 is_simple_module = "/" not in fn and fn.endswith(".py")
987 is_package = fn.count("/") == 1 and fn.endswith("__init__.py")
988 if is_simple_module:
989 module_name, _ = os.path.splitext(fn)
990 # we ignore "setup.py" at the root of the distribution
991 # as well as editable installation finder modules made by setuptools
992 if module_name != "setup" and not module_name.startswith("__editable__"):
993 seen_some = True
994 yield module_name
995 elif is_package:
996 package_name = os.path.dirname(fn)
997 seen_some = True
998 yield package_name
999
1000 if not seen_some:
1001 # At this point we did not find any packages or modules suitable for assertion
1002 # rewriting, so we try again by stripping the first path component (to account for
1003 # "src" based source trees for example).
1004 # This approach lets us have the common case continue to be fast, as egg-distributions
1005 # are rarer.
1006 new_package_files = []
1007 for fn in package_files:
1008 parts = fn.split("/")
1009 new_fn = "/".join(parts[1:])
1010 if new_fn:
1011 new_package_files.append(new_fn)
1012 if new_package_files:
1013 yield from _iter_rewritable_modules(new_package_files)
1014
1015
1016 class _DeprecatedInicfgProxy(MutableMapping[str, Any]):
1017 """Compatibility proxy for the deprecated Config.inicfg."""
1018
1019 __slots__ = ("_config",)
1020
1021 def __init__(self, config: Config) -> None:
1022 self._config = config
1023
1024 def __getitem__(self, key: str) -> Any:
1025 return self._config._inicfg[key].value
1026
1027 def __setitem__(self, key: str, value: Any) -> None:
1028 self._config._inicfg[key] = ConfigValue(value, origin="override", mode="toml")
1029
1030 def __delitem__(self, key: str) -> None:
1031 del self._config._inicfg[key]
1032
1033 def __iter__(self) -> Iterator[str]:
1034 return iter(self._config._inicfg)
1035
1036 def __len__(self) -> int:
1037 return len(self._config._inicfg)
1038
1039
1040 @final
1041 class Config:
1042 """Access to configuration values, pluginmanager and plugin hooks.
1043
1044 :param PytestPluginManager pluginmanager:
1045 A pytest PluginManager.
1046
1047 :param InvocationParams invocation_params:
1048 Object containing parameters regarding the :func:`pytest.main`
1049 invocation.
1050 """
1051
1052 @final
1053 @dataclasses.dataclass(frozen=True)
1054 class InvocationParams:
1055 """Holds parameters passed during :func:`pytest.main`.
1056
1057 The object attributes are read-only.
1058
1059 .. versionadded:: 5.1
1060
1061 .. note::
1062
1063 Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts``
1064 configuration option are handled by pytest, not being included in the ``args`` attribute.
1065
1066 Plugins accessing ``InvocationParams`` must be aware of that.
1067 """
1068
1069 args: tuple[str, ...]
1070 """The command-line arguments as passed to :func:`pytest.main`."""
1071 plugins: Sequence[str | _PluggyPlugin] | None
1072 """Extra plugins, might be `None`."""
1073 dir: pathlib.Path
1074 """The directory from which :func:`pytest.main` was invoked."""
1075
1076 def __init__(
1077 self,
1078 *,
1079 args: Iterable[str],
1080 plugins: Sequence[str | _PluggyPlugin] | None,
1081 dir: pathlib.Path,
1082 ) -> None:
1083 object.__setattr__(self, "args", tuple(args))
1084 object.__setattr__(self, "plugins", plugins)
1085 object.__setattr__(self, "dir", dir)
1086
1087 class ArgsSource(enum.Enum):
1088 """Indicates the source of the test arguments.
1089
1090 .. versionadded:: 7.2
1091 """
1092
1093 #: Command line arguments.
1094 ARGS = enum.auto()
1095 #: Invocation directory.
1096 INVOCATION_DIR = enum.auto()
1097 INCOVATION_DIR = INVOCATION_DIR # backwards compatibility alias
1098 #: 'testpaths' configuration value.
1099 TESTPATHS = enum.auto()
1100
1101 # Set by cacheprovider plugin.
1102 cache: Cache
1103
1104 def __init__(
1105 self,
1106 pluginmanager: PytestPluginManager,
1107 *,
1108 invocation_params: InvocationParams | None = None,
1109 prog: str | None = None,
1110 ) -> None:
1111 if invocation_params is None:
1112 invocation_params = self.InvocationParams(
1113 args=(), plugins=None, dir=pathlib.Path.cwd()
1114 )
1115
1116 self.option = argparse.Namespace()
1117 """Access to command line option as attributes.
1118
1119 :type: argparse.Namespace
1120 """
1121
1122 self.invocation_params = invocation_params
1123 """The parameters with which pytest was invoked.
1124
1125 :type: InvocationParams
1126 """
1127
1128 self._parser = Parser(
1129 usage=f"%(prog)s [options] [{FILE_OR_DIR}] [{FILE_OR_DIR}] [...]",
1130 processopt=self._processopt,
1131 prog=prog,
1132 _ispytest=True,
1133 )
1134 self.pluginmanager = pluginmanager
1135 """The plugin manager handles plugin registration and hook invocation.
1136
1137 :type: PytestPluginManager
1138 """
1139
1140 self.stash = Stash()
1141 """A place where plugins can store information on the config for their
1142 own use.
1143
1144 :type: Stash
1145 """
1146 # Deprecated alias. Was never public. Can be removed in a few releases.
1147 self._store = self.stash
1148
1149 self.trace = self.pluginmanager.trace.root.get("config")
1150 self.hook = self.pluginmanager.hook
1151 self._inicache: dict[str, Any] = {}
1152 self._inicfg: ConfigDict = {}
1153 self._cleanup_stack = contextlib.ExitStack()
1154 self.pluginmanager.register(self, "pytestconfig")
1155 self._configured = False
1156 self.hook.pytest_addoption.call_historic(
1157 kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager)
1158 )
1159 self.args_source = Config.ArgsSource.ARGS
1160 self.args: list[str] = []
1161
1162 if TYPE_CHECKING:
1163
1164 @deprecated(
1165 "config.inicfg is deprecated, use config.getini() to access configuration values instead.",
1166 )
1167 @property
1168 def inicfg(self) -> _DeprecatedInicfgProxy:
1169 raise NotImplementedError()
1170 else:
1171
1172 @property
1173 def inicfg(self) -> _DeprecatedInicfgProxy:
1174 warnings.warn(
1175 _pytest.deprecated.CONFIG_INICFG,
1176 stacklevel=2,
1177 )
1178 return _DeprecatedInicfgProxy(self)
1179
1180 @property
1181 def rootpath(self) -> pathlib.Path:
1182 """The path to the :ref:`rootdir <rootdir>`.
1183
1184 .. versionadded:: 6.1
1185 """
1186 return self._rootpath
1187
1188 @property
1189 def inipath(self) -> pathlib.Path | None:
1190 """The path to the :ref:`configfile <configfiles>`.
1191
1192 .. versionadded:: 6.1
1193 """
1194 return self._inipath
1195
1196 def add_cleanup(self, func: Callable[[], None]) -> None:
1197 """Add a function to be called when the config object gets out of
1198 use (usually coinciding with pytest_unconfigure).
1199 """
1200 self._cleanup_stack.callback(func)
1201
1202 def _do_configure(self) -> None:
1203 assert not self._configured
1204 self._configured = True
1205 self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
1206
1207 def _ensure_unconfigure(self) -> None:
1208 try:
1209 if self._configured:
1210 self._configured = False
1211 try:
1212 self.hook.pytest_unconfigure(config=self)
1213 finally:
1214 self.hook.pytest_configure._call_history = []
1215 finally:
1216 try:
1217 self._cleanup_stack.close()
1218 finally:
1219 self._cleanup_stack = contextlib.ExitStack()
1220
1221 def get_terminal_writer(self) -> TerminalWriter:
1222 terminalreporter: TerminalReporter | None = self.pluginmanager.get_plugin(
1223 "terminalreporter"
1224 )
1225 assert terminalreporter is not None
1226 return terminalreporter._tw
1227
1228 def pytest_cmdline_parse(
1229 self, pluginmanager: PytestPluginManager, args: list[str]
1230 ) -> Config:
1231 try:
1232 self.parse(args)
1233 except UsageError:
1234 # Handle `--version --version` and `--help` here in a minimal fashion.
1235 # This gets done via helpconfig normally, but its
1236 # pytest_cmdline_main is not called in case of errors.
1237 if getattr(self.option, "version", False) or "--version" in args:
1238 from _pytest.helpconfig import show_version_verbose
1239
1240 # Note that `--version` (single argument) is handled early by `Config.main()`, so the only
1241 # way we are reaching this point is via `--version --version`.
1242 show_version_verbose(self)
1243 elif (
1244 getattr(self.option, "help", False) or "--help" in args or "-h" in args
1245 ):
1246 self._parser.optparser.print_help()
1247 sys.stdout.write(
1248 "\nNOTE: displaying only minimal help due to UsageError.\n\n"
1249 )
1250
1251 raise
1252
1253 return self
1254
1255 def notify_exception(
1256 self,
1257 excinfo: ExceptionInfo[BaseException],
1258 option: argparse.Namespace | None = None,
1259 ) -> None:
1260 if option and getattr(option, "fulltrace", False):
1261 style: TracebackStyle = "long"
1262 else:
1263 style = "native"
1264 excrepr = excinfo.getrepr(
1265 funcargs=True, showlocals=getattr(option, "showlocals", False), style=style
1266 )
1267 res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
1268 if not any(res):
1269 for line in str(excrepr).split("\n"):
1270 sys.stderr.write(f"INTERNALERROR> {line}\n")
1271 sys.stderr.flush()
1272
1273 def cwd_relative_nodeid(self, nodeid: str) -> str:
1274 # nodeid's are relative to the rootpath, compute relative to cwd.
1275 if self.invocation_params.dir != self.rootpath:
1276 base_path_part, *nodeid_part = nodeid.split("::")
1277 # Only process path part
1278 fullpath = self.rootpath / base_path_part
1279 relative_path = bestrelpath(self.invocation_params.dir, fullpath)
1280
1281 nodeid = "::".join([relative_path, *nodeid_part])
1282 return nodeid
1283
1284 @classmethod
1285 def fromdictargs(cls, option_dict: Mapping[str, Any], args: list[str]) -> Config:
1286 """Constructor usable for subprocesses."""
1287 config = get_config(args)
1288 config.option.__dict__.update(option_dict)
1289 config.parse(args, addopts=False)
1290 for x in config.option.plugins:
1291 config.pluginmanager.consider_pluginarg(x)
1292 return config
1293
1294 def _processopt(self, opt: Argument) -> None:
1295 if not hasattr(self.option, opt.dest):
1296 setattr(self.option, opt.dest, opt.default)
1297
1298 @hookimpl(trylast=True)
1299 def pytest_load_initial_conftests(self, early_config: Config) -> None:
1300 # We haven't fully parsed the command line arguments yet, so
1301 # early_config.args it not set yet. But we need it for
1302 # discovering the initial conftests. So "pre-run" the logic here.
1303 # It will be done for real in `parse()`.
1304 args, _args_source = early_config._decide_args(
1305 args=early_config.known_args_namespace.file_or_dir,
1306 pyargs=early_config.known_args_namespace.pyargs,
1307 testpaths=early_config.getini("testpaths"),
1308 invocation_dir=early_config.invocation_params.dir,
1309 rootpath=early_config.rootpath,
1310 warn=False,
1311 )
1312 self.pluginmanager._set_initial_conftests(
1313 args=args,
1314 pyargs=early_config.known_args_namespace.pyargs,
1315 noconftest=early_config.known_args_namespace.noconftest,
1316 rootpath=early_config.rootpath,
1317 confcutdir=early_config.known_args_namespace.confcutdir,
1318 invocation_dir=early_config.invocation_params.dir,
1319 importmode=early_config.known_args_namespace.importmode,
1320 consider_namespace_packages=early_config.getini(
1321 "consider_namespace_packages"
1322 ),
1323 )
1324
1325 def _consider_importhook(self) -> None:
1326 """Install the PEP 302 import hook if using assertion rewriting.
1327
1328 Needs to parse the --assert=<mode> option from the commandline
1329 and find all the installed plugins to mark them for rewriting
1330 by the importhook.
1331 """
1332 mode = getattr(self.known_args_namespace, "assertmode", "plain")
1333
1334 disable_autoload = getattr(
1335 self.known_args_namespace, "disable_plugin_autoload", False
1336 ) or bool(os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"))
1337 if mode == "rewrite":
1338 import _pytest.assertion
1339
1340 try:
1341 hook = _pytest.assertion.install_importhook(self)
1342 except SystemError:
1343 mode = "plain"
1344 else:
1345 self._mark_plugins_for_rewrite(hook, disable_autoload)
1346 self._warn_about_missing_assertion(mode)
1347
1348 def _mark_plugins_for_rewrite(
1349 self, hook: AssertionRewritingHook, disable_autoload: bool
1350 ) -> None:
1351 """Given an importhook, mark for rewrite any top-level
1352 modules or packages in the distribution package for
1353 all pytest plugins."""
1354 self.pluginmanager.rewrite_hook = hook
1355
1356 if disable_autoload:
1357 # We don't autoload from distribution package entry points,
1358 # no need to continue.
1359 return
1360
1361 package_files = (
1362 str(file)
1363 for dist in importlib.metadata.distributions()
1364 if any(ep.group == "pytest11" for ep in dist.entry_points)
1365 for file in dist.files or []
1366 )
1367
1368 for name in _iter_rewritable_modules(package_files):
1369 hook.mark_rewrite(name)
1370
1371 def _configure_python_path(self) -> None:
1372 # `pythonpath = a b` will set `sys.path` to `[a, b, x, y, z, ...]`
1373 for path in reversed(self.getini("pythonpath")):
1374 sys.path.insert(0, str(path))
1375 self.add_cleanup(self._unconfigure_python_path)
1376
1377 def _unconfigure_python_path(self) -> None:
1378 for path in self.getini("pythonpath"):
1379 path_str = str(path)
1380 if path_str in sys.path:
1381 sys.path.remove(path_str)
1382
1383 def _validate_args(self, args: list[str], via: str) -> list[str]:
1384 """Validate known args."""
1385 self._parser.extra_info["config source"] = via
1386 try:
1387 self._parser.parse_known_and_unknown_args(
1388 args, namespace=copy.copy(self.option)
1389 )
1390 finally:
1391 self._parser.extra_info.pop("config source", None)
1392
1393 return args
1394
1395 def _decide_args(
1396 self,
1397 *,
1398 args: list[str],
1399 pyargs: bool,
1400 testpaths: list[str],
1401 invocation_dir: pathlib.Path,
1402 rootpath: pathlib.Path,
1403 warn: bool,
1404 ) -> tuple[list[str], ArgsSource]:
1405 """Decide the args (initial paths/nodeids) to use given the relevant inputs.
1406
1407 :param warn: Whether can issue warnings.
1408
1409 :returns: The args and the args source. Guaranteed to be non-empty.
1410 """
1411 if args:
1412 source = Config.ArgsSource.ARGS
1413 result = args
1414 else:
1415 if invocation_dir == rootpath:
1416 source = Config.ArgsSource.TESTPATHS
1417 if pyargs:
1418 result = testpaths
1419 else:
1420 result = []
1421 for path in testpaths:
1422 result.extend(sorted(glob.iglob(path, recursive=True)))
1423 if testpaths and not result:
1424 if warn:
1425 warning_text = (
1426 "No files were found in testpaths; "
1427 "consider removing or adjusting your testpaths configuration. "
1428 "Searching recursively from the current directory instead."
1429 )
1430 self.issue_config_time_warning(
1431 PytestConfigWarning(warning_text), stacklevel=3
1432 )
1433 else:
1434 result = []
1435 if not result:
1436 source = Config.ArgsSource.INVOCATION_DIR
1437 result = [str(invocation_dir)]
1438 return result, source
1439
1440 @hookimpl(wrapper=True)
1441 def pytest_collection(self) -> Generator[None, object, object]:
1442 # Validate invalid configuration keys after collection is done so we
1443 # take in account options added by late-loading conftest files.
1444 try:
1445 return (yield)
1446 finally:
1447 self._validate_config_options()
1448
1449 def _checkversion(self) -> None:
1450 import pytest
1451
1452 minver = self.getini("minversion")
1453 if minver:
1454 # Imported lazily to improve start-up time.
1455 from packaging.version import Version
1456
1457 if Version(minver) > Version(pytest.__version__):
1458 raise pytest.UsageError(
1459 f"{self.inipath}: 'minversion' requires pytest-{minver}, actual pytest-{pytest.__version__}'"
1460 )
1461
1462 def _validate_config_options(self) -> None:
1463 for key in sorted(self._get_unknown_ini_keys()):
1464 self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")
1465
1466 def _validate_plugins(self) -> None:
1467 required_plugins = sorted(self.getini("required_plugins"))
1468 if not required_plugins:
1469 return
1470
1471 # Imported lazily to improve start-up time.
1472 from packaging.requirements import InvalidRequirement
1473 from packaging.requirements import Requirement
1474 from packaging.version import Version
1475
1476 plugin_info = self.pluginmanager.list_plugin_distinfo()
1477 plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info}
1478
1479 missing_plugins = []
1480 for required_plugin in required_plugins:
1481 try:
1482 req = Requirement(required_plugin)
1483 except InvalidRequirement:
1484 missing_plugins.append(required_plugin)
1485 continue
1486
1487 if req.name not in plugin_dist_info:
1488 missing_plugins.append(required_plugin)
1489 elif not req.specifier.contains(
1490 Version(plugin_dist_info[req.name]), prereleases=True
1491 ):
1492 missing_plugins.append(required_plugin)
1493
1494 if missing_plugins:
1495 raise UsageError(
1496 "Missing required plugins: {}".format(", ".join(missing_plugins)),
1497 )
1498
1499 def _warn_or_fail_if_strict(self, message: str) -> None:
1500 strict_config = self.getini("strict_config")
1501 if strict_config is None:
1502 strict_config = self.getini("strict")
1503 if strict_config:
1504 raise UsageError(message)
1505
1506 self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3)
1507
1508 def _get_unknown_ini_keys(self) -> set[str]:
1509 known_keys = self._parser._inidict.keys() | self._parser._ini_aliases.keys()
1510 return self._inicfg.keys() - known_keys
1511
1512 def parse(self, args: list[str], addopts: bool = True) -> None:
1513 # Parse given cmdline arguments into this config object.
1514 assert self.args == [], (
1515 "can only parse cmdline args at most once per Config object"
1516 )
1517
1518 self.hook.pytest_addhooks.call_historic(
1519 kwargs=dict(pluginmanager=self.pluginmanager)
1520 )
1521
1522 if addopts:
1523 env_addopts = os.environ.get("PYTEST_ADDOPTS", "")
1524 if len(env_addopts):
1525 args[:] = (
1526 self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS")
1527 + args
1528 )
1529
1530 # At this point, self.option contains only defaults from the _processopt
1531 # callback.
1532 ns = self._parser.parse_known_args(args, namespace=copy.copy(self.option))
1533 rootpath, inipath, inicfg, ignored_config_files = determine_setup(
1534 inifile=ns.inifilename,
1535 override_ini=ns.override_ini,
1536 args=ns.file_or_dir,
1537 rootdir_cmd_arg=ns.rootdir or None,
1538 invocation_dir=self.invocation_params.dir,
1539 )
1540 self._rootpath = rootpath
1541 self._inipath = inipath
1542 self._ignored_config_files = ignored_config_files
1543 self._inicfg = inicfg
1544 self._parser.extra_info["rootdir"] = str(self.rootpath)
1545 self._parser.extra_info["inifile"] = str(self.inipath)
1546
1547 self._parser.addini("addopts", "Extra command line options", "args")
1548 self._parser.addini("minversion", "Minimally required pytest version")
1549 self._parser.addini(
1550 "pythonpath", type="paths", help="Add paths to sys.path", default=[]
1551 )
1552 self._parser.addini(
1553 "required_plugins",
1554 "Plugins that must be present for pytest to run",
1555 type="args",
1556 default=[],
1557 )
1558
1559 if addopts:
1560 args[:] = (
1561 self._validate_args(self.getini("addopts"), "via addopts config") + args
1562 )
1563
1564 self.known_args_namespace = self._parser.parse_known_args(
1565 args, namespace=copy.copy(self.option)
1566 )
1567 if addopts:
1568 # addopts may have added overrides (especially via OverrideIniAction).
1569 # The thing can be endlessly circular but we only do one level (#14442).
1570 if overrides := parse_override_ini(self.known_args_namespace.override_ini):
1571 self._inicfg.update(overrides)
1572 self._inicache.clear()
1573 self._checkversion()
1574 self._consider_importhook()
1575 self._configure_python_path()
1576 self.pluginmanager.consider_preparse(args, exclude_only=False)
1577 if (
1578 not os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD")
1579 and not self.known_args_namespace.disable_plugin_autoload
1580 ):
1581 # Autoloading from distribution package entry point has
1582 # not been disabled.
1583 self.pluginmanager.load_setuptools_entrypoints("pytest11")
1584 # Otherwise only plugins explicitly specified in PYTEST_PLUGINS
1585 # are going to be loaded.
1586 self.pluginmanager.consider_env()
1587
1588 # Parse again, now including options added in pytest_addoption
1589 # by third-party plugins loaded above. This way they're available
1590 # on early_config in the pytest_load_initial_conftests hook call below.
1591 self.known_args_namespace = self._parser.parse_known_args(
1592 args, namespace=copy.copy(self.option)
1593 )
1594
1595 self._validate_plugins()
1596 self._warn_about_skipped_plugins()
1597
1598 if self.known_args_namespace.confcutdir is None:
1599 if self.inipath is not None:
1600 confcutdir = str(self.inipath.parent)
1601 else:
1602 confcutdir = str(self.rootpath)
1603 self.known_args_namespace.confcutdir = confcutdir
1604 try:
1605 self.hook.pytest_load_initial_conftests(
1606 early_config=self, args=args, parser=self._parser
1607 )
1608 except ConftestImportFailure as e:
1609 if self.known_args_namespace.help or self.known_args_namespace.version:
1610 # we don't want to prevent --help/--version to work
1611 # so just let it pass and print a warning at the end
1612 self.issue_config_time_warning(
1613 PytestConfigWarning(f"could not load initial conftests: {e.path}"),
1614 stacklevel=2,
1615 )
1616 else:
1617 raise
1618
1619 try:
1620 self._parser.parse(args, namespace=self.option)
1621 except PrintHelp:
1622 return
1623
1624 self.args, self.args_source = self._decide_args(
1625 args=getattr(self.option, FILE_OR_DIR),
1626 pyargs=self.option.pyargs,
1627 testpaths=self.getini("testpaths"),
1628 invocation_dir=self.invocation_params.dir,
1629 rootpath=self.rootpath,
1630 warn=True,
1631 )
1632
1633 def issue_config_time_warning(self, warning: Warning, stacklevel: int) -> None:
1634 """Issue and handle a warning during the "configure" stage.
1635
1636 During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item``
1637 function because it is not possible to have hook wrappers around ``pytest_configure``.
1638
1639 This function is mainly intended for plugins that need to issue warnings during
1640 ``pytest_configure`` (or similar stages).
1641
1642 :param warning: The warning instance.
1643 :param stacklevel: stacklevel forwarded to warnings.warn.
1644 """
1645 if self.pluginmanager.is_blocked("warnings"):
1646 return
1647
1648 cmdline_filters = self.known_args_namespace.pythonwarnings or []
1649 config_filters = self.getini("filterwarnings")
1650
1651 with warnings.catch_warnings(record=True) as records:
1652 warnings.simplefilter("always", type(warning))
1653 apply_warning_filters(config_filters, cmdline_filters)
1654 warnings.warn(warning, stacklevel=stacklevel)
1655
1656 if records:
1657 frame = sys._getframe(stacklevel - 1)
1658 location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name
1659 self.hook.pytest_warning_recorded.call_historic(
1660 kwargs=dict(
1661 warning_message=records[0],
1662 when="config",
1663 nodeid="",
1664 location=location,
1665 )
1666 )
1667
1668 def addinivalue_line(self, name: str, line: str) -> None:
1669 """Add a line to a configuration option. The option must have been
1670 declared but might not yet be set in which case the line becomes
1671 the first line in its value."""
1672 x = self.getini(name)
1673 assert isinstance(x, list)
1674 x.append(line) # modifies the cached list inline
1675
1676 def getini(self, name: str) -> Any:
1677 """Return configuration value the an :ref:`configuration file <configfiles>`.
1678
1679 If a configuration value is not defined in a
1680 :ref:`configuration file <configfiles>`, then the ``default`` value
1681 provided while registering the configuration through
1682 :func:`parser.addini <pytest.Parser.addini>` will be returned.
1683 Please note that you can even provide ``None`` as a valid
1684 default value.
1685
1686 If ``default`` is not provided while registering using
1687 :func:`parser.addini <pytest.Parser.addini>`, then a default value
1688 based on the ``type`` parameter passed to
1689 :func:`parser.addini <pytest.Parser.addini>` will be returned.
1690 The default values based on ``type`` are:
1691 ``paths``, ``pathlist``, ``args`` and ``linelist`` : empty list ``[]``
1692 ``bool`` : ``False``
1693 ``string`` : empty string ``""``
1694 ``int`` : ``0``
1695 ``float`` : ``0.0``
1696
1697 If neither the ``default`` nor the ``type`` parameter is passed
1698 while registering the configuration through
1699 :func:`parser.addini <pytest.Parser.addini>`, then the configuration
1700 is treated as a string and a default empty string '' is returned.
1701
1702 If the specified name hasn't been registered through a prior
1703 :func:`parser.addini <pytest.Parser.addini>` call (usually from a
1704 plugin), a ValueError is raised.
1705 """
1706 canonical_name = self._parser._ini_aliases.get(name, name)
1707 try:
1708 return self._inicache[canonical_name]
1709 except KeyError:
1710 pass
1711 self._inicache[canonical_name] = val = self._getini(canonical_name)
1712 return val
1713
1714 # Meant for easy monkeypatching by legacypath plugin.
1715 # Can be inlined back (with no cover removed) once legacypath is gone.
1716 def _getini_unknown_type(self, name: str, type: str, value: object):
1717 msg = (
1718 f"Option {name} has unknown configuration type {type} with value {value!r}"
1719 )
1720 raise ValueError(msg) # pragma: no cover
1721
1722 def _getini(self, name: str):
1723 # If this is an alias, resolve to canonical name.
1724 canonical_name = self._parser._ini_aliases.get(name, name)
1725
1726 try:
1727 _description, type, default = self._parser._inidict[canonical_name]
1728 except KeyError as e:
1729 raise ValueError(f"unknown configuration value: {name!r}") from e
1730
1731 # Collect all possible values (canonical name + aliases) from _inicfg.
1732 # Each candidate is (ConfigValue, is_canonical).
1733 candidates = []
1734 if canonical_name in self._inicfg:
1735 candidates.append((self._inicfg[canonical_name], True))
1736 for alias, target in self._parser._ini_aliases.items():
1737 if target == canonical_name and alias in self._inicfg:
1738 candidates.append((self._inicfg[alias], False))
1739
1740 if not candidates:
1741 return default
1742
1743 # Pick the best candidate based on precedence:
1744 # 1. CLI override takes precedence over file, then
1745 # 2. Canonical name takes precedence over alias.
1746 selected = max(candidates, key=lambda x: (x[0].origin == "override", x[1]))[0]
1747 value = selected.value
1748 mode = selected.mode
1749
1750 if mode == "ini":
1751 # In ini mode, values are always str | list[str].
1752 assert isinstance(value, (str, list))
1753 return self._getini_ini(name, canonical_name, type, value, default)
1754 elif mode == "toml":
1755 return self._getini_toml(name, canonical_name, type, value, default)
1756 else:
1757 assert_never(mode)
1758
1759 def _getini_ini(
1760 self,
1761 name: str,
1762 canonical_name: str,
1763 type: str,
1764 value: str | list[str],
1765 default: Any,
1766 ):
1767 """Handle config values read in INI mode.
1768
1769 In INI mode, values are stored as str or list[str] only, and coerced
1770 from string based on the registered type.
1771 """
1772 # Note: some coercions are only required if we are reading from .ini
1773 # files, because the file format doesn't contain type information, but
1774 # when reading from toml (in ini mode) we will get either str or list of
1775 # str values (see load_config_dict_from_file). For example:
1776 #
1777 # ini:
1778 # a_line_list = "tests acceptance"
1779 #
1780 # in this case, we need to split the string to obtain a list of strings.
1781 #
1782 # toml (ini mode):
1783 # a_line_list = ["tests", "acceptance"]
1784 #
1785 # in this case, we already have a list ready to use.
1786 if type == "paths":
1787 dp = (
1788 self.inipath.parent
1789 if self.inipath is not None
1790 else self.invocation_params.dir
1791 )
1792 input_values = shlex.split(value) if isinstance(value, str) else value
1793 return [dp / x for x in input_values]
1794 elif type == "args":
1795 return shlex.split(value) if isinstance(value, str) else value
1796 elif type == "linelist":
1797 if isinstance(value, str):
1798 return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
1799 else:
1800 return value
1801 elif type == "bool":
1802 return _strtobool(str(value).strip())
1803 elif type == "string":
1804 return value
1805 elif type == "int":
1806 if not isinstance(value, str):
1807 raise TypeError(
1808 f"Expected an int string for option {name} of type integer, but got: {value!r}"
1809 ) from None
1810 return int(value)
1811 elif type == "float":
1812 if not isinstance(value, str):
1813 raise TypeError(
1814 f"Expected a float string for option {name} of type float, but got: {value!r}"
1815 ) from None
1816 return float(value)
1817 else:
1818 return self._getini_unknown_type(name, type, value)
1819
1820 def _getini_toml(
1821 self,
1822 name: str,
1823 canonical_name: str,
1824 type: str,
1825 value: object,
1826 default: Any,
1827 ):
1828 """Handle TOML config values with strict type validation and no coercion.
1829
1830 In TOML mode, values already have native types from TOML parsing.
1831 We validate types match expectations exactly, including list items.
1832 """
1833 value_type = builtins.type(value).__name__
1834 if type == "paths":
1835 # Expect a list of strings.
1836 if not isinstance(value, list):
1837 raise TypeError(
1838 f"{self.inipath}: config option '{name}' expects a list for type 'paths', "
1839 f"got {value_type}: {value!r}"
1840 )
1841 for i, item in enumerate(value):
1842 if not isinstance(item, str):
1843 item_type = builtins.type(item).__name__
1844 raise TypeError(
1845 f"{self.inipath}: config option '{name}' expects a list of strings, "
1846 f"but item at index {i} is {item_type}: {item!r}"
1847 )
1848 dp = (
1849 self.inipath.parent
1850 if self.inipath is not None
1851 else self.invocation_params.dir
1852 )
1853 return [dp / x for x in value]
1854 elif type in {"args", "linelist"}:
1855 # Expect a list of strings.
1856 if not isinstance(value, list):
1857 raise TypeError(
1858 f"{self.inipath}: config option '{name}' expects a list for type '{type}', "
1859 f"got {value_type}: {value!r}"
1860 )
1861 for i, item in enumerate(value):
1862 if not isinstance(item, str):
1863 item_type = builtins.type(item).__name__
1864 raise TypeError(
1865 f"{self.inipath}: config option '{name}' expects a list of strings, "
1866 f"but item at index {i} is {item_type}: {item!r}"
1867 )
1868 return list(value)
1869 elif type == "bool":
1870 # Expect a boolean.
1871 if not isinstance(value, bool):
1872 raise TypeError(
1873 f"{self.inipath}: config option '{name}' expects a bool, "
1874 f"got {value_type}: {value!r}"
1875 )
1876 return value
1877 elif type == "int":
1878 # Expect an integer (but not bool, which is a subclass of int).
1879 if not isinstance(value, int) or isinstance(value, bool):
1880 raise TypeError(
1881 f"{self.inipath}: config option '{name}' expects an int, "
1882 f"got {value_type}: {value!r}"
1883 )
1884 return value
1885 elif type == "float":
1886 # Expect a float or integer only.
1887 if not isinstance(value, (float, int)) or isinstance(value, bool):
1888 raise TypeError(
1889 f"{self.inipath}: config option '{name}' expects a float, "
1890 f"got {value_type}: {value!r}"
1891 )
1892 return value
1893 elif type == "string":
1894 # Expect a string.
1895 if not isinstance(value, str):
1896 raise TypeError(
1897 f"{self.inipath}: config option '{name}' expects a string, "
1898 f"got {value_type}: {value!r}"
1899 )
1900 return value
1901 else:
1902 return self._getini_unknown_type(name, type, value)
1903
1904 def _getconftest_pathlist(
1905 self, name: str, path: pathlib.Path
1906 ) -> list[pathlib.Path] | None:
1907 try:
1908 mod, relroots = self.pluginmanager._rget_with_confmod(name, path)
1909 except KeyError:
1910 return None
1911 assert mod.__file__ is not None
1912 modpath = pathlib.Path(mod.__file__).parent
1913 values: list[pathlib.Path] = []
1914 for relroot in relroots:
1915 if isinstance(relroot, os.PathLike):
1916 relroot = pathlib.Path(relroot)
1917 else:
1918 relroot = relroot.replace("/", os.sep)
1919 relroot = absolutepath(modpath / relroot)
1920 values.append(relroot)
1921 return values
1922
1923 def getoption(self, name: str, default: Any = NOTSET, skip: bool = False):
1924 """Return command line option value.
1925
1926 :param name: Name of the option. You may also specify
1927 the literal ``--OPT`` option instead of the "dest" option name.
1928 :param default: Fallback value if no option of that name is **declared** via :hook:`pytest_addoption`.
1929 Note this parameter will be ignored when the option is **declared** even if the option's value is ``None``.
1930 :param skip: If ``True``, raise :func:`pytest.skip` if option is undeclared or has a ``None`` value.
1931 Note that even if ``True``, if a default was specified it will be returned instead of a skip.
1932 """
1933 name = self._parser._opt2dest.get(name, name)
1934 try:
1935 val = getattr(self.option, name)
1936 if val is None and skip:
1937 raise AttributeError(name)
1938 return val
1939 except AttributeError as e:
1940 if default is not NOTSET:
1941 return default
1942 if skip:
1943 import pytest
1944
1945 pytest.skip(f"no {name!r} option found")
1946 raise ValueError(f"no option named {name!r}") from e
1947
1948 def getvalue(self, name: str, path=None):
1949 """Deprecated, use getoption() instead."""
1950 return self.getoption(name)
1951
1952 def getvalueorskip(self, name: str, path=None):
1953 """Deprecated, use getoption(skip=True) instead."""
1954 return self.getoption(name, skip=True)
1955
1956 #: Verbosity type for failed assertions (see :confval:`verbosity_assertions`).
1957 VERBOSITY_ASSERTIONS: Final = "assertions"
1958 #: Verbosity type for test case execution (see :confval:`verbosity_test_cases`).
1959 VERBOSITY_TEST_CASES: Final = "test_cases"
1960 #: Verbosity type for failed subtests (see :confval:`verbosity_subtests`).
1961 VERBOSITY_SUBTESTS: Final = "subtests"
1962
1963 _VERBOSITY_INI_DEFAULT: Final = "auto"
1964
1965 def get_verbosity(self, verbosity_type: str | None = None) -> int:
1966 r"""Retrieve the verbosity level for a fine-grained verbosity type.
1967
1968 :param verbosity_type: Verbosity type to get level for. If a level is
1969 configured for the given type, that value will be returned. If the
1970 given type is not a known verbosity type, the global verbosity
1971 level will be returned. If the given type is None (default), the
1972 global verbosity level will be returned.
1973
1974 To configure a level for a fine-grained verbosity type, the
1975 configuration file should have a setting for the configuration name
1976 and a numeric value for the verbosity level. A special value of "auto"
1977 can be used to explicitly use the global verbosity level.
1978
1979 Example:
1980
1981 .. tab:: toml
1982
1983 .. code-block:: toml
1984
1985 [tool.pytest]
1986 verbosity_assertions = 2
1987
1988 .. tab:: ini
1989
1990 .. code-block:: ini
1991
1992 [pytest]
1993 verbosity_assertions = 2
1994
1995 .. code-block:: console
1996
1997 pytest -v
1998
1999 .. code-block:: python
2000
2001 print(config.get_verbosity()) # 1
2002 print(config.get_verbosity(Config.VERBOSITY_ASSERTIONS)) # 2
2003 """
2004 global_level = self.getoption("verbose", default=0)
2005 assert isinstance(global_level, int)
2006 if verbosity_type is None:
2007 return global_level
2008
2009 ini_name = Config._verbosity_ini_name(verbosity_type)
2010 if ini_name not in self._parser._inidict:
2011 return global_level
2012
2013 level = self.getini(ini_name)
2014 if level == Config._VERBOSITY_INI_DEFAULT:
2015 return global_level
2016
2017 return int(level)
2018
2019 @staticmethod
2020 def _verbosity_ini_name(verbosity_type: str) -> str:
2021 return f"verbosity_{verbosity_type}"
2022
2023 @staticmethod
2024 def _add_verbosity_ini(parser: Parser, verbosity_type: str, help: str) -> None:
2025 """Add a output verbosity configuration option for the given output type.
2026
2027 :param parser: Parser for command line arguments and config-file values.
2028 :param verbosity_type: Fine-grained verbosity category.
2029 :param help: Description of the output this type controls.
2030
2031 The value should be retrieved via a call to
2032 :py:func:`config.get_verbosity(type) <pytest.Config.get_verbosity>`.
2033 """
2034 parser.addini(
2035 Config._verbosity_ini_name(verbosity_type),
2036 help=help,
2037 type="string",
2038 default=Config._VERBOSITY_INI_DEFAULT,
2039 )
2040
2041 def _warn_about_missing_assertion(self, mode: str) -> None:
2042 if not _assertion_supported():
2043 if mode == "plain":
2044 warning_text = (
2045 "ASSERTIONS ARE NOT EXECUTED"
2046 " and FAILING TESTS WILL PASS. Are you"
2047 " using python -O?"
2048 )
2049 else:
2050 warning_text = (
2051 "assertions not in test modules or"
2052 " plugins will be ignored"
2053 " because assert statements are not executed "
2054 "by the underlying Python interpreter "
2055 "(are you using python -O?)\n"
2056 )
2057 self.issue_config_time_warning(
2058 PytestConfigWarning(warning_text),
2059 stacklevel=3,
2060 )
2061
2062 def _warn_about_skipped_plugins(self) -> None:
2063 for module_name, msg in self.pluginmanager.skipped_plugins:
2064 self.issue_config_time_warning(
2065 PytestConfigWarning(f"skipped plugin {module_name!r}: {msg}"),
2066 stacklevel=2,
2067 )
2068
2069
2070 def _assertion_supported() -> bool:
2071 try:
2072 assert False
2073 except AssertionError:
2074 return True
2075 else:
2076 return False # type: ignore[unreachable]
2077
2078
2079 def create_terminal_writer(
2080 config: Config, file: TextIO | None = None
2081 ) -> TerminalWriter:
2082 """Create a TerminalWriter instance configured according to the options
2083 in the config object.
2084
2085 Every code which requires a TerminalWriter object and has access to a
2086 config object should use this function.
2087 """
2088 tw = TerminalWriter(file=file)
2089
2090 if config.option.color == "yes":
2091 tw.hasmarkup = True
2092 elif config.option.color == "no":
2093 tw.hasmarkup = False
2094
2095 if config.option.code_highlight == "yes":
2096 tw.code_highlight = True
2097 elif config.option.code_highlight == "no":
2098 tw.code_highlight = False
2099
2100 return tw
2101
2102
2103 def _strtobool(val: str) -> bool:
2104 """Convert a string representation of truth to True or False.
2105
2106 True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
2107 are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
2108 'val' is anything else.
2109
2110 .. note:: Copied from distutils.util.
2111 """
2112 val = val.lower()
2113 if val in ("y", "yes", "t", "true", "on", "1"):
2114 return True
2115 elif val in ("n", "no", "f", "false", "off", "0"):
2116 return False
2117 else:
2118 raise ValueError(f"invalid truth value {val!r}")
2119
2120
2121 @lru_cache(maxsize=50)
2122 def parse_warning_filter(
2123 arg: str, *, escape: bool
2124 ) -> tuple[warnings._ActionKind, str, type[Warning], str, int]:
2125 """Parse a warnings filter string.
2126
2127 This is copied from warnings._setoption with the following changes:
2128
2129 * Does not apply the filter.
2130 * Escaping is optional.
2131 * Raises UsageError so we get nice error messages on failure.
2132 """
2133 __tracebackhide__ = True
2134 error_template = dedent(
2135 f"""\
2136 while parsing the following warning configuration:
2137
2138 {arg}
2139
2140 This error occurred:
2141
2142 {{error}}
2143 """
2144 )
2145
2146 parts = arg.split(":")
2147 if len(parts) > 5:
2148 doc_url = (
2149 "https://docs.python.org/3/library/warnings.html#describing-warning-filters"
2150 )
2151 error = dedent(
2152 f"""\
2153 Too many fields ({len(parts)}), expected at most 5 separated by colons:
2154
2155 action:message:category:module:line
2156
2157 For more information please consult: {doc_url}
2158 """
2159 )
2160 raise UsageError(error_template.format(error=error))
2161
2162 while len(parts) < 5:
2163 parts.append("")
2164 action_, message, category_, module, lineno_ = (s.strip() for s in parts)
2165 try:
2166 action: warnings._ActionKind = warnings._getaction(action_) # type: ignore[attr-defined]
2167 except warnings._OptionError as e:
2168 raise UsageError(error_template.format(error=str(e))) from None
2169 try:
2170 category: type[Warning] = _resolve_warning_category(category_)
2171 except ImportError:
2172 raise
2173 except Exception:
2174 exc_info = ExceptionInfo.from_current()
2175 exception_text = exc_info.getrepr(style="native")
2176 raise UsageError(error_template.format(error=exception_text)) from None
2177 if message and escape:
2178 message = re.escape(message)
2179 if module and escape:
2180 module = re.escape(module) + r"\Z"
2181 if lineno_:
2182 try:
2183 lineno = int(lineno_)
2184 if lineno < 0:
2185 raise ValueError("number is negative")
2186 except ValueError as e:
2187 raise UsageError(
2188 error_template.format(error=f"invalid lineno {lineno_!r}: {e}")
2189 ) from None
2190 else:
2191 lineno = 0
2192 try:
2193 re.compile(message)
2194 re.compile(module)
2195 except re.error as e:
2196 raise UsageError(
2197 error_template.format(error=f"Invalid regex {e.pattern!r}: {e}")
2198 ) from None
2199 return action, message, category, module, lineno
2200
2201
2202 def _resolve_warning_category(category: str) -> type[Warning]:
2203 """
2204 Copied from warnings._getcategory, but changed so it lets exceptions (specially ImportErrors)
2205 propagate so we can get access to their tracebacks (#9218).
2206 """
2207 __tracebackhide__ = True
2208 if not category:
2209 return Warning
2210
2211 if "." not in category:
2212 import builtins as m
2213
2214 klass = category
2215 else:
2216 module, _, klass = category.rpartition(".")
2217 m = importlib.import_module(module)
2218 cat = getattr(m, klass)
2219 if not issubclass(cat, Warning):
2220 raise UsageError(f"{cat} is not a Warning subclass")
2221 return cast(type[Warning], cat)
2222
2223
2224 def apply_warning_filters(
2225 config_filters: Iterable[str], cmdline_filters: Iterable[str]
2226 ) -> None:
2227 """Applies pytest-configured filters to the warnings module"""
2228 # Filters should have this precedence: cmdline options, config.
2229 # Filters should be applied in the inverse order of precedence.
2230 for arg in config_filters:
2231 try:
2232 warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
2233 except ImportError as e:
2234 warnings.warn(
2235 f"Failed to import filter module '{e.name}': {arg}", PytestConfigWarning
2236 )
2237 continue
2238
2239 for arg in cmdline_filters:
2240 try:
2241 warnings.filterwarnings(*parse_warning_filter(arg, escape=True))
2242 except ImportError as e:
2243 warnings.warn(
2244 f"Failed to import filter module '{e.name}': {arg}", PytestConfigWarning
2245 )
2246 continue