Bird
Raised Fist0
Djangoframework~10 mins

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

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Mocking external services
Test starts
Patch external service call
Run code that calls external service
Mock intercepts call and returns fake response
Test uses fake response to check behavior
Test ends
This flow shows how a test replaces an external service call with a mock, so the test controls the response and checks code behavior safely.
Execution Sample
Django
from unittest.mock import patch

def test_fetch_data():
    with patch('myapp.services.requests.get') as mock_get:
        mock_get.return_value.status_code = 200
        mock_get.return_value.json.return_value = {'key': 'value'}
        result = fetch_data()
        assert result == {'key': 'value'}
This test replaces the real HTTP GET call with a mock that returns a preset response, then checks the function output.
Execution Table
StepActionMock StateFunction CallReturned ValueTest Assertion
1Patch 'requests.get' with mock_getmock_get ready, no calls yetNo call yetN/AN/A
2Call fetch_data(), which calls requests.getmock_get called oncerequests.get() calledMock response with status 200 and JSON {'key': 'value'}N/A
3fetch_data() processes mock responsemock_get still called onceN/A{'key': 'value'}N/A
4Test asserts result equals {'key': 'value'}mock_get still called onceN/A{'key': 'value'}Pass
5Test ends, patch removedmock_get removedN/AN/AN/A
💡 Test ends after assertion passes using mocked external service response
Variable Tracker
VariableStartAfter Step 2After Step 3Final
mock_get.call_count0111
mock_get.return_value.status_codenull200200200
mock_get.return_value.json.return_valuenull{'key': 'value'}{'key': 'value'}{'key': 'value'}
resultnullnull{'key': 'value'}{'key': 'value'}
Key Moments - 3 Insights
Why does the test not make a real HTTP request?
Because the 'requests.get' function is replaced by a mock (see Step 1 and 2 in execution_table), so the real network call is never made.
How does the mock know what to return when called?
We set 'mock_get.return_value.status_code' and 'mock_get.return_value.json.return_value' before calling the function (Step 2), so the mock returns these values.
What happens if the function calls 'requests.get' multiple times?
The mock tracks each call in 'mock_get.call_count' (see variable_tracker), so you can check how many times it was called and control responses accordingly.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 2, what is the mock_get.call_count value?
A2
B0
C1
Dnull
💡 Hint
Check the 'Mock State' column at Step 2 in the execution_table.
At which step does the test check the function's returned value?
AStep 3
BStep 4
CStep 1
DStep 5
💡 Hint
Look for 'Test asserts result equals' in the 'Action' column of the execution_table.
If we did not patch 'requests.get', what would happen during Step 2?
AThe test would call the real external service
BThe mock would still intercept the call
CThe test would fail immediately
DThe function would return null
💡 Hint
Refer to the 'Action' and 'Mock State' columns in the execution_table and the key moment about patching.
Concept Snapshot
Mocking external services in Django tests:
- Use unittest.mock.patch to replace external calls
- Set mock return values before calling your code
- Your code calls the mock, not the real service
- Assert your code handles the mock response correctly
- Patch is removed after test ends
Full Transcript
This visual execution shows how to mock external services in Django tests using unittest.mock.patch. The test replaces the real HTTP request function with a mock object. The mock is set up to return a fake response with a status code and JSON data. When the tested function calls the external service, it receives the mock response instead of making a real network call. The test then asserts that the function returns the expected data from the mock. This approach avoids slow or unreliable real service calls during testing and lets you control test scenarios precisely.

Practice

(1/5)
1. What is the main reason to use mocking for external services in Django tests?
easy
A. To avoid making real network calls during tests
B. To speed up the Django development server
C. To automatically generate API documentation
D. To deploy the Django app faster

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 testing context

    By not making real network calls, tests run faster and are more reliable.
  3. Final Answer:

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

    Mocking avoids real calls = A [OK]
Hint: Mock external calls to keep tests fast and reliable [OK]
Common Mistakes:
  • Thinking mocking speeds up the server
  • Confusing mocking with deployment
  • Assuming mocking generates docs
