You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1607 lines
56KB

  1. """Command line options, ini-file and conftest.py processing."""
  2. import argparse
  3. import collections.abc
  4. import contextlib
  5. import copy
  6. import enum
  7. import inspect
  8. import os
  9. import re
  10. import shlex
  11. import sys
  12. import types
  13. import warnings
  14. from functools import lru_cache
  15. from pathlib import Path
  16. from types import TracebackType
  17. from typing import Any
  18. from typing import Callable
  19. from typing import Dict
  20. from typing import Generator
  21. from typing import IO
  22. from typing import Iterable
  23. from typing import Iterator
  24. from typing import List
  25. from typing import Optional
  26. from typing import Sequence
  27. from typing import Set
  28. from typing import TextIO
  29. from typing import Tuple
  30. from typing import Type
  31. from typing import TYPE_CHECKING
  32. from typing import Union
  33. import attr
  34. import py
  35. from pluggy import HookimplMarker
  36. from pluggy import HookspecMarker
  37. from pluggy import PluginManager
  38. import _pytest._code
  39. import _pytest.deprecated
  40. import _pytest.hookspec
  41. from .exceptions import PrintHelp as PrintHelp
  42. from .exceptions import UsageError as UsageError
  43. from .findpaths import determine_setup
  44. from _pytest._code import ExceptionInfo
  45. from _pytest._code import filter_traceback
  46. from _pytest._io import TerminalWriter
  47. from _pytest.compat import final
  48. from _pytest.compat import importlib_metadata
  49. from _pytest.outcomes import fail
  50. from _pytest.outcomes import Skipped
  51. from _pytest.pathlib import bestrelpath
  52. from _pytest.pathlib import import_path
  53. from _pytest.pathlib import ImportMode
  54. from _pytest.store import Store
  55. from _pytest.warning_types import PytestConfigWarning
  56. if TYPE_CHECKING:
  57. from _pytest._code.code import _TracebackStyle
  58. from _pytest.terminal import TerminalReporter
  59. from .argparsing import Argument
  60. _PluggyPlugin = object
  61. """A type to represent plugin objects.
  62. Plugins can be any namespace, so we can't narrow it down much, but we use an
  63. alias to make the intent clear.
  64. Ideally this type would be provided by pluggy itself.
  65. """
  66. hookimpl = HookimplMarker("pytest")
  67. hookspec = HookspecMarker("pytest")
  68. @final
  69. class ExitCode(enum.IntEnum):
  70. """Encodes the valid exit codes by pytest.
  71. Currently users and plugins may supply other exit codes as well.
  72. .. versionadded:: 5.0
  73. """
  74. #: Tests passed.
  75. OK = 0
  76. #: Tests failed.
  77. TESTS_FAILED = 1
  78. #: pytest was interrupted.
  79. INTERRUPTED = 2
  80. #: An internal error got in the way.
  81. INTERNAL_ERROR = 3
  82. #: pytest was misused.
  83. USAGE_ERROR = 4
  84. #: pytest couldn't find tests.
  85. NO_TESTS_COLLECTED = 5
  86. class ConftestImportFailure(Exception):
  87. def __init__(
  88. self,
  89. path: py.path.local,
  90. excinfo: Tuple[Type[Exception], Exception, TracebackType],
  91. ) -> None:
  92. super().__init__(path, excinfo)
  93. self.path = path
  94. self.excinfo = excinfo
  95. def __str__(self) -> str:
  96. return "{}: {} (from {})".format(
  97. self.excinfo[0].__name__, self.excinfo[1], self.path
  98. )
  99. def filter_traceback_for_conftest_import_failure(
  100. entry: _pytest._code.TracebackEntry,
  101. ) -> bool:
  102. """Filter tracebacks entries which point to pytest internals or importlib.
  103. Make a special case for importlib because we use it to import test modules and conftest files
  104. in _pytest.pathlib.import_path.
  105. """
  106. return filter_traceback(entry) and "importlib" not in str(entry.path).split(os.sep)
  107. def main(
  108. args: Optional[Union[List[str], py.path.local]] = None,
  109. plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None,
  110. ) -> Union[int, ExitCode]:
  111. """Perform an in-process test run.
  112. :param args: List of command line arguments.
  113. :param plugins: List of plugin objects to be auto-registered during initialization.
  114. :returns: An exit code.
  115. """
  116. try:
  117. try:
  118. config = _prepareconfig(args, plugins)
  119. except ConftestImportFailure as e:
  120. exc_info = ExceptionInfo(e.excinfo)
  121. tw = TerminalWriter(sys.stderr)
  122. tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
  123. exc_info.traceback = exc_info.traceback.filter(
  124. filter_traceback_for_conftest_import_failure
  125. )
  126. exc_repr = (
  127. exc_info.getrepr(style="short", chain=False)
  128. if exc_info.traceback
  129. else exc_info.exconly()
  130. )
  131. formatted_tb = str(exc_repr)
  132. for line in formatted_tb.splitlines():
  133. tw.line(line.rstrip(), red=True)
  134. return ExitCode.USAGE_ERROR
  135. else:
  136. try:
  137. ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
  138. config=config
  139. )
  140. try:
  141. return ExitCode(ret)
  142. except ValueError:
  143. return ret
  144. finally:
  145. config._ensure_unconfigure()
  146. except UsageError as e:
  147. tw = TerminalWriter(sys.stderr)
  148. for msg in e.args:
  149. tw.line(f"ERROR: {msg}\n", red=True)
  150. return ExitCode.USAGE_ERROR
  151. def console_main() -> int:
  152. """The CLI entry point of pytest.
  153. This function is not meant for programmable use; use `main()` instead.
  154. """
  155. # https://docs.python.org/3/library/signal.html#note-on-sigpipe
  156. try:
  157. code = main()
  158. sys.stdout.flush()
  159. return code
  160. except BrokenPipeError:
  161. # Python flushes standard streams on exit; redirect remaining output
  162. # to devnull to avoid another BrokenPipeError at shutdown
  163. devnull = os.open(os.devnull, os.O_WRONLY)
  164. os.dup2(devnull, sys.stdout.fileno())
  165. return 1 # Python exits with error code 1 on EPIPE
  166. class cmdline: # compatibility namespace
  167. main = staticmethod(main)
  168. def filename_arg(path: str, optname: str) -> str:
  169. """Argparse type validator for filename arguments.
  170. :path: Path of filename.
  171. :optname: Name of the option.
  172. """
  173. if os.path.isdir(path):
  174. raise UsageError(f"{optname} must be a filename, given: {path}")
  175. return path
  176. def directory_arg(path: str, optname: str) -> str:
  177. """Argparse type validator for directory arguments.
  178. :path: Path of directory.
  179. :optname: Name of the option.
  180. """
  181. if not os.path.isdir(path):
  182. raise UsageError(f"{optname} must be a directory, given: {path}")
  183. return path
  184. # Plugins that cannot be disabled via "-p no:X" currently.
  185. essential_plugins = (
  186. "mark",
  187. "main",
  188. "runner",
  189. "fixtures",
  190. "helpconfig", # Provides -p.
  191. )
  192. default_plugins = essential_plugins + (
  193. "python",
  194. "terminal",
  195. "debugging",
  196. "unittest",
  197. "capture",
  198. "skipping",
  199. "tmpdir",
  200. "monkeypatch",
  201. "recwarn",
  202. "pastebin",
  203. "nose",
  204. "assertion",
  205. "junitxml",
  206. "doctest",
  207. "cacheprovider",
  208. "freeze_support",
  209. "setuponly",
  210. "setupplan",
  211. "stepwise",
  212. "warnings",
  213. "logging",
  214. "reports",
  215. *(["unraisableexception", "threadexception"] if sys.version_info >= (3, 8) else []),
  216. "faulthandler",
  217. )
  218. builtin_plugins = set(default_plugins)
  219. builtin_plugins.add("pytester")
  220. builtin_plugins.add("pytester_assertions")
  221. def get_config(
  222. args: Optional[List[str]] = None,
  223. plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None,
  224. ) -> "Config":
  225. # subsequent calls to main will create a fresh instance
  226. pluginmanager = PytestPluginManager()
  227. config = Config(
  228. pluginmanager,
  229. invocation_params=Config.InvocationParams(
  230. args=args or (), plugins=plugins, dir=Path.cwd(),
  231. ),
  232. )
  233. if args is not None:
  234. # Handle any "-p no:plugin" args.
  235. pluginmanager.consider_preparse(args, exclude_only=True)
  236. for spec in default_plugins:
  237. pluginmanager.import_plugin(spec)
  238. return config
  239. def get_plugin_manager() -> "PytestPluginManager":
  240. """Obtain a new instance of the
  241. :py:class:`_pytest.config.PytestPluginManager`, with default plugins
  242. already loaded.
  243. This function can be used by integration with other tools, like hooking
  244. into pytest to run tests into an IDE.
  245. """
  246. return get_config().pluginmanager
  247. def _prepareconfig(
  248. args: Optional[Union[py.path.local, List[str]]] = None,
  249. plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] = None,
  250. ) -> "Config":
  251. if args is None:
  252. args = sys.argv[1:]
  253. elif isinstance(args, py.path.local):
  254. args = [str(args)]
  255. elif not isinstance(args, list):
  256. msg = "`args` parameter expected to be a list of strings, got: {!r} (type: {})"
  257. raise TypeError(msg.format(args, type(args)))
  258. config = get_config(args, plugins)
  259. pluginmanager = config.pluginmanager
  260. try:
  261. if plugins:
  262. for plugin in plugins:
  263. if isinstance(plugin, str):
  264. pluginmanager.consider_pluginarg(plugin)
  265. else:
  266. pluginmanager.register(plugin)
  267. config = pluginmanager.hook.pytest_cmdline_parse(
  268. pluginmanager=pluginmanager, args=args
  269. )
  270. return config
  271. except BaseException:
  272. config._ensure_unconfigure()
  273. raise
  274. @final
  275. class PytestPluginManager(PluginManager):
  276. """A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with
  277. additional pytest-specific functionality:
  278. * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and
  279. ``pytest_plugins`` global variables found in plugins being loaded.
  280. * ``conftest.py`` loading during start-up.
  281. """
  282. def __init__(self) -> None:
  283. import _pytest.assertion
  284. super().__init__("pytest")
  285. # The objects are module objects, only used generically.
  286. self._conftest_plugins: Set[types.ModuleType] = set()
  287. # State related to local conftest plugins.
  288. self._dirpath2confmods: Dict[py.path.local, List[types.ModuleType]] = {}
  289. self._conftestpath2mod: Dict[Path, types.ModuleType] = {}
  290. self._confcutdir: Optional[py.path.local] = None
  291. self._noconftest = False
  292. self._duplicatepaths: Set[py.path.local] = set()
  293. # plugins that were explicitly skipped with pytest.skip
  294. # list of (module name, skip reason)
  295. # previously we would issue a warning when a plugin was skipped, but
  296. # since we refactored warnings as first citizens of Config, they are
  297. # just stored here to be used later.
  298. self.skipped_plugins: List[Tuple[str, str]] = []
  299. self.add_hookspecs(_pytest.hookspec)
  300. self.register(self)
  301. if os.environ.get("PYTEST_DEBUG"):
  302. err: IO[str] = sys.stderr
  303. encoding: str = getattr(err, "encoding", "utf8")
  304. try:
  305. err = open(
  306. os.dup(err.fileno()), mode=err.mode, buffering=1, encoding=encoding,
  307. )
  308. except Exception:
  309. pass
  310. self.trace.root.setwriter(err.write)
  311. self.enable_tracing()
  312. # Config._consider_importhook will set a real object if required.
  313. self.rewrite_hook = _pytest.assertion.DummyRewriteHook()
  314. # Used to know when we are importing conftests after the pytest_configure stage.
  315. self._configured = False
  316. def parse_hookimpl_opts(self, plugin: _PluggyPlugin, name: str):
  317. # pytest hooks are always prefixed with "pytest_",
  318. # so we avoid accessing possibly non-readable attributes
  319. # (see issue #1073).
  320. if not name.startswith("pytest_"):
  321. return
  322. # Ignore names which can not be hooks.
  323. if name == "pytest_plugins":
  324. return
  325. method = getattr(plugin, name)
  326. opts = super().parse_hookimpl_opts(plugin, name)
  327. # Consider only actual functions for hooks (#3775).
  328. if not inspect.isroutine(method):
  329. return
  330. # Collect unmarked hooks as long as they have the `pytest_' prefix.
  331. if opts is None and name.startswith("pytest_"):
  332. opts = {}
  333. if opts is not None:
  334. # TODO: DeprecationWarning, people should use hookimpl
  335. # https://github.com/pytest-dev/pytest/issues/4562
  336. known_marks = {m.name for m in getattr(method, "pytestmark", [])}
  337. for name in ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
  338. opts.setdefault(name, hasattr(method, name) or name in known_marks)
  339. return opts
  340. def parse_hookspec_opts(self, module_or_class, name: str):
  341. opts = super().parse_hookspec_opts(module_or_class, name)
  342. if opts is None:
  343. method = getattr(module_or_class, name)
  344. if name.startswith("pytest_"):
  345. # todo: deprecate hookspec hacks
  346. # https://github.com/pytest-dev/pytest/issues/4562
  347. known_marks = {m.name for m in getattr(method, "pytestmark", [])}
  348. opts = {
  349. "firstresult": hasattr(method, "firstresult")
  350. or "firstresult" in known_marks,
  351. "historic": hasattr(method, "historic")
  352. or "historic" in known_marks,
  353. }
  354. return opts
  355. def register(
  356. self, plugin: _PluggyPlugin, name: Optional[str] = None
  357. ) -> Optional[str]:
  358. if name in _pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS:
  359. warnings.warn(
  360. PytestConfigWarning(
  361. "{} plugin has been merged into the core, "
  362. "please remove it from your requirements.".format(
  363. name.replace("_", "-")
  364. )
  365. )
  366. )
  367. return None
  368. ret: Optional[str] = super().register(plugin, name)
  369. if ret:
  370. self.hook.pytest_plugin_registered.call_historic(
  371. kwargs=dict(plugin=plugin, manager=self)
  372. )
  373. if isinstance(plugin, types.ModuleType):
  374. self.consider_module(plugin)
  375. return ret
  376. def getplugin(self, name: str):
  377. # Support deprecated naming because plugins (xdist e.g.) use it.
  378. plugin: Optional[_PluggyPlugin] = self.get_plugin(name)
  379. return plugin
  380. def hasplugin(self, name: str) -> bool:
  381. """Return whether a plugin with the given name is registered."""
  382. return bool(self.get_plugin(name))
  383. def pytest_configure(self, config: "Config") -> None:
  384. """:meta private:"""
  385. # XXX now that the pluginmanager exposes hookimpl(tryfirst...)
  386. # we should remove tryfirst/trylast as markers.
  387. config.addinivalue_line(
  388. "markers",
  389. "tryfirst: mark a hook implementation function such that the "
  390. "plugin machinery will try to call it first/as early as possible.",
  391. )
  392. config.addinivalue_line(
  393. "markers",
  394. "trylast: mark a hook implementation function such that the "
  395. "plugin machinery will try to call it last/as late as possible.",
  396. )
  397. self._configured = True
  398. #
  399. # Internal API for local conftest plugin handling.
  400. #
  401. def _set_initial_conftests(self, namespace: argparse.Namespace) -> None:
  402. """Load initial conftest files given a preparsed "namespace".
  403. As conftest files may add their own command line options which have
  404. arguments ('--my-opt somepath') we might get some false positives.
  405. All builtin and 3rd party plugins will have been loaded, however, so
  406. common options will not confuse our logic here.
  407. """
  408. current = py.path.local()
  409. self._confcutdir = (
  410. current.join(namespace.confcutdir, abs=True)
  411. if namespace.confcutdir
  412. else None
  413. )
  414. self._noconftest = namespace.noconftest
  415. self._using_pyargs = namespace.pyargs
  416. testpaths = namespace.file_or_dir
  417. foundanchor = False
  418. for testpath in testpaths:
  419. path = str(testpath)
  420. # remove node-id syntax
  421. i = path.find("::")
  422. if i != -1:
  423. path = path[:i]
  424. anchor = current.join(path, abs=1)
  425. if anchor.exists(): # we found some file object
  426. self._try_load_conftest(anchor, namespace.importmode)
  427. foundanchor = True
  428. if not foundanchor:
  429. self._try_load_conftest(current, namespace.importmode)
  430. def _try_load_conftest(
  431. self, anchor: py.path.local, importmode: Union[str, ImportMode]
  432. ) -> None:
  433. self._getconftestmodules(anchor, importmode)
  434. # let's also consider test* subdirs
  435. if anchor.check(dir=1):
  436. for x in anchor.listdir("test*"):
  437. if x.check(dir=1):
  438. self._getconftestmodules(x, importmode)
  439. @lru_cache(maxsize=128)
  440. def _getconftestmodules(
  441. self, path: py.path.local, importmode: Union[str, ImportMode],
  442. ) -> List[types.ModuleType]:
  443. if self._noconftest:
  444. return []
  445. if path.isfile():
  446. directory = path.dirpath()
  447. else:
  448. directory = path
  449. # XXX these days we may rather want to use config.rootpath
  450. # and allow users to opt into looking into the rootdir parent
  451. # directories instead of requiring to specify confcutdir.
  452. clist = []
  453. for parent in directory.parts():
  454. if self._confcutdir and self._confcutdir.relto(parent):
  455. continue
  456. conftestpath = parent.join("conftest.py")
  457. if conftestpath.isfile():
  458. mod = self._importconftest(conftestpath, importmode)
  459. clist.append(mod)
  460. self._dirpath2confmods[directory] = clist
  461. return clist
  462. def _rget_with_confmod(
  463. self, name: str, path: py.path.local, importmode: Union[str, ImportMode],
  464. ) -> Tuple[types.ModuleType, Any]:
  465. modules = self._getconftestmodules(path, importmode)
  466. for mod in reversed(modules):
  467. try:
  468. return mod, getattr(mod, name)
  469. except AttributeError:
  470. continue
  471. raise KeyError(name)
  472. def _importconftest(
  473. self, conftestpath: py.path.local, importmode: Union[str, ImportMode],
  474. ) -> types.ModuleType:
  475. # Use a resolved Path object as key to avoid loading the same conftest
  476. # twice with build systems that create build directories containing
  477. # symlinks to actual files.
  478. # Using Path().resolve() is better than py.path.realpath because
  479. # it resolves to the correct path/drive in case-insensitive file systems (#5792)
  480. key = Path(str(conftestpath)).resolve()
  481. with contextlib.suppress(KeyError):
  482. return self._conftestpath2mod[key]
  483. pkgpath = conftestpath.pypkgpath()
  484. if pkgpath is None:
  485. _ensure_removed_sysmodule(conftestpath.purebasename)
  486. try:
  487. mod = import_path(conftestpath, mode=importmode)
  488. except Exception as e:
  489. assert e.__traceback__ is not None
  490. exc_info = (type(e), e, e.__traceback__)
  491. raise ConftestImportFailure(conftestpath, exc_info) from e
  492. self._check_non_top_pytest_plugins(mod, conftestpath)
  493. self._conftest_plugins.add(mod)
  494. self._conftestpath2mod[key] = mod
  495. dirpath = conftestpath.dirpath()
  496. if dirpath in self._dirpath2confmods:
  497. for path, mods in self._dirpath2confmods.items():
  498. if path and path.relto(dirpath) or path == dirpath:
  499. assert mod not in mods
  500. mods.append(mod)
  501. self.trace(f"loading conftestmodule {mod!r}")
  502. self.consider_conftest(mod)
  503. return mod
  504. def _check_non_top_pytest_plugins(
  505. self, mod: types.ModuleType, conftestpath: py.path.local,
  506. ) -> None:
  507. if (
  508. hasattr(mod, "pytest_plugins")
  509. and self._configured
  510. and not self._using_pyargs
  511. ):
  512. msg = (
  513. "Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\n"
  514. "It affects the entire test suite instead of just below the conftest as expected.\n"
  515. " {}\n"
  516. "Please move it to a top level conftest file at the rootdir:\n"
  517. " {}\n"
  518. "For more information, visit:\n"
  519. " https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files"
  520. )
  521. fail(msg.format(conftestpath, self._confcutdir), pytrace=False)
  522. #
  523. # API for bootstrapping plugin loading
  524. #
  525. #
  526. def consider_preparse(
  527. self, args: Sequence[str], *, exclude_only: bool = False
  528. ) -> None:
  529. i = 0
  530. n = len(args)
  531. while i < n:
  532. opt = args[i]
  533. i += 1
  534. if isinstance(opt, str):
  535. if opt == "-p":
  536. try:
  537. parg = args[i]
  538. except IndexError:
  539. return
  540. i += 1
  541. elif opt.startswith("-p"):
  542. parg = opt[2:]
  543. else:
  544. continue
  545. if exclude_only and not parg.startswith("no:"):
  546. continue
  547. self.consider_pluginarg(parg)
  548. def consider_pluginarg(self, arg: str) -> None:
  549. if arg.startswith("no:"):
  550. name = arg[3:]
  551. if name in essential_plugins:
  552. raise UsageError("plugin %s cannot be disabled" % name)
  553. # PR #4304: remove stepwise if cacheprovider is blocked.
  554. if name == "cacheprovider":
  555. self.set_blocked("stepwise")
  556. self.set_blocked("pytest_stepwise")
  557. self.set_blocked(name)
  558. if not name.startswith("pytest_"):
  559. self.set_blocked("pytest_" + name)
  560. else:
  561. name = arg
  562. # Unblock the plugin. None indicates that it has been blocked.
  563. # There is no interface with pluggy for this.
  564. if self._name2plugin.get(name, -1) is None:
  565. del self._name2plugin[name]
  566. if not name.startswith("pytest_"):
  567. if self._name2plugin.get("pytest_" + name, -1) is None:
  568. del self._name2plugin["pytest_" + name]
  569. self.import_plugin(arg, consider_entry_points=True)
  570. def consider_conftest(self, conftestmodule: types.ModuleType) -> None:
  571. self.register(conftestmodule, name=conftestmodule.__file__)
  572. def consider_env(self) -> None:
  573. self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
  574. def consider_module(self, mod: types.ModuleType) -> None:
  575. self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
  576. def _import_plugin_specs(
  577. self, spec: Union[None, types.ModuleType, str, Sequence[str]]
  578. ) -> None:
  579. plugins = _get_plugin_specs_as_list(spec)
  580. for import_spec in plugins:
  581. self.import_plugin(import_spec)
  582. def import_plugin(self, modname: str, consider_entry_points: bool = False) -> None:
  583. """Import a plugin with ``modname``.
  584. If ``consider_entry_points`` is True, entry point names are also
  585. considered to find a plugin.
  586. """
  587. # Most often modname refers to builtin modules, e.g. "pytester",
  588. # "terminal" or "capture". Those plugins are registered under their
  589. # basename for historic purposes but must be imported with the
  590. # _pytest prefix.
  591. assert isinstance(modname, str), (
  592. "module name as text required, got %r" % modname
  593. )
  594. if self.is_blocked(modname) or self.get_plugin(modname) is not None:
  595. return
  596. importspec = "_pytest." + modname if modname in builtin_plugins else modname
  597. self.rewrite_hook.mark_rewrite(importspec)
  598. if consider_entry_points:
  599. loaded = self.load_setuptools_entrypoints("pytest11", name=modname)
  600. if loaded:
  601. return
  602. try:
  603. __import__(importspec)
  604. except ImportError as e:
  605. raise ImportError(
  606. 'Error importing plugin "{}": {}'.format(modname, str(e.args[0]))
  607. ).with_traceback(e.__traceback__) from e
  608. except Skipped as e:
  609. self.skipped_plugins.append((modname, e.msg or ""))
  610. else:
  611. mod = sys.modules[importspec]
  612. self.register(mod, modname)
  613. def _get_plugin_specs_as_list(
  614. specs: Union[None, types.ModuleType, str, Sequence[str]]
  615. ) -> List[str]:
  616. """Parse a plugins specification into a list of plugin names."""
  617. # None means empty.
  618. if specs is None:
  619. return []
  620. # Workaround for #3899 - a submodule which happens to be called "pytest_plugins".
  621. if isinstance(specs, types.ModuleType):
  622. return []
  623. # Comma-separated list.
  624. if isinstance(specs, str):
  625. return specs.split(",") if specs else []
  626. # Direct specification.
  627. if isinstance(specs, collections.abc.Sequence):
  628. return list(specs)
  629. raise UsageError(
  630. "Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: %r"
  631. % specs
  632. )
  633. def _ensure_removed_sysmodule(modname: str) -> None:
  634. try:
  635. del sys.modules[modname]
  636. except KeyError:
  637. pass
  638. class Notset:
  639. def __repr__(self):
  640. return "<NOTSET>"
  641. notset = Notset()
  642. def _iter_rewritable_modules(package_files: Iterable[str]) -> Iterator[str]:
  643. """Given an iterable of file names in a source distribution, return the "names" that should
  644. be marked for assertion rewrite.
  645. For example the package "pytest_mock/__init__.py" should be added as "pytest_mock" in
  646. the assertion rewrite mechanism.
  647. This function has to deal with dist-info based distributions and egg based distributions
  648. (which are still very much in use for "editable" installs).
  649. Here are the file names as seen in a dist-info based distribution:
  650. pytest_mock/__init__.py
  651. pytest_mock/_version.py
  652. pytest_mock/plugin.py
  653. pytest_mock.egg-info/PKG-INFO
  654. Here are the file names as seen in an egg based distribution:
  655. src/pytest_mock/__init__.py
  656. src/pytest_mock/_version.py
  657. src/pytest_mock/plugin.py
  658. src/pytest_mock.egg-info/PKG-INFO
  659. LICENSE
  660. setup.py
  661. We have to take in account those two distribution flavors in order to determine which
  662. names should be considered for assertion rewriting.
  663. More information:
  664. https://github.com/pytest-dev/pytest-mock/issues/167
  665. """
  666. package_files = list(package_files)
  667. seen_some = False
  668. for fn in package_files:
  669. is_simple_module = "/" not in fn and fn.endswith(".py")
  670. is_package = fn.count("/") == 1 and fn.endswith("__init__.py")
  671. if is_simple_module:
  672. module_name, _ = os.path.splitext(fn)
  673. # we ignore "setup.py" at the root of the distribution
  674. if module_name != "setup":
  675. seen_some = True
  676. yield module_name
  677. elif is_package:
  678. package_name = os.path.dirname(fn)
  679. seen_some = True
  680. yield package_name
  681. if not seen_some:
  682. # At this point we did not find any packages or modules suitable for assertion
  683. # rewriting, so we try again by stripping the first path component (to account for
  684. # "src" based source trees for example).
  685. # This approach lets us have the common case continue to be fast, as egg-distributions
  686. # are rarer.
  687. new_package_files = []
  688. for fn in package_files:
  689. parts = fn.split("/")
  690. new_fn = "/".join(parts[1:])
  691. if new_fn:
  692. new_package_files.append(new_fn)
  693. if new_package_files:
  694. yield from _iter_rewritable_modules(new_package_files)
  695. def _args_converter(args: Iterable[str]) -> Tuple[str, ...]:
  696. return tuple(args)
  697. @final
  698. class Config:
  699. """Access to configuration values, pluginmanager and plugin hooks.
  700. :param PytestPluginManager pluginmanager:
  701. :param InvocationParams invocation_params:
  702. Object containing parameters regarding the :func:`pytest.main`
  703. invocation.
  704. """
  705. @final
  706. @attr.s(frozen=True)
  707. class InvocationParams:
  708. """Holds parameters passed during :func:`pytest.main`.
  709. The object attributes are read-only.
  710. .. versionadded:: 5.1
  711. .. note::
  712. Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts``
  713. ini option are handled by pytest, not being included in the ``args`` attribute.
  714. Plugins accessing ``InvocationParams`` must be aware of that.
  715. """
  716. args = attr.ib(type=Tuple[str, ...], converter=_args_converter)
  717. """The command-line arguments as passed to :func:`pytest.main`.
  718. :type: Tuple[str, ...]
  719. """
  720. plugins = attr.ib(type=Optional[Sequence[Union[str, _PluggyPlugin]]])
  721. """Extra plugins, might be `None`.
  722. :type: Optional[Sequence[Union[str, plugin]]]
  723. """
  724. dir = attr.ib(type=Path)
  725. """The directory from which :func:`pytest.main` was invoked.
  726. :type: pathlib.Path
  727. """
  728. def __init__(
  729. self,
  730. pluginmanager: PytestPluginManager,
  731. *,
  732. invocation_params: Optional[InvocationParams] = None,
  733. ) -> None:
  734. from .argparsing import Parser, FILE_OR_DIR
  735. if invocation_params is None:
  736. invocation_params = self.InvocationParams(
  737. args=(), plugins=None, dir=Path.cwd()
  738. )
  739. self.option = argparse.Namespace()
  740. """Access to command line option as attributes.
  741. :type: argparse.Namespace
  742. """
  743. self.invocation_params = invocation_params
  744. """The parameters with which pytest was invoked.
  745. :type: InvocationParams
  746. """
  747. _a = FILE_OR_DIR
  748. self._parser = Parser(
  749. usage=f"%(prog)s [options] [{_a}] [{_a}] [...]",
  750. processopt=self._processopt,
  751. )
  752. self.pluginmanager = pluginmanager
  753. """The plugin manager handles plugin registration and hook invocation.
  754. :type: PytestPluginManager
  755. """
  756. self.trace = self.pluginmanager.trace.root.get("config")
  757. self.hook = self.pluginmanager.hook
  758. self._inicache: Dict[str, Any] = {}
  759. self._override_ini: Sequence[str] = ()
  760. self._opt2dest: Dict[str, str] = {}
  761. self._cleanup: List[Callable[[], None]] = []
  762. # A place where plugins can store information on the config for their
  763. # own use. Currently only intended for internal plugins.
  764. self._store = Store()
  765. self.pluginmanager.register(self, "pytestconfig")
  766. self._configured = False
  767. self.hook.pytest_addoption.call_historic(
  768. kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager)
  769. )
  770. if TYPE_CHECKING:
  771. from _pytest.cacheprovider import Cache
  772. self.cache: Optional[Cache] = None
  773. @property
  774. def invocation_dir(self) -> py.path.local:
  775. """The directory from which pytest was invoked.
  776. Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`,
  777. which is a :class:`pathlib.Path`.
  778. :type: py.path.local
  779. """
  780. return py.path.local(str(self.invocation_params.dir))
  781. @property
  782. def rootpath(self) -> Path:
  783. """The path to the :ref:`rootdir <rootdir>`.
  784. :type: pathlib.Path
  785. .. versionadded:: 6.1
  786. """
  787. return self._rootpath
  788. @property
  789. def rootdir(self) -> py.path.local:
  790. """The path to the :ref:`rootdir <rootdir>`.
  791. Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`.
  792. :type: py.path.local
  793. """
  794. return py.path.local(str(self.rootpath))
  795. @property
  796. def inipath(self) -> Optional[Path]:
  797. """The path to the :ref:`configfile <configfiles>`.
  798. :type: Optional[pathlib.Path]
  799. .. versionadded:: 6.1
  800. """
  801. return self._inipath
  802. @property
  803. def inifile(self) -> Optional[py.path.local]:
  804. """The path to the :ref:`configfile <configfiles>`.
  805. Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`.
  806. :type: Optional[py.path.local]
  807. """
  808. return py.path.local(str(self.inipath)) if self.inipath else None
  809. def add_cleanup(self, func: Callable[[], None]) -> None:
  810. """Add a function to be called when the config object gets out of
  811. use (usually coninciding with pytest_unconfigure)."""
  812. self._cleanup.append(func)
  813. def _do_configure(self) -> None:
  814. assert not self._configured
  815. self._configured = True
  816. with warnings.catch_warnings():
  817. warnings.simplefilter("default")
  818. self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
  819. def _ensure_unconfigure(self) -> None:
  820. if self._configured:
  821. self._configured = False
  822. self.hook.pytest_unconfigure(config=self)
  823. self.hook.pytest_configure._call_history = []
  824. while self._cleanup:
  825. fin = self._cleanup.pop()
  826. fin()
  827. def get_terminal_writer(self) -> TerminalWriter:
  828. terminalreporter: TerminalReporter = self.pluginmanager.get_plugin(
  829. "terminalreporter"
  830. )
  831. return terminalreporter._tw
  832. def pytest_cmdline_parse(
  833. self, pluginmanager: PytestPluginManager, args: List[str]
  834. ) -> "Config":
  835. try:
  836. self.parse(args)
  837. except UsageError:
  838. # Handle --version and --help here in a minimal fashion.
  839. # This gets done via helpconfig normally, but its
  840. # pytest_cmdline_main is not called in case of errors.
  841. if getattr(self.option, "version", False) or "--version" in args:
  842. from _pytest.helpconfig import showversion
  843. showversion(self)
  844. elif (
  845. getattr(self.option, "help", False) or "--help" in args or "-h" in args
  846. ):
  847. self._parser._getparser().print_help()
  848. sys.stdout.write(
  849. "\nNOTE: displaying only minimal help due to UsageError.\n\n"
  850. )
  851. raise
  852. return self
  853. def notify_exception(
  854. self,
  855. excinfo: ExceptionInfo[BaseException],
  856. option: Optional[argparse.Namespace] = None,
  857. ) -> None:
  858. if option and getattr(option, "fulltrace", False):
  859. style: _TracebackStyle = "long"
  860. else:
  861. style = "native"
  862. excrepr = excinfo.getrepr(
  863. funcargs=True, showlocals=getattr(option, "showlocals", False), style=style
  864. )
  865. res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
  866. if not any(res):
  867. for line in str(excrepr).split("\n"):
  868. sys.stderr.write("INTERNALERROR> %s\n" % line)
  869. sys.stderr.flush()
  870. def cwd_relative_nodeid(self, nodeid: str) -> str:
  871. # nodeid's are relative to the rootpath, compute relative to cwd.
  872. if self.invocation_params.dir != self.rootpath:
  873. fullpath = self.rootpath / nodeid
  874. nodeid = bestrelpath(self.invocation_params.dir, fullpath)
  875. return nodeid
  876. @classmethod
  877. def fromdictargs(cls, option_dict, args) -> "Config":
  878. """Constructor usable for subprocesses."""
  879. config = get_config(args)
  880. config.option.__dict__.update(option_dict)
  881. config.parse(args, addopts=False)
  882. for x in config.option.plugins:
  883. config.pluginmanager.consider_pluginarg(x)
  884. return config
  885. def _processopt(self, opt: "Argument") -> None:
  886. for name in opt._short_opts + opt._long_opts:
  887. self._opt2dest[name] = opt.dest
  888. if hasattr(opt, "default"):
  889. if not hasattr(self.option, opt.dest):
  890. setattr(self.option, opt.dest, opt.default)
  891. @hookimpl(trylast=True)
  892. def pytest_load_initial_conftests(self, early_config: "Config") -> None:
  893. self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)
  894. def _initini(self, args: Sequence[str]) -> None:
  895. ns, unknown_args = self._parser.parse_known_and_unknown_args(
  896. args, namespace=copy.copy(self.option)
  897. )
  898. rootpath, inipath, inicfg = determine_setup(
  899. ns.inifilename,
  900. ns.file_or_dir + unknown_args,
  901. rootdir_cmd_arg=ns.rootdir or None,
  902. config=self,
  903. )
  904. self._rootpath = rootpath
  905. self._inipath = inipath
  906. self.inicfg = inicfg
  907. self._parser.extra_info["rootdir"] = str(self.rootpath)
  908. self._parser.extra_info["inifile"] = str(self.inipath)
  909. self._parser.addini("addopts", "extra command line options", "args")
  910. self._parser.addini("minversion", "minimally required pytest version")
  911. self._parser.addini(
  912. "required_plugins",
  913. "plugins that must be present for pytest to run",
  914. type="args",
  915. default=[],
  916. )
  917. self._override_ini = ns.override_ini or ()
  918. def _consider_importhook(self, args: Sequence[str]) -> None:
  919. """Install the PEP 302 import hook if using assertion rewriting.
  920. Needs to parse the --assert=<mode> option from the commandline
  921. and find all the installed plugins to mark them for rewriting
  922. by the importhook.
  923. """
  924. ns, unknown_args = self._parser.parse_known_and_unknown_args(args)
  925. mode = getattr(ns, "assertmode", "plain")
  926. if mode == "rewrite":
  927. import _pytest.assertion
  928. try:
  929. hook = _pytest.assertion.install_importhook(self)
  930. except SystemError:
  931. mode = "plain"
  932. else:
  933. self._mark_plugins_for_rewrite(hook)
  934. self._warn_about_missing_assertion(mode)
  935. def _mark_plugins_for_rewrite(self, hook) -> None:
  936. """Given an importhook, mark for rewrite any top-level
  937. modules or packages in the distribution package for
  938. all pytest plugins."""
  939. self.pluginmanager.rewrite_hook = hook
  940. if os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"):
  941. # We don't autoload from setuptools entry points, no need to continue.
  942. return
  943. package_files = (
  944. str(file)
  945. for dist in importlib_metadata.distributions()
  946. if any(ep.group == "pytest11" for ep in dist.entry_points)
  947. for file in dist.files or []
  948. )
  949. for name in _iter_rewritable_modules(package_files):
  950. hook.mark_rewrite(name)
  951. def _validate_args(self, args: List[str], via: str) -> List[str]:
  952. """Validate known args."""
  953. self._parser._config_source_hint = via # type: ignore
  954. try:
  955. self._parser.parse_known_and_unknown_args(
  956. args, namespace=copy.copy(self.option)
  957. )
  958. finally:
  959. del self._parser._config_source_hint # type: ignore
  960. return args
  961. def _preparse(self, args: List[str], addopts: bool = True) -> None:
  962. if addopts:
  963. env_addopts = os.environ.get("PYTEST_ADDOPTS", "")
  964. if len(env_addopts):
  965. args[:] = (
  966. self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS")
  967. + args
  968. )
  969. self._initini(args)
  970. if addopts:
  971. args[:] = (
  972. self._validate_args(self.getini("addopts"), "via addopts config") + args
  973. )
  974. self.known_args_namespace = self._parser.parse_known_args(
  975. args, namespace=copy.copy(self.option)
  976. )
  977. self._checkversion()
  978. self._consider_importhook(args)
  979. self.pluginmanager.consider_preparse(args, exclude_only=False)
  980. if not os.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"):
  981. # Don't autoload from setuptools entry point. Only explicitly specified
  982. # plugins are going to be loaded.
  983. self.pluginmanager.load_setuptools_entrypoints("pytest11")
  984. self.pluginmanager.consider_env()
  985. self.known_args_namespace = self._parser.parse_known_args(
  986. args, namespace=copy.copy(self.known_args_namespace)
  987. )
  988. self._validate_plugins()
  989. self._warn_about_skipped_plugins()
  990. if self.known_args_namespace.strict:
  991. self.issue_config_time_warning(
  992. _pytest.deprecated.STRICT_OPTION, stacklevel=2
  993. )
  994. if self.known_args_namespace.confcutdir is None and self.inipath is not None:
  995. confcutdir = str(self.inipath.parent)
  996. self.known_args_namespace.confcutdir = confcutdir
  997. try:
  998. self.hook.pytest_load_initial_conftests(
  999. early_config=self, args=args, parser=self._parser
  1000. )
  1001. except ConftestImportFailure as e:
  1002. if self.known_args_namespace.help or self.known_args_namespace.version:
  1003. # we don't want to prevent --help/--version to work
  1004. # so just let is pass and print a warning at the end
  1005. self.issue_config_time_warning(
  1006. PytestConfigWarning(f"could not load initial conftests: {e.path}"),
  1007. stacklevel=2,
  1008. )
  1009. else:
  1010. raise
  1011. @hookimpl(hookwrapper=True)
  1012. def pytest_collection(self) -> Generator[None, None, None]:
  1013. """Validate invalid ini keys after collection is done so we take in account
  1014. options added by late-loading conftest files."""
  1015. yield
  1016. self._validate_config_options()
  1017. def _checkversion(self) -> None:
  1018. import pytest
  1019. minver = self.inicfg.get("minversion", None)
  1020. if minver:
  1021. # Imported lazily to improve start-up time.
  1022. from packaging.version import Version
  1023. if not isinstance(minver, str):
  1024. raise pytest.UsageError(
  1025. "%s: 'minversion' must be a single value" % self.inipath
  1026. )
  1027. if Version(minver) > Version(pytest.__version__):
  1028. raise pytest.UsageError(
  1029. "%s: 'minversion' requires pytest-%s, actual pytest-%s'"
  1030. % (self.inipath, minver, pytest.__version__,)
  1031. )
  1032. def _validate_config_options(self) -> None:
  1033. for key in sorted(self._get_unknown_ini_keys()):
  1034. self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")
  1035. def _validate_plugins(self) -> None:
  1036. required_plugins = sorted(self.getini("required_plugins"))
  1037. if not required_plugins:
  1038. return
  1039. # Imported lazily to improve start-up time.
  1040. from packaging.version import Version
  1041. from packaging.requirements import InvalidRequirement, Requirement
  1042. plugin_info = self.pluginmanager.list_plugin_distinfo()
  1043. plugin_dist_info = {dist.project_name: dist.version for _, dist in plugin_info}
  1044. missing_plugins = []
  1045. for required_plugin in required_plugins:
  1046. try:
  1047. spec = Requirement(required_plugin)
  1048. except InvalidRequirement:
  1049. missing_plugins.append(required_plugin)
  1050. continue
  1051. if spec.name not in plugin_dist_info:
  1052. missing_plugins.append(required_plugin)
  1053. elif Version(plugin_dist_info[spec.name]) not in spec.specifier:
  1054. missing_plugins.append(required_plugin)
  1055. if missing_plugins:
  1056. raise UsageError(
  1057. "Missing required plugins: {}".format(", ".join(missing_plugins)),
  1058. )
  1059. def _warn_or_fail_if_strict(self, message: str) -> None:
  1060. if self.known_args_namespace.strict_config:
  1061. raise UsageError(message)
  1062. self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3)
  1063. def _get_unknown_ini_keys(self) -> List[str]:
  1064. parser_inicfg = self._parser._inidict
  1065. return [name for name in self.inicfg if name not in parser_inicfg]
  1066. def parse(self, args: List[str], addopts: bool = True) -> None:
  1067. # Parse given cmdline arguments into this config object.
  1068. assert not hasattr(
  1069. self, "args"
  1070. ), "can only parse cmdline args at most once per Config object"
  1071. self.hook.pytest_addhooks.call_historic(
  1072. kwargs=dict(pluginmanager=self.pluginmanager)
  1073. )
  1074. self._preparse(args, addopts=addopts)
  1075. # XXX deprecated hook:
  1076. self.hook.pytest_cmdline_preparse(config=self, args=args)
  1077. self._parser.after_preparse = True # type: ignore
  1078. try:
  1079. args = self._parser.parse_setoption(
  1080. args, self.option, namespace=self.option
  1081. )
  1082. if not args:
  1083. if self.invocation_params.dir == self.rootpath:
  1084. args = self.getini("testpaths")
  1085. if not args:
  1086. args = [str(self.invocation_params.dir)]
  1087. self.args = args
  1088. except PrintHelp:
  1089. pass
  1090. def issue_config_time_warning(self, warning: Warning, stacklevel: int) -> None:
  1091. """Issue and handle a warning during the "configure" stage.
  1092. During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item``
  1093. function because it is not possible to have hookwrappers around ``pytest_configure``.
  1094. This function is mainly intended for plugins that need to issue warnings during
  1095. ``pytest_configure`` (or similar stages).
  1096. :param warning: The warning instance.
  1097. :param stacklevel: stacklevel forwarded to warnings.warn.
  1098. """
  1099. if self.pluginmanager.is_blocked("warnings"):
  1100. return
  1101. cmdline_filters = self.known_args_namespace.pythonwarnings or []
  1102. config_filters = self.getini("filterwarnings")
  1103. with warnings.catch_warnings(record=True) as records:
  1104. warnings.simplefilter("always", type(warning))
  1105. apply_warning_filters(config_filters, cmdline_filters)
  1106. warnings.warn(warning, stacklevel=stacklevel)
  1107. if records:
  1108. frame = sys._getframe(stacklevel - 1)
  1109. location = frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_name
  1110. self.hook.pytest_warning_captured.call_historic(
  1111. kwargs=dict(
  1112. warning_message=records[0],
  1113. when="config",
  1114. item=None,
  1115. location=location,
  1116. )
  1117. )
  1118. self.hook.pytest_warning_recorded.call_historic(
  1119. kwargs=dict(
  1120. warning_message=records[0],
  1121. when="config",
  1122. nodeid="",
  1123. location=location,
  1124. )
  1125. )
  1126. def addinivalue_line(self, name: str, line: str) -> None:
  1127. """Add a line to an ini-file option. The option must have been
  1128. declared but might not yet be set in which case the line becomes
  1129. the first line in its value."""
  1130. x = self.getini(name)
  1131. assert isinstance(x, list)
  1132. x.append(line) # modifies the cached list inline
  1133. def getini(self, name: str):
  1134. """Return configuration value from an :ref:`ini file <configfiles>`.
  1135. If the specified name hasn't been registered through a prior
  1136. :py:func:`parser.addini <_pytest.config.argparsing.Parser.addini>`
  1137. call (usually from a plugin), a ValueError is raised.
  1138. """
  1139. try:
  1140. return self._inicache[name]
  1141. except KeyError:
  1142. self._inicache[name] = val = self._getini(name)
  1143. return val
  1144. def _getini(self, name: str):
  1145. try:
  1146. description, type, default = self._parser._inidict[name]
  1147. except KeyError as e:
  1148. raise ValueError(f"unknown configuration value: {name!r}") from e
  1149. override_value = self._get_override_ini_value(name)
  1150. if override_value is None:
  1151. try:
  1152. value = self.inicfg[name]
  1153. except KeyError:
  1154. if default is not None:
  1155. return default
  1156. if type is None:
  1157. return ""
  1158. return []
  1159. else:
  1160. value = override_value
  1161. # Coerce the values based on types.
  1162. #
  1163. # Note: some coercions are only required if we are reading from .ini files, because
  1164. # the file format doesn't contain type information, but when reading from toml we will
  1165. # get either str or list of str values (see _parse_ini_config_from_pyproject_toml).
  1166. # For example:
  1167. #
  1168. # ini:
  1169. # a_line_list = "tests acceptance"
  1170. # in this case, we need to split the string to obtain a list of strings.
  1171. #
  1172. # toml:
  1173. # a_line_list = ["tests", "acceptance"]
  1174. # in this case, we already have a list ready to use.
  1175. #
  1176. if type == "pathlist":
  1177. # TODO: This assert is probably not valid in all cases.
  1178. assert self.inipath is not None
  1179. dp = self.inipath.parent
  1180. input_values = shlex.split(value) if isinstance(value, str) else value
  1181. return [py.path.local(str(dp / x)) for x in input_values]
  1182. elif type == "args":
  1183. return shlex.split(value) if isinstance(value, str) else value
  1184. elif type == "linelist":
  1185. if isinstance(value, str):
  1186. return [t for t in map(lambda x: x.strip(), value.split("\n")) if t]
  1187. else:
  1188. return value
  1189. elif type == "bool":
  1190. return _strtobool(str(value).strip())
  1191. else:
  1192. assert type in [None, "string"]
  1193. return value
  1194. def _getconftest_pathlist(
  1195. self, name: str, path: py.path.local
  1196. ) -> Optional[List[py.path.local]]:
  1197. try:
  1198. mod, relroots = self.pluginmanager._rget_with_confmod(
  1199. name, path, self.getoption("importmode")
  1200. )
  1201. except KeyError:
  1202. return None
  1203. modpath = py.path.local(mod.__file__).dirpath()
  1204. values: List[py.path.local] = []
  1205. for relroot in relroots:
  1206. if not isinstance(relroot, py.path.local):
  1207. relroot = relroot.replace("/", os.sep)
  1208. relroot = modpath.join(relroot, abs=True)
  1209. values.append(relroot)
  1210. return values
  1211. def _get_override_ini_value(self, name: str) -> Optional[str]:
  1212. value = None
  1213. # override_ini is a list of "ini=value" options.
  1214. # Always use the last item if multiple values are set for same ini-name,
  1215. # e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2.
  1216. for ini_config in self._override_ini:
  1217. try:
  1218. key, user_ini_value = ini_config.split("=", 1)
  1219. except ValueError as e:
  1220. raise UsageError(
  1221. "-o/--override-ini expects option=value style (got: {!r}).".format(
  1222. ini_config
  1223. )
  1224. ) from e
  1225. else:
  1226. if key == name:
  1227. value = user_ini_value
  1228. return value
  1229. def getoption(self, name: str, default=notset, skip: bool = False):
  1230. """Return command line option value.
  1231. :param name: Name of the option. You may also specify
  1232. the literal ``--OPT`` option instead of the "dest" option name.
  1233. :param default: Default value if no option of that name exists.
  1234. :param skip: If True, raise pytest.skip if option does not exists
  1235. or has a None value.
  1236. """
  1237. name = self._opt2dest.get(name, name)
  1238. try:
  1239. val = getattr(self.option, name)
  1240. if val is None and skip:
  1241. raise AttributeError(name)
  1242. return val
  1243. except AttributeError as e:
  1244. if default is not notset:
  1245. return default
  1246. if skip:
  1247. import pytest
  1248. pytest.skip(f"no {name!r} option found")
  1249. raise ValueError(f"no option named {name!r}") from e
  1250. def getvalue(self, name: str, path=None):
  1251. """Deprecated, use getoption() instead."""
  1252. return self.getoption(name)
  1253. def getvalueorskip(self, name: str, path=None):
  1254. """Deprecated, use getoption(skip=True) instead."""
  1255. return self.getoption(name, skip=True)
  1256. def _warn_about_missing_assertion(self, mode: str) -> None:
  1257. if not _assertion_supported():
  1258. if mode == "plain":
  1259. warning_text = (
  1260. "ASSERTIONS ARE NOT EXECUTED"
  1261. " and FAILING TESTS WILL PASS. Are you"
  1262. " using python -O?"
  1263. )
  1264. else:
  1265. warning_text = (
  1266. "assertions not in test modules or"
  1267. " plugins will be ignored"
  1268. " because assert statements are not executed "
  1269. "by the underlying Python interpreter "
  1270. "(are you using python -O?)\n"
  1271. )
  1272. self.issue_config_time_warning(
  1273. PytestConfigWarning(warning_text), stacklevel=3,
  1274. )
  1275. def _warn_about_skipped_plugins(self) -> None:
  1276. for module_name, msg in self.pluginmanager.skipped_plugins:
  1277. self.issue_config_time_warning(
  1278. PytestConfigWarning(f"skipped plugin {module_name!r}: {msg}"),
  1279. stacklevel=2,
  1280. )
  1281. def _assertion_supported() -> bool:
  1282. try:
  1283. assert False
  1284. except AssertionError:
  1285. return True
  1286. else:
  1287. return False # type: ignore[unreachable]
  1288. def create_terminal_writer(
  1289. config: Config, file: Optional[TextIO] = None
  1290. ) -> TerminalWriter:
  1291. """Create a TerminalWriter instance configured according to the options
  1292. in the config object.
  1293. Every code which requires a TerminalWriter object and has access to a
  1294. config object should use this function.
  1295. """
  1296. tw = TerminalWriter(file=file)
  1297. if config.option.color == "yes":
  1298. tw.hasmarkup = True
  1299. elif config.option.color == "no":
  1300. tw.hasmarkup = False
  1301. if config.option.code_highlight == "yes":
  1302. tw.code_highlight = True
  1303. elif config.option.code_highlight == "no":
  1304. tw.code_highlight = False
  1305. return tw
  1306. def _strtobool(val: str) -> bool:
  1307. """Convert a string representation of truth to True or False.
  1308. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
  1309. are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if
  1310. 'val' is anything else.
  1311. .. note:: Copied from distutils.util.
  1312. """
  1313. val = val.lower()
  1314. if val in ("y", "yes", "t", "true", "on", "1"):
  1315. return True
  1316. elif val in ("n", "no", "f", "false", "off", "0"):
  1317. return False
  1318. else:
  1319. raise ValueError(f"invalid truth value {val!r}")
  1320. @lru_cache(maxsize=50)
  1321. def parse_warning_filter(
  1322. arg: str, *, escape: bool
  1323. ) -> Tuple[str, str, Type[Warning], str, int]:
  1324. """Parse a warnings filter string.
  1325. This is copied from warnings._setoption, but does not apply the filter,
  1326. only parses it, and makes the escaping optional.
  1327. """
  1328. parts = arg.split(":")
  1329. if len(parts) > 5:
  1330. raise warnings._OptionError(f"too many fields (max 5): {arg!r}")
  1331. while len(parts) < 5:
  1332. parts.append("")
  1333. action_, message, category_, module, lineno_ = [s.strip() for s in parts]
  1334. action: str = warnings._getaction(action_) # type: ignore[attr-defined]
  1335. category: Type[Warning] = warnings._getcategory(category_) # type: ignore[attr-defined]
  1336. if message and escape:
  1337. message = re.escape(message)
  1338. if module and escape:
  1339. module = re.escape(module) + r"\Z"
  1340. if lineno_:
  1341. try:
  1342. lineno = int(lineno_)
  1343. if lineno < 0:
  1344. raise ValueError
  1345. except (ValueError, OverflowError) as e:
  1346. raise warnings._OptionError(f"invalid lineno {lineno_!r}") from e
  1347. else:
  1348. lineno = 0
  1349. return action, message, category, module, lineno
  1350. def apply_warning_filters(
  1351. config_filters: Iterable[str], cmdline_filters: Iterable[str]
  1352. ) -> None:
  1353. """Applies pytest-configured filters to the warnings module"""
  1354. # Filters should have this precedence: cmdline options, config.
  1355. # Filters should be applied in the inverse order of precedence.
  1356. for arg in config_filters:
  1357. warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
  1358. for arg in cmdline_filters:
  1359. warnings.filterwarnings(*parse_warning_filter(arg, escape=True))