Skip to content

Commit 6cfd0c2

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 6cfd0c2

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

doc/en/example/simple.rst

+48-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,51 @@ 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+
440+
# This method above will return True even if your code is not actually running from within a pytest run
441+
# as there is a pytest import in your code flow
442+
443+
This is a bit long but a robust way to do it:
444+
445+
.. code-block:: python
446+
447+
# content of your_module.py
448+
449+
450+
_called_from_test_by_pytest = False
451+
452+
.. code-block:: python
453+
454+
# content of conftest.py
455+
456+
457+
def pytest_configure(config):
458+
your_module._called_from_test_by_pytest = True
459+
460+
and then check for the ``your_module._called_from_test_by_pytest`` flag:
461+
462+
.. code-block:: python
463+
464+
if your_module._called_from_test_by_pytest:
465+
# called from within a test run
466+
...
467+
else:
468+
# called "normally"
469+
...
470+
424471
accordingly in your application.
425472

426473
Adding info to test report header

0 commit comments

Comments
 (0)