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

67 lines
4.5 KiB
Python

"""Actual pipeline: one system, parsed body/history/TTS, emotion before any PCM, turn fencing."""
import asyncio
import io
import json
import time
import unittest
import wave
import httpx
from gateway import Dialogue
from tests_fake import FakeModel
from test_gateway import Socket
class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
async def test_seven_states_no_envelope_in_body_history_or_tts(self):
for emotion,intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]+[('invalid',2),('damaged',0)]:
socket=Socket();tts=[];history=[];order=[]
class OrderedSocket(Socket):
async def send_json(self,event): order.append(event['type']);await super().send_json(event)
async def send_bytes(self,frame): order.append('pcm');await super().send_bytes(frame)
class History:
async def begin(self,*args): pass
async def context(self,*args): return []
async def rows(self,*args): return []
async def finish(self,rid,answer,status): history.append((answer,status))
body=json.dumps(dict(reply='测试回答。',emotion=emotion,intensity=intensity),ensure_ascii=False)
if emotion=='damaged':body='{"reply":"测试回答。","emotion":'
expected=(emotion,intensity,'model') if emotion not in ('invalid','damaged') else ('neutral',0,'fallback')
def backend(request):
if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开测试'})
if 'chat' in request.url.path:
data=json.loads(request.content);self.assertEqual([m['role'] for m in data['messages']],['system','user'])
self.assertNotIn('摄像头观察',data['messages'][0]['content'])
# Even a JSON envelope split inside a key must never leak as text.
return httpx.Response(200,text=''.join('data: '+json.dumps({'choices':[{'delta':{'content':part}}]})+'\n\n' for part in (body[:5],body[5:]))+'data: [DONE]\n\n')
tts.append(json.loads(request.content)['input']);out=io.BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(b'\x11\x01'*960)
return httpx.Response(200,content=out.getvalue())
socket=OrderedSocket()
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(socket,FakeModel(),client,History(),'synthetic');d.run_id='synthetic'
# Exercise both accepted voice modes; both synthesize just the parsed reply once.
d.voice_mode='fragment' if intensity==1 else 'continuous_voice'
await d.run(0,bytes(640))
self.assertEqual(tts,['测试回答。']);self.assertEqual(history,[('测试回答。','completed')])
self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'],['测试回答。'])
events=[e for e in socket.events if e['type']=='reply.emotion'];self.assertEqual(len(events),1)
self.assertEqual((events[0]['emotion'],events[0]['intensity'],events[0]['source'],events[0]['turn_id']),(*expected,0))
self.assertGreater(events[0]['seq'],0);self.assertLess(order.index('reply.emotion'),order.index('pcm'))
self.assertTrue(socket.frames)
async def test_stale_generation_cannot_publish_emotion_or_speak(self):
entered=asyncio.Event();resume=asyncio.Event();socket=Socket()
class Slow(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'data: {"choices":[{"delta":{"content":"{\\\"reply\\\":\\\"hello\\\""}}]}\n\n'
entered.set();await resume.wait()
yield b'data: [DONE]\n\n'
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req:httpx.Response(200,stream=Slow()))) as client:
d=Dialogue(socket,FakeModel(),client);queue=asyncio.Queue(2)
task=asyncio.create_task(d.generate(0,'test',queue,{},time.perf_counter()))
await entered.wait();await d.invalidate('new_turn');resume.set();await task
self.assertTrue(queue.empty())
self.assertFalse(any(e['type'] in ('llm','reply.emotion') for e in socket.events))
await d.event('reply.emotion',0,emotion='angry',intensity=2,source='model')
self.assertEqual([e['type'] for e in socket.events],['abort'])