Как протестировать внешнюю функцию API fetch с исключением connectionerror Django
Мой фрагмент кода получает данные из внешнего API. Он отлично работает, и я проверил результаты, когда у меня нет проблем с подключением. Однако меня интересует тестирование моего блока try
except
, который обрабатывает любые проблемы с соединением во время выполнения функции. Я использую библиотеку python 'requests', и у меня нет никаких претензий к ней, но я чувствую, что тестирование проблемы с соединением позволит убедиться, что мой код не выбросит исключение.
Это самый близкий ответ StackOverflow только для python, но я не смог реализовать его в своем коде. Также я нашел другой ответ, в котором предлагалось использовать Httpretty, но я не думаю, что это подход к данному вопросу.
Кто-нибудь знает, как имитировать сбои при получении данных из внешнего API?
views.py
def fetch_question(request):
handler = APIHandler()
match request.POST["difficulty"]:
case "easy":
url = (
"https://opentdb.com/api.php?amount=1&category=9&difficulty=easy&type=multiple&token="
+ handler.token
)
case "medium":
url = (
"https://opentdb.com/api.php?amount=1&category=9&difficulty=medium&type=multiple&token="
+ handler.token
)
case "hard":
url = (
"https://opentdb.com/api.php?amount=1&category=9&difficulty=hard&type=multiple&token="
+ handler.token
)
try:
response = requests.get(url)
except ConnectionError: # Want to test this exception
response.raise_for_status()
else:
return render_question(request, response.json())
test_views.py
from django.test import TestCase, Client
client = Client()
class QuestionTest(TestCase):
def test_page_load(self):
response = self.client.get("/log/question")
self.assertEqual(response["content-type"], "text/html; charset=utf-8")
self.assertTemplateUsed(response, "log/question.html")
self.assertContains(response, "Choose your question level", status_code=200)
def test_fetch_question(self): #Test for successful data fetch
response = self.client.post(
"/log/question", {"level": "level", "difficulty": "hard"}, follow=True
)
self.assertEqual(len(response.context), 2)
self.assertIn("question", response.context)
self.assertIn("answers", response.context)
self.assertEqual(len(response.context["answers"]), 4)
self.assertTemplateUsed(response, "log/question.html")
# how to test connection error?