Skip to content

Updated docs: Now we can use environment variable PYTEST_VERSION to detect if a code is run by a pytest run #12153

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 8 commits into from
Apr 28, 2024
1 change: 1 addition & 0 deletions changelog/12153.doc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Documented using :envvar:`PYTEST_VERSION` to detect if code is running from within a pytest run.
25 changes: 5 additions & 20 deletions doc/en/example/simple.rst
Original file line number Diff line number Diff line change
Expand Up @@ -405,35 +405,20 @@ Detect if running from within a pytest run
Usually it is a bad idea to make application code
behave differently if called from a test. But if you
absolutely must find out if your application code is
running from a test you can do something like this:
running from a test you can do this:

.. code-block:: python

# content of your_module.py
import os


_called_from_test = False

.. code-block:: python

# content of conftest.py


def pytest_configure(config):
your_module._called_from_test = True

and then check for the ``your_module._called_from_test`` flag:

.. code-block:: python

if your_module._called_from_test:
# called from within a test run
if os.environ.get("PYTEST_VERSION") is not None:
# Things you want to to do if your code is called by pytest.
...
else:
# called "normally"
# Things you want to to do if your code is not called by pytest.
...

accordingly in your application.

Adding info to test report header
--------------------------------------------------------------
Expand Down
Loading