or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-configuration.mddata-filtering.mderror-handling.mdindex.mdrecord-modes.mdrequest-matching.mdrequest-response.mdserialization.mdtest-integration.md

core-configuration.mddocs/

0

# Core VCR Configuration

1

2

Central configuration and context management for HTTP recording and playback. The VCR class provides extensive customization options for controlling recording behavior, request/response filtering, and cassette management.

3

4

## Capabilities

5

6

### VCR Class

7

8

The main configuration class that manages all VCR behavior including recording modes, filtering, matching, and cassette persistence.

9

10

```python { .api }

11

class VCR:

12

"""

13

Main VCR configuration class for HTTP recording and playback.

14

15

Args:

16

path_transformer (callable, optional): Function to transform cassette file paths

17

before_record_request (callable, optional): Function to filter/modify requests before recording

18

custom_patches (tuple, optional): Additional HTTP library patches beyond default ones

19

filter_query_parameters (tuple, optional): Query parameter names to filter out of recordings

20

ignore_hosts (tuple, optional): Host names to ignore during recording (won't be recorded/matched)

21

record_mode (RecordMode, optional): When to record interactions (default: RecordMode.ONCE)

22

ignore_localhost (bool, optional): Whether to ignore localhost requests (default: False)

23

filter_headers (tuple, optional): Header names to filter out of recordings

24

before_record_response (callable, optional): Function to filter/modify responses before recording

25

filter_post_data_parameters (tuple, optional): POST data parameter names to filter out

26

match_on (tuple, optional): Request matching criteria (default: method,scheme,host,port,path,query)

27

before_record (callable, optional): Legacy parameter, use before_record_request instead

28

inject_cassette (bool, optional): Whether to inject cassette object into decorated functions

29

serializer (str, optional): Serialization format - "yaml" or "json" (default: "yaml")

30

cassette_library_dir (str, optional): Base directory for cassette files

31

func_path_generator (callable, optional): Function to generate cassette paths from function objects

32

decode_compressed_response (bool, optional): Whether to decode compressed response content

33

record_on_exception (bool, optional): Whether to record interactions that raise exceptions

34

"""

35

def __init__(

36

self,

37

path_transformer=None,

38

before_record_request=None,

39

custom_patches=(),

40

filter_query_parameters=(),

41

ignore_hosts=(),

42

record_mode=RecordMode.ONCE,

43

ignore_localhost=False,

44

filter_headers=(),

45

before_record_response=None,

46

filter_post_data_parameters=(),

47

match_on=("method", "scheme", "host", "port", "path", "query"),

48

before_record=None,

49

inject_cassette=False,

50

serializer="yaml",

51

cassette_library_dir=None,

52

func_path_generator=None,

53

decode_compressed_response=False,

54

record_on_exception=True,

55

): ...

56

```

57

58

### Context Manager and Decorator

59

60

The primary interface for using VCR to record and replay HTTP interactions.

61

62

```python { .api }

63

def use_cassette(self, path=None, **kwargs):

64

"""

65

Context manager and decorator for HTTP recording/playback.

66

67

Args:

68

path (str or Path, optional): Cassette file path. If None, auto-generated from function name

69

**kwargs: Override any VCR configuration parameters for this cassette

70

71

Returns:

72

Context manager that can also be used as a decorator

73

74

Usage:

75

# As decorator

76

@my_vcr.use_cassette('test.yaml')

77

def test_function():

78

# HTTP requests here will be recorded/replayed

79

80

# As context manager

81

with my_vcr.use_cassette('test.yaml'):

82

# HTTP requests here will be recorded/replayed

83

"""

84

```

85

86

### Configuration Management

87

88

Methods for getting merged configuration and managing VCR settings.

89

90

```python { .api }

91

def get_merged_config(self, **kwargs) -> dict:

92

"""

93

Get configuration with parameter overrides merged in.

94

95

Args:

96

**kwargs: Configuration overrides

97

98

Returns:

99

dict: Complete configuration for cassette creation

100

"""

101

```

102

103

