import asyncio import contextlib import io import struct import unittest import wave import httpx from fastapi.testclient import TestClient from gateway import Dialogue, app from protocol import WavStream, pack, unpack from tests_fake import FakeModel class Socket: def __init__(self): self.events = []; self.frames = [] async def send_json(self, data): self.events.append(data) async def send_bytes(self, data): self.frames.append(data) class ProtocolTests(unittest.TestCase): def test_frame(self): self.assertEqual(unpack(pack(1, 7, 3, bytes(640)), 1), (7, 3, bytes(640))) for data in (b'', pack(2, 7, 3, bytes(640)), b'wrong header!'): with self.assertRaises(ValueError): unpack(data, 1) def test_incremental_wav(self): wav = io.BytesIO() with wave.open(wav, 'wb') as w: w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(bytes(3840)) for size in (1, 3, 137, 4096): parser = WavStream(); out = b''; data = wav.getvalue() for i in range(0, len(data), size): out += parser.feed(data[i:i + size]) parser.finish(); self.assertEqual(out, bytes(3840)) def test_auth_origin_and_no_pre_auth_audio(self): app.state.busy = False; app.state.token = 'x' * 40 client = TestClient(app) with contextlib.nullcontext(client) as client: with self.assertRaises(Exception): with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://evil.invalid'}): pass with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://192.168.31.61:5011'}) as ws: ws.send_json({'type': 'auth', 'token': 'wrong'}) with self.assertRaises(Exception): ws.receive_json() self.assertFalse(app.state.busy) with client.websocket_connect('/ws/dialogue', headers={'Origin': 'https://192.168.31.61:5011'}) as ws: ws.send_bytes(pack(1, 0, 1, bytes(640))) with self.assertRaises(Exception): ws.receive_json() class DialogueTests(unittest.IsolatedAsyncioTestCase): async def test_cancel_and_sequence(self): socket = Socket(); dialogue = Dialogue(socket, FakeModel(), None) await dialogue.listen('manual') old = dialogue.turn await dialogue.input(pack(1, old, 1, bytes(640))) with self.assertRaises(ValueError): await dialogue.input(pack(1, old, 3, bytes(640))) dialogue.task = asyncio.create_task(asyncio.sleep(10)) await dialogue.invalidate('test_abort') await dialogue.audio(old, bytes(1920)) await dialogue.event('llm', old, text='stale') await dialogue.input(pack(1, old, 2, bytes(640))) self.assertEqual(socket.frames, []) self.assertFalse(any(e.get('text') == 'stale' for e in socket.events)) self.assertEqual(len(dialogue.capture), 0) await dialogue.close() async def test_barge_preserves_coordinates_and_submits(self): class SpeechModel(FakeModel): def infer(self, pcm, state): return (0.9 if pcm[0] else 0.0), state socket = Socket(); dialogue = Dialogue(socket, SpeechModel(), None) await dialogue.listen('auto', barge=True) old = dialogue.turn dialogue.task = asyncio.create_task(asyncio.sleep(10)) await dialogue.input(pack(1, old, 1, struct.pack('