CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pook

HTTP traffic mocking and expectations made easy for Python testing and development

Pending
Overview
Eval results
Files

mock-configuration.mddocs/

Mock Configuration

Mock class and request/response configuration for detailed HTTP mock setup. This module provides the core classes for defining complex request matching criteria and response behaviors using pook's fluent API.

Capabilities

Mock Class

The primary interface for creating and configuring HTTP mocks with comprehensive request matching and response definition capabilities.

class Mock:
    """
    Mock is used to declare and compose HTTP request/response mock 
    definition and matching expectations with fluent API DSL.
    """
    
    def __init__(self, url=None, method=None, path=None, headers=None, 
                 header_present=None, headers_present=None, type=None, 
                 content=None, params=None, param_exists=None, 
                 params_exists=None, body=None, json=None, jsonschema=None, 
                 xml=None, file=None, times=None, persist=None, delay=None, 
                 callback=None, reply=None, response_status=None, 
                 response_headers=None, response_type=None, response_body=None, 
                 response_json=None, response_xml=None, request=None, response=None):
        """
        Parameters:
        - url (str): URL to match
        - method (str): HTTP method name to match  
        - path (str): URL path to match
        - headers (dict): Header values to match
        - header_present (str): Matches if a header is present
        - headers_present (list|tuple): Matches if multiple headers are present
        - type (str): Matches MIME Content-Type header
        - content (str): Same as type argument
        - params (dict): Matches the given URL params
        - param_exists (str): Matches if a given URL param exists
        - params_exists (list|tuple): Matches if given URL params exist
        - body (str|regex): Matches the payload body
        - json (dict|list|str|regex): Matches JSON payload body
        - jsonschema (dict|str): Matches payload body against JSONSchema
        - xml (str|regex): Matches XML payload body
        - file (str): Disk file path to load body from
        - times (int): Mock TTL or maximum number of matches
        - persist (bool): Enable persistent mode
        - delay (int): Optional network delay simulation
        - callback (function): Callback function called when mock is matched
        - reply (int): Mock response status. Defaults to 200
        - response_status (int): Alias to reply param
        - response_headers (dict): Response headers to use
        - response_type (str): Response MIME type expression or alias
        - response_body (str): Response body to use
        - response_json (dict|list|str): Response JSON to use
        - response_xml (str): XML body string to use
        - request (Request): Optional Request mock definition object
        - response (Response): Optional Response mock definition object
        """
    
    # Request Configuration Methods
    def url(self, url):
        """
        Defines mock URL to match.
        
        Parameters:
        - url (str|regex): URL pattern to match
        
        Returns:
        Mock: Self for method chaining
        """
    
    def method(self, method):
        """
        Defines HTTP method to match.
        
        Parameters:
        - method (str): HTTP method name (GET, POST, PUT, etc.)
        
        Returns:
        Mock: Self for method chaining
        """
    
    def path(self, path):
        """
        Defines URL path to match.
        
        Parameters:
        - path (str|regex): URL path pattern to match
        
        Returns:
        Mock: Self for method chaining
        """
    
    def header(self, name, value):
        """
        Defines header to match.
        
        Parameters:
        - name (str): Header name
        - value (str|regex): Header value or pattern
        
        Returns:
        Mock: Self for method chaining
        """
    
    def headers(self, headers):
        """
        Defines multiple headers to match.
        
        Parameters:
        - headers (dict): Dictionary of header name-value pairs
        
        Returns:
        Mock: Self for method chaining
        """
    
    def header_present(self, *names):
        """
        Matches if headers are present (regardless of value).
        
        Parameters:
        - *names (str): Header names to check for presence
        
        Returns:
        Mock: Self for method chaining
        """
    
    def headers_present(self, headers):
        """
        Matches if multiple headers are present (regardless of values).
        
        Parameters:
        - headers (list|tuple): List of header names to check for presence
        
        Returns:
        Mock: Self for method chaining
        """
    
    def type(self, value):
        """
        Defines Content-Type header to match.
        
        Parameters:
        - value (str): Content-Type value or alias (json, xml, form, etc.)
        
        Returns:
        Mock: Self for method chaining
        """
    
    def content(self, value):
        """
        Alias to type() method for Content-Type matching.
        
        Parameters:
        - value (str): Content-Type value or alias
        
        Returns:
        Mock: Self for method chaining
        """
    
    def param(self, name, value):
        """
        Defines URL parameter to match.
        
        Parameters:
        - name (str): Parameter name
        - value (str|regex): Parameter value or pattern
        
        Returns:
        Mock: Self for method chaining
        """
    
    def params(self, params):
        """
        Defines multiple URL parameters to match.
        
        Parameters:
        - params (dict): Dictionary of parameter name-value pairs
        
        Returns:
        Mock: Self for method chaining
        """
    
    def param_exists(self, name, allow_empty=False):
        """
        Checks if URL parameter exists.
        
        Parameters:
        - name (str): Parameter name to check
        - allow_empty (bool): Allow empty parameter values
        
        Returns:
        Mock: Self for method chaining
        """
    
    def body(self, body):
        """
        Defines body data to match.
        
        Parameters:
        - body (str|bytes|regex): Request body content or pattern
        
        Returns:
        Mock: Self for method chaining
        """
    
    def json(self, json_data):
        """
        Defines JSON body to match.
        
        Parameters:
        - json_data (dict|list|str|regex): JSON data or pattern
        
        Returns:
        Mock: Self for method chaining
        """
    
    def jsonschema(self, schema):
        """
        Defines JSONSchema for body matching.
        
        Parameters:
        - schema (dict|str): JSONSchema definition
        
        Returns:
        Mock: Self for method chaining
        """
    
    def xml(self, xml_data):
        """
        Defines XML body to match.
        
        Parameters:
        - xml_data (str|regex): XML content or pattern
        
        Returns:
        Mock: Self for method chaining
        """
    
    def file(self, path):
        """
        Reads body from disk file.
        
        Parameters:
        - path (str): File path to read body content from
        
        Returns:
        Mock: Self for method chaining
        """
    
    # Mock Behavior Configuration
    def times(self, times=1):
        """
        Defines TTL limit for mock (how many times it can be matched).
        
        Parameters:
        - times (int): Number of times mock can be matched
        
        Returns:
        Mock: Self for method chaining
        """
    
    def persist(self, status=None):
        """
        Enables persistent mode (mock never expires).
        
        Parameters:
        - status (bool, optional): Enable/disable persistence
        
        Returns:
        Mock: Self for method chaining
        """
    
    def delay(self, delay=1000):
        """
        Delays network response simulation.
        
        Parameters:
        - delay (int): Delay in milliseconds
        
        Returns:
        Mock: Self for method chaining
        """
    
    def callback(self, *callbacks):
        """
        Registers callbacks for matched requests.
        
        Parameters:
        - *callbacks (function): Callback functions to register
        
        Returns:
        Mock: Self for method chaining
        """
    
    def error(self, error):
        """
        Defines error exception to raise when mock is matched.
        
        Parameters:
        - error (Exception): Exception instance to raise
        
        Returns:
        Mock: Self for method chaining
        """
    
    def add_matcher(self, matcher):
        """
        Adds custom matcher function to mock.
        
        Parameters:
        - matcher (function): Custom matcher function that accepts request parameter
        
        Returns:
        Mock: Self for method chaining
        """
    
    def use(self, *matchers):
        """
        Adds multiple matcher functions to mock.
        
        Parameters:
        - *matchers (function): Matcher functions to add
        
        Returns:
        Mock: Self for method chaining
        """
    
    def filter(self, *filters):
        """
        Adds request filter functions for pre-processing.
        
        Parameters:
        - *filters (function): Filter functions to add
        
        Returns:
        Mock: Self for method chaining
        """
    
    def map(self, *mappers):
        """
        Adds request mapper functions for request transformation.
        
        Parameters:
        - *mappers (function): Mapper functions to add
        
        Returns:
        Mock: Self for method chaining
        """
    
    # Response Configuration
    def reply(self, status=200, **kw):
        """
        Defines mock response.
        
        Parameters:
        - status (int): Response status code
        - **kw: Additional response configuration
        
        Returns:
        Mock: Self for method chaining
        """
    
    def status(self, code=200):
        """
        Defines response status code.
        
        Parameters:
        - code (int): HTTP status code
        
        Returns:
        Mock: Self for method chaining
        """
    
    def response(self, status=200, **kw):
        """
        Alias to reply() method.
        
        Parameters:
        - status (int): Response status code
        - **kw: Additional response configuration
        
        Returns:
        Mock: Self for method chaining
        """
    
    # State Methods
    def isdone(self):
        """
        Returns if mock has been matched/completed.
        
        Returns:
        bool: True if mock is done
        """
    
    def ismatched(self):
        """
        Returns if mock has been matched at least once.
        
        Returns:
        bool: True if mock has been matched
        """
    
    def match(self, request):
        """
        Matches outgoing HTTP request against this mock.
        
        Parameters:
        - request: HTTP request to match
        
        Returns:
        bool: True if request matches this mock
        """
    
    # Properties
    @property
    def done(self):
        """True if mock is done/matched."""
        
    @property
    def matched(self):
        """True if mock has been matched at least once."""
        
    @property
    def total_matches(self):
        """Total number of times mock has been matched."""
        
    @property
    def calls(self):
        """Number of mock matched calls."""
        
    @property
    def matches(self):
        """Number of times this mock has been matched (alias to calls)."""

