or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-pytest-env

pytest plugin that allows you to add environment variables

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pytest-env@1.1.x

To install, run

npx @tessl/cli install tessl/pypi-pytest-env@1.1.0

index.mddocs/

pytest-env

A 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.

Package Information

  • Package Name: pytest-env
  • Package Type: pypi
  • Language: Python
  • Installation: pip install pytest-env

Core Imports

The 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

Basic Usage

INI-style Configuration (pytest.ini)

# pytest.ini
[pytest]
env = 
    HOME=/tmp/pytest-home
    DEBUG=1
    API_KEY=test-key-123

TOML Configuration (pyproject.toml)

# 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"

Capabilities

Plugin System Integration

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
    """

Configuration Entry Management

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 Information

__version__: str

Package version string available from the main module.

import pytest_env
print(pytest_env.__version__)  # e.g., "1.1.5"

Advanced Configuration Features

Variable Transformation

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}

Conditional Setting (Default Values)

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}

Raw Values (Skip Transformation)

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}

Combined Flags

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}

Configuration Precedence

When multiple configuration files exist, precedence follows this order:

  1. TOML native format ([tool.pytest_env])
  2. INI format ([pytest] env = ...)
  3. TOML ini_options format ([tool.pytest.ini_options] env = [...])

Configuration Discovery

The plugin searches for configuration files in this order:

  1. Current working directory
  2. Parent directories (walking up the tree)
  3. First found pyproject.toml or pytest.ini file is used

Error Handling

The plugin handles various error conditions:

  • TOML Parse Errors: Invalid TOML syntax causes pytest startup failure with descriptive error messages
  • Variable Reference Errors: Missing environment variables in {VAR_NAME} references cause KeyError during string formatting
  • Configuration Validation: Malformed entries are processed with reasonable defaults where possible

Integration Notes

  • Automatic Activation: Plugin activates automatically when installed, no manual registration required
  • Load Order: Executes with tryfirst=True to ensure environment variables are available to other plugins
  • Global Scope: Environment variables are set globally for the entire pytest process and all tests
  • Configuration Caching: Configuration is parsed once during pytest startup for optimal performance