# Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved. """The link sink against a fake link on a local socket: hello, a stored batch, a refused one, a wrong site, and a command answered as not taken.""" import asyncio import json import pytest from cantabile_edge.sinks import LinkSink SITE = "ab" * 16 async def fake_link(path, site=SITE, refuse=False, command=False): seen = [] async def handle(r, w): while line := await r.readline(): m = json.loads(line) seen.append(m) if m["op"] == "hello": w.write(json.dumps({"op": "hello", "site": site}).encode() + b"\n") if command: w.write(b'{"op":"command","id":"c1","cmd":"mode","args":{"mode":"auto"}}\n') elif m["op"] == "tel": ans = {"op": "ack", "id": m["id"], "ok": not refuse} if refuse: ans["error"] = "not connected" w.write(json.dumps(ans).encode() + b"\n") await w.drain() srv = await asyncio.start_unix_server(handle, path) return srv, seen @pytest.mark.asyncio async def test_stored_batch(tmp_path): p = str(tmp_path / "link.sock") srv, seen = await fake_link(p) s = LinkSink(p, SITE) assert await s.send(5, "tel", {"window": "x", "assets": {}}) tel = [m for m in seen if m["op"] == "tel"][0] assert tel["msg_id"] == f"{SITE}:5" and tel["data"]["seq"] == 5 and tel["data"]["site"] == SITE await s.close() srv.close() @pytest.mark.asyncio async def test_refused_batch_is_kept(tmp_path): p = str(tmp_path / "link.sock") srv, _ = await fake_link(p, refuse=True) s = LinkSink(p, SITE) assert not await s.send(1, "tel", {}) await s.close() srv.close() @pytest.mark.asyncio async def test_wrong_site(tmp_path): p = str(tmp_path / "link.sock") srv, _ = await fake_link(p, site="cd" * 16) s = LinkSink(p, SITE) assert not await s.send(1, "tel", {}) srv.close() @pytest.mark.asyncio async def test_command_not_taken(tmp_path): p = str(tmp_path / "link.sock") srv, seen = await fake_link(p, command=True) s = LinkSink(p, SITE) assert await s.send(1, "tel", {}) for _ in range(50): if any(m["op"] == "result" for m in seen): break await asyncio.sleep(0.02) r = [m for m in seen if m["op"] == "result"][0] assert r["id"] == "c1" and r["ok"] is False await s.close() srv.close()