From 8ac15b31f52fc044bbcf2711e97669893578d128 Mon Sep 17 00:00:00 2001 From: dheerajck Date: Sat, 23 Mar 2024 02:14:18 +0530 Subject: [PATCH] Update docs: Mention two methods which can let you know if your code is running from within a pytest run --- doc/en/example/simple.rst | 49 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/doc/en/example/simple.rst b/doc/en/example/simple.rst index ca1abc279..ac44d9956 100644 --- a/doc/en/example/simple.rst +++ b/doc/en/example/simple.rst @@ -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 @@ -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