pytest plugin that allows you to add environment variables
npx @tessl/cli install tessl/pypi-pytest-env@1.1.0A pytest plugin that enables setting environment variables in pytest configuration files (pytest.ini or pyproject.toml). The plugin automatically integrates with pytest's configuration system to set environment variables before test execution, supporting both simple key-value pairs and advanced features like variable transformation, conditional setting, and configuration precedence handling.
pip install pytest-envThe plugin automatically activates when installed - no explicit imports needed for basic usage.
For programmatic access to the plugin internals:
import pytest_env
from pytest_env.plugin import Entry, pytest_addoption, pytest_load_initial_conftests
from dataclasses import dataclass # Required for Entry class usage# pytest.ini
[pytest]
env =
HOME=/tmp/pytest-home
DEBUG=1
API_KEY=test-key-123# Via pytest.ini_options
[tool.pytest.ini_options]
env = [
"HOME=/tmp/pytest-home",
"DEBUG=1",
"API_KEY=test-key-123"
]
# Native pytest_env format (recommended)
[tool.pytest_env]
HOME = "/tmp/pytest-home"
DEBUG = 1
API_KEY = "test-key-123"Simple test demonstrating environment variable access:
import os
def test_environment_variables():
assert os.environ["HOME"] == "/tmp/pytest-home"
assert os.environ["DEBUG"] == "1"
assert os.environ["API_KEY"] == "test-key-123"The plugin automatically registers with pytest and provides configuration parsing functionality.
def pytest_addoption(parser):
"""
Add the 'env' configuration option to pytest ini files.
Args:
parser: pytest.Parser - pytest configuration parser
Returns:
None
"""
def pytest_load_initial_conftests(args, early_config, parser):
"""
Load and apply environment variables from configuration files.
Hook runs with tryfirst=True to ensure environment variables are
set before other plugins load.
Args:
args: list[str] - command line arguments
early_config: pytest.Config - pytest configuration object
parser: pytest.Parser - pytest parser object
Returns:
None
"""Internal representation of environment variable configurations.
@dataclass
class Entry:
"""
Configuration entries for environment variables.
Attributes:
key: str - Environment variable name
value: str - Environment variable value (may contain placeholders)
transform: bool - Whether to perform variable interpolation
skip_if_set: bool - Whether to skip setting if variable already exists
"""
key: str
value: str
transform: bool
skip_if_set: bool__version__: strPackage version string available from the main module.
import pytest_env
print(pytest_env.__version__) # e.g., "1.1.5"Reference existing environment variables using Python string formatting:
# pytest.ini
[pytest]
env =
USER_HOME=/home/{USER}
CUSTOM_PATH={PATH}:/custom/bin
PROJECT_DIR={PWD}/my-project# pyproject.toml - native format
[tool.pytest_env]
USER_HOME = {value = "/home/{USER}", transform = true}
CUSTOM_PATH = {value = "{PATH}:/custom/bin", transform = true}
PROJECT_DIR = {value = "{PWD}/my-project", transform = true}Set variables only if they don't already exist using the D: prefix in INI format or skip_if_set option in TOML:
# pytest.ini
[pytest]
env =
D:HOME=/tmp/default-home
D:DEBUG=0# pyproject.toml
[tool.pytest_env]
HOME = {value = "/tmp/default-home", skip_if_set = true}
DEBUG = {value = "0", skip_if_set = true}Preserve literal values without variable interpolation using R: prefix in INI format or transform = false in TOML:
# pytest.ini
[pytest]
env =
R:TEMPLATE_STRING=Hello {USER}!
R:LITERAL_BRACES={{not_a_variable}}# pyproject.toml
[tool.pytest_env]
TEMPLATE_STRING = {value = "Hello {USER}!", transform = false}
LITERAL_BRACES = {value = "{{not_a_variable}}", transform = false}Combine multiple flags for complex behavior:
# pytest.ini - order doesn't matter
[pytest]
env =
D:R:COMPLEX_VAR=literal_{VALUE}_here
R:D:ANOTHER_VAR=also_literal_{THING}When multiple configuration files exist, precedence follows this order:
[tool.pytest_env])[pytest] env = ...)[tool.pytest.ini_options] env = [...])The plugin searches for configuration files in this order:
pyproject.toml or pytest.ini file is usedThe plugin handles various error conditions:
{VAR_NAME} references cause KeyError during string formattingtryfirst=True to ensure environment variables are available to other plugins