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.
pip install pytest-dotenvVerified import paths — ran on the pinned version, not inferred.
To get started, simply install the plugin and create a `.env` file in your project's root directory. pytest-dotenv will automatically load these variables when tests are run. For advanced usage, you can configure custom `.env` file paths or override existing system environment variables using a `pytest.ini` configuration file.
Add `env_override_existing_values = 1` under the `[pytest]` section in your `pytest.ini` file, or use `pytest --envfile path/to/.env`.
Specify `env_files = .env.test .env.local .env` in your `pytest.ini` to define a custom loading order and paths. Files are loaded in the order listed.
Always add `.env` (and any other files containing sensitive data) to your `.gitignore` file to prevent accidental commits.
Standardize on a single method for loading environment variables. If using `pytest-dotenv`, rely on its configuration options. If manual loading is preferred, ensure `autouse=True` fixtures are properly scoped and handle overrides as expected.