|
1 | 1 | import logging |
2 | 2 |
|
3 | | -from unittest.mock import MagicMock |
| 3 | +from collections.abc import AsyncIterator |
| 4 | +from unittest.mock import AsyncMock, MagicMock |
4 | 5 |
|
5 | 6 | import pytest |
6 | 7 |
|
|
22 | 23 | from google.protobuf import json_format |
23 | 24 | from httpx import ASGITransport, AsyncClient |
24 | 25 | from starlette.applications import Starlette |
| 26 | +from starlette.datastructures import Headers |
| 27 | +from starlette.requests import Request |
25 | 28 |
|
26 | 29 |
|
27 | 30 | logger = logging.getLogger(__name__) |
@@ -200,3 +203,42 @@ async def test_cancel_task_v03( |
200 | 203 | actual_response = a2a_v0_3_pb2.Task() |
201 | 204 | json_format.Parse(response.text, actual_response) |
202 | 205 | assert expected_response == actual_response |
| 206 | + |
| 207 | + |
| 208 | +@pytest.mark.anyio |
| 209 | +async def test_v03_streaming_does_not_ascii_escape_non_ascii( |
| 210 | + request_handler: RequestHandler, |
| 211 | +) -> None: |
| 212 | + """v0.3 REST streaming must emit raw UTF-8 for non-ASCII characters. |
| 213 | +
|
| 214 | + Regression test for https://github.com/a2aproject/a2a-python/issues/1078. |
| 215 | + """ |
| 216 | + adapter = REST03Adapter(http_handler=request_handler) |
| 217 | + non_ascii_text = '你好' |
| 218 | + |
| 219 | + async def stream_with_non_ascii( |
| 220 | + request: Request, context: object |
| 221 | + ) -> AsyncIterator[dict]: |
| 222 | + yield {'msg': {'text': non_ascii_text}} |
| 223 | + |
| 224 | + mock_req = MagicMock(spec=Request) |
| 225 | + mock_req.body = AsyncMock(return_value=b'{}') |
| 226 | + mock_req.headers = Headers({'a2a-version': '0.3'}) |
| 227 | + mock_req.user = MagicMock(is_authenticated=False) |
| 228 | + mock_req.auth = None |
| 229 | + mock_req.scope = {} |
| 230 | + |
| 231 | + response = await adapter._handle_streaming_request( |
| 232 | + stream_with_non_ascii, mock_req |
| 233 | + ) |
| 234 | + chunks = [] |
| 235 | + async for chunk in response.body_iterator: |
| 236 | + chunks.append(chunk) |
| 237 | + |
| 238 | + assert len(chunks) == 1 |
| 239 | + chunk = chunks[0] |
| 240 | + payload = getattr(chunk, 'data', chunk) |
| 241 | + if isinstance(payload, bytes): |
| 242 | + payload = payload.decode('utf-8') |
| 243 | + assert non_ascii_text in payload |
| 244 | + assert '\\u4f60\\u597d' not in payload |
0 commit comments