Skip to content

getsentry/responses

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Responses

image

image

image

image

A utility library for mocking out the requests Python library.

Note

Responses requires Python 3.8 or newer, and requests >= 2.30.0

Table of Contents

Installing

pip install responses

Deprecations and Migration Path

Here you will find a list of deprecated functionality and a migration path for each. Please ensure to update your code according to the guidance.

Deprecation and Migration
Deprecated Functionality Deprecated in Version Migration Path
responses.json_params_matcher 0.14.0 responses.matchers.json_params_matcher
responses.urlencoded_params_matcher 0.14.0 responses.matchers.urlencoded_params_matcher
stream argument in Response and CallbackResponse 0.15.0 Use stream argument in request directly.
match_querystring argument in Response and CallbackResponse. 0.17.0 Use responses.matchers.query_param_matcher or responses.matchers.query_string_matcher
responses.assert_all_requests_are_fired, responses.passthru_prefixes, responses.target 0.20.0 Use responses.mock.assert_all_requests_are_fired, responses.mock.passthru_prefixes, responses.mock.target instead.

BETA Features

Below you can find a list of BETA features. Although we will try to keep the API backwards compatible with released version, we reserve the right to change these APIs before they are considered stable. Please share your feedback via GitHub Issues.

Record Responses to files

You can perform real requests to the server and responses will automatically record the output to the file. Recorded data is stored in YAML format.

Apply @responses._recorder.record(file_path="out.yaml") decorator to any function where you perform requests to record responses to out.yaml file.

Following code

will produce next output:

Replay responses (populate registry) from files

You can populate your active registry from a yaml file with recorded responses. (See Record Responses to files to understand how to obtain a file). To do that you need to execute responses._add_from_file(file_path="out.yaml") within an activated decorator or a context manager.

The following code example registers a patch response, then all responses present in out.yaml file and a post response at the end.

Basics

The core of responses comes from registering mock responses and covering test function with responses.activate decorator. responses provides similar interface as requests.

Main Interface

  • responses.add(Response or Response args) - allows either to register Response object or directly provide arguments of Response object. See Response Parameters

If you attempt to fetch a url which doesn't hit a match, responses will raise a ConnectionError:

Shortcuts

Shortcuts provide a shorten version of responses.add() where method argument is prefilled

  • responses.delete(Response args) - register DELETE response
  • responses.get(Response args) - register GET response
  • responses.head(Response args) - register HEAD response
  • responses.options(Response args) - register OPTIONS response
  • responses.patch(Response args) - register PATCH response
  • responses.post(Response args) - register POST response
  • responses.put(Response args) - register PUT response

Responses as a context manager

Instead of wrapping the whole function with decorator you can use a context manager.

Response Parameters

The following attributes can be passed to a Response mock:

method (str)

The HTTP method (GET, POST, etc).

url (str or compiled regular expression)

The full resource URL.

match_querystring (bool)

DEPRECATED: Use responses.matchers.query_param_matcher or responses.matchers.query_string_matcher

Include the query string when matching requests. Enabled by default if the response URL contains a query string, disabled if it doesn't or the URL is a regular expression.

body (str or BufferedReader or Exception)

The response body. Read more Exception as Response body

json

A Python object representing the JSON response body. Automatically configures the appropriate Content-Type.

status (int)

The HTTP status code.

content_type (content_type)

Defaults to text/plain.

headers (dict)

Response headers.

stream (bool)

DEPRECATED: use stream argument in request directly

auto_calculate_content_length (bool)

Disabled by default. Automatically calculates the length of a supplied string or JSON body.

match (tuple)

An iterable (tuple is recommended) of callbacks to match requests based on request attributes. Current module provides multiple matchers that you can use to match:

  • body contents in JSON format
  • body contents in URL encoded data format
  • request query parameters
  • request query string (similar to query parameters but takes string as input)
  • kwargs provided to request e.g. stream, verify
  • 'multipart/form-data' content and headers in request
  • request headers
  • request fragment identifier

Alternatively user can create custom matcher. Read more Matching Requests

Exception as Response body

You can pass an Exception as the body to trigger an error on the request:

Matching Requests

Matching Request Body Contents

When adding responses for endpoints that are sent request data you can add matchers to ensure your code is sending the right parameters and provide different responses based on the request body contents. responses provides matchers for JSON and URL-encoded request bodies.

URL-encoded data

JSON encoded data

Matching JSON encoded data can be done with matchers.json_params_matcher().

Query Parameters Matcher

Query Parameters as a Dictionary

You can use the matchers.query_param_matcher function to match against the params request parameter. Just use the same dictionary as you will use in params argument in request.

Note, do not use query parameters as part of the URL. Avoid using match_querystring deprecated argument.

By default, matcher will validate that all parameters match strictly. To validate that only parameters specified in the matcher are present in original request use strict_match=False.

Query Parameters as a String

As alternative, you can use query string value in matchers.query_string_matcher to match query parameters in your request

Request Keyword Arguments Matcher

To validate request arguments use the matchers.request_kwargs_matcher function to match against the request kwargs.

Only following arguments are supported: timeout, verify, proxies, stream, cert.

Note, only arguments provided to matchers.request_kwargs_matcher will be validated.

Request multipart/form-data Data Validation

To validate request body and headers for multipart/form-data data you can use matchers.multipart_matcher. The data, and files parameters provided will be compared to the request:

Request Fragment Identifier Validation

