0
0
Flaskframework~8 mins

Mocking external services in Flask - Performance & Optimization

Choose your learning style9 modes available
Performance: Mocking external services
MEDIUM IMPACT
This concept affects page load speed and interaction responsiveness by reducing delays caused by real external service calls during development and testing.
Testing a Flask app that calls an external API
Flask
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 the external call to return instant, controlled data, avoiding network delays and failures.
📈 Performance GainRemoves network latency, making tests run instantly and improving INP during development.
Testing a Flask app that calls an external API
Flask
import requests

def get_data():
    response = requests.get('https://api.example.com/data')
    return response.json()
This makes a real network call every time, causing slow tests and possible flakiness if the external service is down.
📉 Performance CostBlocks test execution for network latency (100-500ms per call), increasing INP and slowing feedback.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Real external API calls during testsMinimal00[X] Bad
Mocked external API calls during testsMinimal00[OK] Good
Rendering Pipeline
Mocking external services bypasses the network request stage, so the browser or server does not wait for slow external responses, improving responsiveness.
Network Request
JavaScript Execution
Rendering
⚠️ BottleneckNetwork Request stage is the most expensive due to latency and unpredictability.
Core Web Vital Affected
INP
This concept affects page load speed and interaction responsiveness by reducing delays caused by real external service calls during development and testing.
Optimization Tips
1Always mock slow or unreliable external services during development and testing.
2Use mocking to avoid network latency that blocks user interactions or test runs.
3Verify mocks prevent real network calls using browser DevTools Network panel.
Performance Quiz - 3 Questions
Test your performance knowledge
Why does mocking external services improve test performance in a Flask app?
AIt reduces CSS complexity, speeding up style calculations.
BIt avoids slow network calls, making tests faster and more reliable.
CIt increases the number of DOM nodes, improving rendering.
DIt decreases JavaScript bundle size significantly.
DevTools: Network
How to check: Open DevTools Network panel, run your app or tests, and observe if external API calls are made or blocked/mocked.
What to look for: No real external requests should appear during tests if mocking is correctly implemented, indicating faster response.