How to Mock a Remote Config Fetch in Python
Simulate a remote config API response with metadata, timestamps, and mock data for testing or local development.
Python code
22 linesimport json
from datetime import datetime
from typing import Any, Dict
def fetch_remote_config(mock_data: Dict[str, Any]) -> Dict[str, Any]:
"""Simulate fetching a remote config with metadata and timestamps."""
return {
"status": "success",
"source": "mock",
"fetched_at": datetime.utcnow().isoformat(),
"config": mock_data
}
if __name__ == "__main__":
mock_config = {
"feature_flag": True,
"timeout_seconds": 30,
"service_url": "https://api.example.com",
"max_retries": 3
}
result = fetch_remote_config(mock_config)
print(json.dumps(result, indent=2))
Output
{
"status": "success",
"source": "mock",
"fetched_at": "2025-01-15T10:30:45.123456",
"config": {
"feature_flag": true,
"timeout_seconds": 30,
"service_url": "https://api.example.com",
"max_retries": 3
}
}
How it works
The fetch_remote_config function wraps the mock data in a structured envelope that mimics a real remote config API response. The datetime.utcnow().isoformat() adds an ISO-8601 timestamp, making the output look like a live fetch. The nested config key preserves the original mock dictionary so callers can access the configuration values directly. This pattern is useful for development, testing, and A/B experimentation when a real backend isn't available or shouldn't be hit repeatedly.
Common mistakes
- Forgetting to add the metadata fields (status, source, fetched_at) that real APIs include
- Using `datetime.utcnow()` which is deprecated in Python 3.12+ — prefer `datetime.now(timezone.utc)`
- Not handling the case where the mock dict may contain nested data or non-serializable types
Variations
- Add latency simulation with `time.sleep(random.uniform(0.1, 0.5))` before returning
- Read mock config from a JSON file instead of hardcoding it in the script
- Use `functools.lru_cache` to cache the fetched config for repeated calls
Real-world use cases
- Local development where the real config service isn't reachable or is rate-limited.
- Unit testing feature-flag logic without making network calls to the production config service.
- A/B experiment rollouts where teams need a deterministic config baseline before traffic ramps up.
Sponsored
More from A/B testing & experimentation
Keep learning
Related tutorials and quizzes for this topic.