@@ -621,12 +621,61 @@ the new plugin:
621
621
622
622
Hooks are usually declared as do-nothing functions that contain only
623
623
documentation describing when the hook will be called and what return values
624
- are expected.
624
+ are expected. The names of the functions must start with ` pytest_ ` otherwise pytest won't recognize them.
625
625
626
- For an example, see `newhooks.py `_ from `xdist <https://github.com/pytest-dev/pytest-xdist >`_.
626
+ Here's an example. Let's assume this code is in the ``hooks.py `` module.
627
+
628
+ .. code-block :: python
629
+
630
+ def pytest_my_hook (config ):
631
+ """
632
+ Receives the pytest config and does things with it
633
+ """
634
+
635
+ To register the hooks with pytest they need to be structured in their own module or class. This
636
+ class or module can then be passed to the ``pluginmanager `` using the ``pytest_addhooks `` function
637
+ (which itself is a hook exposed by pytest).
638
+
639
+ .. code-block :: python
640
+
641
+ def pytest_addhooks (pluginmanager ):
642
+ """ This example assumes the hooks are grouped in the 'hooks' module. """
643
+ from my_app.tests import hooks
644
+
645
+ pluginmanager.add_hookspecs(hooks)
646
+
647
+ For a real world example, see `newhooks.py `_ from `xdist <https://github.com/pytest-dev/pytest-xdist >`_.
627
648
628
649
.. _`newhooks.py` : https://github.com/pytest-dev/pytest-xdist/blob/974bd566c599dc6a9ea291838c6f226197208b46/xdist/newhooks.py
629
650
651
+ Hooks may be called both from fixtures or from other hooks. In both cases, hooks are called
652
+ through the ``hook `` object, available in the ``config `` object. Most hooks receive a
653
+ ``config `` object directly, while fixtures may use the ``pytestconfig `` fixture which provides the same object.
654
+
655
+ .. code-block :: python
656
+
657
+ @pytest.fixture ()
658
+ def my_fixture (pytestconfig ):
659
+ # call the hook called "pytest_my_hook"
660
+ # 'result' will be a list of return values from all registered functions.
661
+ result = pytestconfig.hook.pytest_my_hook(config = pytestconfig)
662
+
663
+ .. note ::
664
+ Hooks receive parameters using only keyword arguments.
665
+
666
+ Now your hook is ready to be used. To register a function at the hook, other plugins or users must
667
+ now simply define the function ``pytest_my_hook `` with the correct signature in their ``conftest.py ``.
668
+
669
+ Example:
670
+
671
+ .. code-block :: python
672
+
673
+ def pytest_my_hook (config ):
674
+ """
675
+ Print all active hooks to the screen.
676
+ """
677
+ print (config.hook)
678
+
630
679
631
680
Optionally using hooks from 3rd party plugins
632
681
---------------------------------------------
0 commit comments