Reputation: 3008
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 ?
Upvotes: 0
Views: 926
Reputation: 83557
The key here is to patch a function or class where it is used not where it is defined. So assuming that you have a file named views.py
with
from weather.utils import get_weather_data
...
class CityWeather...
Then you should patch like this:
with mock.patch('weather.views.get_weather_data') as mock_get:
On the other hand if you
import weather.utils
and then use the fully qualified weather.utils.get_weather_data()
, then you should patch like this:
with mock.patch('weather.utils.get_weather_data') as mock_get:
Upvotes: 2