0
0
Djangoframework~30 mins

Mocking external services in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use self.assertEqual to check the values in data.