or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

basic-mocking.mdindex.mdmatchers.mdrecording.mdregistries.mdrequests-mock.mdresponse-types.md
tile.json

tessl/pypi-responses

A utility library for mocking out the requests Python library

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/responses@0.25.x

To install, run

npx @tessl/cli install tessl/pypi-responses@0.25.0

index.mddocs/

Responses

A utility library for mocking out the requests Python library. Responses enables developers to create isolated unit tests without making actual HTTP calls by intercepting HTTP requests and returning predefined responses. It provides a decorator-based approach supporting all major HTTP methods with customizable status codes, headers, and response bodies.

Package Information

  • Package Name: responses
  • Language: Python
  • Installation: pip install responses

Core Imports

import responses

For direct class usage:

from responses import RequestsMock, Response, CallbackResponse

For matchers:

from responses.matchers import json_params_matcher, query_param_matcher

For registries:

from responses.registries import FirstMatchRegistry, OrderedRegistry

For recording:

from responses import _add_from_file
from responses._recorder import Recorder, record

Basic Usage

import responses
import requests

@responses.activate
def test_simple():
    # Register a mock response
    responses.add(
        responses.GET,
        "http://example.com/api/data",
        json={"message": "success"},
        status=200
    )
    
    # Make request - will hit the mock
    resp = requests.get("http://example.com/api/data")
    
    assert resp.json() == {"message": "success"}
    assert resp.status_code == 200

# Context manager approach
def test_with_context():
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.POST,
            "http://example.com/api/submit",
            json={"result": "created"},
            status=201
        )
        
        resp = requests.post("http://example.com/api/submit", json={"data": "test"})
        assert resp.status_code == 201

Architecture

The responses library uses a patching mechanism to intercept requests.adapters.HTTPAdapter.send calls. When a request is made, responses:

  1. Request Matching: Compares the request against registered mock responses using URL, method, and optional matchers
  2. Response Selection: Uses a registry system (default: FirstMatchRegistry) to find the appropriate response
  3. Response Generation: Creates an HTTPResponse object from the registered response data
  4. Call Tracking: Records all requests and responses for test verification

The flexible matcher system allows precise control over which requests are intercepted, while the registry system supports different response selection strategies for complex testing scenarios.

Capabilities

Basic Response Mocking

Core functionality for registering mock responses and activating the mocking system. Includes decorator-based activation, context manager usage, and HTTP method shortcuts.

@responses.activate
def decorator_function(): ...

def add(method, url, body="", json=None, status=200, headers=None, **kwargs): ...
def get(url, **kwargs): ...
def post(url, **kwargs): ...
def put(url, **kwargs): ...
def patch(url, **kwargs): ...
def delete(url, **kwargs): ...
def head(url, **kwargs): ...
def options(url, **kwargs): ...

Basic Response Mocking

Request Matchers

Advanced request matching capabilities for precise control over which requests are intercepted. Includes matchers for JSON payloads, query parameters, headers, and custom matching logic.

def json_params_matcher(params, *, strict_match=True): ...
def query_param_matcher(params, *, strict_match=True): ...
def header_matcher(headers, strict_match=False): ...
def body_matcher(params, *, allow_blank=False): ...

Request Matchers

Response Types

Different types of mock responses including static responses, callback-based dynamic responses, and passthrough responses for selective mocking.

class Response:
    def __init__(self, method, url, body="", json=None, status=200, headers=None, **kwargs): ...

class CallbackResponse:
    def __init__(self, method, url, callback, **kwargs): ...

class PassthroughResponse:
    def __init__(self, *args, **kwargs): ...

Response Types

RequestsMock Class

The core RequestsMock class for programmatic control over response mocking, including registry management, call tracking, and advanced configuration options.

class RequestsMock:
    def __init__(self, assert_all_requests_are_fired=True, response_callback=None, **kwargs): ...
    def start(self): ...
    def stop(self, allow_assert=True): ...
    def add_passthru(self, prefix): ...
    def assert_call_count(self, url, count): ...

RequestsMock Class

Request Recording

Record actual HTTP requests and responses to generate response configurations for future mocking. Enables capturing real API interactions and replaying them in tests.

@record(file_path="responses.yaml")
def function_making_requests(): ...

class Recorder:
    def __init__(self, *, target="requests.adapters.HTTPAdapter.send", registry=OrderedRegistry): ...
    def record(self, *, file_path="response.yaml"): ...
    def dump_to_file(self, file_path, *, registered=None): ...

def _add_from_file(file_path): ...

Request Recording

Response Registries

Registry systems that control how responses are matched and selected, including order-dependent response handling for complex testing scenarios.

class FirstMatchRegistry:
    def __init__(self): ...
    def find(self, request): ...
    def add(self, response): ...
    def remove(self, response): ...

class OrderedRegistry(FirstMatchRegistry):
    def find(self, request): ...

Response Registries

Types

# HTTP Method Constants
GET: str = "GET"
POST: str = "POST"
PUT: str = "PUT"
PATCH: str = "PATCH"
DELETE: str = "DELETE"
HEAD: str = "HEAD"
OPTIONS: str = "OPTIONS"

# Call tracking
class Call:
    request: PreparedRequest
    response: Any

class CallList:
    def __len__(self) -> int: ...
    def __getitem__(self, index) -> Call: ...
    def reset(self) -> None: ...