Test external calendar api

This commit is contained in:
Antoine Bartuccio 2025-01-05 01:04:11 +01:00
parent ba76015c71
commit fa7f5d24b0
3 changed files with 56 additions and 2 deletions

View File

@ -12,7 +12,7 @@ from core.views.files import send_raw_file
class CalendarController(ControllerBase):
CACHE_FOLDER: Path = settings.MEDIA_ROOT / "com" / "calendars"
@route.get("/external.ics")
@route.get("/external.ics", url_name="calendar_external")
def calendar_external(self):
"""Return the ICS file of the AE Google Calendar
@ -27,6 +27,6 @@ class CalendarController(ControllerBase):
return send_raw_file(calendar)
raise Http404
@route.get("/internal.ics")
@route.get("/internal.ics", url_name="calendar_internal")
def calendar_internal(self):
return send_raw_file(IcsCalendar.get_internal())

54
com/tests/test_api.py Normal file
View File

@ -0,0 +1,54 @@
from dataclasses import dataclass
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from django.conf import settings
from django.test.client import Client
from django.urls import reverse
from com.calendar import IcsCalendar
@dataclass
class MockResponse:
status: int
value: str
@property
def data(self):
return self.value.encode("utf8")
@pytest.mark.django_db
class TestExternalCalendar:
@pytest.fixture
def mock_request(self):
request = MagicMock()
with patch("urllib3.request", request):
yield request
@pytest.fixture(autouse=True)
def clear_cache(self):
IcsCalendar._EXTERNAL_CALENDAR.unlink(missing_ok=True)
@pytest.mark.parametrize("error_code", [403, 404, 500])
def test_fetch_error(
self, client: Client, mock_request: MagicMock, error_code: int
):
mock_request.return_value = MockResponse(error_code, "not allowed")
assert client.get(reverse("api:calendar_external")).status_code == 404
def test_fetch_success(self, client: Client, mock_request: MagicMock):
external_response = MockResponse(200, "Definitely an ICS")
mock_request.return_value = external_response
response = client.get(reverse("api:calendar_external"))
assert response.status_code == 200
redirect = Path(response.headers.get("X-Accel-Redirect", ""))
assert redirect.is_relative_to(Path("/") / settings.MEDIA_ROOT.stem)
out_file = settings.MEDIA_ROOT / redirect.relative_to(
Path("/") / settings.MEDIA_ROOT.stem
)
assert out_file.exists()
with open(out_file, "r") as f:
assert f.read() == external_response.value