pytest-env is a pytest plugin that allows users to define and manage environment variables for their tests directly within configuration files such as `pyproject.toml`, `pytest.toml`, `.pytest.toml`, or `pytest.ini`. It also supports loading variables from `.env` files and via command-line options. The library is actively maintained, with frequent releases to add features and address issues. The current version is 1.6.0.
pip install pytest-envVerified import paths — ran on the pinned version, not inferred.
Configure environment variables in your `pyproject.toml` (or `pytest.ini`). The plugin will automatically make these variables available to your tests via `os.environ`. You can use `transform = true` in TOML (or by default in INI) to enable variable expansion like `${VAR:-default}`. Use `--pytest-env-verbose` to debug how variables are assigned.
Upgrade to Python 3.10 or newer.
Be mindful of the configuration file hierarchy and how inline variables override `.env` file contents. Use `--pytest-env-verbose` for debugging source attribution.
Explicitly choose between override (`PATH`) and extend (`+PATH`) modes based on desired behavior. Ensure that any file specified via `--envfile` exists.
For versions <1.6.0, use the `D:` prefix or `default=true` if you wish to preserve existing variables. For 1.6.0+, understand that existing variables are preserved by default, but you can explicitly override them by omitting `D:` or `default=true`.
Upgrade to `pytest-env` 1.3.0 or newer to use the unsetting functionality.
Place `pytest-env` configuration in recognized project configuration files (`pyproject.toml`, `pytest.toml`, `pytest.ini`) according to their respective formats (TOML or INI), and do not embed them directly into Python scripts.
Ensure `pytest-env` configuration (e.g., `[tool.pytest_env]`) is placed in a dedicated TOML file (`pyproject.toml`, `pytest.toml`) or INI file (`pytest.ini`), not directly inside Python scripts.