Explore Kartoza

Try searching for: QGIS, Training, GeoNode, PostGIS

Mocking Requests with Responses
Back to Blog
Python Testing
February 1, 2022 Zulfikar Akbar Muzakki

Mocking Requests with Responses

The article presents an alternative to the requests_mock library for testing HTTP requests in Python.

Mocking Requests with Responses

Python

Introduction

The article presents an alternative to the requests_mock library for testing HTTP requests in Python. The author demonstrates why “responses” library offers simpler usage with more advanced features. As noted, mocking external service calls prevents test failures when services are unavailable and eliminates unnecessary costs during testing.

Installation

Simple installation via: pip install responses

Basic Usage

The author illustrates replacing requests_mock with responses using a weather subscription test case. The decorator @responses.activate enables mocking functionality, followed by configuring mock responses:

responses.add(
    method=responses.POST,
    url='https://real-weather-service.com/weather/subscribe/',
    json=return_value,
    status=201
)

Request Matching

The library supports eight matching strategies:

  • JSON body contents
  • URL-encoded data
  • Query parameters
  • Query strings
  • Request kwargs (stream, verify)
  • Multipart form-data content
  • Headers
  • Fragment identifiers

A practical example demonstrates URL-encoded parameter matching, with a critical note: parameters must be converted to strings for proper matching, as URL encoding converts all values to strings.

Dynamic Responses

Using callbacks enables conditional response logic. Callbacks examine request details and return tuples of (status, headers, body):

def request_callback(request):
    payload = dict(parse_qsl(request.body))
    # Process and return response
    return (status, headers, json.dumps(resp_body))

responses.add_callback(
    method=responses.POST,
    url='https://...',
    callback=request_callback
)

Conclusion

The author concludes that “responses” provides more sophisticated features with greater ease of use compared to alternatives, making it the preferred choice for request mocking in Python testing.

Want to Learn More?

Explore our training courses or get in touch to discuss how we can help your organization.