or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# pytest-env

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: pytest-env

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install pytest-env`

10

11

## Core Imports

12

13

The plugin automatically activates when installed - no explicit imports needed for basic usage.

14

15

For programmatic access to the plugin internals:

16

17

```python

18

import pytest_env

19

from pytest_env.plugin import Entry, pytest_addoption, pytest_load_initial_conftests

20

from dataclasses import dataclass # Required for Entry class usage

21

```

22

23

## Basic Usage

24

25

### INI-style Configuration (pytest.ini)

26

27

```ini

28

# pytest.ini

29

[pytest]

30

env =

31

HOME=/tmp/pytest-home

32

DEBUG=1

33

API_KEY=test-key-123

34

```

35

36

### TOML Configuration (pyproject.toml)

37

38

```toml

39

# Via pytest.ini_options

40

[tool.pytest.ini_options]

41

env = [

42

"HOME=/tmp/pytest-home",

43

"DEBUG=1",

44

"API_KEY=test-key-123"

45

]

46

47

# Native pytest_env format (recommended)

48

[tool.pytest_env]

49

HOME = "/tmp/pytest-home"

50

DEBUG = 1

51

API_KEY = "test-key-123"

52

```

53

54

Simple test demonstrating environment variable access:

55

56

```python

57

import os

58

59

def test_environment_variables():

60

assert os.environ["HOME"] == "/tmp/pytest-home"

61

assert os.environ["DEBUG"] == "1"

62

assert os.environ["API_KEY"] == "test-key-123"

63

```

64

65

## Capabilities

66

67

### Plugin System Integration

68

69

The plugin automatically registers with pytest and provides configuration parsing functionality.

70

71

```python { .api }

72

def pytest_addoption(parser):

73

"""

74

Add the 'env' configuration option to pytest ini files.

75

76

Args:

77

parser: pytest.Parser - pytest configuration parser

78

79

Returns:

80

None

81

"""

82

83

def pytest_load_initial_conftests(args, early_config, parser):

84

"""

85

Load and apply environment variables from configuration files.

86

Hook runs with tryfirst=True to ensure environment variables are

87

set before other plugins load.

88

89

Args:

90

args: list[str] - command line arguments

91

early_config: pytest.Config - pytest configuration object

92

parser: pytest.Parser - pytest parser object

93

94

Returns:

95

None

96

"""

97

```

98

99

### Configuration Entry Management

100

101

Internal representation of environment variable configurations.

102

103

```python { .api }

104

@dataclass

105

class Entry:

106

"""

107

Configuration entries for environment variables.

108

109

Attributes:

110

key: str - Environment variable name

111

value: str - Environment variable value (may contain placeholders)

112

transform: bool - Whether to perform variable interpolation

113

skip_if_set: bool - Whether to skip setting if variable already exists

114

"""

115

key: str

116

value: str

117

transform: bool

118

skip_if_set: bool

119

```

120

121

### Version Information

122

123

```python { .api }

124

__version__: str

125

```

126

127

Package version string available from the main module.

128

129

```python

130

import pytest_env

131

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

132

```

133

134

### Advanced Configuration Features

135

136

#### Variable Transformation

137

138

Reference existing environment variables using Python string formatting:

139

140

```ini

141

# pytest.ini

142

[pytest]

143

env =

144

USER_HOME=/home/{USER}

145

CUSTOM_PATH={PATH}:/custom/bin

146

PROJECT_DIR={PWD}/my-project

147

```

148

149

```toml

150

# pyproject.toml - native format

151

[tool.pytest_env]

152

USER_HOME = {value = "/home/{USER}", transform = true}

153

CUSTOM_PATH = {value = "{PATH}:/custom/bin", transform = true}

154

PROJECT_DIR = {value = "{PWD}/my-project", transform = true}

155

```

156

157

#### Conditional Setting (Default Values)

158

159

Set variables only if they don't already exist using the `D:` prefix in INI format or `skip_if_set` option in TOML:

160

161

```ini

162

# pytest.ini

163

[pytest]

164

env =

165

D:HOME=/tmp/default-home

166

D:DEBUG=0

167

```

168

169

```toml

170

# pyproject.toml

171

[tool.pytest_env]

172

HOME = {value = "/tmp/default-home", skip_if_set = true}

173

DEBUG = {value = "0", skip_if_set = true}

174

```

175

176

#### Raw Values (Skip Transformation)

177

178

Preserve literal values without variable interpolation using `R:` prefix in INI format or `transform = false` in TOML:

179

180

```ini

181

# pytest.ini

182

[pytest]

183

env =

184

R:TEMPLATE_STRING=Hello {USER}!

185

R:LITERAL_BRACES={{not_a_variable}}

186

```

187

188

```toml

189

# pyproject.toml

190

[tool.pytest_env]

191

TEMPLATE_STRING = {value = "Hello {USER}!", transform = false}

192

LITERAL_BRACES = {value = "{{not_a_variable}}", transform = false}

193

```

194

195

#### Combined Flags

196

197

Combine multiple flags for complex behavior:

198

199

```ini

200

# pytest.ini - order doesn't matter

201

[pytest]

202

env =

203

D:R:COMPLEX_VAR=literal_{VALUE}_here

204

R:D:ANOTHER_VAR=also_literal_{THING}

205

```

206

207

#### Configuration Precedence

208

209

When multiple configuration files exist, precedence follows this order:

210

211

1. **TOML native format** (`[tool.pytest_env]`)

212

2. **INI format** (`[pytest] env = ...`)

213

3. **TOML ini_options format** (`[tool.pytest.ini_options] env = [...]`)

214

215

#### Configuration Discovery

216

217

The plugin searches for configuration files in this order:

218

219

1. Current working directory

220

2. Parent directories (walking up the tree)

221

3. First found `pyproject.toml` or `pytest.ini` file is used

222

223

## Error Handling

224

225

The plugin handles various error conditions:

226

227

- **TOML Parse Errors**: Invalid TOML syntax causes pytest startup failure with descriptive error messages

228

- **Variable Reference Errors**: Missing environment variables in `{VAR_NAME}` references cause KeyError during string formatting

229

- **Configuration Validation**: Malformed entries are processed with reasonable defaults where possible

230

231

## Integration Notes

232

233

- **Automatic Activation**: Plugin activates automatically when installed, no manual registration required

234

- **Load Order**: Executes with `tryfirst=True` to ensure environment variables are available to other plugins

235

- **Global Scope**: Environment variables are set globally for the entire pytest process and all tests

236

- **Configuration Caching**: Configuration is parsed once during pytest startup for optimal performance