Debian Codegraph @

doc/en/how-to/writing_hook_functions.rst

raw
1 .. _`writinghooks`:
2
3 Writing hook functions
4 ======================
5
6
7 .. _validation:
8
9 hook function validation and execution
10 --------------------------------------
11
12 pytest calls hook functions from registered plugins for any
13 given hook specification. Let's look at a typical hook function
14 for the ``pytest_collection_modifyitems(session, config,
15 items)`` hook which pytest calls after collection of all test items is
16 completed.
17
18 When we implement a ``pytest_collection_modifyitems`` function in our plugin
19 pytest will during registration verify that you use argument
20 names which match the specification and bail out if not.
21
22 Let's look at a possible implementation:
23
24 .. code-block:: python
25
26 def pytest_collection_modifyitems(config, items):
27 # called after collection is completed
28 # you can modify the ``items`` list
29 ...
30
31 Here, ``pytest`` will pass in ``config`` (the pytest config object)
32 and ``items`` (the list of collected test items) but will not pass
33 in the ``session`` argument because we didn't list it in the function
34 signature. This dynamic "pruning" of arguments allows ``pytest`` to
35 be "future-compatible": we can introduce new hook named parameters without
36 breaking the signatures of existing hook implementations. It is one of
37 the reasons for the general long-lived compatibility of pytest plugins.
38
39 Note that hook functions other than ``pytest_runtest_*`` are not
40 allowed to raise exceptions. Doing so will break the pytest run.
41
42
43
44 .. _firstresult:
45
46 firstresult: stop at first non-None result
47 -------------------------------------------
48
49 Most calls to ``pytest`` hooks result in a **list of results** which contains
50 all non-None results of the called hook functions.
51
52 Some hook specifications use the ``firstresult=True`` option so that the hook
53 call only executes until the first of N registered functions returns a
54 non-None result which is then taken as result of the overall hook call.
55 The remaining hook functions will not be called in this case.
56
57 .. _`hookwrapper`:
58
59 hook wrappers: executing around other hooks
60 -------------------------------------------------
61
62 pytest plugins can implement hook wrappers which wrap the execution
63 of other hook implementations. A hook wrapper is a generator function
64 which yields exactly once. When pytest invokes hooks it first executes
65 hook wrappers and passes the same arguments as to the regular hooks.
66
67 At the yield point of the hook wrapper pytest will execute the next hook
68 implementations and return their result to the yield point, or will
69 propagate an exception if they raised.
70
71 Here is an example definition of a hook wrapper:
72
73 .. code-block:: python
74
75 import pytest
76
77
78 @pytest.hookimpl(wrapper=True)
79 def pytest_pyfunc_call(pyfuncitem):
80 do_something_before_next_hook_executes()
81
82 # If the outcome is an exception, will raise the exception.
83 res = yield
84
85 new_res = post_process_result(res)
86
87 # Override the return value to the plugin system.
88 return new_res
89
90 The hook wrapper needs to return a result for the hook, or raise an exception.
91
92 In many cases, the wrapper only needs to perform tracing or other side effects
93 around the actual hook implementations, in which case it can return the result
94 value of the ``yield``. The simplest (though useless) hook wrapper is
95 ``return (yield)``.
96
97 In other cases, the wrapper wants to adjust or adapt the result, in which case
98 it can return a new value. If the result of the underlying hook is a mutable
99 object, the wrapper may modify that result, but it's probably better to avoid it.
100
101 If the hook implementation failed with an exception, the wrapper can handle that
102 exception using a ``try-catch-finally`` around the ``yield``, by propagating it,
103 suppressing it, or raising a different exception entirely.
104
105 For more information, consult the
106 :ref:`pluggy documentation about hook wrappers <pluggy:hookwrappers>`.
107
108 .. _plugin-hookorder:
109
110 Hook function ordering / call example
111 -------------------------------------
112
113 For any given hook specification there may be more than one
114 implementation and we thus generally view ``hook`` execution as a
115 ``1:N`` function call where ``N`` is the number of registered functions.
116 There are ways to influence if a hook implementation comes before or
117 after others, i.e. the position in the ``N``-sized list of functions:
118
119 .. code-block:: python
120
121 # Plugin 1
122 @pytest.hookimpl(tryfirst=True)
123 def pytest_collection_modifyitems(items):
124 # will execute as early as possible
125 ...
126
127
128 # Plugin 2
129 @pytest.hookimpl(trylast=True)
130 def pytest_collection_modifyitems(items):
131 # will execute as late as possible
132 ...
133
134
135 # Plugin 3
136 @pytest.hookimpl(wrapper=True)
137 def pytest_collection_modifyitems(items):
138 # will execute even before the tryfirst one above!
139 try:
140 return (yield)
141 finally:
142 # will execute after all non-wrappers executed
143 ...
144
145 Here is the order of execution:
146
147 1. Plugin3's pytest_collection_modifyitems called until the yield point
148 because it is a hook wrapper.
149
150 2. Plugin1's pytest_collection_modifyitems is called because it is marked
151 with ``tryfirst=True``.
152
153 3. Plugin2's pytest_collection_modifyitems is called because it is marked
154 with ``trylast=True`` (but even without this mark it would come after
155 Plugin1).
156
157 4. Plugin3's pytest_collection_modifyitems then executing the code after the yield
158 point. The yield receives the result from calling the non-wrappers, or raises
159 an exception if the non-wrappers raised.
160
161 It's possible to use ``tryfirst`` and ``trylast`` also on hook wrappers
162 in which case it will influence the ordering of hook wrappers among each other.
163
164 .. note::
165
166 pytest only searches for hook implementations whose names start with
167 ``pytest_``. The ``specname`` argument to ``@pytest.hookimpl`` can be used
168 to give an implementation a different suffix, for example
169 ``pytest_collection_modifyitems_tryfirst``, but the function name still
170 needs to start with ``pytest_``. A hook implementation named
171 ``my_collection_modifyitems`` is ignored even if it is decorated with
172 ``@pytest.hookimpl(specname="pytest_collection_modifyitems")``.
173
174 .. _`declaringhooks`:
175
176 Declaring new hooks
177 ------------------------
178
179 .. note::
180
181 This is a quick overview on how to add new hooks and how they work in general, but a more complete
182 overview can be found in `the pluggy documentation <https://pluggy.readthedocs.io/en/latest/>`__.
183
184 Plugins and ``conftest.py`` files may declare new hooks that can then be
185 implemented by other plugins in order to alter behaviour or interact with
186 the new plugin:
187
188 .. autofunction:: _pytest.hookspec.pytest_addhooks
189 :noindex:
190
191 Hooks are usually declared as do-nothing functions that contain only
192 documentation describing when the hook will be called and what return values
193 are expected. The names of the functions must start with `pytest_` otherwise pytest won't recognize them.
194
195 Here's an example. Let's assume this code is in the ``sample_hook.py`` module.
196
197 .. code-block:: python
198
199 def pytest_my_hook(config):
200 """
201 Receives the pytest config and does things with it
202 """
203
204 To register the hooks with pytest they need to be structured in their own module or class. This
205 class or module can then be passed to the ``pluginmanager`` using the ``pytest_addhooks`` function
206 (which itself is a hook exposed by pytest).
207
208 .. code-block:: python
209
210 def pytest_addhooks(pluginmanager):
211 """This example assumes the hooks are grouped in the 'sample_hook' module."""
212 from my_app.tests import sample_hook
213
214 pluginmanager.add_hookspecs(sample_hook)
215
216 For a real world example, see `newhooks.py`_ from `xdist <https://github.com/pytest-dev/pytest-xdist>`_.
217
218 .. _`newhooks.py`: https://github.com/pytest-dev/pytest-xdist/blob/v3.8.0/src/xdist/newhooks.py
219
220 Hooks may be called both from fixtures or from other hooks. In both cases, hooks are called
221 through the ``hook`` object, available in the ``config`` object. Most hooks receive a
222 ``config`` object directly, while fixtures may use the ``pytestconfig`` fixture which provides the same object.
223
224 .. code-block:: python
225
226 @pytest.fixture()
227 def my_fixture(pytestconfig):
228 # call the hook called "pytest_my_hook"
229 # 'result' will be a list of return values from all registered functions.
230 result = pytestconfig.hook.pytest_my_hook(config=pytestconfig)
231
232 .. note::
233 Hooks receive parameters using only keyword arguments.
234
235 Now your hook is ready to be used. To register a function at the hook, other plugins or users must
236 now simply define the function ``pytest_my_hook`` with the correct signature in their ``conftest.py``.
237
238 Example:
239
240 .. code-block:: python
241
242 def pytest_my_hook(config):
243 """
244 Print all active hooks to the screen.
245 """
246 print(config.hook)
247
248 .. note::
249
250 Unlike other hooks, the :hook:`pytest_generate_tests` hook is also discovered when
251 defined inside a test module or test class. Other hooks must live in
252 :ref:`conftest.py plugins <localplugin>` or external plugins.
253 See :ref:`parametrize-basics` and the :ref:`hook-reference`.
254
255 .. _`addoptionhooks`:
256
257
258 Using hooks in pytest_addoption
259 -------------------------------
260
261 Occasionally, it is necessary to change the way in which command line options
262 are defined by one plugin based on hooks in another plugin. For example,
263 a plugin may expose a command line option for which another plugin needs
264 to define the default value. The pluginmanager can be used to install and
265 use hooks to accomplish this. The plugin would define and add the hooks
266 and use pytest_addoption as follows:
267
268 .. code-block:: python
269
270 # contents of hooks.py
271
272
273 # Use firstresult=True because we only want one plugin to define this
274 # default value
275 @hookspec(firstresult=True)
276 def pytest_config_file_default_value():
277 """Return the default value for the config file command line option."""
278
279
280 # contents of myplugin.py
281
282
283 def pytest_addhooks(pluginmanager):
284 """This example assumes the hooks are grouped in the 'hooks' module."""
285 from . import hooks
286
287 pluginmanager.add_hookspecs(hooks)
288
289
290 def pytest_addoption(parser, pluginmanager):
291 default_value = pluginmanager.hook.pytest_config_file_default_value()
292 parser.addoption(
293 "--config-file",
294 help="Config file to use, defaults to %(default)s",
295 default=default_value,
296 )
297
298 Another plugin (installed via setuptools entry points, or via the ``-p`` command-line
299 option) could then define the hook implementation to provide the default value:
300
301 .. code-block:: python
302
303 # contents of third_party_plugin.py
304
305
306 def pytest_config_file_default_value():
307 return "config.yaml"
308
309 .. note::
310
311 **Hook implementations in conftest.py files are not available to other plugins during**
312 **their** ``pytest_addoption()`` **execution**. This is because conftest.py files are
313 discovered and loaded *after* builtin plugins, third-party plugins, and command-line
314 plugins have already been initialized (including the execution of their
315 ``pytest_addoption()`` hooks).
316
317 However, :ref:`initial conftest files <pluginorder>` themselves *can* implement
318 ``pytest_addoption()`` to add their own command-line options. When an initial conftest
319 is loaded, its ``pytest_addoption()`` hook will be called immediately.
320
321 During a plugin's ``pytest_addoption()`` execution, only hook implementations from
322 plugins that were loaded earlier will be available. These include:
323
324 * builtin plugins
325 * plugins explicitly loaded with ``-p`` on the command line
326 * installed third-party plugins (via setuptools entry points)
327 * plugins specified via the ``PYTEST_PLUGINS`` environment variable
328
329 See :ref:`pluginorder` for the complete plugin discovery order.
330
331
332 Optionally using hooks from 3rd party plugins
333 ---------------------------------------------
334
335 Using new hooks from plugins as explained above might be a little tricky
336 because of the standard :ref:`validation mechanism <validation>`:
337 if you depend on a plugin that is not installed, validation will fail and
338 the error message will not make much sense to your users.
339
340 One approach is to defer the hook implementation to a new plugin instead of
341 declaring the hook functions directly in your plugin module, for example:
342
343 .. code-block:: python
344
345 # contents of myplugin.py
346
347
348 class DeferPlugin:
349 """Simple plugin to defer pytest-xdist hook functions."""
350
351 def pytest_testnodedown(self, node, error):
352 """standard xdist hook function."""
353
354
355 def pytest_configure(config):
356 if config.pluginmanager.hasplugin("xdist"):
357 config.pluginmanager.register(DeferPlugin())
358
359 This has the added benefit of allowing you to conditionally install hooks
360 depending on which plugins are installed.
361
362 .. _plugin-stash:
363
364 Storing data on items across hook functions
365 -------------------------------------------
366
367 Plugins often need to store data on :class:`~pytest.Item`\s in one hook
368 implementation, and access it in another. One common solution is to just
369 assign some private attribute directly on the item, but type-checkers like
370 mypy frown upon this, and it may also cause conflicts with other plugins.
371 So pytest offers a better way to do this, :attr:`item.stash <_pytest.nodes.Node.stash>`.
372
373 To use the "stash" in your plugins, first create "stash keys" somewhere at the
374 top level of your plugin:
375
376 .. code-block:: python
377
378 been_there_key = pytest.StashKey[bool]()
379 done_that_key = pytest.StashKey[str]()
380
381 then use the keys to stash your data at some point:
382
383 .. code-block:: python
384
385 def pytest_runtest_setup(item: pytest.Item) -> None:
386 item.stash[been_there_key] = True
387 item.stash[done_that_key] = "no"
388
389 and retrieve them at another point:
390
391 .. code-block:: python
392
393 def pytest_runtest_teardown(item: pytest.Item) -> None:
394 if not item.stash[been_there_key]:
395 print("Oh?")
396 item.stash[done_that_key] = "yes!"
397
398 Stashes are available on all node types (like :class:`~pytest.Class`,
399 :class:`~pytest.Session`) and also on :class:`~pytest.Config`, if needed.