0
0
Djangoframework~8 mins

Mocking external services in Django - Performance & Optimization

Choose your learning style9 modes available
Performance: Mocking external services
MEDIUM IMPACT
This concept affects page load speed and interaction responsiveness by avoiding real network calls during testing or development.
Testing or developing features that rely on external APIs
Django
from unittest.mock import patch

@patch('requests.get')
def test_get_data(mock_get):
    mock_get.return_value.json.return_value = {'key': 'value'}
    data = get_data()
    assert data['key'] == 'value'
Mocks network calls to return instant responses, eliminating network delays and improving test speed.
📈 Performance GainReduces network wait time to near zero, improving INP and developer feedback loop.
Testing or developing features that rely on external APIs
Django
import requests

def get_data():
    response = requests.get('https://api.example.com/data')
    return response.json()
This makes real network calls every time, causing slow tests and possible flakiness due to network issues.
📉 Performance CostBlocks test execution for network latency (100-500ms+ per call), increasing INP during development.
Performance Comparison
PatternNetwork CallsTest SpeedInteraction DelayVerdict
Real external service callsMultiple real HTTP requestsSlow due to network latencyHigh delay causing slow INP[X] Bad
Mocked external service callsNo real HTTP requestsFast with instant responsesMinimal delay, fast INP[OK] Good
Rendering Pipeline
Mocking external services bypasses the network request stage, so the browser or server does not wait for external responses, speeding up rendering and interaction.
Network Request
JavaScript Execution
Interaction Responsiveness
⚠️ BottleneckNetwork Request stage is the most expensive when calling real external services.
Core Web Vital Affected
INP
This concept affects page load speed and interaction responsiveness by avoiding real network calls during testing or development.
Optimization Tips
1Always mock external services in tests to avoid network delays.
2Use lightweight mocks to keep tests fast and reliable.
3Check DevTools Network tab to confirm no real HTTP calls during tests.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is mocking external services beneficial for test performance?
AIt makes tests slower by adding extra code.
BIt increases the number of HTTP requests for better coverage.
CIt eliminates network latency by avoiding real HTTP calls.
DIt reduces CPU usage by skipping tests.
DevTools: Network
How to check: Open DevTools, go to the Network tab, run your tests or app, and observe if HTTP requests to external services are made.
What to look for: No external HTTP requests during tests means mocks are working; many requests indicate real calls causing delays.