|
| 1 | +"""E2E: Admin endpoints — cleanup, inactive relations, wellness aggregate.""" |
| 2 | + |
| 3 | +from datetime import UTC, datetime, timedelta |
| 4 | +from unittest.mock import patch |
| 5 | + |
| 6 | +import pytest |
| 7 | +from httpx import AsyncClient |
| 8 | +from sqlalchemy.ext.asyncio import AsyncSession |
| 9 | + |
| 10 | +from src.notifications.model import DeviceToken |
| 11 | +from src.relations.model import CareRelation |
| 12 | +from src.users.model import User |
| 13 | +from src.wellness.model import WellnessLog |
| 14 | +from tests.e2e.conftest import CAREGIVER_USER_ID, HOST_USER_ID |
| 15 | + |
| 16 | +pytestmark = [ |
| 17 | + pytest.mark.filterwarnings("ignore::jwt.warnings.InsecureKeyLengthWarning"), |
| 18 | +] |
| 19 | + |
| 20 | + |
| 21 | +# ── Seed helpers ────────────────────────────────────────────────── |
| 22 | +async def _seed_host_and_caregiver(db: AsyncSession) -> tuple[User, User]: |
| 23 | + """Insert host + caregiver users.""" |
| 24 | + host = User( |
| 25 | + id=HOST_USER_ID, |
| 26 | + email="host-admin@test.com", |
| 27 | + name="Admin Host", |
| 28 | + role="host", |
| 29 | + provider="google", |
| 30 | + provider_id="google-admin-host", |
| 31 | + email_verified=True, |
| 32 | + ) |
| 33 | + caregiver = User( |
| 34 | + id=CAREGIVER_USER_ID, |
| 35 | + email="cg-admin@test.com", |
| 36 | + name="Admin Caregiver", |
| 37 | + role="concierge", |
| 38 | + provider="google", |
| 39 | + provider_id="google-admin-cg", |
| 40 | + email_verified=True, |
| 41 | + ) |
| 42 | + db.add_all([host, caregiver]) |
| 43 | + await db.commit() |
| 44 | + return host, caregiver |
| 45 | + |
| 46 | + |
| 47 | +# ── Tests ───────────────────────────────────────────────────────── |
| 48 | + |
| 49 | + |
| 50 | +class TestAdminCleanup: |
| 51 | + async def test_cleanup_deletes_old_wellness_logs( |
| 52 | + self, client: AsyncClient, db_session: AsyncSession |
| 53 | + ) -> None: |
| 54 | + host, _ = await _seed_host_and_caregiver(db_session) |
| 55 | + |
| 56 | + # Insert old wellness log (120 days ago) |
| 57 | + old_log = WellnessLog( |
| 58 | + host_id=host.id, |
| 59 | + status="normal", |
| 60 | + summary="Old log", |
| 61 | + details={}, |
| 62 | + created_at=datetime.now(UTC) - timedelta(days=120), |
| 63 | + ) |
| 64 | + # Insert recent wellness log |
| 65 | + new_log = WellnessLog( |
| 66 | + host_id=host.id, |
| 67 | + status="normal", |
| 68 | + summary="Recent log", |
| 69 | + details={}, |
| 70 | + ) |
| 71 | + db_session.add_all([old_log, new_log]) |
| 72 | + await db_session.commit() |
| 73 | + |
| 74 | + resp = await client.post( |
| 75 | + "/api/v1/admin/cleanup", |
| 76 | + json={"retention_days": 90, "resource_type": "wellness_logs"}, |
| 77 | + ) |
| 78 | + assert resp.status_code == 200 |
| 79 | + data = resp.json() |
| 80 | + assert data["deleted_wellness_logs"] == 1 |
| 81 | + assert data["deactivated_tokens"] == 0 |
| 82 | + |
| 83 | + async def test_cleanup_deactivates_old_tokens( |
| 84 | + self, client: AsyncClient, db_session: AsyncSession |
| 85 | + ) -> None: |
| 86 | + host, _ = await _seed_host_and_caregiver(db_session) |
| 87 | + |
| 88 | + # Insert old device token |
| 89 | + old_token = DeviceToken( |
| 90 | + user_id=host.id, |
| 91 | + token="old-fcm-token-001", # noqa: S106 |
| 92 | + platform="android", |
| 93 | + is_active=True, |
| 94 | + updated_at=datetime.now(UTC) - timedelta(days=100), |
| 95 | + ) |
| 96 | + db_session.add(old_token) |
| 97 | + await db_session.commit() |
| 98 | + |
| 99 | + resp = await client.post( |
| 100 | + "/api/v1/admin/cleanup", |
| 101 | + json={"retention_days": 90, "resource_type": "device_tokens"}, |
| 102 | + ) |
| 103 | + assert resp.status_code == 200 |
| 104 | + data = resp.json() |
| 105 | + assert data["deactivated_tokens"] == 1 |
| 106 | + |
| 107 | + |
| 108 | +class TestAdminInactiveRelations: |
| 109 | + async def test_list_inactive_relations( |
| 110 | + self, client: AsyncClient, db_session: AsyncSession |
| 111 | + ) -> None: |
| 112 | + host, caregiver = await _seed_host_and_caregiver(db_session) |
| 113 | + |
| 114 | + # Create active relation with no wellness logs → should be inactive |
| 115 | + relation = CareRelation( |
| 116 | + host_id=host.id, |
| 117 | + caregiver_id=caregiver.id, |
| 118 | + role="concierge", |
| 119 | + is_active=True, |
| 120 | + ) |
| 121 | + db_session.add(relation) |
| 122 | + await db_session.commit() |
| 123 | + |
| 124 | + resp = await client.get( |
| 125 | + "/api/v1/admin/inactive-relations", |
| 126 | + params={"threshold_days": 7}, |
| 127 | + ) |
| 128 | + assert resp.status_code == 200 |
| 129 | + data = resp.json() |
| 130 | + assert len(data) >= 1 |
| 131 | + found = [r for r in data if r["host_id"] == str(host.id)] |
| 132 | + assert len(found) == 1 |
| 133 | + assert found[0]["role"] == "concierge" |
| 134 | + |
| 135 | + async def test_active_relation_with_recent_log_excluded( |
| 136 | + self, client: AsyncClient, db_session: AsyncSession |
| 137 | + ) -> None: |
| 138 | + host, caregiver = await _seed_host_and_caregiver(db_session) |
| 139 | + |
| 140 | + relation = CareRelation( |
| 141 | + host_id=host.id, |
| 142 | + caregiver_id=caregiver.id, |
| 143 | + role="concierge", |
| 144 | + is_active=True, |
| 145 | + ) |
| 146 | + recent_log = WellnessLog( |
| 147 | + host_id=host.id, |
| 148 | + status="normal", |
| 149 | + summary="Just now", |
| 150 | + details={}, |
| 151 | + ) |
| 152 | + db_session.add_all([relation, recent_log]) |
| 153 | + await db_session.commit() |
| 154 | + |
| 155 | + resp = await client.get( |
| 156 | + "/api/v1/admin/inactive-relations", |
| 157 | + params={"threshold_days": 7}, |
| 158 | + ) |
| 159 | + assert resp.status_code == 200 |
| 160 | + data = resp.json() |
| 161 | + # Host with recent log should NOT appear |
| 162 | + found = [r for r in data if r["host_id"] == str(host.id)] |
| 163 | + assert len(found) == 0 |
| 164 | + |
| 165 | + |
| 166 | +class TestAdminWellnessAggregate: |
| 167 | + async def test_aggregate_returns_counts_by_status( |
| 168 | + self, client: AsyncClient, db_session: AsyncSession |
| 169 | + ) -> None: |
| 170 | + host, _ = await _seed_host_and_caregiver(db_session) |
| 171 | + today = datetime.now(UTC).strftime("%Y-%m-%d") |
| 172 | + |
| 173 | + logs = [ |
| 174 | + WellnessLog(host_id=host.id, status="normal", summary="ok", details={}), |
| 175 | + WellnessLog(host_id=host.id, status="normal", summary="ok2", details={}), |
| 176 | + WellnessLog(host_id=host.id, status="warning", summary="hmm", details={}), |
| 177 | + ] |
| 178 | + db_session.add_all(logs) |
| 179 | + await db_session.commit() |
| 180 | + |
| 181 | + resp = await client.get( |
| 182 | + "/api/v1/admin/wellness/aggregate", |
| 183 | + params={"host_id": str(host.id), "date": today}, |
| 184 | + ) |
| 185 | + assert resp.status_code == 200 |
| 186 | + data = resp.json() |
| 187 | + assert data["total_logs"] == 3 |
| 188 | + assert data["by_status"]["normal"] == 2 |
| 189 | + assert data["by_status"]["warning"] == 1 |
| 190 | + |
| 191 | + async def test_aggregate_empty_date( |
| 192 | + self, client: AsyncClient, db_session: AsyncSession |
| 193 | + ) -> None: |
| 194 | + host, _ = await _seed_host_and_caregiver(db_session) |
| 195 | + |
| 196 | + resp = await client.get( |
| 197 | + "/api/v1/admin/wellness/aggregate", |
| 198 | + params={"host_id": str(host.id), "date": "2020-01-01"}, |
| 199 | + ) |
| 200 | + assert resp.status_code == 200 |
| 201 | + data = resp.json() |
| 202 | + assert data["total_logs"] == 0 |
| 203 | + assert data["by_status"] == {} |
| 204 | + |
| 205 | + |
| 206 | +class TestAdminAuth: |
| 207 | + @patch("src.lib.internal_auth.settings") |
| 208 | + async def test_missing_key_returns_401_when_configured( |
| 209 | + self, mock_settings: object, client: AsyncClient |
| 210 | + ) -> None: |
| 211 | + """When INTERNAL_API_KEY is set, missing header returns 401.""" |
| 212 | + mock_settings.INTERNAL_API_KEY = "e2e-secret" # type: ignore[attr-defined] |
| 213 | + resp = await client.post( |
| 214 | + "/api/v1/admin/cleanup", |
| 215 | + json={"retention_days": 90}, |
| 216 | + ) |
| 217 | + assert resp.status_code == 401 |
0 commit comments