Merge pull request #8697 from bluetech/expose-config

config: expose Config and PytestPluginManager for typing purposes
This commit is contained in:
Ran Benita 2021-05-26 11:20:42 +03:00 committed by GitHub
commit 1ba5b48565
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 53 additions and 40 deletions

View File

@ -2,11 +2,13 @@ The types of objects used in pytest's API are now exported so they may be used i
The newly-exported types are: The newly-exported types are:
- ``pytest.Config`` for :class:`Config <pytest.Config>`.
- ``pytest.Mark`` for :class:`marks <pytest.Mark>`. - ``pytest.Mark`` for :class:`marks <pytest.Mark>`.
- ``pytest.MarkDecorator`` for :class:`mark decorators <pytest.MarkDecorator>`. - ``pytest.MarkDecorator`` for :class:`mark decorators <pytest.MarkDecorator>`.
- ``pytest.MarkGenerator`` for the :class:`pytest.mark <pytest.MarkGenerator>` singleton. - ``pytest.MarkGenerator`` for the :class:`pytest.mark <pytest.MarkGenerator>` singleton.
- ``pytest.Metafunc`` for the :class:`metafunc <pytest.MarkGenerator>` argument to the :func:`pytest_generate_tests <pytest.hookspec.pytest_generate_tests>` hook. - ``pytest.Metafunc`` for the :class:`metafunc <pytest.MarkGenerator>` argument to the :func:`pytest_generate_tests <pytest.hookspec.pytest_generate_tests>` hook.
- ``pytest.CallInfo`` for the :class:`CallInfo <pytest.CallInfo>` type passed to various hooks. - ``pytest.CallInfo`` for the :class:`CallInfo <pytest.CallInfo>` type passed to various hooks.
- ``pytest.PytestPluginManager`` for :class:`PytestPluginManager <pytest.PytestPluginManager>`.
- ``pytest.ExceptionInfo`` for the :class:`ExceptionInfo <pytest.ExceptionInfo>` type returned from :func:`pytest.raises` and passed to various hooks. - ``pytest.ExceptionInfo`` for the :class:`ExceptionInfo <pytest.ExceptionInfo>` type returned from :func:`pytest.raises` and passed to various hooks.
- ``pytest.Parser`` for the :class:`Parser <pytest.Parser>` type passed to the :func:`pytest_addoption <pytest.hookspec.pytest_addoption>` hook. - ``pytest.Parser`` for the :class:`Parser <pytest.Parser>` type passed to the :func:`pytest_addoption <pytest.hookspec.pytest_addoption>` hook.
- ``pytest.OptionGroup`` for the :class:`OptionGroup <pytest.OptionGroup>` type returned from the :func:`parser.addgroup <pytest.Parser.getgroup>` method. - ``pytest.OptionGroup`` for the :class:`OptionGroup <pytest.OptionGroup>` type returned from the :func:`parser.addgroup <pytest.Parser.getgroup>` method.

View File

@ -61,7 +61,7 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
namespace of doctests. namespace of doctests.
pytestconfig [session scope] pytestconfig [session scope]
Session-scoped fixture that returns the :class:`_pytest.config.Config` object. Session-scoped fixture that returns the :class:`pytest.Config` object.
Example:: Example::

View File

@ -337,7 +337,7 @@ testing directory:
Alternatively you can invoke pytest with the ``-p pytester`` command line Alternatively you can invoke pytest with the ``-p pytester`` command line
option. option.
This will allow you to use the :py:class:`pytester <_pytest.pytester.Pytester>` This will allow you to use the :py:class:`pytester <pytest.Pytester>`
fixture for testing your plugin code. fixture for testing your plugin code.
Let's demonstrate what you can do with the plugin with an example. Imagine we Let's demonstrate what you can do with the plugin with an example. Imagine we

View File

@ -179,12 +179,12 @@ Files will only be matched for configuration if:
The files are considered in the order above. Options from multiple ``configfiles`` candidates The files are considered in the order above. Options from multiple ``configfiles`` candidates
are never merged - the first match wins. are never merged - the first match wins.
The internal :class:`Config <_pytest.config.Config>` object (accessible via hooks or through the :fixture:`pytestconfig` fixture) The :class:`Config <pytest.Config>` object (accessible via hooks or through the :fixture:`pytestconfig` fixture)
will subsequently carry these attributes: will subsequently carry these attributes:
- :attr:`config.rootpath <_pytest.config.Config.rootpath>`: the determined root directory, guaranteed to exist. - :attr:`config.rootpath <pytest.Config.rootpath>`: the determined root directory, guaranteed to exist.
- :attr:`config.inipath <_pytest.config.Config.inipath>`: the determined ``configfile``, may be ``None`` - :attr:`config.inipath <pytest.Config.inipath>`: the determined ``configfile``, may be ``None``
(it is named ``inipath`` for historical reasons). (it is named ``inipath`` for historical reasons).
.. versionadded:: 6.1 .. versionadded:: 6.1

