"""工具异常处理测试."""
import pytest
from unittest.mock import Mock, MagicMock, patch
from src.tools import handle_tool_call
from src.config_manager import ConfigManager
class TestToolsExceptionHandling:
"""工具异常处理测试类."""
@pytest.fixture
def config_manager(self, temp_config_dir):
"""创建配置管理器."""
return ConfigManager(config_path=temp_config_dir / ".graphitiace" / "config.json")
@pytest.mark.asyncio
async def test_handle_tool_call_key_error(self, config_manager):
"""测试工具调用 KeyError 异常."""
# 模拟 KeyError(缺少必需参数)
result = await handle_tool_call(
tool_name="configure_neo4j",
arguments={
"uri": "bolt://localhost:7687"
# 缺少 username 和 password
},
config_manager=config_manager,
graphiti_client=None
)
assert result is not None
assert isinstance(result, list)
result_text = "".join([str(item.text) if hasattr(item, 'text') else str(item) for item in result])
assert "参数错误" in result_text or "参数" in result_text or "parameter" in result_text.lower() or "错误" in result_text
@pytest.mark.asyncio
async def test_handle_tool_call_value_error(self, config_manager):
"""测试工具调用 ValueError 异常."""
# 模拟 ValueError(参数值错误)
from src.graphiti_client import GraphitiClient
mock_client = Mock(spec=GraphitiClient)
mock_client.is_connected.return_value = True
mock_client.add_episode.side_effect = ValueError("Invalid value")
result = await handle_tool_call(
tool_name="add_episode",
arguments={"content": "test"},
config_manager=config_manager,
graphiti_client=mock_client
)
assert result is not None
assert isinstance(result, list)
result_text = "".join([str(item.text) if hasattr(item, 'text') else str(item) for item in result])
assert "参数值错误" in result_text or "参数" in result_text or "value" in result_text.lower() or "错误" in result_text
@pytest.mark.asyncio
async def test_handle_tool_call_general_exception(self, config_manager):
"""测试工具调用通用异常."""
from src.graphiti_client import GraphitiClient
mock_client = Mock(spec=GraphitiClient)
mock_client.is_connected.return_value = True
mock_client.add_episode.side_effect = Exception("General error")
result = await handle_tool_call(
tool_name="add_episode",
arguments={"content": "test"},
config_manager=config_manager,
graphiti_client=mock_client
)
assert result is not None
assert isinstance(result, list)
result_text = "".join([str(item.text) if hasattr(item, 'text') else str(item) for item in result])
assert "出错" in result_text or "错误" in result_text or "error" in result_text.lower()
# 验证包含提示信息
assert "提示" in result_text or "💡" in result_text or "tip" in result_text.lower() or "Neo4j" in result_text