File size: 11,662 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
"""Tests for the latest batch of features:

  * Multi-step auto-escalation (lazy checker)
  * Volunteer trust score helper
  * Anonymous alert posting + per-IP rate limit
  * Resource map (POST/GET/DELETE)
  * Inbound WhatsApp webhook (auth gate, happy path)
  * Live responder tracking (privacy + status gating)

Each test isolates one behaviour so a regression points to the right
file without grep archaeology.
"""

from __future__ import annotations

from unittest.mock import AsyncMock, MagicMock

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})


# ──────────────────────────────────────────────────────────────────────
# Trust score
# ──────────────────────────────────────────────────────────────────────


def test_trust_score_zero_when_no_accepts():
    from app.routes.stats import _compute_trust

    out = _compute_trust(0, 0)
    assert out["score"] == 0.0
    assert out["label"] == "new"


def test_trust_score_caps_a_perfect_one_off_below_trusted():
    """1-of-1 success shouldn't auto-promote to 'trusted'. Sample-size
    smoothing pulls it down."""
    from app.routes.stats import _compute_trust

    out = _compute_trust(1, 1)
    assert out["score"] < 0.85
    assert out["label"] != "trusted"


def test_trust_score_eventually_reaches_trusted_with_volume():
    from app.routes.stats import _compute_trust

    out = _compute_trust(50, 50)
    assert out["score"] >= 0.85
    assert out["label"] == "trusted"


def test_trust_score_label_thresholds():
    from app.routes.stats import _trust_label

    assert _trust_label(0.9) == "trusted"
    assert _trust_label(0.7) == "reliable"
    assert _trust_label(0.4) == "new"
    assert _trust_label(0.1) == "unproven"


# ──────────────────────────────────────────────────────────────────────
# Auto-escalation
# ──────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_auto_escalate_skips_recent_alerts():
    """An alert created 1 minute ago shouldn't be escalated even if it's
    sitting unaccepted at MEDIUM."""
    from app.routes import alerts as alerts_route

    db = MagicMock()

    async def empty_cursor():
        if False:
            yield

    db.alerts.find = MagicMock(return_value=empty_cursor())
    bumped = await alerts_route._auto_escalate_unaccepted(db)
    assert bumped == []


# ──────────────────────────────────────────────────────────────────────
# Anonymous alert + rate limit
# ──────────────────────────────────────────────────────────────────────


def test_rate_limiter_lets_through_under_cap():
    from app.services.ratelimit import RateLimiter

    rl = RateLimiter(max_per_window=3, window_seconds=60)
    assert rl.allow("ip-1") is True
    assert rl.allow("ip-1") is True
    assert rl.allow("ip-1") is True
    assert rl.allow("ip-1") is False


def test_rate_limiter_isolates_keys():
    from app.services.ratelimit import RateLimiter

    rl = RateLimiter(max_per_window=2, window_seconds=60)
    rl.allow("ip-a")
    rl.allow("ip-a")
    # ip-a is full but ip-b should still be allowed
    assert rl.allow("ip-a") is False
    assert rl.allow("ip-b") is True


def test_rate_limiter_reset_clears_state():
    from app.services.ratelimit import RateLimiter

    rl = RateLimiter(max_per_window=1, window_seconds=60)
    rl.allow("ip")
    assert rl.allow("ip") is False
    rl.reset()
    assert rl.allow("ip") is True


# ──────────────────────────────────────────────────────────────────────
# Resource map
# ──────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_resources_create_requires_auth(client):
    c, _ = client
    resp = await c.post("/api/resources/", json={
        "kind": "shelter",
        "name": "Sector 17 Community Hall",
        "location": {"type": "Point", "coordinates": [76.7794, 30.7333]},
    })
    assert resp.status_code in (401, 403)


@pytest.mark.asyncio
async def test_resources_create_persists(client):
    c, db = client
    db.users.find_one = AsyncMock(return_value={"_id": ObjectId(), "name": "Volunteer"})
    db.resources.create_index = AsyncMock()
    db.resources.insert_one = AsyncMock(
        return_value=MagicMock(inserted_id=ObjectId())
    )
    resp = await c.post(
        "/api/resources/",
        json={
            "kind": "shelter",
            "name": "Sector 17 Community Hall",
            "location": {"type": "Point", "coordinates": [76.7794, 30.7333]},
            "valid_for_hours": 12,
        },
        headers={"Authorization": f"Bearer {_token()}"},
    )
    assert resp.status_code == 201
    body = resp.json()
    assert body["kind"] == "shelter"
    assert body["name"] == "Sector 17 Community Hall"


@pytest.mark.asyncio
async def test_resources_near_is_public(client):
    c, db = client

    async def empty_cursor():
        if False:
            yield

    db.resources.create_index = AsyncMock()
    cursor = MagicMock()
    cursor.limit = MagicMock(return_value=empty_cursor())
    db.resources.find = MagicMock(return_value=cursor)
    resp = await c.get(
        "/api/resources/near", params={"lat": 30.7333, "lng": 76.7794}
    )
    assert resp.status_code == 200
    assert resp.json() == []


@pytest.mark.asyncio
async def test_resources_delete_invalid_id_returns_400(client):
    c, _ = client
    resp = await c.delete(
        "/api/resources/not-a-real-id",
        headers={"Authorization": f"Bearer {_token()}"},
    )
    assert resp.status_code == 400


# ──────────────────────────────────────────────────────────────────────
# Inbound WhatsApp webhook
# ──────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_inbound_disabled_when_token_unset(client, monkeypatch):
    c, _ = client
    from app.core import config as cfg

    monkeypatch.setattr(cfg.settings, "INBOUND_TOKEN", "")
    resp = await c.post(
        "/api/inbound/whatsapp",
        json={
            "sender": "+91xxxxxxxxxx",
            "body": "Fire near Sector 17 Plaza, sending photo next",
            "location": {"type": "Point", "coordinates": [76.7794, 30.7333]},
            "category": "fire",
        },
    )
    assert resp.status_code == 503


@pytest.mark.asyncio
async def test_inbound_rejects_wrong_token(client, monkeypatch):
    c, _ = client
    from app.core import config as cfg

    monkeypatch.setattr(cfg.settings, "INBOUND_TOKEN", "real-token")
    resp = await c.post(
        "/api/inbound/whatsapp",
        json={
            "sender": "+91xxxxxxxxxx",
            "body": "Fire near Sector 17 Plaza, sending photo next",
            "location": {"type": "Point", "coordinates": [76.7794, 30.7333]},
            "category": "fire",
        },
        headers={"X-Inbound-Token": "wrong"},
    )
    assert resp.status_code == 401


# ──────────────────────────────────────────────────────────────────────
# Responder tracking
# ──────────────────────────────────────────────────────────────────────


@pytest.mark.asyncio
async def test_responder_404_when_alert_missing(client):
    c, db = client
    db.alerts.find_one = AsyncMock(return_value=None)
    resp = await c.get(
        f"/api/alerts/{ObjectId()}/responder",
        headers={"Authorization": f"Bearer {_token()}"},
    )
    assert resp.status_code == 404


@pytest.mark.asyncio
async def test_responder_returns_null_for_unaccepted_alert(client):
    c, db = client
    db.alerts.find_one = AsyncMock(
        return_value={
            "_id": ObjectId(),
            "reporter_id": ObjectId(),
            "accepted_by": None,
            "status": "open",
        }
    )
    resp = await c.get(
        f"/api/alerts/{ObjectId()}/responder",
        headers={"Authorization": f"Bearer {_token()}"},
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["responder_id"] is None
    assert body["coordinates"] is None
    assert body["live"] is False


@pytest.mark.asyncio
async def test_responder_403_when_random_user_asks(client):
    """Strangers can't track random volunteers β€” only the reporter or
    the accepting volunteer can read this."""
    c, db = client
    reporter = ObjectId()
    volunteer = ObjectId()
    db.alerts.find_one = AsyncMock(
        return_value={
            "_id": ObjectId(),
            "reporter_id": reporter,
            "accepted_by": volunteer,
            "status": "accepted",
        }
    )
    # Token sub is a brand-new id β€” not the reporter, not the volunteer
    resp = await c.get(
        f"/api/alerts/{ObjectId()}/responder",
        headers={"Authorization": f"Bearer {_token()}"},
    )
    assert resp.status_code == 403


@pytest.mark.asyncio
async def test_responder_returns_coords_for_reporter(client):
    """The reporter is allowed; if the volunteer is offline we fall back
    to the volunteer's saved home location."""
    c, db = client
    reporter = ObjectId()
    volunteer = ObjectId()
    token = _token(sub=str(reporter))
    db.alerts.find_one = AsyncMock(
        return_value={
            "_id": ObjectId(),
            "reporter_id": reporter,
            "accepted_by": volunteer,
            "status": "accepted",
            "eta_minutes": 12,
        }
    )
    db.users.find_one = AsyncMock(
        return_value={
            "_id": volunteer,
            "name": "Aman",
            "location": {"type": "Point", "coordinates": [76.7, 30.7]},
        }
    )
    resp = await c.get(
        f"/api/alerts/{ObjectId()}/responder",
        headers={"Authorization": f"Bearer {token}"},
    )
    assert resp.status_code == 200
    body = resp.json()
    assert body["live"] is False  # no live WS connection in this test
    assert body["coordinates"] == [76.7, 30.7]
    assert body["responder_name"] == "Aman"
    assert body["eta_minutes"] == 12