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.
pip install lib-detect-testenvVerified import paths — ran on the pinned version, not inferred.
This example demonstrates how to use `is_testenv_active()` to automatically detect if the code is running in any supported test environment (pytest, doctest, setup.py test) based on `sys.argv`. It also shows how to explicitly check for doctest activity or pass a custom `arg_string` for detection.
Always check for specific exit codes when using the CLI in shell scripts or CI/CD pipelines (e.g., `if [ $? -eq 0 ]; then ... elif [ $? -eq 1 ]; then ... else ... fi`).
Use `is_testenv_active()` for general test environment detection, or manually inspect `sys.argv` for `unittest`-specific patterns if finer-grained control is needed beyond the provided dedicated functions.
For consistent or specific detection needs, explicitly pass the `arg_string` parameter if `sys.argv` is not reliably structured or if testing different invocation scenarios.
Ensure the library is installed using pip: `pip install lib-detect-testenv` or `python -m pip install lib-detect-testenv`.
Use the correct function name: `from lib_detect_testenv import is_pytest_active`.
Access the correct function name: `lib_detect_testenv.is_pytest_active()`.
Consult the CLI help for available commands and arguments: `lib_detect_testenv --help` or `lib_detect_testenv [command] --help`.