Usage examples:

import pook

# Basic mock configuration
mock = pook.Mock('https://api.example.com/users')
mock.method('GET').header('Authorization', 'Bearer token').reply(200)

# Fluent API chaining
pook.Mock() \
    .url('https://api.example.com/data') \
    .method('POST') \
    .json({'type': 'test'}) \
    .header('Content-Type', 'application/json') \
    .reply(201) \
    .json({'id': 123, 'status': 'created'})

# Advanced matching with regex
import re
pook.Mock() \
    .url(re.compile(r'https://api\.example\.com/users/\d+')) \
    .method('PUT') \
    .jsonschema({'type': 'object', 'properties': {'name': {'type': 'string'}}}) \
    .reply(200)

# Context manager usage
with pook.Mock('https://api.example.com/temp') as mock:
    mock.get().reply(200).json({'temp': True})
    # Mock is automatically activated and cleaned up

Request Class

Represents request mock expectations with detailed matching criteria for HTTP requests.

class Request:
    """
    Request object representing the request mock expectation DSL.
    """
    
    def __init__(self, method="GET", url=None, headers=None, query=None, 
                 body=None, json=None, xml=None):
        """
        Parameters:
        - method (str): HTTP method to match. Defaults to "GET"
        - url (str): URL request to intercept and match
        - headers (dict): HTTP headers to match
        - query (dict): URL query params to match
        - body (bytes|regex): Request body payload to match
        - json (str|dict|list): JSON payload body structure to match
        - xml (str): XML payload data structure to match
        """
    
    def copy(self):
        """
        Copies the current Request object for side-effects purposes.
        
        Returns:
        Request: Copy of this request object
        """
    
    # Properties
    @property
    def method(self):
        """HTTP method to match."""
        
    @property
    def headers(self):
        """HTTP headers to match (HTTPHeaderDict)."""
        
    @property
    def url(self):
        """URL request to intercept and match (parsed URL or regex)."""
        
    @property
    def rawurl(self):
        """Raw URL string representation."""
        
    @property
    def query(self):
        """URL query params to match (dict)."""
        
    @property
    def body(self):
        """Request body payload to match (bytes)."""
        
    @property
    def json(self):
        """JSON payload body structure to match (parsed JSON)."""
        
    @property
    def xml(self):
        """XML payload data structure to match (str)."""
        
    @property
    def extra(self):
        """Additional extra data (dict)."""

