Skip to content

Commit

Permalink
doc(plugin_hooks): Improve documentation for writing plugin hooks.
Browse files Browse the repository at this point in the history
  • Loading branch information
NiklasMM committed Jun 28, 2019
1 parent 3c9b46f commit 8411394
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/5517.doc.rst
@@ -0,0 +1 @@
Improve "Declaring new hooks" section in chapter "Writing Plugins"
29 changes: 28 additions & 1 deletion doc/en/writing_plugins.rst
Expand Up @@ -621,12 +621,39 @@ the new plugin:

Hooks are usually declared as do-nothing functions that contain only
documentation describing when the hook will be called and what return values
are expected.
are expected. The names of the functions must start with `pytest_` otherwise pytest won't recognize them.

For an example, see `newhooks.py`_ from `xdist <https://github.com/pytest-dev/pytest-xdist>`_.

.. _`newhooks.py`: https://github.com/pytest-dev/pytest-xdist/blob/974bd566c599dc6a9ea291838c6f226197208b46/xdist/newhooks.py

To register the hooks with pytest they need to be structured in their own module or class. This
class or module can then be passed to the `pluginmanager` using the `pytest_addhooks` function
(which itself is a hook exposed by pytest):

.. code-block:: python
def pytest_addhooks(pluginmanager):
""" This example assumes the hooks are grouped in the pytest_hooks module. """
from my_app.tests import pytest_hooks
pluginmanager.add_hookspecs(pytest_hooks)
To execute hooks in one of your fixtures, use the `pytestconfig` fixture. It holds all registered
hooks under `hook` by their name.

.. code-block:: python
@pytest.fixture()
def my_fixture(pytestconfig):
# call the hook called "pytest_my_hook"
# `result` will be a list of return values from all registered functions.
result = pytestconfig.hook.pytest_my_hook()
Now your hook is ready to be used. To register a function at the hook, other plugins or users must
now simply define the function `pytest_my_hook` with the correct signature in their `conftest.py`.

.. note::
If a hook uses parameters only keyword arguments can be used to invoke it.

Optionally using hooks from 3rd party plugins
---------------------------------------------
Expand Down

0 comments on commit 8411394

Please sign in to comment.