pytest-env

1.6.0 · active · verified Tue Mar 31

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.

Warnings

Install

Imports

Quickstart

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.

# pyproject.toml
[tool.pytest_env]
DATABASE_URL = "postgresql://localhost/test_db"
DEBUG = "true"
MY_API_KEY = "${MY_API_KEY:-default_key}"

# tests/test_my_app.py
import os

def test_database_connection():
    assert os.environ["DATABASE_URL"] == "postgresql://localhost/test_db"
    assert os.environ["DEBUG"] == "true"

def test_api_key():
    # MY_API_KEY will be expanded using existing env var or default_key
    assert "MY_API_KEY" in os.environ
    print(f"API Key: {os.environ['MY_API_KEY']}")

# Run from your terminal:
# pytest
# To see verbose output of env var assignments:
# pytest --pytest-env-verbose

view raw JSON →