pytest-env
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.
Installation
pip install pytest-env
Quick start
Add 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)
How-to guides
Load variables from .env files
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 top
To 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:
[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 = true
Control variable behavior
Variables 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. 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.
Set different environments for test suites
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.
Reference
TOML configuration format
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.
INI configuration format
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].
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.
.env file format
Specify .env files using the env_files configuration option:
[tool.pytest_env]
env_files = [".env", ".env.test"]
[pytest]
env_files =
.env
.env.test
Files 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.
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}
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.
CLI options
--envfile PATH
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.
--pytest-env-verbose
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)
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.
Explanation
Precedence
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.
File discovery
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.
Choosing a configuration format
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.
Metadata
Release files for pytest-env 1.8.6
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pytest_env-1.8.6.tar.gz | 59.4 kB | With provenance | Details for pytest_env-1.8.6.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pytest_env-1.8.6-py3-none-any.whl | Python 3 | none | any | Details for pytest_env-1.8.6-py3-none-any.whl |
Total release size: 122.8 kB
Release files / pytest_env-1.8.6.tar.gz
| Download URL | pytest_env-1.8.6.tar.gz |
|---|---|
| Size | 59.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
2bfa4c2f911b6e8239291dd4652a4547dbf6a44050942e12eea300204b168162
|
|
BLAKE2b-256 checksum How to use checksums |
c60b68d9ba18cf4fd7690d9833b54d96b281411733df3b8b875c9be163ef0e85
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logRelease files / pytest_env-1.8.6-py3-none-any.whl
| Download URL | pytest_env-1.8.6-py3-none-any.whl |
|---|---|
| Size | 63.4 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
11f3b45cddb4b03fce83ef0b9661f50e9ffdac93581e86d8a88a1a4d1c85587d
|
|
BLAKE2b-256 checksum How to use checksums |
5c5f1d806c209ccf2f65369e234ea0d55824d40f98c0d1671da2eaf92753c56f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logSecurity for pytest-env 1.8.6
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for pytest_env-1.8.6.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.