Bird
Raised Fist0
Flaskframework~10 mins

Mocking external services in Flask - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Mocking external services
Start Test
↓
Patch external call
↓
Run code that calls external service
↓
Mock returns fake response
↓
Code uses fake response
↓
Assert expected behavior
↓
End Test
This flow shows how a test replaces an external service call with a fake response to test code behavior safely.
Execution Sample
Flask
from unittest.mock import patch
import requests

def get_data():
    return requests.get('https://api.example.com/data').json()
This code defines a function that fetches JSON data from an external API using requests.get.
Execution Table
StepActionEvaluationResult
1Patch requests.getrequests.get replaced by mockMock ready to intercept calls
2Call get_data()Inside get_data, requests.get calledMock intercepts call
3Mock returns fake JSONMock returns {'key': 'value'}get_data receives fake JSON
4get_data returns JSONReturns {'key': 'value'}Function output is fake data
5Assert outputCheck output == {'key': 'value'}Test passes
6Unpatch requests.getRestore original requests.getExternal calls back to normal
💡 Test ends after asserting expected behavior with mocked external call
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
requests.getoriginal functionmock functionmock functionmock functionoriginal function
get_data outputnonenone{'key': 'value'}{'key': 'value'}{'key': 'value'}
Key Moments - 2 Insights
Why does get_data return fake data instead of calling the real API?
Because requests.get is patched (replaced) by a mock that returns fake data, as shown in execution_table step 1 and 3.
What happens if we forget to unpatch requests.get after the test?
The mock stays active, so real external calls remain mocked, which can cause unexpected behavior in other tests or code, as noted in step 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what does the mock return when get_data calls requests.get?
ANone
B{'key': 'value'}
CReal API response
DAn error
💡 Hint
Check step 3 in the execution table where the mock returns fake JSON.
At which step is requests.get replaced by the mock?
AStep 1
BStep 2
CStep 4
DStep 6
💡 Hint
Check step 1 in the execution table where requests.get is replaced by mock.
If we do not unpatch requests.get, what variable_tracker value remains incorrect?
Aget_data output
Brequests.get becomes None
Crequests.get remains mock function
Dget_data output becomes None
💡 Hint
See variable_tracker row for requests.get after final step.
Concept Snapshot
Mocking external services in Flask tests:
- Use unittest.mock.patch to replace external calls
- Patch before calling code that uses the service
- Mock returns fake data to avoid real HTTP requests
- Assert code behavior with fake data
- Unpatch to restore original functions after test
Full Transcript
This lesson shows how to mock external services in Flask using unittest.mock.patch. We replace the real HTTP call with a fake one that returns controlled data. The flow starts by patching the external call, then running the code that calls it. The mock returns fake JSON data, which the code uses. We then check that the code behaves as expected with this fake data. Finally, we unpatch to restore the original external call. This prevents tests from depending on real external services and makes them faster and more reliable.

Practice

(1/5)
1. What is the main reason to mock external services in Flask testing?
easy
A. To change the Flask app configuration permanently
B. To speed up the Flask server in production
C. To add more routes to the Flask app
D. To avoid making real network calls during tests

Solution

  1. Step 1: Understand the purpose of mocking

    Mocking replaces real external calls with fake ones to avoid delays and failures during tests.
  2. Step 2: Identify the benefit in Flask testing

    This avoids real network calls, making tests faster and more reliable.
  3. Final Answer:

    To avoid making real network calls during tests -> Option D
  4. Quick Check:

    Mocking = Avoid real network calls [OK]
Hint: Mock to skip real network calls in tests [OK]
Common Mistakes:
  • Thinking mocking speeds up production
  • Confusing mocking with adding routes
  • Believing mocking changes app config permanently
2. Which of the following is the correct way to patch an external function requests.get in a Flask test using unittest.mock?
easy
A. with patch('requests.get') as mock_get:
B. with patch(requests.get) as mock_get:
C. with patch('requests->get') as mock_get:
D. with patch('requests_get') as mock_get:

