From 2ede8778d063756663c508f0a39c949d4943e03d Mon Sep 17 00:00:00 2001 From: dj <112573278+dheerajck@users.noreply.github.com> Date: Mon, 29 Apr 2024 00:22:29 +0530 Subject: [PATCH] Document using PYTEST_VERSION to detect if a code is running inside pytest (#12153) Related to #9502 --- changelog/12153.doc.rst | 1 + doc/en/example/simple.rst | 25 +++++-------------------- 2 files changed, 6 insertions(+), 20 deletions(-) create mode 100644 changelog/12153.doc.rst diff --git a/changelog/12153.doc.rst b/changelog/12153.doc.rst new file mode 100644 index 000000000..ac36becf9 --- /dev/null +++ b/changelog/12153.doc.rst @@ -0,0 +1 @@ +Documented using :envvar:`PYTEST_VERSION` to detect if code is running from within a pytest run. diff --git a/doc/en/example/simple.rst b/doc/en/example/simple.rst index 7064f61f0..dec1bed5f 100644 --- a/doc/en/example/simple.rst +++ b/doc/en/example/simple.rst @@ -405,35 +405,20 @@ 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 do this: .. code-block:: python - # content of your_module.py + import os - _called_from_test = False - -.. code-block:: python - - # content of conftest.py - - - def pytest_configure(config): - your_module._called_from_test = True - -and then check for the ``your_module._called_from_test`` flag: - -.. code-block:: python - - if your_module._called_from_test: - # called from within a test run + if os.environ.get("PYTEST_VERSION") is not None: + # Things you want to to do if your code is called by pytest. ... else: - # called "normally" + # Things you want to to do if your code is not called by pytest. ... -accordingly in your application. Adding info to test report header --------------------------------------------------------------