Debian Codegraph @

tests/test_streaming.py

raw
1 from __future__ import annotations
2
3 from typing import TypeVar, Iterator, AsyncIterator
4
5 import httpx2
6 import pytest
7
8 from anthropic import Anthropic, AsyncAnthropic
9 from anthropic._streaming import Stream, AsyncStream, ServerSentEvent
10 from anthropic._exceptions import APIStatusError
11
12 _T = TypeVar("_T")
13
14
15 @pytest.mark.asyncio
16 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
17 async def test_basic(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
18 def body() -> Iterator[bytes]:
19 yield b"event: completion\n"
20 yield b'data: {"foo":true}\n'
21 yield b"\n"
22
23 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
24
25 sse = await iter_next(iterator)
26 assert sse.event == "completion"
27 assert sse.json() == {"foo": True}
28
29 await assert_empty_iter(iterator)
30
31
32 @pytest.mark.asyncio
33 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
34 async def test_data_missing_event(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
35 def body() -> Iterator[bytes]:
36 yield b'data: {"foo":true}\n'
37 yield b"\n"
38
39 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
40
41 sse = await iter_next(iterator)
42 assert sse.event is None
43 assert sse.json() == {"foo": True}
44
45 await assert_empty_iter(iterator)
46
47
48 @pytest.mark.asyncio
49 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
50 async def test_event_missing_data(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
51 def body() -> Iterator[bytes]:
52 yield b"event: ping\n"
53 yield b"\n"
54
55 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
56
57 sse = await iter_next(iterator)
58 assert sse.event == "ping"
59 assert sse.data == ""
60
61 await assert_empty_iter(iterator)
62
63
64 @pytest.mark.asyncio
65 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
66 async def test_multiple_events(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
67 def body() -> Iterator[bytes]:
68 yield b"event: ping\n"
69 yield b"\n"
70 yield b"event: completion\n"
71 yield b"\n"
72
73 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
74
75 sse = await iter_next(iterator)
76 assert sse.event == "ping"
77 assert sse.data == ""
78
79 sse = await iter_next(iterator)
80 assert sse.event == "completion"
81 assert sse.data == ""
82
83 await assert_empty_iter(iterator)
84
85
86 @pytest.mark.asyncio
87 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
88 async def test_multiple_events_with_data(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
89 def body() -> Iterator[bytes]:
90 yield b"event: ping\n"
91 yield b'data: {"foo":true}\n'
92 yield b"\n"
93 yield b"event: completion\n"
94 yield b'data: {"bar":false}\n'
95 yield b"\n"
96
97 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
98
99 sse = await iter_next(iterator)
100 assert sse.event == "ping"
101 assert sse.json() == {"foo": True}
102
103 sse = await iter_next(iterator)
104 assert sse.event == "completion"
105 assert sse.json() == {"bar": False}
106
107 await assert_empty_iter(iterator)
108
109
110 @pytest.mark.asyncio
111 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
112 async def test_multiple_data_lines_with_empty_line(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
113 def body() -> Iterator[bytes]:
114 yield b"event: ping\n"
115 yield b"data: {\n"
116 yield b'data: "foo":\n'
117 yield b"data: \n"
118 yield b"data:\n"
119 yield b"data: true}\n"
120 yield b"\n\n"
121
122 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
123
124 sse = await iter_next(iterator)
125 assert sse.event == "ping"
126 assert sse.json() == {"foo": True}
127 assert sse.data == '{\n"foo":\n\n\ntrue}'
128
129 await assert_empty_iter(iterator)
130
131
132 @pytest.mark.asyncio
133 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
134 async def test_data_json_escaped_double_new_line(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
135 def body() -> Iterator[bytes]:
136 yield b"event: ping\n"
137 yield b'data: {"foo": "my long\\n\\ncontent"}'
138 yield b"\n\n"
139
140 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
141
142 sse = await iter_next(iterator)
143 assert sse.event == "ping"
144 assert sse.json() == {"foo": "my long\n\ncontent"}
145
146 await assert_empty_iter(iterator)
147
148
149 @pytest.mark.asyncio
150 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
151 async def test_multiple_data_lines(sync: bool, client: Anthropic, async_client: AsyncAnthropic) -> None:
152 def body() -> Iterator[bytes]:
153 yield b"event: ping\n"
154 yield b"data: {\n"
155 yield b'data: "foo":\n'
156 yield b"data: true}\n"
157 yield b"\n\n"
158
159 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
160
161 sse = await iter_next(iterator)
162 assert sse.event == "ping"
163 assert sse.json() == {"foo": True}
164
165 await assert_empty_iter(iterator)
166
167
168 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
169 async def test_special_new_line_character(
170 sync: bool,
171 client: Anthropic,
172 async_client: AsyncAnthropic,
173 ) -> None:
174 def body() -> Iterator[bytes]:
175 yield b'data: {"content":" culpa"}\n'
176 yield b"\n"
177 yield b'data: {"content":" \xe2\x80\xa8"}\n'
178 yield b"\n"
179 yield b'data: {"content":"foo"}\n'
180 yield b"\n"
181
182 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
183
184 sse = await iter_next(iterator)
185 assert sse.event is None
186 assert sse.json() == {"content": " culpa"}
187
188 sse = await iter_next(iterator)
189 assert sse.event is None
190 assert sse.json() == {"content": " 
"}
191
192 sse = await iter_next(iterator)
193 assert sse.event is None
194 assert sse.json() == {"content": "foo"}
195
196 await assert_empty_iter(iterator)
197
198
199 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
200 async def test_multi_byte_character_multiple_chunks(
201 sync: bool,
202 client: Anthropic,
203 async_client: AsyncAnthropic,
204 ) -> None:
205 def body() -> Iterator[bytes]:
206 yield b'data: {"content":"'
207 # bytes taken from the string 'известни' and arbitrarily split
208 # so that some multi-byte characters span multiple chunks
209 yield b"\xd0"
210 yield b"\xb8\xd0\xb7\xd0"
211 yield b"\xb2\xd0\xb5\xd1\x81\xd1\x82\xd0\xbd\xd0\xb8"
212 yield b'"}\n'
213 yield b"\n"
214
215 iterator = make_event_iterator(content=body(), sync=sync, client=client, async_client=async_client)
216
217 sse = await iter_next(iterator)
218 assert sse.event is None
219 assert sse.json() == {"content": "известни"}
220
221
222 @pytest.mark.parametrize("sync", [True, False], ids=["sync", "async"])
223 async def test_error_type(
224 sync: bool,
225 client: Anthropic,
226 async_client: AsyncAnthropic,
227 ) -> None:
228 def body() -> Iterator[bytes]:
229 yield b"event: error\n"
230 yield b'data: {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}\n\n'
231
232 iterator = make_stream_iterator(content=body(), sync=sync, client=client, async_client=async_client)
233
234 with pytest.raises(APIStatusError) as exc_info:
235 await iter_next(iterator)
236
237 assert exc_info.value.type == "overloaded_error"
238 assert "Overloaded" in str(exc_info.value)
239
240
241 def test_isinstance_check(client: Anthropic, async_client: AsyncAnthropic) -> None:
242 async_stream = AsyncStream(cast_to=object, client=async_client, response=httpx2.Response(200, content=b"foo"))
243 assert isinstance(async_stream, AsyncStream)
244
245 sync_stream = Stream(cast_to=object, client=client, response=httpx2.Response(200, content=b"foo"))
246 assert isinstance(sync_stream, Stream)
247
248
249 async def to_aiter(iter: Iterator[bytes]) -> AsyncIterator[bytes]:
250 for chunk in iter:
251 yield chunk
252
253
254 async def iter_next(iter: Iterator[_T] | AsyncIterator[_T]) -> _T:
255 if isinstance(iter, AsyncIterator):
256 return await iter.__anext__()
257
258 return next(iter)
259
260
261 async def assert_empty_iter(iter: Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]) -> None:
262 with pytest.raises((StopAsyncIteration, RuntimeError)):
263 await iter_next(iter)
264
265
266 def make_event_iterator(
267 content: Iterator[bytes],
268 *,
269 sync: bool,
270 client: Anthropic,
271 async_client: AsyncAnthropic,
272 ) -> Iterator[ServerSentEvent] | AsyncIterator[ServerSentEvent]:
273 if sync:
274 return Stream(cast_to=object, client=client, response=httpx2.Response(200, content=content))._iter_events()
275
276 return AsyncStream(
277 cast_to=object, client=async_client, response=httpx2.Response(200, content=to_aiter(content))
278 )._iter_events()
279
280
281 # Unlike make_event_iterator which only parses SSE events using _iter_events(),
282 # this helper uses __stream__() to process the full stream pipeline including
283 # parsing message objects and converting error events into raised exceptions.
284 def make_stream_iterator(
285 content: Iterator[bytes],
286 *,
287 sync: bool,
288 client: Anthropic,
289 async_client: AsyncAnthropic,
290 ) -> AsyncIterator[object] | Iterator[object]:
291 if sync:
292 return Stream(
293 cast_to=object,
294 client=client,
295 response=httpx2.Response(200, content=content, request=httpx2.Request("GET", "https://example.com")),
296 ).__stream__()
297
298 return AsyncStream(
299 cast_to=object,
300 client=async_client,
301 response=httpx2.Response(200, content=to_aiter(content), request=httpx2.Request("GET", "https://example.com")),
302 ).__stream__()