用于单元测试的 Django rest 框架视图修补

Django rest framework view patching for unit 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)

到目前为止这是我的 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)

如我们所见,我只想修补视图中的 get_weather_data。我该怎么做?

这里的关键是修补一个函数或者class它被使用的地方而不是它被定义的地方。因此,假设您有一个名为 views.py

的文件
from weather.utils import get_weather_data

...

class CityWeather...

那么你应该这样打补丁:

with mock.patch('weather.views.get_weather_data') as mock_get:

另一方面,如果你

import weather.utils

然后使用完全限定的weather.utils.get_weather_data(),那么你应该这样打补丁:

with mock.patch('weather.utils.get_weather_data') as mock_get: