diff options
author | Bruno Oliveira <nicoddemus@gmail.com> | 2019-11-06 15:18:59 -0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-11-06 15:18:59 -0300 |
commit | 74f4ec59869c417b1891f7a97cd184a2093263a7 (patch) | |
tree | 1e41d120bb96926460457ab80097c4d7aa8de4c7 /doc | |
parent | 8dcee39ce93f36acd2f7daf4482546a6ac9f4041 (diff) | |
parent | f4008042069b64111c4ad4ab047029a5e77f01ea (diff) | |
download | pytest-74f4ec59869c417b1891f7a97cd184a2093263a7.tar.gz |
Making it possible to access the pluginmanager in the pytest_ad… (#6106)
Making it possible to access the pluginmanager in the pytest_addoptio…
Diffstat (limited to 'doc')
-rw-r--r-- | doc/en/writing_plugins.rst | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/doc/en/writing_plugins.rst b/doc/en/writing_plugins.rst index 5f429c219..8660746bd 100644 --- a/doc/en/writing_plugins.rst +++ b/doc/en/writing_plugins.rst @@ -677,6 +677,56 @@ Example: print(config.hook) +.. _`addoptionhooks`: + + +Using hooks in pytest_addoption +------------------------------- + +Occasionally, it is necessary to change the way in which command line options +are defined by one plugin based on hooks in another plugin. For example, +a plugin may expose a command line option for which another plugin needs +to define the default value. The pluginmanager can be used to install and +use hooks to accomplish this. The plugin would define and add the hooks +and use pytest_addoption as follows: + +.. code-block:: python + + # contents of hooks.py + + # Use firstresult=True because we only want one plugin to define this + # default value + @hookspec(firstresult=True) + def pytest_config_file_default_value(): + """ Return the default value for the config file command line option. """ + + + # contents of myplugin.py + + + def pytest_addhooks(pluginmanager): + """ This example assumes the hooks are grouped in the 'hooks' module. """ + from . import hook + + pluginmanager.add_hookspecs(hook) + + + def pytest_addoption(parser, pluginmanager): + default_value = pluginmanager.hook.pytest_config_file_default_value() + parser.addoption( + "--config-file", + help="Config file to use, defaults to %(default)s", + default=default_value, + ) + +The conftest.py that is using myplugin would simply define the hook as follows: + +.. code-block:: python + + def pytest_config_file_default_value(): + return "config.yaml" + + Optionally using hooks from 3rd party plugins --------------------------------------------- |