|
| 1 | +"""Tests for subprocess transport buffering edge cases.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from collections.abc import AsyncIterator |
| 5 | +from typing import Any |
| 6 | +from unittest.mock import AsyncMock, MagicMock |
| 7 | + |
| 8 | +import pytest |
| 9 | + |
| 10 | +from claude_code_sdk._errors import CLIJSONDecodeError |
| 11 | +from claude_code_sdk._internal.transport.subprocess_cli import SubprocessCLITransport |
| 12 | +from claude_code_sdk.types import ClaudeCodeOptions |
| 13 | + |
| 14 | + |
| 15 | +class MockTextReceiveStream: |
| 16 | + """Mock TextReceiveStream for testing.""" |
| 17 | + |
| 18 | + def __init__(self, lines: list[str]) -> None: |
| 19 | + self.lines = lines |
| 20 | + self.index = 0 |
| 21 | + |
| 22 | + def __aiter__(self) -> AsyncIterator[str]: |
| 23 | + return self |
| 24 | + |
| 25 | + async def __anext__(self) -> str: |
| 26 | + if self.index >= len(self.lines): |
| 27 | + raise StopAsyncIteration |
| 28 | + line = self.lines[self.index] |
| 29 | + self.index += 1 |
| 30 | + return line |
| 31 | + |
| 32 | + |
| 33 | +class TestSubprocessBuffering: |
| 34 | + """Test subprocess transport handling of buffered output.""" |
| 35 | + |
| 36 | + @pytest.mark.asyncio |
| 37 | + async def test_multiple_json_objects_on_single_line(self) -> None: |
| 38 | + """Test parsing when multiple JSON objects are concatenated on a single line. |
| 39 | +
|
| 40 | + In some environments, stdout buffering can cause multiple distinct JSON |
| 41 | + objects to be delivered as a single line with embedded newlines. |
| 42 | + """ |
| 43 | + # Two valid JSON objects separated by a newline character |
| 44 | + json_obj1 = {"type": "message", "id": "msg1", "content": "First message"} |
| 45 | + json_obj2 = {"type": "result", "id": "res1", "status": "completed"} |
| 46 | + |
| 47 | + # Simulate buffered output where both objects appear on one line |
| 48 | + buffered_line = json.dumps(json_obj1) + '\n' + json.dumps(json_obj2) |
| 49 | + |
| 50 | + # Create transport |
| 51 | + transport = SubprocessCLITransport( |
| 52 | + prompt="test", |
| 53 | + options=ClaudeCodeOptions(), |
| 54 | + cli_path="/usr/bin/claude" |
| 55 | + ) |
| 56 | + |
| 57 | + # Mock the process and streams |
| 58 | + mock_process = MagicMock() |
| 59 | + mock_process.returncode = None |
| 60 | + mock_process.wait = AsyncMock(return_value=None) |
| 61 | + transport._process = mock_process |
| 62 | + |
| 63 | + # Create mock stream that returns the buffered line |
| 64 | + transport._stdout_stream = MockTextReceiveStream([buffered_line]) # type: ignore[assignment] |
| 65 | + transport._stderr_stream = MockTextReceiveStream([]) # type: ignore[assignment] |
| 66 | + |
| 67 | + # Collect all messages |
| 68 | + messages: list[Any] = [] |
| 69 | + async for msg in transport.receive_messages(): |
| 70 | + messages.append(msg) |
| 71 | + |
| 72 | + # Verify both JSON objects were successfully parsed |
| 73 | + assert len(messages) == 2 |
| 74 | + assert messages[0]["type"] == "message" |
| 75 | + assert messages[0]["id"] == "msg1" |
| 76 | + assert messages[0]["content"] == "First message" |
| 77 | + assert messages[1]["type"] == "result" |
| 78 | + assert messages[1]["id"] == "res1" |
| 79 | + assert messages[1]["status"] == "completed" |
0 commit comments