HTTP traffic mocking and expectations made easy for Python testing and development
npx @tessl/cli install tessl/pypi-pook@2.1.00
# Pook
1
2
Pook is a versatile HTTP mocking library for Python that provides a fluent, declarative interface for creating HTTP request/response mocks. It enables developers to intercept and mock HTTP traffic for testing and development, supporting a wide range of HTTP methods, request matching patterns, and response configurations.
3
4
## Package Information
5
6
- **Package Name**: pook
7
- **Language**: Python
8
- **Installation**: `pip install pook`
9
10
## Core Imports
11
12
```python
13
import pook
14
```
15
16
For specific functionality:
17
18
```python
19
from pook import (
20
# Engine control
21
activate, on, disable, off, reset, use, use_network,
22
# HTTP method functions
23
get, post, put, patch, delete, head, options, mock,
24
# Core classes
25
Mock, Request, Response, Engine, MatcherEngine, MockEngine,
26
# State inspection
27
pending, pending_mocks, unmatched_requests, isactive, isdone,
28
# Network control
29
enable_network, disable_network, use_network_filter,
30
# Utilities
31
regex
32
)
33
```
34
35
Pytest integration (automatic with pytest plugin):
36
37
```python
38
def test_with_pook(pook):
39
# pook fixture automatically available when pook is installed
40
pass
41
```
42
43
## Basic Usage
44
45
```python
46
import pook
47
import requests
48
49
# Activate pook HTTP interception
50
pook.activate()
51
52
# Create a mock for a GET request
53
pook.get('https://api.example.com/users/1').reply(200).json({
54
'id': 1,
55
'name': 'John Doe',
56
'email': 'john@example.com'
57
})
58
59
# Make the HTTP request - it will be intercepted by pook
60
response = requests.get('https://api.example.com/users/1')
61
print(response.json()) # {'id': 1, 'name': 'John Doe', 'email': 'john@example.com'}
62
63
# Clean up
64
pook.off()
65
```
66
67
Using as decorator:
68
69
```python
70
import pook
71
import requests
72
73
@pook.activate
74
def test_api_call():
75
# Mock is active only within this function
76
pook.get('https://api.example.com/health').reply(200).json({'status': 'ok'})
77
78
response = requests.get('https://api.example.com/health')
79
assert response.json()['status'] == 'ok'
80
81
test_api_call()
82
```
83
84
Using with context manager:
85
86
```python
87
import pook
88
import requests
89
90
with pook.use() as mock_engine:
91
# Create mocks within isolated engine
92
pook.post('https://api.example.com/users').reply(201).json({'id': 2})
93
94
response = requests.post('https://api.example.com/users', json={'name': 'Jane'})
95
assert response.status_code == 201
96
# Engine automatically cleaned up
97
```
98
99
## Architecture
100
101
Pook's architecture is built around three core components that work together to provide flexible HTTP mocking:
102
103
- **Mock**: The primary interface for defining request expectations and response behavior using a fluent API. Mocks specify what requests to intercept and how to respond.
104
- **Request**: Represents request matching criteria including URL, method, headers, body content, and custom matchers.
105
- **Response**: Defines the mock response including status code, headers, body content, and response timing.
106
- **Engine**: Manages the mock lifecycle, request interception, and networking modes. Provides isolation and state management.
107
108
This design enables pook to integrate seamlessly with popular HTTP libraries like requests, urllib, and aiohttp while providing comprehensive mocking capabilities for testing and development workflows.
109
110
## Capabilities
111
112
### Mock Creation Functions
113
114
HTTP method-specific functions for creating mocks with fluent API support. These functions provide the primary interface for setting up HTTP request interceptions.
115
116
```python { .api }
117
def mock(url=None, **kw):
118
"""
119
Creates and registers a new HTTP mock.
120
121
Parameters:
122
- url (str, optional): Request URL to mock
123
- activate (bool, optional): Force mock engine activation
124
- **kw: Additional Mock constructor arguments
125
126
Returns:
127
Mock: New mock instance
128
"""
129
130
def get(url, **kw):
131
"""
132
Registers a new mock HTTP request with GET method.
133
134
Parameters:
135
- url (str): Request URL to mock
136
- **kw: Additional Mock constructor arguments
137
138
Returns:
139
Mock: Mock instance
140
"""
141
142
def post(url, **kw):
143
"""
144
Registers a new mock HTTP request with POST method.
145
146
Parameters:
147
- url (str): Request URL to mock
148
- **kw: Additional Mock constructor arguments
149
150
Returns:
151
Mock: Mock instance
152
"""
153
154
def put(url, **kw):
155
"""
156
Registers a new mock HTTP request with PUT method.
157
158
Parameters:
159
- url (str): Request URL to mock
160
- **kw: Additional Mock constructor arguments
161
162
Returns:
163
Mock: Mock instance
164
"""
165
166
def patch(url=None, **kw):
167
"""
168
Registers a new mock HTTP request with PATCH method.
169
170
Parameters:
171
- url (str): Request URL to mock
172
- **kw: Additional Mock constructor arguments
173
174
Returns:
175
Mock: Mock instance
176
"""
177
178
def delete(url, **kw):
179
"""
180
Registers a new mock HTTP request with DELETE method.
181
182
Parameters:
183
- url (str): Request URL to mock
184
- **kw: Additional Mock constructor arguments
185
186
Returns:
187
Mock: Mock instance
188
"""
189
190
def head(url, **kw):
191
"""
192
Registers a new mock HTTP request with HEAD method.
193
194
Parameters:
195
- url (str): Request URL to mock
196
- **kw: Additional Mock constructor arguments
197
198
Returns:
199
Mock: Mock instance
200
"""
201
202
def options(url=None, **kw):
203
"""
204
Registers a new mock HTTP request with OPTIONS method.
205
206
Parameters:
207
- url (str): Request URL to mock
208
- **kw: Additional Mock constructor arguments
209
210
Returns:
211
Mock: Mock instance
212
"""
213
```
214
215
[Mock Creation](./mock-creation.md)
216
217
### Mock Configuration Classes
218
219
Core classes for detailed request matching and response configuration. These classes provide the building blocks for complex mock scenarios.
220
221
```python { .api }
222
class Mock:
223
"""
224
Mock is used to declare and compose HTTP request/response mock
225
definition and matching expectations with fluent API DSL.
226
"""
227
228
def __init__(self, url=None, method=None, **kw):
229
"""
230
Parameters:
231
- url (str): URL to match
232
- method (str): HTTP method name to match
233
- **kw: Additional configuration options
234
"""
235
236
class Request:
237
"""
238
Request object representing the request mock expectation DSL.
239
"""
240
241
def __init__(self, method="GET", url=None, headers=None, query=None, body=None, **kw):
242
"""
243
Parameters:
244
- method (str): HTTP method to match
245
- url (str): URL request to intercept and match
246
- headers (dict): HTTP headers to match
247
- query (dict): URL query params to match
248
- body (bytes): Request body payload to match
249
"""
250
251
class Response:
252
"""
253
Response is used to declare and compose HTTP mock response
254
fields with chainable DSL interface.
255
"""
256
257
def __init__(self, status=200, headers=None, body=None, **kw):
258
"""
259
Parameters:
260
- status (int): HTTP response status code
261
- headers (dict): HTTP response headers
262
- body (str|bytes): HTTP response body
263
"""
264
```
265
266
[Mock Configuration](./mock-configuration.md)
267
268
### Engine Management Functions
269
270
Functions for controlling pook's HTTP interception engine, networking modes, and mock lifecycle management.
271
272
```python { .api }
273
def activate(fn=None):
274
"""
275
Enables HTTP traffic interceptors. Can be used as a decorator.
276
277
Parameters:
278
- fn (function, optional): Function to decorate when used as decorator
279
280
Returns:
281
function: Decorator wrapper when used as decorator, None otherwise
282
"""
283
284
def disable():
285
"""
286
Disables HTTP traffic interceptors without flushing mocks.
287
"""
288
289
def reset():
290
"""
291
Resets current mock engine state, flushing all registered mocks.
292
"""
293
294
def engine():
295
"""
296
Returns the current running mock engine instance.
297
298
Returns:
299
Engine: Current engine instance
300
"""
301
302
def use(network=False):
303
"""
304
Creates a new isolated mock engine to be used via context manager.
305
306
Parameters:
307
- network (bool, optional): Enable networking mode
308
309
Returns:
310
Context manager yielding Engine
311
"""
312
313
def use_network():
314
"""
315
Creates a new isolated mock engine with networking enabled.
316
317
Returns:
318
Context manager yielding Engine with networking mode enabled
319
"""
320
321
def enable_network(*hostnames):
322
"""
323
Enables real networking mode for unmatched mocks.
324
325
Parameters:
326
- *hostnames (str): Optional hostnames to enable networking for
327
"""
328
329
def disable_network():
330
"""
331
Disables real traffic networking mode in the current mock engine.
332
"""
333
334
def use_network_filter(*fn):
335
"""
336
Adds network filters to determine if certain outgoing unmatched HTTP
337
traffic can establish real network connections.
338
339
Parameters:
340
- *fn (function): Variadic function filter arguments to be used
341
"""
342
```
343
344
[Engine Management](./engine-management.md)
345
346
### State Inspection Functions
347
348
Functions for examining mock states, pending mocks, unmatched requests, and engine status for debugging and testing.
349
350
```python { .api }
351
def pending():
352
"""
353
Returns the number of pending mocks to be matched.
354
355
Returns:
356
int: Number of pending mocks
357
"""
358
359
def pending_mocks():
360
"""
361
Returns pending mocks to be matched.
362
363
Returns:
364
list: List of pending mock instances
365
"""
366
367
def unmatched_requests():
368
"""
369
Returns a list of unmatched requests (networking mode only).
370
371
Returns:
372
list: List of unmatched intercepted requests
373
"""
374
375
def unmatched():
376
"""
377
Returns the total number of unmatched requests intercepted by pook.
378
379
Returns:
380
int: Total number of unmatched requests
381
"""
382
383
def isunmatched():
384
"""
385
Returns True if there are unmatched requests (networking mode only).
386
387
Returns:
388
bool: True if unmatched requests exist
389
"""
390
391
def isactive():
392
"""
393
Returns True if pook is active and intercepting traffic.
394
395
Returns:
396
bool: Current activation status
397
"""
398
399
def isdone():
400
"""
401
Returns True if all registered mocks have been triggered.
402
403
Returns:
404
bool: Completion status
405
"""
406
```
407
408
[State Inspection](./state-inspection.md)
409
410
### Pytest Integration
411
412
Built-in pytest fixture for HTTP traffic mocking in test environments.
413
414
```python { .api }
415
def pook():
416
"""
417
Pytest fixture for HTTP traffic mocking and testing.
418
419
Provides an isolated pook engine that automatically activates
420
for the test duration and cleans up afterward.
421
422
Returns:
423
pook module with activated engine in isolated context
424
"""
425
```
426
427
Usage example:
428
429
```python
430
import requests
431
432
def test_api_call(pook):
433
# pook fixture automatically provides isolated engine
434
pook.get('https://api.example.com/users').reply(200).json([
435
{'id': 1, 'name': 'John'}
436
])
437
438
response = requests.get('https://api.example.com/users')
439
assert response.status_code == 200
440
assert len(response.json()) == 1
441
# Engine automatically deactivated and cleaned up
442
```
443
444
## Types
445
446
```python { .api }
447
class Engine:
448
"""
449
Engine represents the mock interceptor and matcher engine responsible
450
for triggering interceptors and matching outgoing HTTP traffic.
451
"""
452
453
def __init__(self, network=False):
454
"""
455
Parameters:
456
- network (bool, optional): Enables/disables real networking mode
457
"""
458
459
# Key attributes
460
debug: bool # Enables/disables debug mode
461
active: bool # Current engine activation status
462
networking: bool # Current engine networking mode status
463
mocks: list # Engine mocks
464
unmatched_reqs: list # Unmatched outgoing HTTP requests
465
466
class MatcherEngine:
467
"""
468
HTTP request matcher engine used by Mock to test if an intercepted
469
outgoing HTTP request should be mocked out.
470
"""
471
472
def add(self, matcher):
473
"""
474
Adds new matcher function to engine.
475
476
Parameters:
477
- matcher: Matcher function or object
478
"""
479
480
def match(self, request):
481
"""
482
Matches HTTP request against registered matchers.
483
484
Parameters:
485
- request: HTTP request to match
486
487
Returns:
488
tuple: (bool, list[str]) - Match result and error messages
489
"""
490
491
class MockEngine:
492
"""
493
Low-level HTTP traffic interceptor engine that manages interceptors
494
for different HTTP clients.
495
"""
496
497
def add_interceptor(self, *interceptors):
498
"""
499
Adds HTTP traffic interceptors.
500
501
Parameters:
502
- *interceptors: Interceptor instances to add
503
"""
504
505
def flush_interceptors(self):
506
"""
507
Flushes all registered HTTP traffic interceptors.
508
"""
509
510
def remove_interceptor(self, name):
511
"""
512
Removes a specific interceptor by name.
513
514
Parameters:
515
- name (str): Name of the interceptor to remove
516
"""
517
518
def activate(self):
519
"""
520
Activates all registered HTTP traffic interceptors.
521
"""
522
523
def disable(self):
524
"""
525
Disables all registered HTTP traffic interceptors.
526
"""
527
528
def regex(expression, flags=None):
529
"""
530
Convenient shortcut to re.compile() for regex compilation.
531
532
Parameters:
533
- expression (str): Regular expression value
534
- flags (int, optional): Regular expression flags
535
536
Returns:
537
Pattern: Compiled regular expression object
538
"""
539
```