HTTP traffic mocking and expectations made easy for Python testing and development
—
HTTP method functions and mock creation patterns for intercepting and mocking HTTP requests. These functions provide the primary interface for creating mocks using pook's fluent API, allowing you to easily set up request interceptions with method-specific shortcuts.
Creates a generic HTTP mock that can be configured for any HTTP method and request pattern.
def mock(url=None, **kw):
"""
Creates and registers a new HTTP mock.
Parameters:
- url (str, optional): Request URL to mock
- activate (bool, optional): Force mock engine activation. Defaults to False
- **kw: Variadic keyword arguments for Mock constructor including:
- method (str): HTTP method name to match
- path (str): URL path to match
- headers (dict): Header values to match
- params (dict): URL params to match
- body (str|regex): Request body to match
- json (dict|list|str|regex): JSON payload body to match
- times (int): Mock TTL or maximum number of matches
- persist (bool): Enable persistent mode
- reply (int): Mock response status code
- response_body (str): Response body to use
- response_json (dict|list|str): Response JSON to use
Returns:
Mock: New mock instance
"""Usage examples:
import pook
# Basic mock creation
mock = pook.mock('https://api.example.com/data')
mock.method('POST').json({'key': 'value'}).reply(201)
# Mock with immediate configuration
pook.mock('https://api.example.com/users',
method='GET',
reply=200,
response_json={'users': []})
# Force engine activation
pook.mock('https://api.example.com/health', activate=True).reply(200)Creates a mock specifically for GET requests with convenient method-specific configuration.
def get(url, **kw):
"""
Registers a new mock HTTP request with GET method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for GET method
"""Usage examples:
import pook
# Simple GET mock
pook.get('https://api.example.com/users').reply(200).json([
{'id': 1, 'name': 'John'},
{'id': 2, 'name': 'Jane'}
])
# GET with query parameters
pook.get('https://api.example.com/users').param('page', '1').param('limit', '10').reply(200)
# GET with headers validation
pook.get('https://api.example.com/protected').header('Authorization', 'Bearer token').reply(200)Creates a mock for POST requests with support for request body validation and response configuration.
def post(url, **kw):
"""
Registers a new mock HTTP request with POST method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for POST method
"""Usage examples:
import pook
# POST with JSON body validation
pook.post('https://api.example.com/users').json({
'name': 'John Doe',
'email': 'john@example.com'
}).reply(201).json({'id': 123, 'name': 'John Doe'})
# POST with form data
pook.post('https://api.example.com/login').body('username=admin&password=secret').reply(200)
# POST with content type validation
pook.post('https://api.example.com/upload').type('application/json').reply(200)Creates a mock for PUT requests, typically used for updating resources.
def put(url, **kw):
"""
Registers a new mock HTTP request with PUT method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for PUT method
"""Usage examples:
import pook
# PUT for resource updates
pook.put('https://api.example.com/users/123').json({
'name': 'John Smith',
'email': 'john.smith@example.com'
}).reply(200).json({'id': 123, 'name': 'John Smith'})
# PUT with path parameters
pook.put('https://api.example.com/users/123').reply(204)Creates a mock for PATCH requests, used for partial resource updates.
def patch(url=None, **kw):
"""
Registers a new mock HTTP request with PATCH method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for PATCH method
"""Usage examples:
import pook
# PATCH for partial updates
pook.patch('https://api.example.com/users/123').json({
'email': 'newemail@example.com'
}).reply(200).json({'id': 123, 'email': 'newemail@example.com'})
# PATCH with validation
pook.patch('https://api.example.com/settings').header('Content-Type', 'application/json').reply(200)Creates a mock for DELETE requests, typically used for resource deletion.
def delete(url, **kw):
"""
Registers a new mock HTTP request with DELETE method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for DELETE method
"""Usage examples:
import pook
# DELETE with no response body
pook.delete('https://api.example.com/users/123').reply(204)
# DELETE with confirmation response
pook.delete('https://api.example.com/users/123').reply(200).json({
'message': 'User deleted successfully'
})
# DELETE with authorization check
pook.delete('https://api.example.com/users/123').header('Authorization', 'Bearer token').reply(204)Creates a mock for HEAD requests, used to retrieve headers without response body.
def head(url, **kw):
"""
Registers a new mock HTTP request with HEAD method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for HEAD method
"""Usage examples:
import pook
# HEAD request for resource existence check
pook.head('https://api.example.com/users/123').reply(200).header('Content-Length', '1024')
# HEAD with custom headers
pook.head('https://api.example.com/files/document.pdf').reply(200).headers({
'Content-Type': 'application/pdf',
'Content-Length': '2048576',
'Last-Modified': 'Wed, 21 Oct 2023 07:28:00 GMT'
})Creates a mock for OPTIONS requests, typically used for CORS preflight requests.
def options(url=None, **kw):
"""
Registers a new mock HTTP request with OPTIONS method.
Parameters:
- url (str): Request URL to mock
- **kw: Additional Mock constructor arguments (same as mock() function)
Returns:
Mock: Mock instance configured for OPTIONS method
"""Usage examples:
import pook
# OPTIONS for CORS preflight
pook.options('https://api.example.com/users').reply(200).headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization'
})
# OPTIONS with specific origin validation
pook.options('https://api.example.com/data').header('Origin', 'https://myapp.com').reply(200)All mock creation functions return Mock instances that support method chaining:
# Chaining multiple configurations
pook.get('https://api.example.com/users') \
.header('Authorization', 'Bearer token') \
.param('page', '1') \
.reply(200) \
.json({'users': [], 'total': 0})
# Complex request matching
pook.post('https://api.example.com/webhooks') \
.header('X-Webhook-Secret', 'secret123') \
.json({'event': 'user.created'}) \
.reply(200) \
.json({'received': True})
# Multiple response scenarios
mock = pook.get('https://api.example.com/flaky-endpoint')
mock.times(3).reply(500) # Fail 3 times
mock.reply(200).json({'data': 'success'}) # Then succeedMock creation functions work seamlessly with pook's context management:
# Using with activation decorator
@pook.activate
def test_api():
pook.get('https://api.example.com/test').reply(200)
# Test code here
# Using with context manager
with pook.use():
pook.post('https://api.example.com/data').reply(201)
# HTTP requests are mocked within this block
# Using with isolated engines
with pook.use() as engine:
engine.mock('https://api.example.com/isolated').reply(200)
# Isolated mock scopeInstall with Tessl CLI
npx tessl i tessl/pypi-pook