A pytest plugin that sets environment variables from pyproject.toml, pytest.toml, .pytest.toml, or pytest.ini
configuration files. It can also load variables from .env files.
pip install pytest-envAdd environment variables to your pyproject.toml:
[tool.pytest_env]
DATABASE_URL = "postgresql://localhost/test_db"
DEBUG = "true"Run your tests. The environment variables are now available:
import os
def test_database_connection():
assert os.environ["DATABASE_URL"] == "postgresql://localhost/test_db"
assert os.environ["DEBUG"] == "true"To see exactly what pytest-env sets, pass --pytest-env-verbose:
$ pytest --pytest-env-verbose
pytest-env:
SET DATABASE_URL=postgresql://localhost/test_db (from /project/pyproject.toml)
SET DEBUG=true (from /project/pyproject.toml)
Specify .env files in your configuration:
[tool.pytest_env]
env_files = [".env", ".env.test"]Create your .env file:
DATABASE_URL=postgres://localhost/mydb
SECRET_KEY='my-secret-key'
DEBUG="true"Files are loaded before inline variables, so inline configuration takes precedence. To switch .env files at runtime
without changing configuration, use the --envfile CLI option:
pytest --envfile .env.local # ignore configured env_files, load only this file
pytest --envfile +.env.override # load configured env_files first, then this file on topTo keep existing environment variables (including with --envfile), set env_files_skip_if_set = true. A ${VAR}
reference in a .env file then expands to the kept value. Native TOML reserves env_files_skip_if_set for this option
and requires an unquoted true or false. A string such as "true" stops pytest before collection.
[tool.pytest_env]
env_files = [".env", ".env.test"]
env_files_skip_if_set = true[pytest]
env_files =
.env
.env.test
env_files_skip_if_set = trueVariables set as plain values are assigned directly. For more control, use inline tables with the transform,
skip_if_set, and unset keys:
[tool.pytest_env]
SIMPLE = "value"
RUN_PATH = { value = "/run/path/{USER}", transform = true }
HOME = { value = "~/tmp", skip_if_set = true }
TEMP_VAR = { unset = true }transform expands {VAR} placeholders using existing environment variables. Windows looks up these names without
regard to case. skip_if_set leaves the variable unchanged when it already exists. For .env files, use
env_files_skip_if_set = true. unset removes it entirely (different from setting to empty string). When an entry
combines skip_if_set with unset, an existing variable is kept.
Create a subdirectory config to override parent settings:
project/
├── pyproject.toml # [tool.pytest_env] DB_HOST = "prod-db"
└── tests_integration/
├── pytest.toml # [pytest_env] DB_HOST = "test-db"
└── test_api.py
Running pytest tests_integration/ uses the subdirectory configuration. The plugin walks up the directory tree and
stops at the first file containing a pytest_env section, so subdirectory configs naturally override parent configs.
Define environment variables under [tool.pytest_env] in pyproject.toml, or [pytest_env] in pytest.toml /
.pytest.toml:
[tool.pytest_env]
SIMPLE_VAR = "value"
NUMBER_VAR = 42
EXPANDED = { value = "{HOME}/path", transform = true }
CONDITIONAL = { value = "default", skip_if_set = true }
REMOVED = { unset = true }A TOML file with another name selected with -c is read like pytest.toml, from its [pytest_env] table.
Each key is the environment variable name. Values can be plain values (cast to string) or inline tables with the following keys:
| Key | Type | Description |
|---|---|---|
value |
string | The value to set. |
transform |
bool | Expand {VAR} references in the value using existing environment variables. |
skip_if_set |
bool | Only set the variable if it is not already defined. |
unset |
bool | Remove the variable from the environment (ignores value). |
A table with any other key, a flag that is not a boolean, or neither value nor unset = true stops pytest with a
usage error that names the entry. A dotted name must be quoted, as in "DATABASE.HOST" = "x": unquoted
DATABASE.HOST = "x" creates a DATABASE table instead.
Define environment variables as line-separated KEY=VALUE entries:
# pytest.ini
[pytest]
env =
HOME=~/tmp
RUN_ENV=test
D:CONDITIONAL=value
R:RAW_VALUE={USER}
U:REMOVED_VAR# pyproject.toml (INI-style)
[tool.pytest]
env = [
"HOME=~/tmp",
"RUN_ENV=test",
]# pytest.toml / .pytest.toml
[pytest]
env = [
"HOME=~/tmp",
"RUN_ENV=test",
]In pytest.toml / .pytest.toml, this pytest-native [pytest] table is an alternative to the plugin-specific
[pytest_env] TOML table described above. Both forms work there, so pytest.toml does not have to use [pytest_env].
In pytest’s native TOML options, env and env_files take lists of strings and env_files_skip_if_set takes a
boolean. A type error names the option and expected type.
Prefix flags modify behavior. Flags are case-insensitive and can be combined in any order (e.g., R:D:KEY=VALUE):
| Flag | Description |
|---|---|
D: |
Default -- only set if the variable is not already defined. |
R: |
Raw -- skip {VAR} expansion (INI expands by default, unlike TOML). |
U: |
Unset -- remove the variable from the environment entirely. |
A line with a flag other than D, R or U, or without a variable name, stops pytest with a usage error that gives
the entry's position. The error does not show the line's value.
In INI format variable expansion is enabled by default. In TOML format it requires transform = true. When an entry
combines D: with U:, an existing variable is kept. A malformed {VAR} template stops pytest with a usage error that
names the entry.
Specify .env files using the env_files configuration option:
[tool.pytest_env]
env_files = [".env", ".env.test"][pytest]
env_files =
.env
.env.testFiles are parsed by python-dotenv and support KEY=VALUE lines, #
comments, export prefix, quoted values with escape sequences in double quotes, and ${VAR:-default} expansion.
Malformed statements are skipped. pytest reports their file and line number in its warning summary.
Example .env file:
DATABASE_URL=postgres://localhost/mydb
export SECRET_KEY='my-secret-key'
DEBUG="true"
MESSAGE="hello\nworld"
API_KEY=${FALLBACK_KEY:-default_key}Both env_files and --envfile accept regular files. A directory or named pipe at a selected path stops pytest with a
usage error. Missing .env files from configuration are silently skipped. Configured env_files are resolved relative
to the project root. An explicit env_files = [] in native TOML configuration disables INI-style env_files fallback;
omitting the key preserves that fallback. CLI --envfile paths still load in either case, resolved relative to the
directory pytest was invoked from, then the project root.
Override or extend configuration-based env_files at runtime.
Override mode (--envfile PATH): loads only the specified file, ignoring all env_files from configuration.
Extend mode (--envfile +PATH): loads configuration files first in their normal order, then loads the CLI file.
Variables from the CLI file override those from configuration files.
Unlike configuration-based env_files, CLI-specified files must exist. Missing files raise FileNotFoundError. Paths
are resolved relative to the directory pytest was invoked from, then the project root. Configured env_files are
resolved relative to the project root.
Print all environment variable assignments in the test session header. Each line shows the action (SET, SKIP, or
UNSET), the variable name with its final value, and the source file:
pytest-env:
SET DATABASE_URL=postgres://localhost/test (from /path/to/.env)
SET DEBUG=true (from /path/to/pyproject.toml)
SKIP HOME=/Users/me (from /path/to/pyproject.toml)
UNSET TEMP_VAR (from /path/to/pyproject.toml)
Entries supplied through -o env=... show -o env as their source.
Non-printable characters in names, values and paths are shown escaped, so each assignment stays on one line.
Useful for debugging when multiple env files, inline configuration, and CLI options interact.
When multiple sources define the same variable, precedence applies in this order (highest to lowest):
- Inline variables in configuration files (TOML or INI format).
- Variables from
.envfiles loaded viaenv_files. When using--envfile, CLI files take precedence over configuration-basedenv_files. - Variables already present in the environment (preserved when
skip_if_set = true,D:flag is used, orenv_files_skip_if_set = true).
When multiple configuration formats are present, TOML native format ([pytest_env] / [tool.pytest_env]) takes
precedence over INI format. Among TOML files, the first file with a pytest_env section wins, checked in order:
pytest.toml, .pytest.toml, pyproject.toml. A TOML file with another name selected with -c is checked first and
is read like pytest.toml. If no TOML file contains pytest_env, the plugin falls back to INI-style env
configuration.
When the operating system rejects an assignment, pytest stops before collection and names the variable and its source.
The plugin walks up the directory tree starting from pytest's resolved configuration directory. For each directory, it
checks pytest.toml, .pytest.toml, and pyproject.toml in order, stopping at the first file containing a
pytest_env section. Only regular files are considered, so directories and other entries with these names are skipped.
A TOML file with another name selected with -c is checked before the walk and is read like pytest.toml. This means
subdirectory configurations take precedence over parent configurations, allowing different settings for integration
tests versus unit tests. A file on that path that is not valid TOML stops pytest with a usage error naming the file.
TOML native format ([pytest_env]) is best when you need fine-grained control over expansion and conditional
setting, or when your configuration uses multiple inline tables. Variable expansion requires explicit
transform = true.
INI format (env key) is best for simple KEY=VALUE pairs with minimal syntax. Variable expansion is on by default
(use R: to disable). Both formats are fully supported and can coexist -- TOML takes precedence if both are present.
.env files work well when you have many variables that would clutter your config file, want to share environment
configuration with other tools (Docker, shell scripts), or need different files for different environments. Inline
configuration is better for a small number of test-specific variables that should be version-controlled, or when you
need transform, skip_if_set, or unset. You can combine both -- inline variables always take precedence over .env
files.