Update docs: Mention two methods which can let you know if your code is running from within a pytest run
This commit is contained in:
parent
7ced6ce9ca
commit
8ac15b31f5
|
@ -405,7 +405,9 @@ Detect if running from within a pytest run
|
||||||
Usually it is a bad idea to make application code
|
Usually it is a bad idea to make application code
|
||||||
behave differently if called from a test. But if you
|
behave differently if called from a test. But if you
|
||||||
absolutely must find out if your application code is
|
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
|
.. code-block:: python
|
||||||
|
|
||||||
|
@ -421,6 +423,51 @@ running from a test you can do something like this:
|
||||||
# called "normally"
|
# 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.
|
accordingly in your application.
|
||||||
|
|
||||||
Adding info to test report header
|
Adding info to test report header
|
||||||
|
|
Loading…
Reference in New Issue