Spaces:
Sleeping
Sleeping
File size: 8,681 Bytes
49e9f9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | """Integration tests for the new endpoints added in the latest update:
* GET /api/alerts/{id}/photos (lazy-load)
* POST /api/alerts/{id}/flag (community moderation)
* PATCH /api/users/me/profile (skills / vehicle / contacts)
These all go through the same FastAPI app + mock-Mongo plumbing as the
existing endpoint tests so the routing/auth wiring is exercised end-to-end.
"""
from __future__ import annotations
from unittest.mock import AsyncMock
import pytest
from bson import ObjectId
from app.core.security import create_token
def _token(role: str = "reporter", sub: str | None = None) -> str:
return create_token({"sub": sub or str(ObjectId()), "role": role})
# -----------------------------------------------------------------------
# /api/alerts/{id}/photos β lazy-loaded photo payload
# -----------------------------------------------------------------------
@pytest.mark.asyncio
async def test_photos_endpoint_returns_data_urls(client):
c, db = client
alert_id = ObjectId()
db.alerts.find_one = AsyncMock(
return_value={
"_id": alert_id,
"photos": ["data:image/jpeg;base64,xxx", "data:image/jpeg;base64,yyy"],
"flags": 0,
}
)
resp = await c.get(f"/api/alerts/{alert_id}/photos")
assert resp.status_code == 200
body = resp.json()
assert len(body["photos"]) == 2
assert body["photos"][0].startswith("data:image/")
@pytest.mark.asyncio
async def test_photos_endpoint_404_on_missing(client):
c, db = client
db.alerts.find_one = AsyncMock(return_value=None)
resp = await c.get(f"/api/alerts/{ObjectId()}/photos")
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_photos_endpoint_hides_flagged(client):
c, db = client
db.alerts.find_one = AsyncMock(
return_value={"_id": ObjectId(), "photos": ["x"], "flags": 99}
)
resp = await c.get(f"/api/alerts/{ObjectId()}/photos")
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_photos_endpoint_400_on_invalid_id(client):
c, _ = client
resp = await c.get("/api/alerts/not-a-real-id/photos")
assert resp.status_code == 400
# -----------------------------------------------------------------------
# /api/alerts/{id}/flag β community moderation
# -----------------------------------------------------------------------
@pytest.mark.asyncio
async def test_flag_requires_auth(client):
c, _ = client
resp = await c.post(f"/api/alerts/{ObjectId()}/flag")
assert resp.status_code in (401, 403)
@pytest.mark.asyncio
async def test_flag_rejects_self_flag(client):
"""A reporter can't flag their own alert."""
c, db = client
user_id = str(ObjectId())
token = _token("reporter", sub=user_id)
db.alerts.find_one = AsyncMock(
return_value={
"_id": ObjectId(),
"reporter_id": ObjectId(user_id),
"flagged_by": [],
"flags": 0,
}
)
resp = await c.post(
f"/api/alerts/{ObjectId()}/flag",
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 400
@pytest.mark.asyncio
async def test_flag_idempotent_for_same_user(client):
c, db = client
user_id = str(ObjectId())
token = _token("reporter", sub=user_id)
db.alerts.find_one = AsyncMock(
return_value={
"_id": ObjectId(),
"reporter_id": ObjectId(), # different user
"flagged_by": [user_id],
"flags": 1,
}
)
resp = await c.post(
f"/api/alerts/{ObjectId()}/flag",
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
body = resp.json()
assert body["already"] is True
assert body["flags"] == 1
@pytest.mark.asyncio
async def test_flag_increments_count(client):
c, db = client
user_id = str(ObjectId())
token = _token("reporter", sub=user_id)
db.alerts.find_one = AsyncMock(
return_value={
"_id": ObjectId(),
"reporter_id": ObjectId(),
"flagged_by": [],
"flags": 0,
}
)
db.alerts.find_one_and_update = AsyncMock(return_value={"flags": 1})
resp = await c.post(
f"/api/alerts/{ObjectId()}/flag",
headers={"Authorization": f"Bearer {token}"},
)
assert resp.status_code == 200
body = resp.json()
assert body["already"] is False
assert body["flags"] == 1
@pytest.mark.asyncio
async def test_flag_404_when_alert_gone(client):
c, db = client
db.alerts.find_one = AsyncMock(return_value=None)
resp = await c.post(
f"/api/alerts/{ObjectId()}/flag",
headers={"Authorization": f"Bearer {_token('reporter')}"},
)
assert resp.status_code == 404
# -----------------------------------------------------------------------
# /api/users/me/profile β patch skills / vehicle / contacts
# -----------------------------------------------------------------------
@pytest.mark.asyncio
async def test_profile_update_rejects_empty_body(client):
c, _ = client
resp = await c.patch(
"/api/users/me/profile",
json={}, # no fields β 400
headers={"Authorization": f"Bearer {_token('volunteer')}"},
)
assert resp.status_code == 400
@pytest.mark.asyncio
async def test_profile_update_rejects_unknown_skill(client):
c, _ = client
resp = await c.patch(
"/api/users/me/profile",
json={"skills": ["telepathy"]}, # not in the enum
headers={"Authorization": f"Bearer {_token('volunteer')}"},
)
assert resp.status_code == 422
@pytest.mark.asyncio
async def test_profile_update_writes_skills_only(client):
c, db = client
db.users.find_one_and_update = AsyncMock(
return_value={
"_id": ObjectId(),
"name": "x",
"email": "x@x.com",
"role": "volunteer",
"location": {"type": "Point", "coordinates": [76.7, 30.7]},
"skills": ["medical", "cpr"],
"has_vehicle": False,
"emergency_contacts": [],
"created_at": "2024-01-01T00:00:00",
}
)
resp = await c.patch(
"/api/users/me/profile",
json={"skills": ["medical", "cpr"]},
headers={"Authorization": f"Bearer {_token('volunteer')}"},
)
assert resp.status_code == 200
body = resp.json()
assert body["skills"] == ["medical", "cpr"]
# Verify the $set call only included the requested field
call = db.users.find_one_and_update.call_args
update = call.args[1] if len(call.args) >= 2 else call.kwargs.get("update")
assert "$set" in update
assert set(update["$set"].keys()) == {"skills"}
@pytest.mark.asyncio
async def test_profile_update_caps_emergency_contacts(client):
"""The model's max_length=5 should reject 6 contacts."""
c, _ = client
resp = await c.patch(
"/api/users/me/profile",
json={
"emergency_contacts": [
{"name": f"Contact {i}", "phone": "+91" + str(i) * 10}
for i in range(6)
]
},
headers={"Authorization": f"Bearer {_token('volunteer')}"},
)
assert resp.status_code == 422
# -----------------------------------------------------------------------
# Webhook service β fire-and-forget no-op when URL unset
# -----------------------------------------------------------------------
def test_webhook_no_op_when_url_unset(monkeypatch):
from app.core import config as cfg
from app.services import webhook
monkeypatch.setattr(cfg.settings, "ALERT_WEBHOOK_URL", "")
# Should not raise even though there's no event loop / asyncio context here
webhook.fire_alert_created({"id": "abc"})
def test_webhook_payload_shape_is_minimal():
from app.services.webhook import _webhook_payload
payload = _webhook_payload(
{
"id": "alert-1",
"category": "fire",
"urgency": "CRITICAL",
"description": "x",
"status": "open",
"address": "...",
"location": {"type": "Point", "coordinates": [76.7, 30.7]},
"photo_count": 1,
"verified_score": 80,
"created_at": "2026-04-25T11:23:00+00:00",
# These should NOT make it into the outbound payload
"photos": ["data:image/jpeg;base64,LARGEBLOB"],
"flagged_by": ["user-x"],
}
)
assert payload["event"] == "alert.created"
assert "photos" not in payload["alert"]
assert "flagged_by" not in payload["alert"]
assert payload["alert"]["photo_count"] == 1
|