To validate request URL fragment identifier you can use matchers.fragment_identifier_matcher. The matcher takes fragment string (everything after # sign) as input for comparison:

Request Headers Validation

When adding responses you can specify matchers to ensure that your code is sending the right headers and provide different responses based on the request headers.

Because requests will send several standard headers in addition to what was specified by your code, request headers that are additional to the ones passed to the matcher are ignored by default. You can change this behaviour by passing strict_match=True to the matcher to ensure that only the headers that you're expecting are sent and no others. Note that you will probably have to use a PreparedRequest in your code to ensure that requests doesn't include any additional headers.

Creating Custom Matcher

If your application requires other encodings or different data validation you can build your own matcher that returns Tuple[matches: bool, reason: str]. Where boolean represents True or False if the request parameters match and the string is a reason in case of match failure. Your matcher can expect a PreparedRequest parameter to be provided by responses.

Note, PreparedRequest is customized and has additional attributes params and req_kwargs.

Response Registry

Default Registry

By default, responses will search all registered Response objects and return a match. If only one Response is registered, the registry is kept unchanged. However, if multiple matches are found for the same request, then first match is returned and removed from registry.

Ordered Registry

In some scenarios it is important to preserve the order of the requests and responses. You can use registries.OrderedRegistry to force all Response objects to be dependent on the insertion order and invocation index. In following example we add multiple Response objects that target the same URL. However, you can see, that status code will depend on the invocation order.

Custom Registry

Built-in registries are suitable for most of use cases, but to handle special conditions, you can implement custom registry which must follow interface of registries.FirstMatchRegistry. Redefining the find method will allow you to create custom search logic and return appropriate Response

Example that shows how to set custom registry

Dynamic Responses

You can utilize callbacks to provide dynamic responses. The callback must return a tuple of (status, headers, body).

You can also pass a compiled regex to add_callback to match multiple urls:

If you want to pass extra keyword arguments to the callback function, for example when reusing a callback function to give a slightly different result, you can use functools.partial:

Integration with unit test frameworks

Responses as a pytest fixture

Add default responses for each test

When run with unittest tests, this can be used to set up some generic class-level responses, that may be complemented by each test. Similar interface could be applied in pytest framework.

RequestMock methods: start, stop, reset

responses has start, stop, reset methods very analogous to unittest.mock.patch. These make it simpler to do requests mocking in setup methods or where you want to do multiple patches without nesting decorators or with statements.

Assertions on declared responses

When used as a context manager, Responses will, by default, raise an assertion error if a url was registered but not accessed. This can be disabled by passing the assert_all_requests_are_fired value:

Assert Request Call Count

Assert based on Response object

Each Response object has call_count attribute that could be inspected to check how many times each request was matched.

Assert based on the exact URL

Assert that the request was called exactly n times.

Assert Request Calls data

Request object has calls list which elements correspond to Call objects in the global list of Registry. This can be useful when the order of requests is not guaranteed, but you need to check their correctness, for example in multithreaded applications.

Multiple Responses

You can also add multiple responses for the same url:

URL Redirection

In the following example you can see how to create a redirection chain and add custom exception that will be raised in the execution chain and contain the history of redirects.

A -> 301 redirect -> B
B -> 301 redirect -> C
C -> connection issue

Validate Retry mechanism

If you are using the Retry features of urllib3 and want to cover scenarios that test your retry limits, you can test those scenarios with responses as well. The best approach will be to use an Ordered Registry

Using a callback to modify the response

If you use customized processing in requests via subclassing/mixins, or if you have library tools that interact with requests at a low level, you may need to add extended processing to the mocked Response object to fully simulate the environment for your tests. A response_callback can be used, which will be wrapped by the library before being returned to the caller. The callback accepts a response as it's single argument, and is expected to return a single response object.

Passing through real requests

In some cases you may wish to allow for certain requests to pass through responses and hit a real server. This can be done with the add_passthru methods:

This will allow any requests matching that prefix, that is otherwise not registered as a mock response, to passthru using the standard behavior.

Pass through endpoints can be configured with regex patterns if you need to allow an entire domain or path subtree to send requests:

Lastly, you can use the passthrough argument of the Response object to force a response to behave as a pass through.

Viewing/Modifying registered responses

Registered responses are available as a public method of the RequestMock instance. It is sometimes useful for debugging purposes to view the stack of registered responses which can be accessed via responses.registered().

The replace function allows a previously registered response to be changed. The method signature is identical to add. response s are identified using method and url. Only the first matched response is replaced.

The upsert function allows a previously registered response to be changed like replace. If the response is registered, the upsert function will registered it like add.

remove takes a method and url argument and will remove all matched responses from the registered list.

Finally, reset will reset all registered responses.

Coroutines and Multithreading

responses supports both Coroutines and Multithreading out of the box. Note, responses locks threading on RequestMock object allowing only single thread to access it.

Contributing

Environment Configuration

Responses uses several linting and autoformatting utilities, so it's important that when submitting patches you use the appropriate toolchain:

Clone the repository:

git clone https://github.com/getsentry/responses.git

Create an environment (e.g. with virtualenv):

virtualenv .env && source .env/bin/activate

Configure development requirements:

make develop

Tests and Code Quality Validation

The easiest way to validate your code is to run tests via tox. Current tox configuration runs the same checks that are used in GitHub Actions CI/CD pipeline.

Please execute the following command line from the project root to validate your code against:

  • Unit tests in all Python versions that are supported by this project
  • Type validation via mypy
  • All pre-commit hooks
tox

Alternatively, you can always run a single test. See documentation below.

Unit tests

Responses uses Pytest for testing. You can run all tests by:

tox -e py37
tox -e py310

OR manually activate required version of Python and run

pytest

And run a single test by:

pytest -k '<test_function_name>'

Type Validation

To verify type compliance, run mypy linter:

tox -e mypy

OR

mypy --config-file=./mypy.ini -p responses

Code Quality and Style

To check code style and reformat it run:

tox -e precom

OR

pre-commit run --all-files