"""Live connection for users and paired devices, device config (plan step 3.1a).""" import pytest from starlette.websockets import WebSocketDisconnect from conftest import TEST_PIN from core.modules import device_config from core.modules.model import ConfigField from services import ws_bus WS = "/api/ws/connect" def err(r): return r.json()["error"]["code"] @pytest.fixture def owner_h(make_user, login): return login(make_user(role="owner")) @pytest.fixture def pair(client, owner_h): def _pair(app_key, name=None, **fields): req = client.post("/api/devices/pair-request").json() r = client.post("/api/devices", headers=owner_h, json={"code": req["code"], "app_key": app_key, "name": name or f"{app_key} screen", **fields}) if r.status_code != 201: return None, r poll = client.get(f"/api/devices/pair-request/{req['code']}", headers={"X-Xenia-Pair-Secret": req["secret"]}) return poll.json()["device_token"], r return _pair def terminal_login(client, token, user): r = client.post("/api/auth/login", headers={"X-Xenia-Device": token}, json={"client": "terminal", "user_id": user.id, "pin": TEST_PIN}) assert r.status_code == 200, r.text return r.json()["access_token"] def open_ws(client, **first): ws = client.websocket_connect(WS) sock = ws.__enter__() sock.send_json({"cursor": 0, **first}) return ws, sock def expect_ready(sock): assert sock.receive_json() == {"type": "ready"} def expect_refused(client, code, close, **first): ws, sock = open_ws(client, **first) try: assert sock.receive_json() == {"type": "refused", "data": {"code": code}} with pytest.raises(WebSocketDisconnect) as e: sock.receive_json() assert e.value.code == close finally: ws.__exit__(None, None, None) def expect_closed(sock, close): with pytest.raises(WebSocketDisconnect) as e: sock.receive_json() assert e.value.code == close # ── who may connect ────────────────────────────────────────────────────────── def test_user_token_in_query_still_works(client, make_user, login): h = login(make_user(role="waiter"), "waiter") with client.websocket_connect(f"{WS}?token={h['Authorization'][7:]}") as sock: sock.send_json({"cursor": 0}) expect_ready(sock) ws_bus.broadcast_sync("order_updated", {"order_id": 1}) assert sock.receive_json() == {"seq": 0, "type": "order_updated", "data": {"order_id": 1}} def test_nothing_or_garbage_is_refused(client): expect_refused(client, "auth.session_ended", 4001) expect_refused(client, "auth.session_ended", 4001, token="nope") expect_refused(client, "device.not_paired", 4003, device="nope") def test_device_only_socket_of_a_login_none_app_gets_events(client, pair): # "done when" 1 token, _ = pair("customer_display") ws, sock = open_ws(client, device=token) try: expect_ready(sock) ws_bus.broadcast_sync("product_updated", {"id": 7}) assert sock.receive_json()["type"] == "product_updated" finally: ws.__exit__(None, None, None) def test_device_only_socket_of_a_sign_in_app_gets_only_its_own_events(client, pair): token, r = pair("kds") dev_id = r.json()["id"] other, r2 = pair("kds", "other") ws, sock = open_ws(client, device=token) try: expect_ready(sock) ws_bus.broadcast_sync("order_updated", {"order_id": 1}) # needs a signed-in chef ws_bus.broadcast_sync("for_other", {}, device_ids=[r2.json()["id"]]) ws_bus.broadcast_sync("display", {"n": 1}, device_ids=[dev_id]) assert sock.receive_json() == {"seq": 0, "type": "display", "data": {"n": 1}} finally: ws.__exit__(None, None, None) def test_terminal_jwt_needs_its_device(client, pair, make_user): # "done when" 2 token, _ = pair("kds") other, _ = pair("kds", "other") jwt = terminal_login(client, token, make_user(role="chef")) expect_refused(client, "device.required", 4003, token=jwt) expect_refused(client, "device.required", 4003, token=jwt, device=other) ws, sock = open_ws(client, token=jwt, device=token) try: expect_ready(sock) ws_bus.broadcast_sync("order_updated", {"order_id": 2}) # a chef sees everything assert sock.receive_json()["type"] == "order_updated" finally: ws.__exit__(None, None, None) def test_revoking_a_device_closes_its_sockets(client, pair, owner_h, make_user): # "done when" 3 token, r = pair("kds") dev_id = r.json()["id"] jwt = terminal_login(client, token, make_user(role="chef")) ws1, user_sock = open_ws(client, token=jwt, device=token) ws2, dev_sock = open_ws(client, device=token) try: expect_ready(user_sock) expect_ready(dev_sock) assert client.post(f"/api/devices/{dev_id}/revoke", headers=owner_h).status_code == 200 for sock in (user_sock, dev_sock): assert sock.receive_json() == {"type": "device.revoked", "data": {"device_id": dev_id}} expect_closed(sock, 4003) finally: ws1.__exit__(None, None, None) ws2.__exit__(None, None, None) expect_refused(client, "device.revoked", 4003, device=token) def test_ending_a_session_closes_its_socket(client, make_user, login, owner_h): w = make_user(role="waiter") h = login(w, "waiter") ws, sock = open_ws(client, token=h["Authorization"][7:]) try: expect_ready(sock) sid = next(s for s in client.get("/api/auth/sessions", headers=owner_h).json() if s["user_id"] == w.id)["id"] assert client.post(f"/api/auth/sessions/{sid}/end", headers=owner_h).status_code == 200 msg = sock.receive_json() assert msg["type"] == "session.ended" and msg["data"]["reason"] expect_closed(sock, 4001) finally: ws.__exit__(None, None, None) def test_reassign_and_edit_tell_the_device(client, pair, owner_h): token, r = pair("kds") dev_id = r.json()["id"] ws, sock = open_ws(client, device=token) try: expect_ready(sock) assert client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"name": "Grill"}).status_code == 200 assert sock.receive_json() == {"type": "device.updated", "data": {"device_id": dev_id}} assert client.put("/api/platform/modules/tabs", headers=owner_h, json={"enabled": False}).status_code == 200 assert sock.receive_json()["type"] == "device.updated" assert client.post(f"/api/devices/{dev_id}/reassign", headers=owner_h, json={"app_key": "pos_counter"}).status_code == 200 assert sock.receive_json() == {"type": "device.updated", "data": {"device_id": dev_id, "app_key": "pos_counter"}} expect_closed(sock, 4003) finally: ws.__exit__(None, None, None) # ── device config ──────────────────────────────────────────────────────────── def test_config_validated_and_effective(client, pair, owner_h): # "done when" 4 _, r = pair("kds", config={"auto_sign_out_minutes": 7}) assert r.status_code == 422 and err(r) == "validation.device_config" assert r.json()["error"]["params"] == {"key": "auto_sign_out_minutes"} _, r = pair("kds", config={"colour": "red"}) assert err(r) == "validation.device_config" token, r = pair("kds") defaults = {f.key: f.default for f in device_config.for_app("kds")} assert r.json()["config"] == defaults # defaults filled dev_id = r.json()["id"] r = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"config": {"auto_sign_out_minutes": 5}}) assert r.status_code == 200 and r.json()["config"] == {**defaults, "auto_sign_out_minutes": 5} assert client.get("/api/devices/me", headers={"X-Xenia-Device": token}).json()["config"] \ == {**defaults, "auto_sign_out_minutes": 5} assert err(client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"config": {"auto_sign_out_minutes": True}})) == "validation.device_config" # an app without config fields refuses any key r = client.post(f"/api/devices/{dev_id}/reassign", headers=owner_h, json={"app_key": "customer_display", "config": {"auto_sign_out_minutes": 5}}) assert err(r) == "validation.device_config" def test_module_catalogue_describes_config(client, owner_h): mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=owner_h).json()["modules"]} assert mods["pos_counter"]["device_app"]["config"] == [{"key": "auto_sign_out_minutes", "type": "int", "default": 0, "choices": [0, 2, 5, 10, 30, 60], "min": None, "max": None, "choices_from": None, "group": None, "after": None}] kds = {f["key"]: f for f in mods["kds"]["device_app"]["config"]} assert kds["prep_zone_id"] == {"key": "prep_zone_id", "type": "ref", "default": None, "choices": [], "min": None, "max": None, "choices_from": "prep_zones", "group": "zone", "after": None} assert kds["age_late_minutes"]["after"] == "age_warning_minutes" and kds["colour_fresh"]["type"] == "color" assert mods["customer_display"]["device_app"]["config"] == [] def test_config_field_types(db, pair): from models.prep_zone import PrepZone zone = PrepZone(name="Grill") db.add(zone) db.commit() _, r = pair("pos_counter") pos_id = r.json()["id"] fields = (ConfigField("zone", "ref", choices_from="prep_zones"), ConfigField("pos", "ref", choices_from="devices:pos_counter"), ConfigField("sound", "bool", default=True), ConfigField("layout", "enum", default="grid", choices=("grid", "list")), ConfigField("scale", "int", default=100, min=50, max=200), ConfigField("title", "str", default="")) ok = {"zone": zone.id, "pos": pos_id, "sound": False, "layout": "list", "scale": 150, "title": " Bar "} assert device_config.validate(fields, ok, db) == {**ok, "title": "Bar"} assert device_config.validate(fields, {}, db) is None for bad in ({"zone": 99999}, {"pos": zone.id + 99999}, {"sound": "yes"}, {"layout": "tiles"}, {"scale": 10}, {"scale": 1.5}, {"title": 5}): with pytest.raises(Exception) as e: device_config.validate(fields, bad, db) assert e.value.code == "validation.device_config" # stale stored values fall back to the default; missing keys get theirs eff = device_config.effective(fields, {"zone": 99999, "layout": "tiles", "scale": 120}, db) assert eff == {"zone": None, "pos": None, "sound": True, "layout": "grid", "scale": 120, "title": ""} assert device_config.effective(fields, "junk") == {f.key: f.default for f in fields} def test_config_colours_and_ordered_fields(): fields = (ConfigField("ink", "color", default="#000000"), ConfigField("warn", "int", default=5, min=1, max=60), ConfigField("late", "int", default=10, min=1, max=60, after="warn")) assert device_config.validate(fields, {"ink": "#A0b1C2"}, None) == {"ink": "#a0b1c2"} for bad in ({"ink": "red"}, {"ink": "#abc"}, {"ink": 5}, {"late": 4}, {"warn": 10}, {"warn": 8, "late": 8}): with pytest.raises(Exception) as e: device_config.validate(fields, bad, None) assert e.value.code == "validation.device_config" assert device_config.validate(fields, {"warn": 20, "late": 30}, None) == {"warn": 20, "late": 30} # a stored config that breaks the order reads back as the defaults of the ordered fields assert device_config.effective(fields, {"ink": "#ffffff", "warn": 30, "late": 20}) == {"ink": "#ffffff", "warn": 5, "late": 10}