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
Mocking External Services in Django Tests
📖 Scenario: You are building a Django app that fetches weather data from an external API. To test your app without calling the real API every time, you will mock the external service.
🎯 Goal: Create a Django test that mocks an external weather API call to return fixed data, so tests run fast and reliably without internet.
📋 What You'll Learn
Create a function that calls an external weather API
Set up a test case in Django
Mock the external API call in the test
Verify the mocked data is used in the test
💡 Why This Matters
🌍 Real World
Mocking external services helps you test your Django apps quickly and reliably without depending on real APIs or internet connection.
💼 Career
Many jobs require writing tests that mock external APIs to ensure code quality and avoid flaky tests caused by network issues.
Progress0 / 4 steps
1
Create a function to fetch weather data
Create a function called get_weather(city) in a file named weather.py. This function should use the requests library to get JSON data from https://api.weather.com/v1/{city} and return the JSON response.
Django
Hint
Use requests.get with an f-string URL and return response.json().
2
Set up a Django test case
Create a Django test case class called WeatherTestCase in tests.py. Import TestCase from django.test and the get_weather function from weather. Define a test method test_get_weather inside the class.
Django
Hint
Import TestCase and create a class with a test method stub.
3
Mock the external API call in the test
In the test_get_weather method, use unittest.mock.patch to mock requests.get. Make the mock return an object whose json() method returns {'temp': 20, 'condition': 'sunny'}. Call get_weather('London') and save the result in a variable called data.
Django
Hint
Use patch as a context manager to replace requests.get. Set mock_response.json.return_value to the fixed dictionary.
4
Verify the mocked data is used in the test
Add an assertion in test_get_weather to check that data['temp'] equals 20 and data['condition'] equals 'sunny'.
Django
Hint
Use self.assertEqual to check the values in data.
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
Step 1: Understand the purpose of mocking
Mocking replaces real external calls with fake ones to avoid delays and failures during tests.
Step 2: Identify the benefit in testing context
By not making real network calls, tests run faster and are more reliable.
Final Answer:
To avoid making real network calls during tests -> Option A
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
Step 1: Understand patch target format
The patch decorator requires the full import path to the function or method to mock.
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'.
Final Answer:
@patch('myapp.services.external_api_call') -> Option D
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
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.
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.
Final Answer:
Error: external_service_call not defined -> Option A
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
Step 1: Check patch context usage
The patch is applied only inside the with block, but external_api_call is called after it ends.
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.
Final Answer:
The patch context ends before calling external_api_call -> Option B
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?