pytest-dotenv
pytest-dotenv is a Pytest plugin that facilitates the loading of environment variables from `.env` files before running tests. It integrates seamlessly with Pytest's plugin system, automatically detecting and parsing `.env` files in your project. The current version is 0.5.2, with its last release in June 2020, indicating a stable but infrequently updated project.
Warnings
- gotcha By default, `pytest-dotenv` will not override environment variables that are already defined in the process's environment. If you need to force overriding, you must explicitly enable `env_override_existing_values = 1` in your `pytest.ini` or use the `--envfile` CLI option (which always overrides).
- gotcha If not explicitly configured, `pytest-dotenv` searches for `.env` files in the working directory and then in ancestor directories. If you have multiple `.env` files or specific naming conventions, ensure you define them using `env_files` in `pytest.ini` to control precedence.
- gotcha Accidentally committing `.env` files, which often contain sensitive credentials, to version control systems like Git is a common security risk.
- gotcha Be aware of potential conflicts or unexpected behavior if you are also using other pytest plugins that manage environment variables (e.g., `pytest-env`) or if you manually load `python-dotenv` within your `conftest.py` with different `override` settings. The precedence rules between multiple plugins or manual loading can be complex.
Install
-
pip install pytest-dotenv
Imports
- No direct imports for basic usage
Configuration is primarily done via pytest.ini or command-line options.
Quickstart
# 1. Create a .env file in your project root:
# .env
MY_SECRET_KEY=supersecretkey123
DATABASE_URL=postgresql://user:password@host:port/dbname
# 2. Create a test file, e.g., test_settings.py:
# test_settings.py
import os
def test_environment_variables_loaded():
assert os.getenv('MY_SECRET_KEY') == 'supersecretkey123'
assert os.getenv('DATABASE_URL') == 'postgresql://user:password@host:port/dbname'
# 3. (Optional) Create a pytest.ini for custom configuration:
# pytest.ini
# [pytest]
# env_files = .env.test .env
# env_override_existing_values = 1
# 4. Run pytest from your terminal:
# pytest