#!/usr/bin/env python3
"""
Tests for Chatlog MCP Server
"""
import pytest
import asyncio
from unittest.mock import Mock, patch
import json
from chatlog_mcp.server import server, handle_call_tool, handle_list_tools
class TestChatlogMCPServer:
"""Test cases for Chatlog MCP Server"""
@pytest.mark.asyncio
async def test_list_tools(self):
"""Test that tools are correctly listed"""
tools = await handle_list_tools()
assert len(tools) == 4
tool_names = [tool.name for tool in tools]
assert 'list_chatrooms' in tool_names
assert 'list_contacts' in tool_names
assert 'get_recent_sessions' in tool_names
assert 'get_chatlog' in tool_names
@pytest.mark.asyncio
async def test_call_list_chatrooms(self):
"""Test list_chatrooms tool"""
with patch('chatlog_mcp.server.call_api') as mock_call_api:
mock_call_api.return_value = '[]'
result = await handle_call_tool('list_chatrooms', {
'keyword': 'test',
'format': 'json'
})
assert len(result) == 1
assert result[0].type == 'text'
mock_call_api.assert_called_once_with('chatroom', {'keyword': 'test', 'format': 'json'})
@pytest.mark.asyncio
async def test_call_get_chatlog(self):
"""Test get_chatlog tool"""
with patch('chatlog_mcp.server.call_api') as mock_call_api:
mock_call_api.return_value = '[]'
result = await handle_call_tool('get_chatlog', {
'time': '2026-01-13',
'talker': 'test@chatroom',
'format': 'json'
})
assert len(result) == 1
assert result[0].type == 'text'
mock_call_api.assert_called_once_with('chatlog', {
'time': '2026-01-13',
'talker': 'test@chatroom',
'format': 'json'
})
@pytest.mark.asyncio
async def test_call_unknown_tool(self):
"""Test unknown tool handling"""
result = await handle_call_tool('unknown_tool', {})
assert len(result) == 1
assert result[0].type == 'text'
assert '未知工具' in result[0].text
@pytest.mark.asyncio
async def test_call_tool_with_error(self):
"""Test error handling"""
with patch('chatlog_mcp.server.call_api') as mock_call_api:
mock_call_api.side_effect = Exception('Test error')
result = await handle_call_tool('list_chatrooms', {})
assert len(result) == 1
assert result[0].type == 'text'
assert '错误' in result[0].text
if __name__ == '__main__':
pytest.main([__file__])