The agent that turns websites into APIs!
test: expand test coverage to 94.5% with 578 tests
Claude791d9baa2976
diff --git a/tests/test_auto_engineer.py b/tests/test_auto_engineer.pyindex edca2d4..46653d6 100644--- a/tests/test_auto_engineer.py+++ b/tests/test_auto_engineer.py@@ -248,6 +248,150 @@ class TestClaudeAutoEngineerAnalyze:if result is not None:assert "usage" in result+ @pytest.mark.asyncio+ async def test_assistant_message_with_tools(self, tmp_path):+ """AssistantMessage with ToolUseBlock, ToolResultBlock, TextBlock are processed."""+ eng = self._make_engineer(tmp_path)++ from claude_agent_sdk import (+ AssistantMessage,+ ResultMessage,+ TextBlock,+ ToolResultBlock,+ ToolUseBlock,+ )++ mock_tool_use = MagicMock(spec=ToolUseBlock)+ mock_tool_use.name = "Read"+ mock_tool_use.input = {"file_path": "/test.py"}++ mock_tool_result = MagicMock(spec=ToolResultBlock)+ mock_tool_result.is_error = False+ mock_tool_result.content = "file contents"++ mock_text = MagicMock(spec=TextBlock)+ mock_text.text = "Analyzing the file..."++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_tool_use, mock_tool_result, mock_text]+ del mock_assistant.usage++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.auto_engineer.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is not None+ assert "script_path" in result++ @pytest.mark.asyncio+ async def test_assistant_message_with_usage(self, tmp_path):+ """AssistantMessage with usage metadata updates tracking."""+ eng = self._make_engineer(tmp_path)++ from claude_agent_sdk import AssistantMessage, ResultMessage++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = []+ mock_assistant.usage = {"input_tokens": 500, "output_tokens": 200}++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.auto_engineer.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is not None+ assert eng.usage_metadata.get("input_tokens") == 500++ @pytest.mark.asyncio+ async def test_tool_result_with_result_attr(self, tmp_path):+ """ToolResultBlock with result attribute (not content) is handled."""+ eng = self._make_engineer(tmp_path)++ from claude_agent_sdk import (+ AssistantMessage,+ ResultMessage,+ ToolResultBlock,+ ToolUseBlock,+ )++ mock_tool_use = MagicMock(spec=ToolUseBlock)+ mock_tool_use.name = "Bash"+ mock_tool_use.input = {"command": "ls"}++ mock_tool_result = MagicMock(spec=ToolResultBlock)+ mock_tool_result.is_error = True+ del mock_tool_result.content+ mock_tool_result.result = "command not found"++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_tool_use, mock_tool_result]+ del mock_assistant.usage++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.auto_engineer.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is not None++ @pytest.mark.asyncio+ async def test_no_result_message_returns_none(self, tmp_path):+ """Empty stream with no ResultMessage returns None (line 365)."""+ eng = self._make_engineer(tmp_path)++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ return+ yield++ mock_client.receive_response = mock_receive++ with patch("reverse_api.auto_engineer.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is None+class TestOpenCodeAutoEngineerInit:"""Test OpenCodeAutoEngineer initialization."""@@ -384,3 +528,102 @@ class TestOpenCodeAutoEngineerAnalyze:result = await eng.analyze_and_generate()assert result is None++ @pytest.mark.asyncio+ async def test_health_check_401_with_custom_username(self, tmp_path):+ """401 with custom username shows username in output."""+ eng = self._make_engineer(tmp_path)+ eng.opencode_username = "custom_user"++ mock_response = MagicMock()+ mock_response.status_code = 401+ error = httpx.HTTPStatusError("401", request=MagicMock(), response=mock_response)++ mock_client = AsyncMock()+ mock_client.get = AsyncMock(side_effect=error)++ with patch("reverse_api.auto_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is None++ @pytest.mark.asyncio+ async def test_health_check_success_then_session_fail(self, tmp_path):+ """Health check succeeds but session creation raises."""+ eng = self._make_engineer(tmp_path)++ mock_health = MagicMock()+ mock_health.json.return_value = {"status": "ok"}+ mock_health.raise_for_status = MagicMock()++ mock_client = AsyncMock()++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return mock_health+ raise Exception("unexpected get")++ mock_client.get = mock_get+ mock_client.post = AsyncMock(side_effect=Exception("session creation failed"))++ with patch("reverse_api.auto_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is None++ @pytest.mark.asyncio+ async def test_health_check_general_exception(self, tmp_path):+ """General exception on health check shows server not responding."""+ eng = self._make_engineer(tmp_path)++ mock_client = AsyncMock()+ mock_client.get = AsyncMock(side_effect=ConnectionError("refused"))++ with patch("reverse_api.auto_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is None++ @pytest.mark.asyncio+ async def test_mcp_registration_failure(self, tmp_path):+ """MCP server registration failure returns None."""+ eng = self._make_engineer(tmp_path)++ mock_health = MagicMock()+ mock_health.json.return_value = {"status": "ok"}+ mock_health.raise_for_status = MagicMock()++ mock_session = MagicMock()+ mock_session.json.return_value = {"id": "sess_123"}+ mock_session.raise_for_status = MagicMock()++ call_count = [0]++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return mock_health+ raise Exception("unexpected get")++ async def mock_post(path, **kwargs):+ if path == "/session":+ return mock_session+ if path == "/mcp":+ raise Exception("MCP registration failed")+ raise Exception(f"unexpected post to {path}")++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post++ with patch("reverse_api.auto_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is Nonediff --git a/tests/test_collector.py b/tests/test_collector.pyindex 62c8de2..5b6db45 100644--- a/tests/test_collector.py+++ b/tests/test_collector.py@@ -236,6 +236,199 @@ class TestCollectorAgentLoop:result = await collector._agent_loop()assert result == {"success": True}+ @pytest.mark.asyncio+ async def test_agent_loop_assistant_message_with_tools(self, tmp_path):+ """Agent loop processes AssistantMessage with ToolUseBlock, ToolResultBlock, TextBlock."""+ with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:+ mock_ui = MagicMock()+ mock_ui_cls.return_value = mock_ui++ collector = Collector(+ run_id="test123",+ prompt="test",+ model="claude-sonnet-4-5",+ )+ collector._collected_dir = tmp_path+ collector.items_path = tmp_path / "items.jsonl"++ from claude_agent_sdk import (+ AssistantMessage,+ ResultMessage,+ TextBlock,+ ToolResultBlock,+ ToolUseBlock,+ )++ # Create an AssistantMessage with various block types+ mock_tool_use = MagicMock(spec=ToolUseBlock)+ mock_tool_use.name = "WebFetch"+ mock_tool_use.input = {"url": "https://example.com"}++ mock_tool_result = MagicMock(spec=ToolResultBlock)+ mock_tool_result.is_error = False++ mock_text = MagicMock(spec=TextBlock)+ mock_text.text = "Analyzing data..."++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_tool_use, mock_tool_result, mock_text]+ # No usage attribute+ del mock_assistant.usage++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False+ mock_result.result = "Done"++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.collector.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await collector._agent_loop()+ assert result == {"success": True}+ mock_ui.tool_start.assert_called_once_with("WebFetch", {"url": "https://example.com"})+ mock_ui.tool_result.assert_called_once_with("WebFetch", False)+ mock_ui.thinking.assert_called_once_with("Analyzing data...")++ @pytest.mark.asyncio+ async def test_agent_loop_write_items_tracking(self, tmp_path):+ """Agent loop tracks Write to items.jsonl."""+ with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:+ mock_ui = MagicMock()+ mock_ui_cls.return_value = mock_ui++ collector = Collector(+ run_id="test123",+ prompt="test",+ model="claude-sonnet-4-5",+ )+ collector._collected_dir = tmp_path+ collector.items_path = tmp_path / "items.jsonl"++ from claude_agent_sdk import AssistantMessage, ResultMessage, ToolUseBlock++ mock_tool_use = MagicMock(spec=ToolUseBlock)+ mock_tool_use.name = "Write"+ mock_tool_use.input = {+ "file_path": "/tmp/items.jsonl",+ "content": '{"name": "Test Item"}',+ }++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_tool_use]+ del mock_assistant.usage++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.collector.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await collector._agent_loop()+ assert result == {"success": True}+ mock_ui.item_saved.assert_called_once()++ @pytest.mark.asyncio+ async def test_agent_loop_usage_tracking(self, tmp_path):+ """Agent loop accumulates usage metadata."""+ with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:+ mock_ui = MagicMock()+ mock_ui_cls.return_value = mock_ui++ collector = Collector(+ run_id="test123",+ prompt="test",+ model="claude-sonnet-4-5",+ )+ collector._collected_dir = tmp_path+ collector.items_path = tmp_path / "items.jsonl"++ from claude_agent_sdk import AssistantMessage, ResultMessage++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = []+ mock_assistant.usage = {"input_tokens": 100, "output_tokens": 50}++ mock_assistant2 = MagicMock(spec=AssistantMessage)+ mock_assistant2.content = []+ mock_assistant2.usage = {"input_tokens": 200, "output_tokens": 75}++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_assistant2+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.collector.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await collector._agent_loop()+ assert result == {"success": True}+ assert collector.usage_metadata["input_tokens"] == 300+ assert collector.usage_metadata["output_tokens"] == 125++ @pytest.mark.asyncio+ async def test_agent_loop_no_result_returns_success(self, tmp_path):+ """Agent loop returns success when no ResultMessage (line 186)."""+ with patch("reverse_api.collector.MessageStore") as mock_ms:+ with patch("reverse_api.collector.CollectorUI") as mock_ui_cls:+ mock_ui = MagicMock()+ mock_ui_cls.return_value = mock_ui++ collector = Collector(+ run_id="test123",+ prompt="test",+ model="claude-sonnet-4-5",+ )+ collector._collected_dir = tmp_path+ collector.items_path = tmp_path / "items.jsonl"++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ # Yield nothing - empty stream+ return+ yield # Make it an async generator++ mock_client.receive_response = mock_receive++ with patch("reverse_api.collector.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await collector._agent_loop()+ assert result == {"success": True}+class TestCollectorExportCsv:"""Test CSV export."""diff --git a/tests/test_native_host.py b/tests/test_native_host.pyindex 4c9851d..b949dad 100644--- a/tests/test_native_host.py+++ b/tests/test_native_host.py@@ -664,3 +664,72 @@ class TestNativeHostChatAsync:"test message", "run123", {"_callbackId": "cb1"})assert result["type"] == "error"++ @pytest.mark.asyncio+ async def test_chat_streaming_success(self, tmp_path):+ """Chat streaming processes messages and returns response."""+ handler = self._make_handler()++ har_dir = tmp_path / "har"+ har_dir.mkdir(parents=True)+ (har_dir / "recording.har").write_text('{"log": {}}')++ scripts_dir = tmp_path / "scripts"+ scripts_dir.mkdir(parents=True)++ from claude_agent_sdk import (+ AssistantMessage,+ ResultMessage,+ TextBlock,+ ToolResultBlock,+ ToolUseBlock,+ )++ mock_text = MagicMock(spec=TextBlock)+ mock_text.text = "Here is the API client."++ mock_tool_use = MagicMock(spec=ToolUseBlock)+ mock_tool_use.name = "Write"+ mock_tool_use.input = {"file_path": "/test.py", "content": "code"}++ mock_tool_result = MagicMock(spec=ToolResultBlock)+ mock_tool_result.is_error = False+ mock_tool_result.content = "File written"++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_text, mock_tool_use, mock_tool_result]++ mock_result = MagicMock(spec=ResultMessage)+ mock_result.is_error = False+ mock_result.total_cost_usd = 0.01+ mock_result.duration_ms = 5000++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant+ yield mock_result++ mock_client.receive_response = mock_receive++ with patch("reverse_api.utils.get_har_dir", return_value=har_dir):+ with patch("reverse_api.utils.get_scripts_dir", return_value=scripts_dir):+ with patch("reverse_api.native_host.send_message") as mock_send:+ mock_sdk = MagicMock()+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)+ with patch("claude_agent_sdk.ClaudeSDKClient", mock_sdk):+ result = await handler._chat_async_streaming(+ "generate client", "run123", {"_callbackId": "cb1"}+ )+ assert result["type"] == "chat_response"+ assert "Here is the API client." in result["message"]+ assert handler.current_run_id == "run123"++ # Verify agent events were sent+ sent_types = [call[0][0].get("event_type") for call in mock_send.call_args_list if call[0][0].get("type") == "agent_event"]+ assert "text" in sent_types+ assert "tool_use" in sent_types+ assert "tool_result" in sent_types+ assert "done" in sent_typesdiff --git a/tests/test_opencode_engineer.py b/tests/test_opencode_engineer.pyindex 90b4770..7d5cb01 100644--- a/tests/test_opencode_engineer.py+++ b/tests/test_opencode_engineer.py@@ -1116,6 +1116,173 @@ class TestOpenCodeEngineerAnalyzeAndGenerate:assert result is None+ @pytest.mark.asyncio+ async def test_success_flow(self, tmp_path):+ """Full success flow: health check → session → event stream → result."""+ eng = self._make_engineer(tmp_path)++ health_response = MagicMock()+ health_response.status_code = 200+ health_response.json.return_value = {"status": "ok"}+ health_response.raise_for_status = MagicMock()++ session_response = MagicMock()+ session_response.json.return_value = {"id": "sess_abc"}+ session_response.raise_for_status = MagicMock()++ prompt_response = MagicMock()+ prompt_response.raise_for_status = MagicMock()++ messages_response = MagicMock()+ messages_response.status_code = 200+ messages_response.json.return_value = [+ {+ "info": {"role": "assistant", "providerID": "anthropic", "modelID": "claude-sonnet-4-5"},+ "parts": [{"type": "text", "text": "Here is the API client."}],+ }+ ]++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return health_response+ if "/message" in path:+ return messages_response+ return MagicMock()++ post_count = [0]++ async def mock_post(path, **kwargs):+ post_count[0] += 1+ if path == "/session":+ return session_response+ return prompt_response++ # Mock event stream that completes immediately+ mock_stream_resp = AsyncMock()++ async def mock_aiter_lines():+ yield 'data: {"type":"session.idle","properties":{"sessionID":"sess_abc"}}'++ mock_stream_resp.aiter_lines = mock_aiter_lines+ mock_stream_cm = AsyncMock()+ mock_stream_cm.__aenter__ = AsyncMock(return_value=mock_stream_resp)+ mock_stream_cm.__aexit__ = AsyncMock(return_value=False)++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post+ mock_client.stream = MagicMock(return_value=mock_stream_cm)++ with patch("reverse_api.opencode_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is not None+ assert "script_path" in result+ assert result["session_id"] == "sess_abc"++ @pytest.mark.asyncio+ async def test_health_401_custom_username(self, tmp_path):+ """401 with custom username shows username."""+ eng = self._make_engineer(tmp_path)+ eng.opencode_username = "custom_user"++ mock_response = MagicMock()+ mock_response.status_code = 401+ error = httpx.HTTPStatusError("401", request=MagicMock(), response=mock_response)++ mock_client = AsyncMock()+ mock_client.get = AsyncMock(side_effect=error)++ with patch("reverse_api.opencode_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is None++ @pytest.mark.asyncio+ async def test_http_non_401_error(self, tmp_path):+ """Non-401 HTTP error during session shows error details."""+ eng = self._make_engineer(tmp_path)++ health_response = MagicMock()+ health_response.status_code = 200+ health_response.json.return_value = {"status": "ok"}+ health_response.raise_for_status = MagicMock()++ mock_response = MagicMock()+ mock_response.status_code = 500+ mock_response.text = "Internal Server Error"+ session_error = httpx.HTTPStatusError("500", request=MagicMock(), response=mock_response)++ mock_client = AsyncMock()+ mock_client.get = AsyncMock(return_value=health_response)+ mock_client.post = AsyncMock(side_effect=session_error)++ with patch("reverse_api.opencode_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await eng.analyze_and_generate()+ assert result is None++ @pytest.mark.asyncio+ async def test_event_timeout(self, tmp_path):+ """Event stream timeout shows error."""+ eng = self._make_engineer(tmp_path)++ health_response = MagicMock()+ health_response.status_code = 200+ health_response.json.return_value = {"status": "ok"}+ health_response.raise_for_status = MagicMock()++ session_response = MagicMock()+ session_response.json.return_value = {"id": "sess_timeout"}+ session_response.raise_for_status = MagicMock()++ prompt_response = MagicMock()+ prompt_response.raise_for_status = MagicMock()++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return health_response+ return MagicMock(status_code=200, json=MagicMock(return_value=[]))++ async def mock_post(path, **kwargs):+ if path == "/session":+ return session_response+ return prompt_response++ # Mock event stream that never yields+ mock_stream_resp = AsyncMock()++ async def mock_aiter_lines():+ # Simulate hanging by not yielding idle+ await asyncio.sleep(100)+ yield "will never reach here"++ mock_stream_resp.aiter_lines = mock_aiter_lines+ mock_stream_cm = AsyncMock()+ mock_stream_cm.__aenter__ = AsyncMock(return_value=mock_stream_resp)+ mock_stream_cm.__aexit__ = AsyncMock(return_value=False)++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post+ mock_client.stream = MagicMock(return_value=mock_stream_cm)++ with patch("reverse_api.opencode_engineer.httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)+ # Patch timeout to be very short+ with patch("reverse_api.opencode_engineer.asyncio.wait_for", side_effect=TimeoutError()):+ result = await eng.analyze_and_generate()+ # Should still return None due to _last_error being set+ assert result is None++class TestRunOpenCodeEngineering:"""Test run_opencode_engineering dispatch function."""diff --git a/tests/test_utils.py b/tests/test_utils.pyindex 40ffdea..663a91b 100644--- a/tests/test_utils.py+++ b/tests/test_utils.py@@ -2,7 +2,7 @@import refrom pathlib import Path-from unittest.mock import MagicMock, patch+from unittest.mock import AsyncMock, MagicMock, patchimport pytest@@ -546,3 +546,350 @@ class TestGenerateFolderName:with patch("reverse_api.utils.asyncio.run", return_value="test_result") as mock_run:result = generate_folder_name("test prompt", sdk="opencode", session_id="sess123")assert result == "test_result"+++class TestGenerateFolderNameAsync:+ """Test _generate_folder_name_async function."""++ @pytest.mark.asyncio+ async def test_async_with_sdk_response(self):+ """Async function returns cleaned folder name from SDK."""+ from reverse_api.utils import _generate_folder_name_async+ from claude_agent_sdk import AssistantMessage, TextBlock++ mock_text = MagicMock(spec=TextBlock)+ mock_text.text = " Apple_Jobs_API "++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_text]++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant++ mock_client.receive_response = mock_receive++ with patch("claude_agent_sdk.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_async("Get Apple jobs API")+ assert result == "apple_jobs_api"++ @pytest.mark.asyncio+ async def test_async_empty_response_falls_back(self):+ """Async function falls back to slugify on empty response."""+ from reverse_api.utils import _generate_folder_name_async++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ return+ yield++ mock_client.receive_response = mock_receive++ with patch("claude_agent_sdk.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_async("test api capture")+ assert result == "test_api_capture"++ @pytest.mark.asyncio+ async def test_async_cleans_special_chars(self):+ """Async function cleans special characters from response."""+ from reverse_api.utils import _generate_folder_name_async+ from claude_agent_sdk import AssistantMessage, TextBlock++ mock_text = MagicMock(spec=TextBlock)+ mock_text.text = "my-cool/api (v2)"++ mock_assistant = MagicMock(spec=AssistantMessage)+ mock_assistant.content = [mock_text]++ mock_client = AsyncMock()+ mock_client.query = AsyncMock()++ async def mock_receive():+ yield mock_assistant++ mock_client.receive_response = mock_receive++ with patch("claude_agent_sdk.ClaudeSDKClient") as mock_sdk:+ mock_sdk.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_sdk.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_async("my cool api")+ assert result == "my_cool_api_v2"+++class TestGenerateFolderNameOpencodeAsync:+ """Test _generate_folder_name_opencode_async function."""++ @pytest.mark.asyncio+ async def test_health_check_fails(self):+ """Raises when OpenCode server not responding."""+ from reverse_api.utils import _generate_folder_name_opencode_async++ mock_client = AsyncMock()+ mock_client.get = AsyncMock(side_effect=ConnectionError("refused"))++ with patch("reverse_api.config.ConfigManager"):+ with patch("reverse_api.utils.get_config_path"):+ with patch("httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ with pytest.raises(Exception, match="not responding"):+ await _generate_folder_name_opencode_async("test prompt")++ @pytest.mark.asyncio+ async def test_creates_session_when_no_id(self):+ """Creates a new session when session_id is None."""+ from reverse_api.utils import _generate_folder_name_opencode_async++ mock_health = AsyncMock()+ mock_session_create = MagicMock()+ mock_session_create.raise_for_status = MagicMock()+ mock_session_create.json.return_value = {"id": "new_sess_123"}++ mock_message_post = AsyncMock()++ mock_messages_response = MagicMock()+ mock_messages_response.status_code = 200+ mock_messages_response.json.return_value = [+ {+ "info": {"role": "assistant"},+ "parts": [{"type": "text", "text": "apple_jobs_api"}],+ }+ ]++ call_idx = [0]++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return MagicMock()+ if "/message" in path:+ return mock_messages_response+ return MagicMock()++ async def mock_post(path, **kwargs):+ if path == "/session":+ return mock_session_create+ return MagicMock()++ # Mock the stream context manager+ mock_stream_response = AsyncMock()++ async def mock_aiter_lines():+ yield 'data: {"type":"session.idle","properties":{"sessionID":"new_sess_123"}}'++ mock_stream_response.aiter_lines = mock_aiter_lines++ mock_stream_cm = AsyncMock()+ mock_stream_cm.__aenter__ = AsyncMock(return_value=mock_stream_response)+ mock_stream_cm.__aexit__ = AsyncMock(return_value=False)++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post+ mock_client.stream = MagicMock(return_value=mock_stream_cm)+ mock_client.delete = AsyncMock()++ with patch("reverse_api.config.ConfigManager") as mock_cm:+ mock_cm.return_value.get.return_value = "anthropic"+ with patch("reverse_api.utils.get_config_path"):+ with patch("httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_opencode_async("Get Apple jobs")+ assert result == "apple_jobs_api"+ # Session should be cleaned up+ mock_client.delete.assert_called_once()++ @pytest.mark.asyncio+ async def test_reuses_existing_session(self):+ """Reuses session_id when provided."""+ from reverse_api.utils import _generate_folder_name_opencode_async++ mock_messages_response = MagicMock()+ mock_messages_response.status_code = 200+ mock_messages_response.json.return_value = [+ {+ "info": {"role": "assistant"},+ "parts": [{"type": "text", "text": "test_api"}],+ }+ ]++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return MagicMock()+ if "/message" in path:+ return mock_messages_response+ return MagicMock()++ async def mock_post(path, **kwargs):+ return MagicMock()++ mock_stream_response = AsyncMock()++ async def mock_aiter_lines():+ yield 'data: {"type":"session.idle","properties":{"sessionID":"existing_sess"}}'++ mock_stream_response.aiter_lines = mock_aiter_lines++ mock_stream_cm = AsyncMock()+ mock_stream_cm.__aenter__ = AsyncMock(return_value=mock_stream_response)+ mock_stream_cm.__aexit__ = AsyncMock(return_value=False)++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post+ mock_client.stream = MagicMock(return_value=mock_stream_cm)+ mock_client.delete = AsyncMock()++ with patch("reverse_api.config.ConfigManager") as mock_cm:+ mock_cm.return_value.get.return_value = "anthropic"+ with patch("reverse_api.utils.get_config_path"):+ with patch("httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_opencode_async("test", session_id="existing_sess")+ assert result == "test_api"+ # Should NOT delete session since we didn't create it+ mock_client.delete.assert_not_called()++ @pytest.mark.asyncio+ async def test_no_assistant_messages_returns_slugified(self):+ """Falls back to slugify when no assistant messages found."""+ from reverse_api.utils import _generate_folder_name_opencode_async++ mock_messages_response = MagicMock()+ mock_messages_response.status_code = 200+ mock_messages_response.json.return_value = [] # No messages++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return MagicMock()+ if "/message" in path:+ return mock_messages_response+ return MagicMock()++ async def mock_post(path, **kwargs):+ return MagicMock()++ mock_stream_response = AsyncMock()++ async def mock_aiter_lines():+ yield 'data: {"type":"session.idle","properties":{"sessionID":"sess1"}}'++ mock_stream_response.aiter_lines = mock_aiter_lines++ mock_stream_cm = AsyncMock()+ mock_stream_cm.__aenter__ = AsyncMock(return_value=mock_stream_response)+ mock_stream_cm.__aexit__ = AsyncMock(return_value=False)++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post+ mock_client.stream = MagicMock(return_value=mock_stream_cm)++ with patch("reverse_api.config.ConfigManager") as mock_cm:+ mock_cm.return_value.get.return_value = "anthropic"+ with patch("reverse_api.utils.get_config_path"):+ with patch("httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_opencode_async("test api", session_id="sess1")+ # Falls through to the final return+ assert result == "test_api"++ @pytest.mark.asyncio+ async def test_session_status_idle_event(self):+ """Handles session.status with idle type."""+ from reverse_api.utils import _generate_folder_name_opencode_async++ mock_messages_response = MagicMock()+ mock_messages_response.status_code = 200+ mock_messages_response.json.return_value = [+ {+ "info": {"role": "assistant"},+ "parts": [{"type": "text", "text": "data_api"}],+ }+ ]++ async def mock_get(path, **kwargs):+ if path == "/global/health":+ return MagicMock()+ if "/message" in path:+ return mock_messages_response+ return MagicMock()++ async def mock_post(path, **kwargs):+ return MagicMock()++ mock_stream_response = AsyncMock()++ async def mock_aiter_lines():+ yield 'data: {"type":"session.status","properties":{"sessionID":"sess1","status":{"type":"idle"}}}'++ mock_stream_response.aiter_lines = mock_aiter_lines++ mock_stream_cm = AsyncMock()+ mock_stream_cm.__aenter__ = AsyncMock(return_value=mock_stream_response)+ mock_stream_cm.__aexit__ = AsyncMock(return_value=False)++ mock_client = AsyncMock()+ mock_client.get = mock_get+ mock_client.post = mock_post+ mock_client.stream = MagicMock(return_value=mock_stream_cm)++ with patch("reverse_api.config.ConfigManager") as mock_cm:+ mock_cm.return_value.get.return_value = "anthropic"+ with patch("reverse_api.utils.get_config_path"):+ with patch("httpx.AsyncClient") as mock_async:+ mock_async.return_value.__aenter__ = AsyncMock(return_value=mock_client)+ mock_async.return_value.__aexit__ = AsyncMock(return_value=False)++ result = await _generate_folder_name_opencode_async("test", session_id="sess1")+ assert result == "data_api"+++class TestPathValidationExceptions:+ """Test path traversal validation exception handling."""++ def test_har_dir_resolve_oserror(self, tmp_path):+ """get_har_dir raises ValueError on OSError during resolve."""+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):+ with patch.object(Path, "resolve", side_effect=OSError("permission denied")):+ with pytest.raises(ValueError, match="Invalid path"):+ get_har_dir("valid_id")++ def test_scripts_dir_resolve_oserror(self, tmp_path):+ """get_scripts_dir raises ValueError on OSError during resolve."""+ from reverse_api.utils import get_scripts_dir+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):+ with patch.object(Path, "resolve", side_effect=OSError("permission denied")):+ with pytest.raises(ValueError, match="Invalid path"):+ get_scripts_dir("valid_id")++ def test_docs_dir_resolve_oserror(self, tmp_path):+ """get_docs_dir raises ValueError on OSError during resolve."""+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):+ with patch.object(Path, "resolve", side_effect=OSError("permission denied")):+ with pytest.raises(ValueError, match="Invalid path"):+ get_docs_dir("valid_id")++ def test_har_dir_resolve_runtime_error(self, tmp_path):+ """get_har_dir raises ValueError on RuntimeError during resolve."""+ with patch("reverse_api.utils.get_base_output_dir", return_value=tmp_path):+ with patch.object(Path, "resolve", side_effect=RuntimeError("symlink loop")):+ with pytest.raises(ValueError, match="Invalid path"):+ get_har_dir("valid_id")