Skip to content

Document how to modify the environment section after tests are finished #400

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Dec 9, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion docs/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,31 @@ Environment
~~~~~~~~~~~

The *Environment* section is provided by the `pytest-metadata`_ plugin, and can be accessed
via the :code:`pytest_configure` hook:
via the :code:`pytest_configure` and :code:`pytest_sessionfinish` hooks:

To modify the *Environment* section **before** tests are run, use :code:`pytest_configure`:

.. code-block:: python

def pytest_configure(config):
config._metadata["foo"] = "bar"

To modify the *Environment* section **after** tests are run, use :code:`pytest_sessionfinish`:

.. code-block:: python

import pytest


@pytest.hookimpl(tryfirst=True)
def pytest_sessionfinish(session, exitstatus):
session.config._metadata["foo"] = "bar"

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
:code:`pytest_sessionfinish` **before** any other plugins ( including :code:`pytest-html` and :code:`pytest-metadata` ) run theirs.
If this line is omitted, then the *Environment* table will **not** be updated since the :code:`pytest_sessionfinish` of the plugins will execute first,
and thus not pick up your change.

The generated table will be sorted alphabetically unless the metadata is a
:code:`collections.OrderedDict`.

Expand Down Expand Up @@ -248,6 +266,7 @@ Below is an example of a :code:`conftest.py` file setting :code:`duration_format

**NOTE**: Milliseconds are always displayed with a precision of 2

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