127 lines
5.6 KiB
Python
127 lines
5.6 KiB
Python
import asyncio
|
|
import json
|
|
import unittest
|
|
import contextlib
|
|
import io
|
|
import os
|
|
from unittest.mock import patch
|
|
|
|
import httpx
|
|
|
|
from ai_chat import AIChatApp, AIConfig, MessageBubble, main
|
|
|
|
|
|
class ChatTests(unittest.IsolatedAsyncioTestCase):
|
|
async def make_app(self, handler, turns=1):
|
|
config = AIConfig('Test', 'https://example.test/v1', 'test-key', 'test-model')
|
|
app = AIChatApp(config, config, 'Start here', turns)
|
|
await app.client.aclose()
|
|
app.client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
|
|
return app
|
|
|
|
async def wait_finished(self, app, pilot):
|
|
for _ in range(100):
|
|
if not app._is_running:
|
|
return
|
|
await pilot.pause(0.02)
|
|
self.fail('Conversation did not finish')
|
|
|
|
async def test_stream_usage_and_speaker_roles(self):
|
|
requests = []
|
|
def handler(request):
|
|
requests.append(json.loads(request.content))
|
|
return httpx.Response(200, text='data:{"choices":[{"delta":{"content":"[bold]hello[/bold]"}}]}\n\ndata: {"choices":[],"usage":{"total_tokens":1}}\n\ndata: [DONE]\n\n')
|
|
app = await self.make_app(handler, turns=3)
|
|
async with app.run_test() as pilot:
|
|
await self.wait_finished(app, pilot)
|
|
self.assertEqual(app.current_turn, 3)
|
|
self.assertEqual(len(app.messages), 4)
|
|
self.assertEqual([m['role'] for m in requests[1]['messages']], ['system', 'user', 'user'])
|
|
self.assertEqual([m['role'] for m in requests[2]['messages']], ['system', 'user', 'assistant', 'user'])
|
|
self.assertEqual(len(app.query(MessageBubble)), 4)
|
|
self.assertEqual(str(app.query(MessageBubble).last()._content_widget.render()), '[bold]hello[/bold]')
|
|
self.assertTrue(app.client.is_closed)
|
|
|
|
async def test_partial_stream_fallback_reuses_bubble(self):
|
|
def handler(request):
|
|
if json.loads(request.content).get('stream'):
|
|
return httpx.Response(200, text='data: {"choices":[{"delta":{"content":"partial"}}]}\n\ndata: {"error":"failed"}\n\n')
|
|
return httpx.Response(200, json={'choices': [{'message': {'content': 'complete'}}]})
|
|
app = await self.make_app(handler)
|
|
async with app.run_test() as pilot:
|
|
await self.wait_finished(app, pilot)
|
|
self.assertEqual([m.content for m in app.messages], ['Start here', 'complete'])
|
|
self.assertEqual(len(app.query(MessageBubble)), 2)
|
|
self.assertFalse(app.query(MessageBubble).last()._streaming)
|
|
|
|
async def test_empty_stream_uses_fallback(self):
|
|
calls = []
|
|
def handler(request):
|
|
calls.append(json.loads(request.content))
|
|
if calls[-1].get('stream'):
|
|
return httpx.Response(200, text='data: [DONE]\n\n')
|
|
return httpx.Response(200, json={'choices': [{'message': {'content': 'fallback'}}]})
|
|
app = await self.make_app(handler)
|
|
async with app.run_test() as pilot:
|
|
await self.wait_finished(app, pilot)
|
|
self.assertEqual(len(calls), 2)
|
|
self.assertEqual(app.messages[-1].content, 'fallback')
|
|
|
|
async def test_error_is_preserved(self):
|
|
app = await self.make_app(lambda request: httpx.Response(500, text='unavailable'))
|
|
async with app.run_test() as pilot:
|
|
await self.wait_finished(app, pilot)
|
|
self.assertIn('Error:', str(app.status_bar.render()))
|
|
self.assertNotIn('Conversation ended', str(app.status_bar.render()))
|
|
self.assertEqual(app.current_turn, 0)
|
|
self.assertEqual(app.messages[-1].role, 'system')
|
|
|
|
async def test_quit_while_request_is_pending(self):
|
|
started = asyncio.Event()
|
|
cancelled = asyncio.Event()
|
|
async def handler(request):
|
|
started.set()
|
|
try:
|
|
await asyncio.Event().wait()
|
|
except asyncio.CancelledError:
|
|
cancelled.set()
|
|
raise
|
|
app = await self.make_app(handler)
|
|
async with app.run_test() as pilot:
|
|
await asyncio.wait_for(started.wait(), 2)
|
|
await pilot.press('ctrl+c')
|
|
self.assertTrue(cancelled.is_set())
|
|
self.assertTrue(app.client.is_closed)
|
|
|
|
async def test_empty_fallback_reports_error(self):
|
|
def handler(request):
|
|
if json.loads(request.content).get('stream'):
|
|
return httpx.Response(200, text='data: [DONE]\n\n')
|
|
return httpx.Response(200, json={'choices': [{'message': {'content': None}}]})
|
|
app = await self.make_app(handler)
|
|
async with app.run_test() as pilot:
|
|
await self.wait_finished(app, pilot)
|
|
self.assertIn('Empty response', str(app.status_bar.render()))
|
|
self.assertEqual(app.current_turn, 0)
|
|
|
|
|
|
class CommandLineTests(unittest.TestCase):
|
|
def test_invalid_environment_turns_reports_usage_error(self):
|
|
with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['ai_chat.py']):
|
|
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
|
with self.assertRaises(SystemExit) as error:
|
|
main()
|
|
self.assertEqual(error.exception.code, 2)
|
|
self.assertIn('invalid int value', stderr.getvalue())
|
|
|
|
def test_help_works_with_invalid_environment_turns(self):
|
|
with patch.dict(os.environ, {"MAX_TURNS": "invalid"}), patch('sys.argv', ['run_example.py', '--help']):
|
|
with contextlib.redirect_stdout(io.StringIO()):
|
|
with self.assertRaises(SystemExit) as error:
|
|
main()
|
|
self.assertEqual(error.exception.code, 0)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|