I’m looking for a way to test a function called fetch_options
that basically renders a returned JSONResponse from an internal API. My approach to this test is to mock requests
because the internal API is located in another app which has already tested in a different test suite.
I’ve got a gut feeling that the function is properly patched with the mock but for some reason my render
call can’t get the response data, I might be wrong about this though.
planner/views/meals.py
def fetch_options(request, meal, field):
if field == "ingredients":
index = 1
else:
index = 0
try:
response = requests.get("log/api/send_" + field) #Trying to mock requests here, request fetches from /log/views/api.py
except ConnectionError:
requests.raise_from_exception()
else:
return render(request, {"meal": meal, "options": list(response)[index]}) # throws list index out range in tests
/log/views/api.py
def send_data(request, option):
match option:
case "ingredients":
data = Log.objects.first().recipe_ingredients
case "areas":
data = Log.objects.first().recipe_area
case "categories":
data = Log.objects.first().recipe_categories
case "activities":
data = Log.objects.first().activities
response = JsonResponse(data, status=200, safe=False)
return response
planner/tests/test_meals_view.py
from unittest import MagicMock, patch
@patch("planner.views.meals.requests")
def test_fetch_options(self, mock_requests):
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json_data = [{"id": "357", "strIngredient": "Orange"}]
mock_requests.get.return_value = mock_response
self.assertContains(
fetch_options("request", "breakfast", "ingredients"), status_code=200
)
Can anyone tell me what I’m missing or doing wrong please?