Usage examples:

import pook

# Using Request object directly
request = pook.Request(
    method='POST',
    url='https://api.example.com/users',
    headers={'Content-Type': 'application/json'},
    json={'name': 'John', 'email': 'john@example.com'}
)

# Using with Mock
mock = pook.Mock(request=request)
mock.reply(201).json({'id': 123})

# Request copying for variations
base_request = pook.Request(method='GET', url='https://api.example.com/data')
specific_request = base_request.copy()

Response Class

Defines HTTP mock response configuration with chainable DSL interface for comprehensive response setup.

class Response:
    """
    Response is used to declare and compose HTTP mock response 
    fields with chainable DSL interface.
    """
    
    def __init__(self, status=200, headers=None, body=None, json=None, 
                 xml=None, type=None, file=None):
        """
        Parameters:
        - status (int): HTTP response status code. Defaults to 200
        - headers (dict): HTTP response headers
        - body (str|bytes): HTTP response body
        - json (str|dict|list): HTTP response JSON body
        - xml (str): HTTP response XML body
        - type (str): HTTP response content MIME type
        - file (str): File path to HTTP body response
        """
    
    def status(self, code=200):
        """
        Defines response status code.
        
        Parameters:
        - code (int): HTTP status code
        
        Returns:
        Response: Self for method chaining
        """
    
    def header(self, key, value):
        """
        Defines new response header.
        
        Parameters:
        - key (str): Header name
        - value (str): Header value
        
        Returns:
        Response: Self for method chaining
        """
    
    def headers(self, headers):
        """
        Defines multiple response headers.
        
        Parameters:
        - headers (dict): Dictionary of header name-value pairs
        
        Returns:
        Response: Self for method chaining
        """
    
    def set(self, header, value):
        """
        Defines new response header (alias to header()).
        
        Parameters:
        - header (str): Header name
        - value (str): Header value
        
        Returns:
        Response: Self for method chaining
        """
    
    def type(self, name):
        """
        Defines Content-Type header.
        
        Parameters:
        - name (str): MIME type or alias (json, xml, html, etc.)
        
        Returns:
        Response: Self for method chaining
        """
    
    def content(self, name):
        """
        Alias to type() method for Content-Type.
        
        Parameters:
        - name (str): MIME type or alias
        
        Returns:
        Response: Self for method chaining
        """
    
    def body(self, body, chunked=False):
        """
        Defines response body data.
        
        Parameters:
        - body (str|bytes): Response body content
        - chunked (bool): Enable chunked transfer encoding
        
        Returns:
        Response: Self for method chaining
        """
    
    def json(self, data):
        """
        Defines mock response JSON body.
        
        Parameters:
        - data (dict|list|str): JSON data to serialize
        
        Returns:
        Response: Self for method chaining
        """
    
    def xml(self, xml_data):
        """
        Defines mock response XML body.
        
        Parameters:
        - xml_data (str): XML content
        
        Returns:
        Response: Self for method chaining
        """
    
    def file(self, path):
        """
        Defines response body from file contents.
        
        Parameters:
        - path (str): File path to read response body from
        
        Returns:
        Response: Self for method chaining
        """
    
    # Properties
    @property
    def mock(self):
        """Reference to mock instance (Mock)."""