2. Which of the following is the correct way to patch an external service call in a Django test using unittest.mock?
easy
A. @patch('services.external_api_call.myapp')
B. @patch('external_api_call.myapp.services')
C. @patch('myapp.external_api_call.services')
D. @patch('myapp.services.external_api_call')

Solution

  1. Step 1: Understand patch target format

    The patch decorator requires the full import path to the function or method to mock.
  2. Step 2: Match the correct import path

    @patch('myapp.services.external_api_call') correctly specifies the module and function as 'myapp.services.external_api_call'.
  3. Final Answer:

    @patch('myapp.services.external_api_call') -> Option D
  4. Quick Check:

    Correct patch path = D [OK]
Hint: Patch using full import path of the function to mock [OK]
Common Mistakes:
  • Reversing module and function order
  • Using incomplete import paths
  • Patching the wrong module
3. Given this test code snippet, what will be printed?
from unittest.mock import patch

def get_data():
    return external_service_call()

@patch('myapp.services.external_service_call')
def test_get_data(mock_call):
    mock_call.return_value = {'status': 'ok'}
    result = get_data()
    print(result)
medium
A. Error: external_service_call not defined
B. None
C. external_service_call
D. {'status': 'ok'}

Solution

  1. Step 1: Understand patch effect on external_service_call

    The patch replaces external_service_call with a mock that returns {'status': 'ok'} only inside the decorated function test_get_data.
  2. Step 2: Analyze get_data call outside patch scope

    get_data() calls external_service_call(), but external_service_call is not defined globally, leading to a NameError.
  3. Final Answer:

    Error: external_service_call not defined -> Option A
  4. Quick Check:

    external_service_call undefined outside patch = D [OK]
Hint: Patch only affects references inside the decorated function [OK]
Common Mistakes:
  • Assuming patch affects global scope
  • Expecting mock return_value outside patch
  • Ignoring NameError due to missing definition
4. What is wrong with this test code that tries to mock an external API call?
from unittest.mock import patch

def test_api_call():
    with patch('myapp.services.external_api_call') as mock_call:
        mock_call.return_value = {'success': True}
    result = external_api_call()
    print(result)
medium
A. external_api_call cannot be patched with patch()
B. The patch context ends before calling external_api_call
C. mock_call.return_value should be set after calling external_api_call
D. Missing import for external_api_call

Solution

  1. Step 1: Check patch context usage

    The patch is applied only inside the with block, but external_api_call is called after it ends.
  2. Step 2: Understand effect on mocking

    Since external_api_call is called outside the patch block, it is not mocked and runs the real function.
  3. Final Answer:

    The patch context ends before calling external_api_call -> Option B
  4. Quick Check:

    Call must be inside patch block = C [OK]
Hint: Call mocked function inside patch block or decorator [OK]
Common Mistakes:
  • Calling function outside patch context
  • Setting return_value too late
  • Assuming patch works globally without context
5. You want to test a Django view that calls an external payment API. Which approach correctly mocks the external call and verifies the view handles a failure response gracefully?
from unittest.mock import patch
from django.test import Client

@patch('payments.api.call_payment')
def test_payment_failure(mock_call):
    mock_call.return_value = {'status': 'error', 'code': 500}
    client = Client()
    response = client.post('/pay/')
    print(response.status_code)
What should you add to the test to check the view's behavior?
hard
A. Assert response.status_code is 500 to confirm failure handling
B. Remove patch decorator to test real API call
C. Assert mock_call was called once and response.status_code is 200
D. Set mock_call.return_value to None to simulate failure

Solution

  1. Step 1: Understand mocking external payment API

    The patch replaces call_payment with a mock returning an error response.
  2. Step 2: Verify view handles error but returns HTTP 200

    The view should catch the error and respond with HTTP 200 (page loads with error message), not propagate 500.
  3. Step 3: Check mock call was made

    Asserting mock_call was called confirms the external API was invoked in the view.
  4. Final Answer:

    Assert mock_call was called once and response.status_code is 200 -> Option C
  5. Quick Check:

    Mock call checked + 200 response = B [OK]
Hint: Check mock call and expect view to handle errors with 200 [OK]
Common Mistakes:
  • Expecting 500 status from view on API error
  • Not asserting mock call was made
  • Removing patch and making real calls