Files
baji-vc/gateway/tests/test_gateway.py
T

116 lines
5.7 KiB
Python

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('<h', 1000) * 1536))
self.assertGreater(dialogue.turn, old)
self.assertTrue(dialogue.vad.active)
submitted = []
async def submit(pcm, end): submitted.append((len(pcm), end))
dialogue.submit = submit
await dialogue.input(pack(1, dialogue.turn, 1, bytes(10240)))
self.assertEqual(submitted, [(3072, 1536)])
await dialogue.close()
async def test_debug_half_duplex_drain_blocks_echo_input(self):
dialogue = Dialogue(Socket(), FakeModel(), None)
await dialogue.listen('auto', barge=False)
dialogue.playback_waiting = True
await dialogue.input(pack(1, dialogue.turn, 1, bytes(640)))
self.assertEqual(dialogue.capture, b'')
self.assertEqual(dialogue.vad.samples, 0)
await dialogue.close()
async def test_stage_metrics_mock_pipeline(self):
socket = Socket()
wav = io.BytesIO()
with wave.open(wav, 'wb') as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(48000); w.writeframes(struct.pack('<h', 1000) * 1920)
def backend(request):
if 'transcriptions' in request.url.path: return httpx.Response(200, json={'text': '喝水有什么用?'})
if 'chat' in request.url.path:
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"补充水分。"}}]}\n\ndata: [DONE]\n\n', headers={'Content-Type': 'text/event-stream'})
return httpx.Response(200, content=wav.getvalue())
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
dialogue = Dialogue(socket, FakeModel(), client)
await dialogue.run(0, bytes(640))
metrics = [e for e in socket.events if e['type'] == 'metrics'][0]['values']
for key in ['stt_ms','llm_first_body_ms','first_fragment_ms','tts_first_pcm_ms','tts_first_voiced_block_ms']: self.assertIn(key, metrics)
segment=metrics['tts_segments'][0]
for key in ['first_pcm_ms','first_voiced_ms','total_ms','audio_seconds','rtf','schedule_gap_ms','pcm_arrival_gap_ms','ready_ahead']: self.assertIn(key,segment)
self.assertNotIn('text',segment)
self.assertEqual(segment['audio_seconds'],.04)
self.assertEqual(len(socket.frames), 2)
self.assertEqual(unpack(socket.frames[0], 2)[:2], (0, 1))