'Django rest framework view patching for unit test

here is my view that I want to test:

# views.py
from weather.utils import get_weather_data

class CityWeather(APIView):

    def get(self, request):
        city = request.GET.get('city', None)
        if city:
            city_weather = get_weather_data(city)
            if city_weather:
                return Response(city_weather, status=status.HTTP_200_OK)
        return Response({"error": "City was not found"}, status=status.HTTP_404_NOT_FOUND)

so far here is my tests.py:

class TestWeatherAPI(TestCase):

    def test_get_weather_data(self):
        with mock.patch('weather.utils.get_weather_data') as mock_get:
            response_data = {
                "current_temperature": "3.1°C",
                "current_pressure": 1033,
                "current_humidity": 86
            }
            mock_get.return_value = response_data
            response = self.client.get(reverse('get_city_weather'), {'city': 'London'})
            self.assertEqual(response.status_code, 200)
            self.assertEqual(response.json(), response_data)

As we can see, I want to patch only the get_weather_data in the view. How can I do this ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source