Consider this Flask route that calls an external API to get user data. The external API is mocked to return a fixed response.
import requests
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/user/')
def get_user(user_id):
response = requests.get(f'https://api.example.com/users/{user_id}')
data = response.json()
return jsonify({'name': data['name'], 'id': data['id']})
# Mock setup:
# requests.get is mocked to always return a response with json() = {'id': 42, 'name': 'Alice'} What will be the JSON output when accessing /user/10?
Remember the mock always returns the same data regardless of the user_id.
The mocked requests.get always returns a response whose json() method returns {'id': 42, 'name': 'Alice'}. So the route returns this data wrapped in JSON, ignoring the URL user_id.
In this Flask test, the external API call is mocked but the test fails with a TypeError.
import pytest
from unittest.mock import patch
@patch('requests.get')
def test_user(mock_get, client):
mock_get.return_value.json = {'id': 1, 'name': 'Bob'}
response = client.get('/user/1')
assert response.json == {'id': 1, 'name': 'Bob'}What is the cause of the error?
Check what response.json expects to be in the mock.
The json attribute of the mocked response must be a callable method returning the dict, not the dict itself. Assigning a dict directly causes a TypeError when called.
You want to mock requests.get in a Flask test to return a JSON response {'status': 'ok'}. Which code snippet is correct?
The mocked json must be a callable method returning the dict.
Option A correctly sets mock_get.return_value.json to a lambda returning the dict. Option A tries to set json on the mock_get itself, which is wrong. Option A sets the return_value to a dict, not a mock response. Option A sets json to a dict, not a callable.
Given this Flask function and test snippet:
def fetch_data():
import requests
response = requests.get('https://api.example.com/data')
return response.json()['value']
# Test with mock:
from unittest.mock import patch
with patch('requests.get') as mock_get:
mock_get.return_value.json = lambda: {'value': 123}
result = fetch_data()What is the value of result?
Look at what fetch_data returns from the mocked JSON.
The mocked json() returns {'value': 123}. The function returns the value of the 'value' key, which is 123.
Why do developers mock external API calls when testing Flask applications?
Think about test speed and reliability.
Mocking external services isolates tests from network failures and variability, making tests faster and more reliable. It avoids dependency on external service availability.