Skip to content

Commit 72db23c

Browse files
committed
Update docs: Mention two methods which can let you know if your code is running from within a pytest run
1 parent 1c96e8e commit 72db23c

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

doc/en/example/simple.rst

+47-1
Original file line numberDiff line numberDiff line change
@@ -405,7 +405,9 @@ Detect if running from within a pytest run
405405
Usually it is a bad idea to make application code
406406
behave differently if called from a test. But if you
407407
absolutely must find out if your application code is
408-
running from a test you can do something like this:
408+
running from a test, you can follow one of the two ways listed below.
409+
410+
This is a simple way to do it:
409411

410412
.. code-block:: python
411413
@@ -421,6 +423,50 @@ running from a test you can do something like this:
421423
# called "normally"
422424
...
423425
426+
This works great, but you should be aware that there is an issue with it. If there is a pytest import anywhere
427+
in your code flow, ``"pytest" in sys.modules`` will return True even if your code is not actually running from within a pytest run.
428+
429+
.. code-block:: python
430+
431+
import sys
432+
433+
import pytest # unused anywhere in your code
434+
435+
436+
def is_called_from_test_by_pytest():
437+
return "pytest" in sys.modules
438+
439+
# This method above will return True even if your code is not actually running from within a pytest run
440+
# as there is a pytest import in your code flow
441+
442+
This is a bit long but a robust way to do it:
443+
444+
.. code-block:: python
445+
446+
# content of your_module.py
447+
448+
449+
_called_from_test_by_pytest = False
450+
451+
.. code-block:: python
452+
453+
# content of conftest.py
454+
455+
456+
def pytest_configure(config):
457+
your_module._called_from_test_by_pytest = True
458+
459+
and then check for the ``your_module._called_from_test_by_pytest`` flag:
460+
461+
.. code-block:: python
462+
463+
if your_module._called_from_test_by_pytest:
464+
# called from within a test run
465+
...
466+
else:
467+
# called "normally"
468+
...
469+
424470
accordingly in your application.
425471

426472
Adding info to test report header

0 commit comments

Comments
 (0)