### Extension and Customization

104

105

Methods for registering custom serializers, matchers, and persisters.

106

107

```python { .api }

108

def register_serializer(self, name: str, serializer) -> None:

109

"""

110

Register a custom serializer for cassette persistence.

111

112

Args:

113

name: Serializer name for reference in configuration

114

serializer: Module with serialize() and deserialize() functions

115

"""

116

117

def register_matcher(self, name: str, matcher: callable) -> None:

118

"""

119

Register a custom request matcher function.

120

121

Args:

122

name: Matcher name for reference in match_on configuration

123

matcher: Function taking (request1, request2) that raises AssertionError if no match

124

"""

125

126

def register_persister(self, persister) -> None:

127

"""

128

Register a custom cassette persister (singleton replacement).

129

130

Args:

131

persister: Persister class with appropriate interface

132

"""

133

```

134

135

### Test Case Integration

136

137

Utility for generating test case metaclasses with automatic VCR decoration.

138

139

```python { .api }

140

def test_case(self, predicate=None):

141

"""

142

Generate a metaclass that automatically decorates test methods with use_cassette.

143

144

Args:

145

predicate (callable, optional): Function to determine if a method should be decorated

146

(default: methods starting with 'test')

147

148

Returns:

149

Metaclass for automatic test method decoration

150

"""

151

```

152

153

### Utility Methods

154

155

Static utility methods for path and test method handling.

156

157

```python { .api }

158

@staticmethod

159

def is_test_method(method_name: str, function) -> bool:

160

"""

161

Determine if a method should be treated as a test method.

162

163

Args:

164

method_name: Name of the method

165

function: Function object

166

167

Returns:

168

bool: True if method should be decorated

169

"""

170

171

@staticmethod

172

def ensure_suffix(suffix: str) -> callable:

173

"""

174

Create a function that ensures file paths have the specified suffix.

175

176

Args:

177

suffix: File extension/suffix to ensure

178

179

Returns:

180

callable: Function that adds suffix if missing

181

"""

182

```

183

184

### Default VCR Instance

185

186

```python { .api }

187

# Pre-configured default VCR instance

188

default_vcr: VCR

189

190

# Convenience function using default instance

191

def use_cassette(path=None, **kwargs):

192

"""

193

Use cassette with the default VCR configuration.

194

195

This is equivalent to default_vcr.use_cassette(path, **kwargs)

196

"""

197

```

198

199

## Usage Examples

200

201

### Basic Configuration

202

203

```python

204

import vcr

205

206

# Use default configuration

207

@vcr.use_cassette('my_cassette.yaml')

208

def test_basic():

209

# HTTP requests recorded/replayed

210

pass

211

212

# Custom configuration

213

my_vcr = vcr.VCR(

214

record_mode=vcr.mode.NEW_EPISODES,

215

serializer='json',

216

filter_headers=['authorization', 'x-api-key'],

217

ignore_hosts=['metrics.example.com']

218

)

219

220

@my_vcr.use_cassette('custom.json')

221

def test_custom():

222

pass

223

```

224

225

### Advanced Filtering

226

227

```python

228

def my_request_filter(request):

229

# Remove sensitive query parameters

230

if 'api_key' in request.uri:

231

# Custom logic to sanitize request

232

pass

233

return request

234

235

def my_response_filter(response):

236

# Remove sensitive response data

237

return response

238

239

my_vcr = vcr.VCR(

240

before_record_request=my_request_filter,

241

before_record_response=my_response_filter,

242

filter_query_parameters=['api_key', 'session_id'],

243

filter_post_data_parameters=['password', 'secret']

244

)

245

```

246

247

### Custom Matching

248

249

```python

250

def custom_matcher(r1, r2):

251

# Custom matching logic

252

if r1.path != r2.path:

253

raise AssertionError("Paths don't match")

254

255

my_vcr = vcr.VCR(

256

match_on=['method', 'scheme', 'host', 'custom_matcher']

257

)

258

my_vcr.register_matcher('custom_matcher', custom_matcher)

259

```