Usage examples:

import pook

# Using Response object directly
response = pook.Response(status=201)
response.json({'id': 123, 'name': 'John'}).header('Location', '/users/123')

# Using with Mock
mock = pook.Mock('https://api.example.com/users', response=response)

# Chained response configuration  
pook.get('https://api.example.com/data') \
    .reply(200) \
    .type('application/json') \
    .json({'data': [1, 2, 3]}) \
    .header('Cache-Control', 'no-cache')

# File-based response
pook.get('https://api.example.com/large-file') \
    .reply(200) \
    .type('application/octet-stream') \
    .file('/path/to/large-file.bin')

MIME Type Constants

Predefined MIME type aliases for convenient content type specification:

# Available type aliases
'text'        → 'text/plain'
'html'        → 'text/html'  
'json'        → 'application/json'
'xml'         → 'application/xml'
'urlencoded'  → 'application/x-www-form-urlencoded'
'form'        → 'application/x-www-form-urlencoded'
'form-data'   → 'application/x-www-form-urlencoded'

Usage examples:

# Using type aliases
pook.post('https://api.example.com/form') \
    .type('form') \
    .body('name=John&email=john@example.com') \
    .reply(200)

# Using full MIME types
pook.get('https://api.example.com/data') \
    .reply(200) \
    .type('application/vnd.api+json') \
    .json({'data': []})

Advanced Configuration Patterns

Complex Request Matching

import pook
import re

# Multiple criteria matching
pook.post('https://api.example.com/webhooks') \
    .header('X-Webhook-Secret', 'secret123') \
    .header('User-Agent', re.compile(r'MyApp/\d+\.\d+')) \
    .json({'event': re.compile(r'user\.(created|updated)')}) \
    .reply(200)

# JSONSchema validation
schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "number", "minimum": 0}
    },
    "required": ["name"]
}
pook.post('https://api.example.com/users') \
    .jsonschema(schema) \
    .reply(201)

Response Scenarios

# Multiple response behaviors
mock = pook.get('https://api.example.com/flaky')
mock.times(2).reply(500).json({'error': 'Server error'})
mock.reply(200).json({'data': 'success'})

# Conditional responses with callbacks
def validate_request(request, mock):
    if 'admin' in request.headers.get('Authorization', ''):
        mock.reply(200).json({'role': 'admin'})
    else:
        mock.reply(403).json({'error': 'Forbidden'})

pook.get('https://api.example.com/profile') \
    .callback(validate_request)

Install with Tessl CLI

npx tessl i tessl/pypi-pook

docs

engine-management.md

index.md

mock-configuration.md

mock-creation.md

state-inspection.md

tile.json