Skip to content

Commit 21fafe4

Browse files
authored
Document how to modify the environment section after tests are finished (#400)
1 parent 8b7bdc1 commit 21fafe4

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

docs/user_guide.rst

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,13 +55,31 @@ Environment
5555
~~~~~~~~~~~
5656

5757
The *Environment* section is provided by the `pytest-metadata`_ plugin, and can be accessed
58-
via the :code:`pytest_configure` hook:
58+
via the :code:`pytest_configure` and :code:`pytest_sessionfinish` hooks:
59+
60+
To modify the *Environment* section **before** tests are run, use :code:`pytest_configure`:
5961

6062
.. code-block:: python
6163
6264
def pytest_configure(config):
6365
config._metadata["foo"] = "bar"
6466
67+
To modify the *Environment* section **after** tests are run, use :code:`pytest_sessionfinish`:
68+
69+
.. code-block:: python
70+
71+
import pytest
72+
73+
74+
@pytest.hookimpl(tryfirst=True)
75+
def pytest_sessionfinish(session, exitstatus):
76+
session.config._metadata["foo"] = "bar"
77+
78+
Note that in the above example `@pytest.hookimpl(tryfirst=True)`_ is important, as this ensures that a best effort attempt is made to run your
79+
:code:`pytest_sessionfinish` **before** any other plugins ( including :code:`pytest-html` and :code:`pytest-metadata` ) run theirs.
80+
If this line is omitted, then the *Environment* table will **not** be updated since the :code:`pytest_sessionfinish` of the plugins will execute first,
81+
and thus not pick up your change.
82+
6583
The generated table will be sorted alphabetically unless the metadata is a
6684
:code:`collections.OrderedDict`.
6785

@@ -248,6 +266,7 @@ Below is an example of a :code:`conftest.py` file setting :code:`duration_format
248266
249267
**NOTE**: Milliseconds are always displayed with a precision of 2
250268

269+
.. _@pytest.hookimpl(tryfirst=True): https://docs.pytest.org/en/stable/writing_plugins.html#hook-function-ordering-call-example
251270
.. _ansi2html: https://pypi.python.org/pypi/ansi2html/
252271
.. _Content Security Policy (CSP): https://developer.mozilla.org/docs/Web/Security/CSP/
253272
.. _JSON: https://json.org/

0 commit comments

Comments
 (0)