Solution

  1. Step 1: Understand patch syntax

    Patch requires the full path as a string, e.g., 'requests.get'.
  2. Step 2: Identify correct string format

    with patch('requests.get') as mock_get: uses the correct string 'requests.get'. Others use invalid syntax or missing quotes.
  3. Final Answer:

    with patch('requests.get') as mock_get: -> Option A
  4. Quick Check:

    Patch needs string path = with patch('requests.get') as mock_get: [OK]
Hint: Patch uses string path like 'module.function' [OK]
Common Mistakes:
  • Passing function object instead of string
  • Using wrong string format with arrows
  • Missing quotes around patch target
3. Given this Flask test code snippet, what will be printed?
from unittest.mock import patch
import requests

def fetch_data():
    response = requests.get('http://example.com')
    return response.status_code

with patch('requests.get') as mock_get:
    mock_get.return_value.status_code = 404
    print(fetch_data())
medium
A. None
B. 200
C. 404
D. Raises an error

Solution

  1. Step 1: Understand patch effect on requests.get

    The patch replaces requests.get with a mock whose return_value.status_code is set to 404.
  2. Step 2: Trace fetch_data call inside patch

    fetch_data calls requests.get, which returns the mock with status_code 404, so fetch_data returns 404.
  3. Final Answer:

    404 -> Option C
  4. Quick Check:

    Mocked status_code = 404 [OK]
Hint: Mock return_value sets fake response attributes [OK]
Common Mistakes:
  • Expecting real HTTP 200 response
  • Confusing mock object with None
  • Thinking patch causes error
4. What is wrong with this Flask test code that tries to mock requests.post?
from unittest.mock import patch
import requests

def send_data():
    response = requests.post('http://example.com', data={'key': 'value'})
    return response.ok

with patch('requests.post') as mock_post:
    mock_post.ok = True
    print(send_data())
medium
A. mock_post.ok should be set on return_value, not mock_post
B. patch target should be 'requests.get' not 'requests.post'
C. send_data should use requests.get instead of post
D. mock_post.ok is correct and code works fine

Solution

  1. Step 1: Identify mock object usage

    mock_post is the mock for requests.post function, its return_value simulates the response object.
  2. Step 2: Correct attribute assignment

    Setting mock_post.ok sets attribute on the function mock, not the response. It should be mock_post.return_value.ok = True.
  3. Final Answer:

    mock_post.ok should be set on return_value, not mock_post -> Option A
  4. Quick Check:

    Mock response attributes go on return_value [OK]
Hint: Set mock response attributes on return_value [OK]
Common Mistakes:
  • Setting attributes on mock function instead of return_value
  • Confusing post with get method
  • Assuming code works without fixing mock
5. You want to test a Flask route that calls an external API and returns JSON data. Which approach correctly mocks the external API call and returns a custom JSON response {"success": true} during the test?
hard
A. Use patch on the Flask route function and return {"success": true} directly
B. Use patch on the external call, set return_value.json.return_value = {"success": true}
C. Call the real external API and check if it returns {"success": true}
D. Mock the Flask app config to include {"success": true}

Solution

  1. Step 1: Identify what to mock

    The external API call (e.g., requests.get) should be mocked to avoid real network calls.
  2. Step 2: Set mock return JSON data

    Set the mock's return_value.json.return_value to the desired JSON dict to simulate API response.
  3. Final Answer:

    Use patch on the external call, set return_value.json.return_value = {"success": true} -> Option B
  4. Quick Check:

    Mock external call's json() method = Use patch on the external call, set return_value.json.return_value = {"success": true} [OK]
Hint: Mock return_value.json.return_value for JSON responses [OK]
Common Mistakes:
  • Mocking Flask route instead of external call
  • Calling real API in tests
  • Changing app config instead of mocking
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard