File size: 4,469 Bytes
2756f0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from sqlalchemy import select

from app.core.database import get_session_factory
from app.modules.devices.models import Device
from tests.factories import make_account


async def _rows() -> list[tuple]:
    async with get_session_factory()() as db:
        return [(d.account_id, d.platform, d.push_token, d.last_seen_at) for d in await db.scalars(select(Device))]


async def test_register_device_and_reregister(client):
    me = await make_account("player")
    response = await client.post("/v1/devices", headers=me["headers"], json={"platform": "ios", "push_token": "tok-1"})
    assert response.status_code == 201
    device = response.json()["device"]
    assert set(device) == {"id", "platform", "push_token", "created_at"}
    assert (device["platform"], device["push_token"]) == ("ios", "tok-1")
    [(_, _, _, first_seen)] = await _rows()

    response = await client.post("/v1/devices", headers=me["headers"],
                                 json={"platform": "android", "push_token": "tok-1"})
    assert response.status_code == 200
    assert response.json()["device"]["id"] == device["id"]
    [(account_id, platform, _, last_seen)] = await _rows()
    assert (account_id, platform) == (me["id"], "android")
    assert last_seen >= first_seen


async def test_token_moves_to_new_account(client):
    first, second = await make_account("player"), await make_account("coach")
    await client.post("/v1/devices", headers=first["headers"], json={"platform": "ios", "push_token": "shared"})
    response = await client.post("/v1/devices", headers=second["headers"],
                                 json={"platform": "ios", "push_token": "shared"})
    assert response.status_code == 201
    [(account_id, *_)] = await _rows()
    assert account_id == second["id"]


async def test_register_validation_and_auth(client):
    me = await make_account("player")
    for body in ({"platform": "web", "push_token": "t"}, {"platform": "ios", "push_token": ""},
                 {"platform": "ios"}, {"platform": "ios", "push_token": "t", "extra": 1}):
        response = await client.post("/v1/devices", headers=me["headers"], json=body)
        assert response.status_code == 400
        assert response.json()["error"]["code"] == "VALIDATION"
    response = await client.post("/v1/devices", json={"platform": "ios", "push_token": "t"})
    assert response.status_code == 401


async def test_delete_device_only_own(client):
    me, other = await make_account("player"), await make_account("player")
    await client.post("/v1/devices", headers=me["headers"], json={"platform": "ios", "push_token": "mine"})

    response = await client.delete("/v1/devices/mine", headers=other["headers"])
    assert response.status_code == 204
    assert len(await _rows()) == 1

    assert (await client.delete("/v1/devices/mine", headers=me["headers"])).status_code == 204
    assert await _rows() == []
    assert (await client.delete("/v1/devices/mine", headers=me["headers"])).status_code == 204
    assert (await client.delete("/v1/devices/mine")).status_code == 401


async def test_push_client_unconfigured_is_noop():
    from app.core.config import Settings
    from app.integrations.push import PushClient

    assert await PushClient(Settings(fcm_project_id="", fcm_service_account_file="")).send(["t"], {"a": 1}) == []


async def test_push_client_reports_dead_tokens(monkeypatch):
    import httpx

    from app.core.config import Settings
    from app.integrations import push as push_module

    def handler(request: httpx.Request) -> httpx.Response:
        token = request.read().decode()
        if "gone" in token:
            return httpx.Response(404, json={"error": {"status": "NOT_FOUND", "details": [
                {"@type": "type.googleapis.com/google.firebase.fcm.v1.FcmError", "errorCode": "UNREGISTERED"}]}})
        if "busy" in token:
            return httpx.Response(503, json={"error": {"status": "UNAVAILABLE"}})
        return httpx.Response(200, json={"name": "projects/p/messages/1"})

    real_client = httpx.AsyncClient
    monkeypatch.setattr(push_module.httpx, "AsyncClient",
                        lambda **kw: real_client(transport=httpx.MockTransport(handler), **kw))
    client = push_module.PushClient(Settings(fcm_project_id="p", fcm_service_account_file="sa.json"))
    monkeypatch.setattr(client, "_access_token", lambda: "access")
    assert await client.send(["ok", "gone", "busy"], {"type": "review.received"}) == ["gone"]