How to mock a fallback return value in Python

Test a function that returns a default value on failure by mocking requests.get and its side effects.

Easy Python 3.9+ Aug 9, 2026 Reliability & rate limiting 15 views 0 copies

Requires third-party packages — install first
pip install requests

Python code

20 lines
Python 3.9+
from unittest.mock import Mock, patch
import requests

def fetch_data(url, default=None):
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.json()
    except (requests.RequestException, ValueError):
        return default

with patch("requests.get") as mock_get:
    mock_get.return_value.raise_for_status.side_effect = requests.RequestException("Network error")
    result = fetch_data("https://api.example.com/data", default={"fallback": True})
    print(result)

    mock_get.return_value = Mock(status_code=200)
    mock_get.return_value.json.return_value = {"data": "real"}
    result = fetch_data("https://api.example.com/data", default={"fallback": True})
    print(result)

Output

stdout
{'fallback': True}
{'data': 'real'}

How it works

The patch context manager replaces requests.get with a Mock. Setting raise_for_status.side_effect makes the mocked response raise an exception, triggering the fallback. Reassigning return_value creates a new mocked response for the successful path. The try/except in fetch_data catches both network errors and invalid JSON, returning the default when needed.

Common mistakes

  • Forgetting to set `raise_for_status.side_effect` so the error path is actually exercised
  • Reusing the same Mock return_value for both success and failure without reassigning
  • Not catching JSON decode errors, so invalid responses crash instead of falling back

Variations

  1. Use `mock_get.side_effect` with a list of responses to simulate sequential calls
  2. Use `responses` or `requests_mock` libraries for HTTP-level mocking rather than patching internals

Real-world use cases

  • Unit-testing an API client that must return cached data when the network is down.
  • Verifying a retry wrapper falls back to local defaults on service degradation.
  • Testing rate-limit handling where a 429 response must degrade to a safe fallback value.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Reliability & rate limiting

Related tutorials and quizzes for this topic.