View File

@ -787,7 +787,7 @@ CollectReport
Config Config
~~~~~~ ~~~~~~
.. autoclass:: _pytest.config.Config() .. autoclass:: pytest.Config()
:members: :members:
ExceptionInfo ExceptionInfo
@ -901,7 +901,7 @@ OptionGroup
PytestPluginManager PytestPluginManager
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
.. autoclass:: _pytest.config.PytestPluginManager() .. autoclass:: pytest.PytestPluginManager()
:members: :members:
:undoc-members: :undoc-members:
:inherited-members: :inherited-members:

View File

@ -290,7 +290,7 @@ def get_config(
def get_plugin_manager() -> "PytestPluginManager": def get_plugin_manager() -> "PytestPluginManager":
"""Obtain a new instance of the """Obtain a new instance of the
:py:class:`_pytest.config.PytestPluginManager`, with default plugins :py:class:`pytest.PytestPluginManager`, with default plugins
already loaded. already loaded.
This function can be used by integration with other tools, like hooking This function can be used by integration with other tools, like hooking
@ -632,6 +632,7 @@ class PytestPluginManager(PluginManager):
def consider_preparse( def consider_preparse(
self, args: Sequence[str], *, exclude_only: bool = False self, args: Sequence[str], *, exclude_only: bool = False
) -> None: ) -> None:
""":meta private:"""
i = 0 i = 0
n = len(args) n = len(args)
while i < n: while i < n:
@ -653,6 +654,7 @@ class PytestPluginManager(PluginManager):
self.consider_pluginarg(parg) self.consider_pluginarg(parg)
def consider_pluginarg(self, arg: str) -> None: def consider_pluginarg(self, arg: str) -> None:
""":meta private:"""
if arg.startswith("no:"): if arg.startswith("no:"):
name = arg[3:] name = arg[3:]
if name in essential_plugins: if name in essential_plugins:
@ -678,12 +680,15 @@ class PytestPluginManager(PluginManager):
self.import_plugin(arg, consider_entry_points=True) self.import_plugin(arg, consider_entry_points=True)
def consider_conftest(self, conftestmodule: types.ModuleType) -> None: def consider_conftest(self, conftestmodule: types.ModuleType) -> None:
""":meta private:"""
self.register(conftestmodule, name=conftestmodule.__file__) self.register(conftestmodule, name=conftestmodule.__file__)
def consider_env(self) -> None: def consider_env(self) -> None:
""":meta private:"""
self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS")) self._import_plugin_specs(os.environ.get("PYTEST_PLUGINS"))
def consider_module(self, mod: types.ModuleType) -> None: def consider_module(self, mod: types.ModuleType) -> None:
""":meta private:"""
self._import_plugin_specs(getattr(mod, "pytest_plugins", [])) self._import_plugin_specs(getattr(mod, "pytest_plugins", []))
def _import_plugin_specs( def _import_plugin_specs(
@ -841,6 +846,7 @@ class Config:
"""Access to configuration values, pluginmanager and plugin hooks. """Access to configuration values, pluginmanager and plugin hooks.
:param PytestPluginManager pluginmanager: :param PytestPluginManager pluginmanager:
A pytest PluginManager.
:param InvocationParams invocation_params: :param InvocationParams invocation_params:
Object containing parameters regarding the :func:`pytest.main` Object containing parameters regarding the :func:`pytest.main`
@ -1227,8 +1233,8 @@ class Config:
@hookimpl(hookwrapper=True) @hookimpl(hookwrapper=True)
def pytest_collection(self) -> Generator[None, None, None]: def pytest_collection(self) -> Generator[None, None, None]:
"""Validate invalid ini keys after collection is done so we take in account # Validate invalid ini keys after collection is done so we take in account
options added by late-loading conftest files.""" # options added by late-loading conftest files.
yield yield
self._validate_config_options() self._validate_config_options()

View File

@ -193,7 +193,7 @@ class Parser:
Default value if no ini-file option exists but is queried. Default value if no ini-file option exists but is queried.
The value of ini-variables can be retrieved via a call to The value of ini-variables can be retrieved via a call to
:py:func:`config.getini(name) <_pytest.config.Config.getini>`. :py:func:`config.getini(name) <pytest.Config.getini>`.
""" """
assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool") assert type in (None, "string", "paths", "pathlist", "args", "linelist", "bool")
self._inidict[name] = (help, type, default) self._inidict[name] = (help, type, default)

View File

@ -1379,7 +1379,8 @@ def yield_fixture(
@fixture(scope="session") @fixture(scope="session")
def pytestconfig(request: FixtureRequest) -> Config: def pytestconfig(request: FixtureRequest) -> Config:
"""Session-scoped fixture that returns the :class:`_pytest.config.Config` object. """Session-scoped fixture that returns the session's :class:`pytest.Config`
object.
Example:: Example::

View File

@ -56,7 +56,7 @@ def pytest_addhooks(pluginmanager: "PytestPluginManager") -> None:
"""Called at plugin registration time to allow adding new hooks via a call to """Called at plugin registration time to allow adding new hooks via a call to
``pluginmanager.add_hookspecs(module_or_class, prefix)``. ``pluginmanager.add_hookspecs(module_or_class, prefix)``.
:param _pytest.config.PytestPluginManager pluginmanager: pytest plugin manager. :param pytest.PytestPluginManager pluginmanager: The pytest plugin manager.
.. note:: .. note::
This hook is incompatible with ``hookwrapper=True``. This hook is incompatible with ``hookwrapper=True``.
@ -70,7 +70,7 @@ def pytest_plugin_registered(
"""A new pytest plugin got registered. """A new pytest plugin got registered.
:param plugin: The plugin module or instance. :param plugin: The plugin module or instance.
:param _pytest.config.PytestPluginManager manager: pytest plugin manager. :param pytest.PytestPluginManager manager: pytest plugin manager.
.. note:: .. note::
This hook is incompatible with ``hookwrapper=True``. This hook is incompatible with ``hookwrapper=True``.
@ -94,18 +94,18 @@ def pytest_addoption(parser: "Parser", pluginmanager: "PytestPluginManager") ->
To add ini-file values call :py:func:`parser.addini(...) To add ini-file values call :py:func:`parser.addini(...)
<pytest.Parser.addini>`. <pytest.Parser.addini>`.
:param _pytest.config.PytestPluginManager pluginmanager: :param pytest.PytestPluginManager pluginmanager:
pytest plugin manager, which can be used to install :py:func:`hookspec`'s The pytest plugin manager, which can be used to install :py:func:`hookspec`'s
or :py:func:`hookimpl`'s and allow one plugin to call another plugin's hooks or :py:func:`hookimpl`'s and allow one plugin to call another plugin's hooks
to change how command line options are added. to change how command line options are added.
Options can later be accessed through the Options can later be accessed through the
:py:class:`config <_pytest.config.Config>` object, respectively: :py:class:`config <pytest.Config>` object, respectively:
- :py:func:`config.getoption(name) <_pytest.config.Config.getoption>` to - :py:func:`config.getoption(name) <pytest.Config.getoption>` to
retrieve the value of a command line option. retrieve the value of a command line option.
- :py:func:`config.getini(name) <_pytest.config.Config.getini>` to retrieve - :py:func:`config.getini(name) <pytest.Config.getini>` to retrieve
a value read from an ini-style file. a value read from an ini-style file.
The config object is passed around on many internal objects via the ``.config`` The config object is passed around on many internal objects via the ``.config``
@ -129,7 +129,7 @@ def pytest_configure(config: "Config") -> None:
.. note:: .. note::
This hook is incompatible with ``hookwrapper=True``. This hook is incompatible with ``hookwrapper=True``.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
""" """
@ -152,7 +152,7 @@ def pytest_cmdline_parse(
``plugins`` arg when using `pytest.main`_ to perform an in-process ``plugins`` arg when using `pytest.main`_ to perform an in-process
test run. test run.
:param _pytest.config.PytestPluginManager pluginmanager: Pytest plugin manager. :param pytest.PytestPluginManager pluginmanager: The pytest plugin manager.
:param List[str] args: List of arguments passed on the command line. :param List[str] args: List of arguments passed on the command line.
""" """
@ -166,7 +166,7 @@ def pytest_cmdline_preparse(config: "Config", args: List[str]) -> None:
.. note:: .. note::
This hook will not be called for ``conftest.py`` files, only for setuptools plugins. This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param List[str] args: Arguments passed on the command line. :param List[str] args: Arguments passed on the command line.
""" """
@ -178,7 +178,7 @@ def pytest_cmdline_main(config: "Config") -> Optional[Union["ExitCode", int]]:
Stops at first non-None result, see :ref:`firstresult`. Stops at first non-None result, see :ref:`firstresult`.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
""" """
@ -191,7 +191,7 @@ def pytest_load_initial_conftests(
.. note:: .. note::
This hook will not be called for ``conftest.py`` files, only for setuptools plugins. This hook will not be called for ``conftest.py`` files, only for setuptools plugins.
:param _pytest.config.Config early_config: The pytest config object. :param pytest.Config early_config: The pytest config object.
:param List[str] args: Arguments passed on the command line. :param List[str] args: Arguments passed on the command line.
:param pytest.Parser parser: To add command line options. :param pytest.Parser parser: To add command line options.
""" """
@ -246,7 +246,7 @@ def pytest_collection_modifyitems(
the items in-place. the items in-place.
:param pytest.Session session: The pytest session object. :param pytest.Session session: The pytest session object.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param List[pytest.Item] items: List of item objects. :param List[pytest.Item] items: List of item objects.
""" """
@ -271,7 +271,7 @@ def pytest_ignore_collect(
:param pathlib.Path fspath: The path to analyze. :param pathlib.Path fspath: The path to analyze.
:param LEGACY_PATH path: The path to analyze. :param LEGACY_PATH path: The path to analyze.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
.. versionchanged:: 6.3.0 .. versionchanged:: 6.3.0
The ``fspath`` parameter was added as a :class:`pathlib.Path` The ``fspath`` parameter was added as a :class:`pathlib.Path`
@ -385,7 +385,7 @@ def pytest_make_parametrize_id(
Stops at first non-None result, see :ref:`firstresult`. Stops at first non-None result, see :ref:`firstresult`.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param val: The parametrized value. :param val: The parametrized value.
:param str argname: The automatic parameter name produced by pytest. :param str argname: The automatic parameter name produced by pytest.
""" """
@ -609,7 +609,7 @@ def pytest_sessionfinish(
def pytest_unconfigure(config: "Config") -> None: def pytest_unconfigure(config: "Config") -> None:
"""Called before test process is exited. """Called before test process is exited.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
""" """
@ -628,7 +628,7 @@ def pytest_assertrepr_compare(
*in* a string will be escaped. Note that all but the first line will *in* a string will be escaped. Note that all but the first line will
be indented slightly, the intention is for the first line to be a summary. be indented slightly, the intention is for the first line to be a summary.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
""" """
@ -677,7 +677,7 @@ def pytest_report_header(
) -> Union[str, List[str]]: ) -> Union[str, List[str]]:
"""Return a string or list of strings to be displayed as header info for terminal reporting. """Return a string or list of strings to be displayed as header info for terminal reporting.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param Path startpath: The starting dir. :param Path startpath: The starting dir.
:param LEGACY_PATH startdir: The starting dir. :param LEGACY_PATH startdir: The starting dir.
@ -713,7 +713,7 @@ def pytest_report_collectionfinish(
.. versionadded:: 3.2 .. versionadded:: 3.2
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param Path startpath: The starting path. :param Path startpath: The starting path.
:param LEGACY_PATH startdir: The starting dir. :param LEGACY_PATH startdir: The starting dir.
:param items: List of pytest items that are going to be executed; this list should not be modified. :param items: List of pytest items that are going to be executed; this list should not be modified.
@ -752,7 +752,7 @@ def pytest_report_teststatus(
for example ``"rerun", "R", ("RERUN", {"yellow": True})``. for example ``"rerun", "R", ("RERUN", {"yellow": True})``.
:param report: The report object whose status is to be returned. :param report: The report object whose status is to be returned.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
Stops at first non-None result, see :ref:`firstresult`. Stops at first non-None result, see :ref:`firstresult`.
""" """
@ -767,7 +767,7 @@ def pytest_terminal_summary(
:param _pytest.terminal.TerminalReporter terminalreporter: The internal terminal reporter object. :param _pytest.terminal.TerminalReporter terminalreporter: The internal terminal reporter object.
:param int exitstatus: The exit status that will be reported back to the OS. :param int exitstatus: The exit status that will be reported back to the OS.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
.. versionadded:: 4.2 .. versionadded:: 4.2
The ``config`` parameter. The ``config`` parameter.
@ -857,7 +857,7 @@ def pytest_markeval_namespace(config: "Config") -> Dict[str, Any]:
.. versionadded:: 6.2 .. versionadded:: 6.2
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:returns: A dictionary of additional globals to add. :returns: A dictionary of additional globals to add.
""" """
@ -909,7 +909,7 @@ def pytest_enter_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
Can be used by plugins to take special action just before the python Can be used by plugins to take special action just before the python
debugger enters interactive mode. debugger enters interactive mode.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param pdb.Pdb pdb: The Pdb instance. :param pdb.Pdb pdb: The Pdb instance.
""" """
@ -920,6 +920,6 @@ def pytest_leave_pdb(config: "Config", pdb: "pdb.Pdb") -> None:
Can be used by plugins to take special action just after the python Can be used by plugins to take special action just after the python
debugger leaves interactive mode. debugger leaves interactive mode.
:param _pytest.config.Config config: The pytest config object. :param pytest.Config config: The pytest config object.
:param pdb.Pdb pdb: The Pdb instance. :param pdb.Pdb pdb: The Pdb instance.
""" """

View File

@ -954,7 +954,7 @@ class Pytester:
) -> Optional[Union[Collector, Item]]: ) -> Optional[Union[Collector, Item]]:
"""Return the collection node of a file. """Return the collection node of a file.
:param _pytest.config.Config config: :param pytest.Config config:
A pytest config. A pytest config.
See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it. See :py:meth:`parseconfig` and :py:meth:`parseconfigure` for creating it.
:param os.PathLike[str] arg: :param os.PathLike[str] arg:
@ -1186,7 +1186,7 @@ class Pytester:
This invokes the pytest bootstrapping code in _pytest.config to create This invokes the pytest bootstrapping code in _pytest.config to create
a new :py:class:`_pytest.core.PluginManager` and call the a new :py:class:`_pytest.core.PluginManager` and call the
pytest_cmdline_parse hook to create a new pytest_cmdline_parse hook to create a new
:py:class:`_pytest.config.Config` instance. :py:class:`pytest.Config` instance.
If :py:attr:`plugins` has been populated they should be plugin modules If :py:attr:`plugins` has been populated they should be plugin modules
to be registered with the PluginManager. to be registered with the PluginManager.
@ -1206,7 +1206,7 @@ class Pytester:
def parseconfigure(self, *args: Union[str, "os.PathLike[str]"]) -> Config: def parseconfigure(self, *args: Union[str, "os.PathLike[str]"]) -> Config:
"""Return a new pytest configured Config instance. """Return a new pytest configured Config instance.
Returns a new :py:class:`_pytest.config.Config` instance like Returns a new :py:class:`pytest.Config` instance like
:py:meth:`parseconfig`, but also calls the pytest_configure hook. :py:meth:`parseconfig`, but also calls the pytest_configure hook.
""" """
config = self.parseconfig(*args) config = self.parseconfig(*args)

View File

@ -970,7 +970,7 @@ class Metafunc:
#: Access to the underlying :class:`_pytest.python.FunctionDefinition`. #: Access to the underlying :class:`_pytest.python.FunctionDefinition`.
self.definition = definition self.definition = definition
#: Access to the :class:`_pytest.config.Config` object for the test session. #: Access to the :class:`pytest.Config` object for the test session.
self.config = config self.config = config
#: The module object where the test function is defined in. #: The module object where the test function is defined in.

View File

@ -7,11 +7,13 @@ from _pytest.assertion import register_assert_rewrite
from _pytest.cacheprovider import Cache from _pytest.cacheprovider import Cache
from _pytest.capture import CaptureFixture from _pytest.capture import CaptureFixture
from _pytest.config import cmdline from _pytest.config import cmdline
from _pytest.config import Config
from _pytest.config import console_main from _pytest.config import console_main
from _pytest.config import ExitCode from _pytest.config import ExitCode
from _pytest.config import hookimpl from _pytest.config import hookimpl
from _pytest.config import hookspec from _pytest.config import hookspec
from _pytest.config import main from _pytest.config import main
from _pytest.config import PytestPluginManager
from _pytest.config import UsageError from _pytest.config import UsageError
from _pytest.config.argparsing import OptionGroup from _pytest.config.argparsing import OptionGroup
from _pytest.config.argparsing import Parser from _pytest.config.argparsing import Parser
@ -79,6 +81,7 @@ __all__ = [
"cmdline", "cmdline",
"collect", "collect",
"Collector", "Collector",
"Config",
"console_main", "console_main",
"deprecated_call", "deprecated_call",
"exit", "exit",
@ -116,6 +119,7 @@ __all__ = [
"PytestDeprecationWarning", "PytestDeprecationWarning",
"PytestExperimentalApiWarning", "PytestExperimentalApiWarning",
"Pytester", "Pytester",
"PytestPluginManager",
"PytestUnhandledCoroutineWarning", "PytestUnhandledCoroutineWarning",
"PytestUnhandledThreadExceptionWarning", "PytestUnhandledThreadExceptionWarning",
"PytestUnknownMarkWarning", "PytestUnknownMarkWarning",