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.
Requires third-party packages — install first
pip install requests
Python code
20 linesfrom 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
{'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
- Use `mock_get.side_effect` with a list of responses to simulate sequential calls
- 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
More from Reliability & rate limiting
- At Least Once with Idempotent Consumer in Python medium
- Build a Rate Limiter Decorator in Python easy
- Build a queue-based admission control system in Python easy
- Chaos Inject Random Failures in Python easy
- Circuit breaker failure threshold count in Python medium
- Exactly Once Processing Dedupe Mock in Python easy
Keep learning
Related tutorials and quizzes for this topic.