You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# TODO: DeprecationWarning, people should use hookimpl
"""Command line options, ini-file and conftest.py processing."""importargparseimportcollections.abcimportcontextlibimportcopyimportenumimportinspectimportosimportreimportshleximportsysimporttypesimportwarningsfromfunctoolsimportlru_cachefrompathlibimportPathfromtypesimportTracebackTypefromtypingimportAnyfromtypingimportCallablefromtypingimportDictfromtypingimportGeneratorfromtypingimportIOfromtypingimportIterablefromtypingimportIteratorfromtypingimportListfromtypingimportOptionalfromtypingimportSequencefromtypingimportSetfromtypingimportTextIOfromtypingimportTuplefromtypingimportTypefromtypingimportTYPE_CHECKINGfromtypingimportUnionimportattrimportpyfrompluggyimportHookimplMarkerfrompluggyimportHookspecMarkerfrompluggyimportPluginManagerimport_pytest._codeimport_pytest.deprecatedimport_pytest.hookspecfrom .exceptionsimportPrintHelpasPrintHelpfrom .exceptionsimportUsageErrorasUsageErrorfrom .findpathsimportdetermine_setupfrom_pytest._codeimportExceptionInfofrom_pytest._codeimportfilter_tracebackfrom_pytest._ioimportTerminalWriterfrom_pytest.compatimportfinalfrom_pytest.compatimportimportlib_metadatafrom_pytest.outcomesimportfailfrom_pytest.outcomesimportSkippedfrom_pytest.pathlibimportbestrelpathfrom_pytest.pathlibimportimport_pathfrom_pytest.pathlibimportImportModefrom_pytest.storeimportStorefrom_pytest.warning_typesimportPytestConfigWarningifTYPE_CHECKING:
from_pytest._code.codeimport_TracebackStylefrom_pytest.terminalimportTerminalReporterfrom .argparsingimportArgument_PluggyPlugin=object"""A type to represent plugin objects.Plugins can be any namespace, so we can't narrow it down much, but we use analias to make the intent clear.Ideally this type would be provided by pluggy itself."""hookimpl=HookimplMarker("pytest")
hookspec=HookspecMarker("pytest")
@finalclassExitCode(enum.IntEnum):
"""Encodes the valid exit codes by pytest. Currently users and plugins may supply other exit codes as well. .. versionadded:: 5.0 """#: Tests passed.OK=0#: Tests failed.TESTS_FAILED=1#: pytest was interrupted.INTERRUPTED=2#: An internal error got in the way.INTERNAL_ERROR=3#: pytest was misused.USAGE_ERROR=4#: pytest couldn't find tests.NO_TESTS_COLLECTED=5classConftestImportFailure(Exception):
def__init__(
self,
path: py.path.local,
excinfo: Tuple[Type[Exception], Exception, TracebackType],
) ->None:
super().__init__(path, excinfo)
self.path=pathself.excinfo=excinfodef__str__(self) ->str:
return"{}: {} (from {})".format(
self.excinfo[0].__name__, self.excinfo[1], self.path
)
deffilter_traceback_for_conftest_import_failure(
entry: _pytest._code.TracebackEntry,
) ->bool:
"""Filter tracebacks entries which point to pytest internals or importlib. Make a special case for importlib because we use it to import test modules and conftest files in _pytest.pathlib.import_path. """returnfilter_traceback(entry) and"importlib"notinstr(entry.path).split(os.sep)
defmain(
args: Optional[Union[List[str], py.path.local]] =None,
plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] =None,
) ->Union[int, ExitCode]:
"""Perform an in-process test run. :param args: List of command line arguments. :param plugins: List of plugin objects to be auto-registered during initialization. :returns: An exit code. """try:
try:
config=_prepareconfig(args, plugins)
exceptConftestImportFailurease:
exc_info=ExceptionInfo(e.excinfo)
tw=TerminalWriter(sys.stderr)
tw.line(f"ImportError while loading conftest '{e.path}'.", red=True)
exc_info.traceback=exc_info.traceback.filter(
filter_traceback_for_conftest_import_failure
)
exc_repr= (
exc_info.getrepr(style="short", chain=False)
ifexc_info.tracebackelseexc_info.exconly()
)
formatted_tb=str(exc_repr)
forlineinformatted_tb.splitlines():
tw.line(line.rstrip(), red=True)
returnExitCode.USAGE_ERRORelse:
try:
ret: Union[ExitCode, int] =config.hook.pytest_cmdline_main(
config=config
)
try:
returnExitCode(ret)
exceptValueError:
returnretfinally:
config._ensure_unconfigure()
exceptUsageErrorase:
tw=TerminalWriter(sys.stderr)
formsgine.args:
tw.line(f"ERROR: {msg}\n", red=True)
returnExitCode.USAGE_ERRORdefconsole_main() ->int:
"""The CLI entry point of pytest. This function is not meant for programmable use; use `main()` instead. """# https://docs.python.org/3/library/signal.html#note-on-sigpipetry:
code=main()
sys.stdout.flush()
returncodeexceptBrokenPipeError:
# Python flushes standard streams on exit; redirect remaining output# to devnull to avoid another BrokenPipeError at shutdowndevnull=os.open(os.devnull, os.O_WRONLY)
os.dup2(devnull, sys.stdout.fileno())
return1# Python exits with error code 1 on EPIPEclasscmdline: # compatibility namespacemain=staticmethod(main)
deffilename_arg(path: str, optname: str) ->str:
"""Argparse type validator for filename arguments. :path: Path of filename. :optname: Name of the option. """ifos.path.isdir(path):
raiseUsageError(f"{optname} must be a filename, given: {path}")
returnpathdefdirectory_arg(path: str, optname: str) ->str:
"""Argparse type validator for directory arguments. :path: Path of directory. :optname: Name of the option. """ifnotos.path.isdir(path):
raiseUsageError(f"{optname} must be a directory, given: {path}")
returnpath# Plugins that cannot be disabled via "-p no:X" currently.essential_plugins= (
"mark",
"main",
"runner",
"fixtures",
"helpconfig", # Provides -p.
)
default_plugins=essential_plugins+ (
"python",
"terminal",
"debugging",
"unittest",
"capture",
"skipping",
"tmpdir",
"monkeypatch",
"recwarn",
"pastebin",
"nose",
"assertion",
"junitxml",
"doctest",
"cacheprovider",
"freeze_support",
"setuponly",
"setupplan",
"stepwise",
"warnings",
"logging",
"reports",
*(["unraisableexception", "threadexception"] ifsys.version_info>= (3, 8) else []),
"faulthandler",
)
builtin_plugins=set(default_plugins)
builtin_plugins.add("pytester")
builtin_plugins.add("pytester_assertions")
defget_config(
args: Optional[List[str]] =None,
plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] =None,
) ->"Config":
# subsequent calls to main will create a fresh instancepluginmanager=PytestPluginManager()
config=Config(
pluginmanager,
invocation_params=Config.InvocationParams(
args=argsor (), plugins=plugins, dir=Path.cwd(),
),
)
ifargsisnotNone:
# Handle any "-p no:plugin" args.pluginmanager.consider_preparse(args, exclude_only=True)
forspecindefault_plugins:
pluginmanager.import_plugin(spec)
returnconfigdefget_plugin_manager() ->"PytestPluginManager":
"""Obtain a new instance of the :py:class:`_pytest.config.PytestPluginManager`, with default plugins already loaded. This function can be used by integration with other tools, like hooking into pytest to run tests into an IDE. """returnget_config().pluginmanagerdef_prepareconfig(
args: Optional[Union[py.path.local, List[str]]] =None,
plugins: Optional[Sequence[Union[str, _PluggyPlugin]]] =None,
) ->"Config":
ifargsisNone:
args=sys.argv[1:]
elifisinstance(args, py.path.local):
args= [str(args)]
elifnotisinstance(args, list):
msg="`args` parameter expected to be a list of strings, got: {!r} (type: {})"raiseTypeError(msg.format(args, type(args)))
config=get_config(args, plugins)
pluginmanager=config.pluginmanagertry:
ifplugins:
forplugininplugins:
ifisinstance(plugin, str):
pluginmanager.consider_pluginarg(plugin)
else:
pluginmanager.register(plugin)
config=pluginmanager.hook.pytest_cmdline_parse(
pluginmanager=pluginmanager, args=args
)
returnconfigexceptBaseException:
config._ensure_unconfigure()
raise@finalclassPytestPluginManager(PluginManager):
"""A :py:class:`pluggy.PluginManager <pluggy.PluginManager>` with additional pytest-specific functionality: * Loading plugins from the command line, ``PYTEST_PLUGINS`` env variable and ``pytest_plugins`` global variables found in plugins being loaded. * ``conftest.py`` loading during start-up. """def__init__(self) ->None:
import_pytest.assertionsuper().__init__("pytest")
# The objects are module objects, only used generically.self._conftest_plugins: Set[types.ModuleType] =set()
# State related to local conftest plugins.self._dirpath2confmods: Dict[py.path.local, List[types.ModuleType]] = {}
self._conftestpath2mod: Dict[Path, types.ModuleType] = {}
self._confcutdir: Optional[py.path.local] =Noneself._noconftest=Falseself._duplicatepaths: Set[py.path.local] =set()
# plugins that were explicitly skipped with pytest.skip# list of (module name, skip reason)# previously we would issue a warning when a plugin was skipped, but# since we refactored warnings as first citizens of Config, they are# just stored here to be used later.self.skipped_plugins: List[Tuple[str, str]] = []
self.add_hookspecs(_pytest.hookspec)
self.register(self)
ifos.environ.get("PYTEST_DEBUG"):
err: IO[str] =sys.stderrencoding: str=getattr(err, "encoding", "utf8")
try:
err=open(
os.dup(err.fileno()), mode=err.mode, buffering=1, encoding=encoding,
)
exceptException:
passself.trace.root.setwriter(err.write)
self.enable_tracing()
# Config._consider_importhook will set a real object if required.self.rewrite_hook=_pytest.assertion.DummyRewriteHook()
# Used to know when we are importing conftests after the pytest_configure stage.self._configured=Falsedefparse_hookimpl_opts(self, plugin: _PluggyPlugin, name: str):
# pytest hooks are always prefixed with "pytest_",# so we avoid accessing possibly non-readable attributes# (see issue #1073).ifnotname.startswith("pytest_"):
return# Ignore names which can not be hooks.ifname=="pytest_plugins":
returnmethod=getattr(plugin, name)
opts=super().parse_hookimpl_opts(plugin, name)
# Consider only actual functions for hooks (#3775).ifnotinspect.isroutine(method):
return# Collect unmarked hooks as long as they have the `pytest_' prefix.ifoptsisNoneandname.startswith("pytest_"):
opts= {}
ifoptsisnotNone:
# TODO: DeprecationWarning, people should use hookimpl# https://github.com/pytest-dev/pytest/issues/4562known_marks= {m.nameformingetattr(method, "pytestmark", [])}
fornamein ("tryfirst", "trylast", "optionalhook", "hookwrapper"):
opts.setdefault(name, hasattr(method, name) ornameinknown_marks)
returnoptsdefparse_hookspec_opts(self, module_or_class, name: str):
opts=super().parse_hookspec_opts(module_or_class, name)
ifoptsisNone:
method=getattr(module_or_class, name)
ifname.startswith("pytest_"):
# todo: deprecate hookspec hacks# https://github.com/pytest-dev/pytest/issues/4562known_marks= {m.nameformingetattr(method, "pytestmark", [])}
opts= {
"firstresult": hasattr(method, "firstresult")
or"firstresult"inknown_marks,
"historic": hasattr(method, "historic")
or"historic"inknown_marks,
}
returnoptsdefregister(
self, plugin: _PluggyPlugin, name: Optional[str] =None
) ->Optional[str]:
ifnamein_pytest.deprecated.DEPRECATED_EXTERNAL_PLUGINS:
warnings.warn(
PytestConfigWarning(
"{} plugin has been merged into the core, ""please remove it from your requirements.".format(
name.replace("_", "-")
)
)
)
returnNoneret: Optional[str] =super().register(plugin, name)
ifret:
self.hook.pytest_plugin_registered.call_historic(
kwargs=dict(plugin=plugin, manager=self)
)
ifisinstance(plugin, types.ModuleType):
self.consider_module(plugin)
returnretdefgetplugin(self, name: str):
# Support deprecated naming because plugins (xdist e.g.) use it.plugin: Optional[_PluggyPlugin] =self.get_plugin(name)
returnplugindefhasplugin(self, name: str) ->bool:
"""Return whether a plugin with the given name is registered."""returnbool(self.get_plugin(name))
defpytest_configure(self, config: "Config") ->None:
""":meta private:"""# XXX now that the pluginmanager exposes hookimpl(tryfirst...)# we should remove tryfirst/trylast as markers.config.addinivalue_line(
"markers",
"tryfirst: mark a hook implementation function such that the ""plugin machinery will try to call it first/as early as possible.",
)
config.addinivalue_line(
"markers",
"trylast: mark a hook implementation function such that the ""plugin machinery will try to call it last/as late as possible.",
)
self._configured=True## Internal API for local conftest plugin handling.#def_set_initial_conftests(self, namespace: argparse.Namespace) ->None:
"""Load initial conftest files given a preparsed "namespace". As conftest files may add their own command line options which have arguments ('--my-opt somepath') we might get some false positives. All builtin and 3rd party plugins will have been loaded, however, so common options will not confuse our logic here. """current=py.path.local()
self._confcutdir= (
current.join(namespace.confcutdir, abs=True)
ifnamespace.confcutdirelseNone
)
self._noconftest=namespace.noconftestself._using_pyargs=namespace.pyargstestpaths=namespace.file_or_dirfoundanchor=Falsefortestpathintestpaths:
path=str(testpath)
# remove node-id syntaxi=path.find("::")
ifi!=-1:
path=path[:i]
anchor=current.join(path, abs=1)
ifanchor.exists(): # we found some file objectself._try_load_conftest(anchor, namespace.importmode)
foundanchor=Trueifnotfoundanchor:
self._try_load_conftest(current, namespace.importmode)
def_try_load_conftest(
self, anchor: py.path.local, importmode: Union[str, ImportMode]
) ->None:
self._getconftestmodules(anchor, importmode)
# let's also consider test* subdirsifanchor.check(dir=1):
forxinanchor.listdir("test*"):
ifx.check(dir=1):
self._getconftestmodules(x, importmode)
@lru_cache(maxsize=128)def_getconftestmodules(
self, path: py.path.local, importmode: Union[str, ImportMode],
) ->List[types.ModuleType]:
ifself._noconftest:
return []
ifpath.isfile():
directory=path.dirpath()
else:
directory=path# XXX these days we may rather want to use config.rootpath# and allow users to opt into looking into the rootdir parent# directories instead of requiring to specify confcutdir.clist= []
forparentindirectory.parts():
ifself._confcutdirandself._confcutdir.relto(parent):
continueconftestpath=parent.join("conftest.py")
ifconftestpath.isfile():
mod=self._importconftest(conftestpath, importmode)
clist.append(mod)
self._dirpath2confmods[directory] =clistreturnclistdef_rget_with_confmod(
self, name: str, path: py.path.local, importmode: Union[str, ImportMode],
) ->Tuple[types.ModuleType, Any]:
modules=self._getconftestmodules(path, importmode)
formodinreversed(modules):
try:
returnmod, getattr(mod, name)
exceptAttributeError:
continueraiseKeyError(name)
def_importconftest(
self, conftestpath: py.path.local, importmode: Union[str, ImportMode],
) ->types.ModuleType:
# Use a resolved Path object as key to avoid loading the same conftest# twice with build systems that create build directories containing# symlinks to actual files.# Using Path().resolve() is better than py.path.realpath because# it resolves to the correct path/drive in case-insensitive file systems (#5792)key=Path(str(conftestpath)).resolve()
withcontextlib.suppress(KeyError):
returnself._conftestpath2mod[key]
pkgpath=conftestpath.pypkgpath()
ifpkgpathisNone:
_ensure_removed_sysmodule(conftestpath.purebasename)
try:
mod=import_path(conftestpath, mode=importmode)
exceptExceptionase:
asserte.__traceback__isnotNoneexc_info= (type(e), e, e.__traceback__)
raiseConftestImportFailure(conftestpath, exc_info) fromeself._check_non_top_pytest_plugins(mod, conftestpath)
self._conftest_plugins.add(mod)
self._conftestpath2mod[key] =moddirpath=conftestpath.dirpath()
ifdirpathinself._dirpath2confmods:
forpath, modsinself._dirpath2confmods.items():
ifpathandpath.relto(dirpath) orpath==dirpath:
assertmodnotinmodsmods.append(mod)
self.trace(f"loading conftestmodule {mod!r}")
self.consider_conftest(mod)
returnmoddef_check_non_top_pytest_plugins(
self, mod: types.ModuleType, conftestpath: py.path.local,
) ->None:
if (
hasattr(mod, "pytest_plugins")
andself._configuredandnotself._using_pyargs
):
msg= (
"Defining 'pytest_plugins' in a non-top-level conftest is no longer supported:\n""It affects the entire test suite instead of just below the conftest as expected.\n"" {}\n""Please move it to a top level conftest file at the rootdir:\n"" {}\n""For more information, visit:\n"" https://docs.pytest.org/en/stable/deprecations.html#pytest-plugins-in-non-top-level-conftest-files"
)
fail(msg.format(conftestpath, self._confcutdir), pytrace=False)
## API for bootstrapping plugin loading##defconsider_preparse(
self, args: Sequence[str], *, exclude_only: bool=False
) ->None:
i=0n=len(args)
whilei<n:
opt=args[i]
i+=1ifisinstance(opt, str):
ifopt=="-p":
try:
parg=args[i]
exceptIndexError:
returni+=1elifopt.startswith("-p"):
parg=opt[2:]
else:
continueifexclude_onlyandnotparg.startswith("no:"):
continueself.consider_pluginarg(parg)
defconsider_pluginarg(self, arg: str) ->None:
ifarg.startswith("no:"):
name=arg[3:]
ifnameinessential_plugins:
raiseUsageError("plugin %s cannot be disabled"%name)
# PR #4304: remove stepwise if cacheprovider is blocked.ifname=="cacheprovider":
self.set_blocked("stepwise")
self.set_blocked("pytest_stepwise")
self.set_blocked(name)
ifnotname.startswith("pytest_"):
self.set_blocked("pytest_"+name)
else:
name=arg# Unblock the plugin. None indicates that it has been blocked.# There is no interface with pluggy for this.ifself._name2plugin.get(name, -1) isNone:
delself._name2plugin[name]
ifnotname.startswith("pytest_"):
ifself._name2plugin.get("pytest_"+name, -1) isNone:
delself._name2plugin["pytest_"+name]
self.import_plugin(arg, consider_entry_points=True)
defconsider_conftest(self, conftestmodule: types.ModuleType) ->None:
self.register(conftestmodule, name=conftestmodule.__file__)
defconsider_env(self) ->None:
self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
defconsider_module(self, mod: types.ModuleType) ->None:
self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
def_import_plugin_specs(
self, spec: Union[None, types.ModuleType, str, Sequence[str]]
) ->None:
plugins=_get_plugin_specs_as_list(spec)
forimport_specinplugins:
self.import_plugin(import_spec)
defimport_plugin(self, modname: str, consider_entry_points: bool=False) ->None:
"""Import a plugin with ``modname``. If ``consider_entry_points`` is True, entry point names are also considered to find a plugin. """# Most often modname refers to builtin modules, e.g. "pytester",# "terminal" or "capture". Those plugins are registered under their# basename for historic purposes but must be imported with the# _pytest prefix.assertisinstance(modname, str), (
"module name as text required, got %r"%modname
)
ifself.is_blocked(modname) orself.get_plugin(modname) isnotNone:
returnimportspec="_pytest."+modnameifmodnameinbuiltin_pluginselsemodnameself.rewrite_hook.mark_rewrite(importspec)
ifconsider_entry_points:
loaded=self.load_setuptools_entrypoints("pytest11", name=modname)
ifloaded:
returntry:
__import__(importspec)
exceptImportErrorase:
raiseImportError(
'Error importing plugin "{}": {}'.format(modname, str(e.args[0]))
).with_traceback(e.__traceback__) fromeexceptSkippedase:
self.skipped_plugins.append((modname, e.msgor""))
else:
mod=sys.modules[importspec]
self.register(mod, modname)
def_get_plugin_specs_as_list(
specs: Union[None, types.ModuleType, str, Sequence[str]]
) ->List[str]:
"""Parse a plugins specification into a list of plugin names."""# None means empty.ifspecsisNone:
return []
# Workaround for #3899 - a submodule which happens to be called "pytest_plugins".ifisinstance(specs, types.ModuleType):
return []
# Comma-separated list.ifisinstance(specs, str):
returnspecs.split(",") ifspecselse []
# Direct specification.ifisinstance(specs, collections.abc.Sequence):
returnlist(specs)
raiseUsageError(
"Plugins may be specified as a sequence or a ','-separated string of plugin names. Got: %r"%specs
)
def_ensure_removed_sysmodule(modname: str) ->None:
try:
delsys.modules[modname]
exceptKeyError:
passclassNotset:
def__repr__(self):
return"<NOTSET>"notset=Notset()
def_iter_rewritable_modules(package_files: Iterable[str]) ->Iterator[str]:
"""Given an iterable of file names in a source distribution, return the "names" that should be marked for assertion rewrite. For example the package "pytest_mock/__init__.py" should be added as "pytest_mock" in the assertion rewrite mechanism. This function has to deal with dist-info based distributions and egg based distributions (which are still very much in use for "editable" installs). Here are the file names as seen in a dist-info based distribution: pytest_mock/__init__.py pytest_mock/_version.py pytest_mock/plugin.py pytest_mock.egg-info/PKG-INFO Here are the file names as seen in an egg based distribution: src/pytest_mock/__init__.py src/pytest_mock/_version.py src/pytest_mock/plugin.py src/pytest_mock.egg-info/PKG-INFO LICENSE setup.py We have to take in account those two distribution flavors in order to determine which names should be considered for assertion rewriting. More information: https://github.com/pytest-dev/pytest-mock/issues/167 """package_files=list(package_files)
seen_some=Falseforfninpackage_files:
is_simple_module="/"notinfnandfn.endswith(".py")
is_package=fn.count("/") ==1andfn.endswith("__init__.py")
ifis_simple_module:
module_name, _=os.path.splitext(fn)
# we ignore "setup.py" at the root of the distributionifmodule_name!="setup":
seen_some=Trueyieldmodule_nameelifis_package:
package_name=os.path.dirname(fn)
seen_some=Trueyieldpackage_nameifnotseen_some:
# At this point we did not find any packages or modules suitable for assertion# rewriting, so we try again by stripping the first path component (to account for# "src" based source trees for example).# This approach lets us have the common case continue to be fast, as egg-distributions# are rarer.new_package_files= []
forfninpackage_files:
parts=fn.split("/")
new_fn="/".join(parts[1:])
ifnew_fn:
new_package_files.append(new_fn)
ifnew_package_files:
yieldfrom_iter_rewritable_modules(new_package_files)
def_args_converter(args: Iterable[str]) ->Tuple[str, ...]:
returntuple(args)
@finalclassConfig:
"""Access to configuration values, pluginmanager and plugin hooks. :param PytestPluginManager pluginmanager: :param InvocationParams invocation_params: Object containing parameters regarding the :func:`pytest.main` invocation. """@final@attr.s(frozen=True)classInvocationParams:
"""Holds parameters passed during :func:`pytest.main`. The object attributes are read-only. .. versionadded:: 5.1 .. note:: Note that the environment variable ``PYTEST_ADDOPTS`` and the ``addopts`` ini option are handled by pytest, not being included in the ``args`` attribute. Plugins accessing ``InvocationParams`` must be aware of that. """args=attr.ib(type=Tuple[str, ...], converter=_args_converter)
"""The command-line arguments as passed to :func:`pytest.main`. :type: Tuple[str, ...] """plugins=attr.ib(type=Optional[Sequence[Union[str, _PluggyPlugin]]])
"""Extra plugins, might be `None`. :type: Optional[Sequence[Union[str, plugin]]] """dir=attr.ib(type=Path)
"""The directory from which :func:`pytest.main` was invoked. :type: pathlib.Path """def__init__(
self,
pluginmanager: PytestPluginManager,
*,
invocation_params: Optional[InvocationParams] =None,
) ->None:
from .argparsingimportParser, FILE_OR_DIRifinvocation_paramsisNone:
invocation_params=self.InvocationParams(
args=(), plugins=None, dir=Path.cwd()
)
self.option=argparse.Namespace()
"""Access to command line option as attributes. :type: argparse.Namespace """self.invocation_params=invocation_params"""The parameters with which pytest was invoked. :type: InvocationParams """_a=FILE_OR_DIRself._parser=Parser(
usage=f"%(prog)s [options] [{_a}] [{_a}] [...]",
processopt=self._processopt,
)
self.pluginmanager=pluginmanager"""The plugin manager handles plugin registration and hook invocation. :type: PytestPluginManager """self.trace=self.pluginmanager.trace.root.get("config")
self.hook=self.pluginmanager.hookself._inicache: Dict[str, Any] = {}
self._override_ini: Sequence[str] = ()
self._opt2dest: Dict[str, str] = {}
self._cleanup: List[Callable[[], None]] = []
# A place where plugins can store information on the config for their# own use. Currently only intended for internal plugins.self._store=Store()
self.pluginmanager.register(self, "pytestconfig")
self._configured=Falseself.hook.pytest_addoption.call_historic(
kwargs=dict(parser=self._parser, pluginmanager=self.pluginmanager)
)
ifTYPE_CHECKING:
from_pytest.cacheproviderimportCacheself.cache: Optional[Cache] =None@propertydefinvocation_dir(self) ->py.path.local:
"""The directory from which pytest was invoked. Prefer to use :attr:`invocation_params.dir <InvocationParams.dir>`, which is a :class:`pathlib.Path`. :type: py.path.local """returnpy.path.local(str(self.invocation_params.dir))
@propertydefrootpath(self) ->Path:
"""The path to the :ref:`rootdir <rootdir>`. :type: pathlib.Path .. versionadded:: 6.1 """returnself._rootpath@propertydefrootdir(self) ->py.path.local:
"""The path to the :ref:`rootdir <rootdir>`. Prefer to use :attr:`rootpath`, which is a :class:`pathlib.Path`. :type: py.path.local """returnpy.path.local(str(self.rootpath))
@propertydefinipath(self) ->Optional[Path]:
"""The path to the :ref:`configfile <configfiles>`. :type: Optional[pathlib.Path] .. versionadded:: 6.1 """returnself._inipath@propertydefinifile(self) ->Optional[py.path.local]:
"""The path to the :ref:`configfile <configfiles>`. Prefer to use :attr:`inipath`, which is a :class:`pathlib.Path`. :type: Optional[py.path.local] """returnpy.path.local(str(self.inipath)) ifself.inipathelseNonedefadd_cleanup(self, func: Callable[[], None]) ->None:
"""Add a function to be called when the config object gets out of use (usually coninciding with pytest_unconfigure)."""self._cleanup.append(func)
def_do_configure(self) ->None:
assertnotself._configuredself._configured=Truewithwarnings.catch_warnings():
warnings.simplefilter("default")
self.hook.pytest_configure.call_historic(kwargs=dict(config=self))
def_ensure_unconfigure(self) ->None:
ifself._configured:
self._configured=Falseself.hook.pytest_unconfigure(config=self)
self.hook.pytest_configure._call_history= []
whileself._cleanup:
fin=self._cleanup.pop()
fin()
defget_terminal_writer(self) ->TerminalWriter:
terminalreporter: TerminalReporter=self.pluginmanager.get_plugin(
"terminalreporter"
)
returnterminalreporter._twdefpytest_cmdline_parse(
self, pluginmanager: PytestPluginManager, args: List[str]
) ->"Config":
try:
self.parse(args)
exceptUsageError:
# Handle --version and --help here in a minimal fashion.# This gets done via helpconfig normally, but its# pytest_cmdline_main is not called in case of errors.ifgetattr(self.option, "version", False) or"--version"inargs:
from_pytest.helpconfigimportshowversionshowversion(self)
elif (
getattr(self.option, "help", False) or"--help"inargsor"-h"inargs
):
self._parser._getparser().print_help()
sys.stdout.write(
"\nNOTE: displaying only minimal help due to UsageError.\n\n"
)
raisereturnselfdefnotify_exception(
self,
excinfo: ExceptionInfo[BaseException],
option: Optional[argparse.Namespace] =None,
) ->None:
ifoptionandgetattr(option, "fulltrace", False):
style: _TracebackStyle="long"else:
style="native"excrepr=excinfo.getrepr(
funcargs=True, showlocals=getattr(option, "showlocals", False), style=style
)
res=self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
ifnotany(res):
forlineinstr(excrepr).split("\n"):
sys.stderr.write("INTERNALERROR> %s\n"%line)
sys.stderr.flush()
defcwd_relative_nodeid(self, nodeid: str) ->str:
# nodeid's are relative to the rootpath, compute relative to cwd.ifself.invocation_params.dir!=self.rootpath:
fullpath=self.rootpath/nodeidnodeid=bestrelpath(self.invocation_params.dir, fullpath)
returnnodeid@classmethoddeffromdictargs(cls, option_dict, args) ->"Config":
"""Constructor usable for subprocesses."""config=get_config(args)
config.option.__dict__.update(option_dict)
config.parse(args, addopts=False)
forxinconfig.option.plugins:
config.pluginmanager.consider_pluginarg(x)
returnconfigdef_processopt(self, opt: "Argument") ->None:
fornameinopt._short_opts+opt._long_opts:
self._opt2dest[name] =opt.destifhasattr(opt, "default"):
ifnothasattr(self.option, opt.dest):
setattr(self.option, opt.dest, opt.default)
@hookimpl(trylast=True)defpytest_load_initial_conftests(self, early_config: "Config") ->None:
self.pluginmanager._set_initial_conftests(early_config.known_args_namespace)
def_initini(self, args: Sequence[str]) ->None:
ns, unknown_args=self._parser.parse_known_and_unknown_args(
args, namespace=copy.copy(self.option)
)
rootpath, inipath, inicfg=determine_setup(
ns.inifilename,
ns.file_or_dir+unknown_args,
rootdir_cmd_arg=ns.rootdirorNone,
config=self,
)
self._rootpath=rootpathself._inipath=inipathself.inicfg=inicfgself._parser.extra_info["rootdir"] =str(self.rootpath)
self._parser.extra_info["inifile"] =str(self.inipath)
self._parser.addini("addopts", "extra command line options", "args")
self._parser.addini("minversion", "minimally required pytest version")
self._parser.addini(
"required_plugins",
"plugins that must be present for pytest to run",
type="args",
default=[],
)
self._override_ini=ns.override_inior ()
def_consider_importhook(self, args: Sequence[str]) ->None:
"""Install the PEP 302 import hook if using assertion rewriting. Needs to parse the --assert=<mode> option from the commandline and find all the installed plugins to mark them for rewriting by the importhook. """ns, unknown_args=self._parser.parse_known_and_unknown_args(args)
mode=getattr(ns, "assertmode", "plain")
ifmode=="rewrite":
import_pytest.assertiontry:
hook=_pytest.assertion.install_importhook(self)
exceptSystemError:
mode="plain"else:
self._mark_plugins_for_rewrite(hook)
self._warn_about_missing_assertion(mode)
def_mark_plugins_for_rewrite(self, hook) ->None:
"""Given an importhook, mark for rewrite any top-level modules or packages in the distribution package for all pytest plugins."""self.pluginmanager.rewrite_hook=hookifos.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"):
# We don't autoload from setuptools entry points, no need to continue.returnpackage_files= (
str(file)
fordistinimportlib_metadata.distributions()
ifany(ep.group=="pytest11"forepindist.entry_points)
forfileindist.filesor []
)
fornamein_iter_rewritable_modules(package_files):
hook.mark_rewrite(name)
def_validate_args(self, args: List[str], via: str) ->List[str]:
"""Validate known args."""self._parser._config_source_hint=via# type: ignoretry:
self._parser.parse_known_and_unknown_args(
args, namespace=copy.copy(self.option)
)
finally:
delself._parser._config_source_hint# type: ignorereturnargsdef_preparse(self, args: List[str], addopts: bool=True) ->None:
ifaddopts:
env_addopts=os.environ.get("PYTEST_ADDOPTS", "")
iflen(env_addopts):
args[:] = (
self._validate_args(shlex.split(env_addopts), "via PYTEST_ADDOPTS")
+args
)
self._initini(args)
ifaddopts:
args[:] = (
self._validate_args(self.getini("addopts"), "via addopts config") +args
)
self.known_args_namespace=self._parser.parse_known_args(
args, namespace=copy.copy(self.option)
)
self._checkversion()
self._consider_importhook(args)
self.pluginmanager.consider_preparse(args, exclude_only=False)
ifnotos.environ.get("PYTEST_DISABLE_PLUGIN_AUTOLOAD"):
# Don't autoload from setuptools entry point. Only explicitly specified# plugins are going to be loaded.self.pluginmanager.load_setuptools_entrypoints("pytest11")
self.pluginmanager.consider_env()
self.known_args_namespace=self._parser.parse_known_args(
args, namespace=copy.copy(self.known_args_namespace)
)
self._validate_plugins()
self._warn_about_skipped_plugins()
ifself.known_args_namespace.strict:
self.issue_config_time_warning(
_pytest.deprecated.STRICT_OPTION, stacklevel=2
)
ifself.known_args_namespace.confcutdirisNoneandself.inipathisnotNone:
confcutdir=str(self.inipath.parent)
self.known_args_namespace.confcutdir=confcutdirtry:
self.hook.pytest_load_initial_conftests(
early_config=self, args=args, parser=self._parser
)
exceptConftestImportFailurease:
ifself.known_args_namespace.helporself.known_args_namespace.version:
# we don't want to prevent --help/--version to work# so just let is pass and print a warning at the endself.issue_config_time_warning(
PytestConfigWarning(f"could not load initial conftests: {e.path}"),
stacklevel=2,
)
else:
raise@hookimpl(hookwrapper=True)defpytest_collection(self) ->Generator[None, None, None]:
"""Validate invalid ini keys after collection is done so we take in account options added by late-loading conftest files."""yieldself._validate_config_options()
def_checkversion(self) ->None:
importpytestminver=self.inicfg.get("minversion", None)
ifminver:
# Imported lazily to improve start-up time.frompackaging.versionimportVersionifnotisinstance(minver, str):
raisepytest.UsageError(
"%s: 'minversion' must be a single value"%self.inipath
)
ifVersion(minver) >Version(pytest.__version__):
raisepytest.UsageError(
"%s: 'minversion' requires pytest-%s, actual pytest-%s'"% (self.inipath, minver, pytest.__version__,)
)
def_validate_config_options(self) ->None:
forkeyinsorted(self._get_unknown_ini_keys()):
self._warn_or_fail_if_strict(f"Unknown config option: {key}\n")
def_validate_plugins(self) ->None:
required_plugins=sorted(self.getini("required_plugins"))
ifnotrequired_plugins:
return# Imported lazily to improve start-up time.frompackaging.versionimportVersionfrompackaging.requirementsimportInvalidRequirement, Requirementplugin_info=self.pluginmanager.list_plugin_distinfo()
plugin_dist_info= {dist.project_name: dist.versionfor_, distinplugin_info}
missing_plugins= []
forrequired_plugininrequired_plugins:
try:
spec=Requirement(required_plugin)
exceptInvalidRequirement:
missing_plugins.append(required_plugin)
continueifspec.namenotinplugin_dist_info:
missing_plugins.append(required_plugin)
elifVersion(plugin_dist_info[spec.name]) notinspec.specifier:
missing_plugins.append(required_plugin)
ifmissing_plugins:
raiseUsageError(
"Missing required plugins: {}".format(", ".join(missing_plugins)),
)
def_warn_or_fail_if_strict(self, message: str) ->None:
ifself.known_args_namespace.strict_config:
raiseUsageError(message)
self.issue_config_time_warning(PytestConfigWarning(message), stacklevel=3)
def_get_unknown_ini_keys(self) ->List[str]:
parser_inicfg=self._parser._inidictreturn [namefornameinself.inicfgifnamenotinparser_inicfg]
defparse(self, args: List[str], addopts: bool=True) ->None:
# Parse given cmdline arguments into this config object.assertnothasattr(
self, "args"
), "can only parse cmdline args at most once per Config object"self.hook.pytest_addhooks.call_historic(
kwargs=dict(pluginmanager=self.pluginmanager)
)
self._preparse(args, addopts=addopts)
# XXX deprecated hook:self.hook.pytest_cmdline_preparse(config=self, args=args)
self._parser.after_preparse=True# type: ignoretry:
args=self._parser.parse_setoption(
args, self.option, namespace=self.option
)
ifnotargs:
ifself.invocation_params.dir==self.rootpath:
args=self.getini("testpaths")
ifnotargs:
args= [str(self.invocation_params.dir)]
self.args=argsexceptPrintHelp:
passdefissue_config_time_warning(self, warning: Warning, stacklevel: int) ->None:
"""Issue and handle a warning during the "configure" stage. During ``pytest_configure`` we can't capture warnings using the ``catch_warnings_for_item`` function because it is not possible to have hookwrappers around ``pytest_configure``. This function is mainly intended for plugins that need to issue warnings during ``pytest_configure`` (or similar stages). :param warning: The warning instance. :param stacklevel: stacklevel forwarded to warnings.warn. """ifself.pluginmanager.is_blocked("warnings"):
returncmdline_filters=self.known_args_namespace.pythonwarningsor []
config_filters=self.getini("filterwarnings")
withwarnings.catch_warnings(record=True) asrecords:
warnings.simplefilter("always", type(warning))
apply_warning_filters(config_filters, cmdline_filters)
warnings.warn(warning, stacklevel=stacklevel)
ifrecords:
frame=sys._getframe(stacklevel-1)
location=frame.f_code.co_filename, frame.f_lineno, frame.f_code.co_nameself.hook.pytest_warning_captured.call_historic(
kwargs=dict(
warning_message=records[0],
when="config",
item=None,
location=location,
)
)
self.hook.pytest_warning_recorded.call_historic(
kwargs=dict(
warning_message=records[0],
when="config",
nodeid="",
location=location,
)
)
defaddinivalue_line(self, name: str, line: str) ->None:
"""Add a line to an ini-file option. The option must have been declared but might not yet be set in which case the line becomes the first line in its value."""x=self.getini(name)
assertisinstance(x, list)
x.append(line) # modifies the cached list inlinedefgetini(self, name: str):
"""Return configuration value from an :ref:`ini file <configfiles>`. If the specified name hasn't been registered through a prior :py:func:`parser.addini <_pytest.config.argparsing.Parser.addini>` call (usually from a plugin), a ValueError is raised. """try:
returnself._inicache[name]
exceptKeyError:
self._inicache[name] =val=self._getini(name)
returnvaldef_getini(self, name: str):
try:
description, type, default=self._parser._inidict[name]
exceptKeyErrorase:
raiseValueError(f"unknown configuration value: {name!r}") fromeoverride_value=self._get_override_ini_value(name)
ifoverride_valueisNone:
try:
value=self.inicfg[name]
exceptKeyError:
ifdefaultisnotNone:
returndefaultiftypeisNone:
return""return []
else:
value=override_value# Coerce the values based on types.## Note: some coercions are only required if we are reading from .ini files, because# the file format doesn't contain type information, but when reading from toml we will# get either str or list of str values (see _parse_ini_config_from_pyproject_toml).# For example:## ini:# a_line_list = "tests acceptance"# in this case, we need to split the string to obtain a list of strings.## toml:# a_line_list = ["tests", "acceptance"]# in this case, we already have a list ready to use.#iftype=="pathlist":
# TODO: This assert is probably not valid in all cases.assertself.inipathisnotNonedp=self.inipath.parentinput_values=shlex.split(value) ifisinstance(value, str) elsevaluereturn [py.path.local(str(dp/x)) forxininput_values]
eliftype=="args":
returnshlex.split(value) ifisinstance(value, str) elsevalueeliftype=="linelist":
ifisinstance(value, str):
return [tfortinmap(lambdax: x.strip(), value.split("\n")) ift]
else:
returnvalueeliftype=="bool":
return_strtobool(str(value).strip())
else:
asserttypein [None, "string"]
returnvaluedef_getconftest_pathlist(
self, name: str, path: py.path.local
) ->Optional[List[py.path.local]]:
try:
mod, relroots=self.pluginmanager._rget_with_confmod(
name, path, self.getoption("importmode")
)
exceptKeyError:
returnNonemodpath=py.path.local(mod.__file__).dirpath()
values: List[py.path.local] = []
forrelrootinrelroots:
ifnotisinstance(relroot, py.path.local):
relroot=relroot.replace("/", os.sep)
relroot=modpath.join(relroot, abs=True)
values.append(relroot)
returnvaluesdef_get_override_ini_value(self, name: str) ->Optional[str]:
value=None# override_ini is a list of "ini=value" options.# Always use the last item if multiple values are set for same ini-name,# e.g. -o foo=bar1 -o foo=bar2 will set foo to bar2.forini_configinself._override_ini:
try:
key, user_ini_value=ini_config.split("=", 1)
exceptValueErrorase:
raiseUsageError(
"-o/--override-ini expects option=value style (got: {!r}).".format(
ini_config
)
) fromeelse:
ifkey==name:
value=user_ini_valuereturnvaluedefgetoption(self, name: str, default=notset, skip: bool=False):
"""Return command line option value. :param name: Name of the option. You may also specify the literal ``--OPT`` option instead of the "dest" option name. :param default: Default value if no option of that name exists. :param skip: If True, raise pytest.skip if option does not exists or has a None value. """name=self._opt2dest.get(name, name)
try:
val=getattr(self.option, name)
ifvalisNoneandskip:
raiseAttributeError(name)
returnvalexceptAttributeErrorase:
ifdefaultisnotnotset:
returndefaultifskip:
importpytestpytest.skip(f"no {name!r} option found")
raiseValueError(f"no option named {name!r}") fromedefgetvalue(self, name: str, path=None):
"""Deprecated, use getoption() instead."""returnself.getoption(name)
defgetvalueorskip(self, name: str, path=None):
"""Deprecated, use getoption(skip=True) instead."""returnself.getoption(name, skip=True)
def_warn_about_missing_assertion(self, mode: str) ->None:
ifnot_assertion_supported():
ifmode=="plain":
warning_text= (
"ASSERTIONS ARE NOT EXECUTED"" and FAILING TESTS WILL PASS. Are you"" using python -O?"
)
else:
warning_text= (
"assertions not in test modules or"" plugins will be ignored"" because assert statements are not executed ""by the underlying Python interpreter ""(are you using python -O?)\n"
)
self.issue_config_time_warning(
PytestConfigWarning(warning_text), stacklevel=3,
)
def_warn_about_skipped_plugins(self) ->None:
formodule_name, msginself.pluginmanager.skipped_plugins:
self.issue_config_time_warning(
PytestConfigWarning(f"skipped plugin {module_name!r}: {msg}"),
stacklevel=2,
)
def_assertion_supported() ->bool:
try:
assertFalseexceptAssertionError:
returnTrueelse:
returnFalse# type: ignore[unreachable]defcreate_terminal_writer(
config: Config, file: Optional[TextIO] =None
) ->TerminalWriter:
"""Create a TerminalWriter instance configured according to the options in the config object. Every code which requires a TerminalWriter object and has access to a config object should use this function. """tw=TerminalWriter(file=file)
ifconfig.option.color=="yes":
tw.hasmarkup=Trueelifconfig.option.color=="no":
tw.hasmarkup=Falseifconfig.option.code_highlight=="yes":
tw.code_highlight=Trueelifconfig.option.code_highlight=="no":
tw.code_highlight=Falsereturntwdef_strtobool(val: str) ->bool:
"""Convert a string representation of truth to True or False. True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. .. note:: Copied from distutils.util. """val=val.lower()
ifvalin ("y", "yes", "t", "true", "on", "1"):
returnTrueelifvalin ("n", "no", "f", "false", "off", "0"):
returnFalseelse:
raiseValueError(f"invalid truth value {val!r}")
@lru_cache(maxsize=50)defparse_warning_filter(
arg: str, *, escape: bool
) ->Tuple[str, str, Type[Warning], str, int]:
"""Parse a warnings filter string. This is copied from warnings._setoption, but does not apply the filter, only parses it, and makes the escaping optional. """parts=arg.split(":")
iflen(parts) >5:
raisewarnings._OptionError(f"too many fields (max 5): {arg!r}")
whilelen(parts) <5:
parts.append("")
action_, message, category_, module, lineno_= [s.strip() forsinparts]
action: str=warnings._getaction(action_) # type: ignore[attr-defined]category: Type[Warning] =warnings._getcategory(category_) # type: ignore[attr-defined]ifmessageandescape:
message=re.escape(message)
ifmoduleandescape:
module=re.escape(module) +r"\Z"iflineno_:
try:
lineno=int(lineno_)
iflineno<0:
raiseValueErrorexcept (ValueError, OverflowError) ase:
raisewarnings._OptionError(f"invalid lineno {lineno_!r}") fromeelse:
lineno=0returnaction, message, category, module, linenodefapply_warning_filters(
config_filters: Iterable[str], cmdline_filters: Iterable[str]
) ->None:
"""Applies pytest-configured filters to the warnings module"""# Filters should have this precedence: cmdline options, config.# Filters should be applied in the inverse order of precedence.forarginconfig_filters:
warnings.filterwarnings(*parse_warning_filter(arg, escape=False))
forargincmdline_filters:
warnings.filterwarnings(*parse_warning_filter(arg, escape=True))
e2ef1a4ed193fd398d5869cd9535190612a8dbd4
The text was updated successfully, but these errors were encountered:
DeprecationWarning, people should use hookimpl
pytest-dev/pytest#4562
pytest-dev/pytest#4562
we should remove tryfirst/trylast as markers.
and allow users to opt into looking into the rootdir parent
directories instead of requiring to specify confcutdir.
twice with build systems that create build directories containing
symlinks to actual files.
Using Path().resolve() is better than py.path.realpath because
it resolves to the correct path/drive in case-insensitive file systems (#5792)
There is no interface with pluggy for this.
"terminal" or "capture". Those plugins are registered under their
basename for historic purposes but must be imported with the
_pytest prefix.
rewriting, so we try again by stripping the first path component (to account for
"src" based source trees for example).
This approach lets us have the common case continue to be fast, as egg-distributions
are rarer.
own use. Currently only intended for internal plugins.
This gets done via helpconfig normally, but its
pytest_cmdline_main is not called in case of errors.
plugins are going to be loaded.
so just let is pass and print a warning at the end
the file format doesn't contain type information, but when reading from toml we will
get either str or list of str values (see _parse_ini_config_from_pyproject_toml).
For example:
a_line_list = "tests acceptance"
in this case, we need to split the string to obtain a list of strings.
a_line_list = ["tests", "acceptance"]
in this case, we already have a list ready to use.
gcp-database-as-a-service-stock-markets/venv/Lib/site-packages/_pytest/config/__init__.py
Line 398 in 62db596
e2ef1a4ed193fd398d5869cd9535190612a8dbd4
The text was updated successfully, but these errors were encountered: