plugins/fixtures/echo-py/test_plugin.py 8.7 KiB 280 lines Raw
1 """The core side of one echo-py chat.2 3 The test binds a private filesystem socket, starts the plugin, and speaks the4 wire by hand. It uses unittest and the standard library only; no network port is5 opened.6 """7 8 import os9 import shutil10 import socket11 import struct12 import subprocess13 import sys14 import tempfile15 import unittest16 from pathlib import Path17 18 PLUGIN = Path(__file__).resolve().parent / "plugin.py"19 TIMEOUT_S = 1020 HEADER_LEN = 821 MAX_PAYLOAD = 0xFFFFFF22 TEXT_MIME = "text/plain; charset=utf-8"23 24 25 class FrameType:26     """The frame types that this test sends and reads."""27 28     HELLO = 0x0129     WELCOME = 0x0230     CATALOGUE = 0x0331     GRANT = 0x0432     READY = 0x0533     BYE = 0x0934     OPEN = 0x1035     ACCEPT = 0x1136     EVENT = 0x1237     DONE = 0x1338 39 40 def _head(major, arg):41     if arg < 24:42         return bytes([(major << 5) | arg])43     if arg <= 0xFF:44         return bytes([(major << 5) | 24, arg])45     if arg <= 0xFFFF:46         return bytes([(major << 5) | 25]) + arg.to_bytes(2, "big")47     if arg <= 0xFFFFFFFF:48         return bytes([(major << 5) | 26]) + arg.to_bytes(4, "big")49     return bytes([(major << 5) | 27]) + arg.to_bytes(8, "big")50 51 52 def cbor_encode(value):53     """The canonical encoding of one item, for the test's own frames."""54     if value is None:55         return b"\xf6"56     if value is False:57         return b"\xf4"58     if value is True:59         return b"\xf5"60     if isinstance(value, int):61         if value >= 0:62             return _head(0, value)63         return _head(1, -1 - value)64     if isinstance(value, bytes):65         return _head(2, len(value)) + value66     if isinstance(value, str):67         body = value.encode("utf-8")68         return _head(3, len(body)) + body69     if isinstance(value, (list, tuple)):70         return _head(4, len(value)) + b"".join(cbor_encode(v) for v in value)71     if isinstance(value, dict):72         entries = [(cbor_encode(k), v) for k, v in value.items()]73         entries.sort(key=lambda entry: (len(entry[0]), entry[0]))74         return _head(5, len(entries)) + b"".join(75             key + cbor_encode(item) for key, item in entries76         )77     raise TypeError(f"cannot encode {type(value).__name__}")78 79 80 def cbor_decode(data):81     """The one item in `data`; trailing bytes are an error."""82 83     def argument(pos, ai):84         if ai < 24:85             return ai, pos86         width = {24: 1, 25: 2, 26: 4, 27: 8}.get(ai)87         if width is None:88             raise ValueError("indefinite length")89         end = pos + width90         if end > len(data):91             raise ValueError("truncated")92         return int.from_bytes(data[pos:end], "big"), end93 94     def item(pos):95         if pos >= len(data):96             raise ValueError("truncated")97         initial = data[pos]98         major = initial >> 599         ai = initial & 0x1F100         pos += 1101         if major == 7:102             if ai == 20:103                 return False, pos104             if ai == 21:105                 return True, pos106             if ai == 22:107                 return None, pos108             raise ValueError("simple value")109         arg, pos = argument(pos, ai)110         if major == 0:111             return arg, pos112         if major == 1:113             return -1 - arg, pos114         if major in (2, 3):115             end = pos + arg116             if end > len(data):117                 raise ValueError("truncated")118             body = data[pos:end]119             return (bytes(body) if major == 2 else body.decode("utf-8")), end120         if major == 4:121             items = []122             for _ in range(arg):123                 value, pos = item(pos)124                 items.append(value)125             return items, pos126         if major == 5:127             result = {}128             for _ in range(arg):129                 key, pos = item(pos)130                 value, pos = item(pos)131                 result[key] = value132             return result, pos133         raise ValueError(f"major type {major}")134 135     value, pos = item(0)136     if pos != len(data):137         raise ValueError("trailing bytes")138     return value139 140 141 def recv_exact(sock, size):142     out = bytearray()143     while len(out) < size:144         chunk = sock.recv(size - len(out))145         if not chunk:146             raise AssertionError("the plugin closed the socket")147         out.extend(chunk)148     return bytes(out)149 150 151 def send_frame(sock, stream, kind, body):152     payload = cbor_encode(body)153     sock.sendall(struct.pack("<IHBB", len(payload), stream, kind, 0) + payload)154 155 156 def recv_frame(sock):157     header = recv_exact(sock, HEADER_LEN)158     length, stream, kind, flags = struct.unpack("<IHBB", header)159     if length > MAX_PAYLOAD:160         raise AssertionError("payload over the wire ceiling")161     if flags != 0:162         raise AssertionError("flags are not zero")163     payload = recv_exact(sock, length)164     return stream, kind, cbor_decode(payload)165 166 167 class EchoPluginTest(unittest.TestCase):168     """One session, one chat, one terminal frame."""169 170     def test_one_chat(self):171         directory = tempfile.mkdtemp(prefix="inf3r-echo-py-")172         path = os.path.join(directory, "socket")173         listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)174         listener.settimeout(TIMEOUT_S)175         listener.bind(path)176         listener.listen(1)177 178         plugin = subprocess.Popen(179             [sys.executable, str(PLUGIN), "--socket", path],180             stdout=subprocess.PIPE,181             stderr=subprocess.PIPE,182         )183         connection = None184         try:185             connection, _ = listener.accept()186             connection.settimeout(TIMEOUT_S)187 188             send_frame(189                 connection,190                 0,191                 FrameType.HELLO,192                 {"v": 1, "role": "call", "id": "echo-py-test"},193             )194 195             stream, kind, body = recv_frame(connection)196             self.assertEqual((stream, kind), (0, FrameType.WELCOME))197             self.assertEqual(body["v"], 2)198 199             stream, kind, catalogue = recv_frame(connection)200             self.assertEqual((stream, kind), (0, FrameType.CATALOGUE))201             self.assertEqual(len(catalogue["models"]), 1)202             model = catalogue["models"][0]203             self.assertEqual(model["serve"], "echo-py")204             self.assertEqual(model["capabilities"]["chat"]["parts"], ["text"])205             self.assertEqual(model["capabilities"]["chat"]["channels"], ["text"])206 207             send_frame(connection, 0, FrameType.GRANT, {"deps": []})208             stream, kind, ready = recv_frame(connection)209             self.assertEqual((stream, kind), (0, FrameType.READY))210             self.assertEqual(ready["load_ms"], 0)211 212             text = b"hello from python"213             send_frame(214                 connection,215                 1,216                 FrameType.OPEN,217                 {218                     "request_id": "r-1",219                     "model": "echo-py",220                     "capability": "chat",221                     "credit": 4096,222                     "budget_ms": 1000,223                     "parts": [224                         {225                             "kind": "text",226                             "mime": TEXT_MIME,227                             "role": None,228                             "len": len(text),229                             "inline": text,230                         }231                     ],232                     "params": {},233                 },234             )235 236             stream, kind, accepted = recv_frame(connection)237             self.assertEqual((stream, kind), (1, FrameType.ACCEPT))238             self.assertIsNone(accepted["est_ms"])239 240             events = []241             done = None242             while done is None:243                 stream, kind, body = recv_frame(connection)244                 self.assertEqual(stream, 1)245                 if kind == FrameType.EVENT:246                     events.append(body)247                 elif kind == FrameType.DONE:248                     done = body249                 else:250                     self.fail(f"unexpected frame {kind:#04x}")251 252             self.assertTrue(253                 any(event["data"] == text for event in events),254                 f"no event carries {text!r}: {events!r}",255             )256             self.assertEqual(done["outcome"], "completed")257 258             send_frame(connection, 0, FrameType.BYE, {"reason": "test done"})259             plugin.wait(timeout=TIMEOUT_S)260             self.assertEqual(plugin.returncode, 0)261         finally:262             if connection is not None:263                 connection.close()264             listener.close()265             if plugin.poll() is None:266                 plugin.terminate()267                 try:268                     plugin.wait(timeout=TIMEOUT_S)269                 except subprocess.TimeoutExpired:270                     plugin.kill()271                     plugin.wait()272             if plugin.stdout is not None:273                 plugin.stdout.close()274             if plugin.stderr is not None:275                 plugin.stderr.close()276             shutil.rmtree(directory, ignore_errors=True)277 278 279 if __name__ == "__main__":280     unittest.main()