Detect Test Environment
The `lib-detect-testenv` library provides utility functions to programmatically detect whether Python code is currently running within a test environment. It supports detection of `pytest`, `doctest` (including PyCharm's docrunner), and `setup.py test` execution contexts. The library also offers a Command Line Interface (CLI) for integration into shell scripts and CI/CD pipelines. The current version is 3.0.1, last released on December 15, 2025, indicating active maintenance.
Warnings
- gotcha The Command Line Interface (CLI) for `lib-detect-testenv` uses a 3-level exit code system: 0 for 'test environment detected', 1 for 'test environment not detected' (normal negative result), and 2 for 'error occurred'. This is a Unix convention but may be unexpected if only anticipating 0 for success and non-zero for any kind of failure.
- gotcha While PyPI tags and some summaries mention 'unittest', the public API functions (`is_pytest_active`, `is_doctest_active`, `is_setup_test_active`) do not include an explicit `is_unittest_active` function. The general `is_testenv_active()` function will detect any supported test environment, including scenarios where a `unittest` runner might invoke Python in a way that matches `setup.py test` or other common patterns. Users specifically looking for `unittest` detection should be aware of this distinction.
- gotcha Functions like `is_testenv_active` accept an optional `arg_string` parameter. If `None` (the default), the library uses `str(sys.argv)` for detection. The exact content and format of `sys.argv` can vary depending on how a Python script is invoked (e.g., direct execution, via `python -m`, or from a wrapper script), which might affect detection accuracy.
Install
-
pip install lib-detect-testenv -
pip install --upgrade lib-detect-testenv[test]
Imports
- is_testenv_active
from lib_detect_testenv import is_testenv_active
- is_pytest_active
from lib_detect_testenv import is_pytest_active
- is_doctest_active
from lib_detect_testenv import is_doctest_active
- is_setup_test_active
from lib_detect_testenv import is_setup_test_active
Quickstart
from lib_detect_testenv import is_testenv_active
# Auto-detect from sys.argv
if is_testenv_active():
print("Test environment detected")
else:
print("Not in a test environment")
# Or pass a custom argument string for specific checks
if is_testenv_active(arg_string="pytest my_module.py"):
print("Pytest environment detected via custom arguments")
if is_doctest_active():
print("Doctest environment detected")