import pytest from middleware.errors import LimitExceeded, PluginFailure from middleware.sse import decode_sse, encode_sse async def pieces(value, size=1): for i in range(0, len(value), size): yield value[i : i + size] async def test_split_unicode_crlf_multiline_comments(): raw = "\ufeff: heartbeat\r\nevent: text_delta\r\nid: 1\r\ndata: 中文\r\ndata: second\r\nretry: 20\r\n\r\n".encode() events = [event async for event in decode_sse(pieces(raw), 1024)] assert events == [ { "data": "中文\nsecond", "comments": [" heartbeat"], "event": "text_delta", "id": "1", "retry": 20, "has_data": True, } ] assert [e async for e in decode_sse(pieces(encode_sse(events[0], 1024)), 1024)] == events async def test_heartbeat_and_incomplete_frame(): events = [e async for e in decode_sse(pieces(b": ping\n\n"), 1024)] assert events[0]["has_data"] is False with pytest.raises(PluginFailure): _ = [e async for e in decode_sse(pieces(b"data: unfinished"), 1024)] async def test_frame_size_and_invalid_utf8(): with pytest.raises(LimitExceeded): _ = [e async for e in decode_sse(pieces(b"data: " + b"x" * 100), 20)] with pytest.raises(UnicodeError): _ = [e async for e in decode_sse(pieces(b"data: \xff\n\n"), 100)] with pytest.raises(PluginFailure): encode_sse({"event": "evil\ndata: bad", "data": "x"}, 1024)