Responses intercepts outbound calls made through the Python Requests library during automated tests. You register fake HTTP answers and run code under a decorator or context manager.
Overview
Responses is a Python package that replaces real network traffic from the Requests library with registered stand-ins while tests run. You add mock responses for specific methods and URLs, then wrap tests so matching calls return your chosen status, headers, and body instead of hitting the Internet.
The workflow centers on registering responses and activating the mock for a test function or block. You can add full Response objects or use shortcuts for common HTTP verbs. Unmatched URLs raise a connection error, which helps catch accidental live requests.
Request matching goes beyond URL alone. Matchers can validate JSON or form-encoded bodies, query parameters, headers, multipart uploads, fragments, and selected keyword arguments. Different responses can apply depending on what the client sends.
You can run the mock as a decorator on test functions or as a context manager when only part of a test should be isolated. Exceptions may be used as response bodies to simulate failures.
Key features
- Mocks Python Requests calls in tests
- Decorator and context manager activation
- HTTP verb shortcut registrations
- Body, query, and header matchers
- JSON and urlencoded body matchers
- Multipart and fragment matchers
- Exception bodies for error simulation
- Installable via pip
Use cases
- Unit tests without live HTTP
- Simulating API error responses
- Asserting request payloads sent
- Isolating tests from remote services