Skip to content

Commit

Permalink
Update docs: Mention two methods which can let you know if your code …
Browse files Browse the repository at this point in the history
…is running from within a pytest run
  • Loading branch information
dheerajck committed Mar 22, 2024
1 parent 1c96e8e commit 6cfd0c2
Showing 1 changed file with 48 additions and 1 deletion.
49 changes: 48 additions & 1 deletion doc/en/example/simple.rst
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,9 @@ 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 follow one of the two ways listed below.

This is a simple way to do it:

.. code-block:: python
Expand All @@ -421,6 +423,51 @@ running from a test you can do something like this:
# called "normally"
...
This works great, but you should be aware that there is an issue with it. If there is a pytest import anywhere
in your code flow, ``"pytest" in sys.modules`` will return True even if your code is not actually running from within a pytest run.

.. code-block:: python
import sys
import pytest # unused anywhere in your code
def is_called_from_test_by_pytest():
return "pytest" in sys.modules
# This method above will return True even if your code is not actually running from within a pytest run
# as there is a pytest import in your code flow
This is a bit long but a robust way to do it:

.. code-block:: python
# content of your_module.py
_called_from_test_by_pytest = False
.. code-block:: python
# content of conftest.py
def pytest_configure(config):
your_module._called_from_test_by_pytest = True
and then check for the ``your_module._called_from_test_by_pytest`` flag:

.. code-block:: python
if your_module._called_from_test_by_pytest:
# called from within a test run
...
else:
# called "normally"
...
accordingly in your application.

Adding info to test report header
Expand Down

0 comments on commit 6cfd0c2

Please sign in to comment.