Files
iishko-public/tests/test_sse_terminal.py
T
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

106 lines
4.7 KiB
Python

"""Runtime contracts: finish at the SSE terminal marker, never at finish_reason alone."""
import asyncio
import importlib.util
import os
from pathlib import Path
import sys
import unittest
import aiohttp
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
ROOT = Path(os.environ.get('IISHKO_SNAPSHOT_ROOT', Path(__file__).resolve().parents[1] / 'gateway'))
sys.path.insert(0, str(ROOT))
spec = importlib.util.spec_from_file_location('terminal_relay_under_test', ROOT / 'transparent_api.py')
if spec is None or spec.loader is None:
raise RuntimeError('Cannot load relay module from snapshot')
relay_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(relay_module)
class TerminalStreamTests(unittest.IsolatedAsyncioTestCase):
async def exercise(self, parts, expected, *, hold_after=True):
release = asyncio.Event()
upstream_sent = asyncio.Event()
calls = []
async def upstream(request):
calls.append(await request.read())
response = web.StreamResponse(headers={'Content-Type': 'text/event-stream'})
await response.prepare(request)
for part in parts:
await response.write(part)
await asyncio.sleep(0)
upstream_sent.set()
if hold_after:
await release.wait()
try:
await response.write_eof()
except (ConnectionResetError, aiohttp.ClientError):
pass
return response
upstream_app = web.Application()
upstream_app.router.add_post('/v1/chat/completions', upstream)
upstream_server = TestServer(upstream_app)
await upstream_server.start_server()
session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=10))
async def proxy(request):
async with session.post(upstream_server.make_url(request.path),
data=await request.read()) as response:
return await relay_module.relay_api(request, response, requested_model='test-model')
proxy_app = web.Application()
proxy_app.router.add_post('/v1/chat/completions', proxy)
client = TestClient(TestServer(proxy_app))
await client.start_server()
try:
async with client.post('/v1/chat/completions', data=b'{"stream":true}') as response:
await asyncio.wait_for(upstream_sent.wait(), 3)
body = await asyncio.wait_for(response.read(), 1)
self.assertEqual(response.status, 200)
self.assertEqual(body, expected)
self.assertEqual(len(calls), 1, 'terminal handling must never replay generation')
self.assertEqual(response.headers.get('Content-Type'), 'text/event-stream')
finally:
release.set()
await client.close()
await session.close()
await upstream_server.close()
async def test_done_closes_without_upstream_eof(self):
raw = b'data: {"model":"test-model","choices":[{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n\n'
await self.exercise([raw], raw)
async def test_fragmented_crlf_done_is_byte_exact(self):
parts = [b': keepalive\r\n\r\ndata: {"model":"test-model","choices":[]}\r\n\r\ndata: [DO', b'NE]\r', b'\n\r\n']
await self.exercise(parts, b''.join(parts))
async def test_usage_after_finish_reason_is_preserved(self):
parts = [b'data: {"model":"test-model","choices":[{"delta":{},"finish_reason":"stop"}]}\n\n',
b'data: {"model":"test-model","choices":[],"usage":{"total_tokens":9}}\n\n',
b'data: [DONE]\n\n']
await self.exercise(parts, b''.join(parts))
async def test_done_suffix_bytes_are_not_forwarded(self):
terminal = b'data: [DONE]\n\n'
await self.exercise([terminal + b'data: {"error":{"message":"late"}}\n\n'], terminal)
async def test_text_containing_done_is_not_terminal(self):
raw = b'data: {"model":"test-model","choices":[{"delta":{"content":"[DONE]"}}]}\n\n'
# A literal in content must not close the stream before its real marker.
terminal = b'data: [DONE]\n\n'
await self.exercise([raw, terminal], raw + terminal)
async def test_provider_error_still_terminates(self):
raw = b'data: {"error":{"message":"upstream failure","status":503}}\n\n'
mapped, terminal = relay_module.safe_sse_frame(raw[:-2], '/v1/chat/completions', 'test-model')
self.assertTrue(terminal)
await self.exercise([raw], mapped + b'\n\n')
if __name__ == '__main__':
unittest.main(verbosity=2)