summaryrefslogtreecommitdiff
path: root/servers/hello_world/tests/test_handlers.py
blob: 0c0a45d6d63071d49614d6f640db6d3c994d8e8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import pytest
import asyncio
import sys
from unittest.mock import AsyncMock, MagicMock, patch
from pydantic import AnyUrl
import mcp.types as types
from mcp_server_hello_world.server import HelloWorldServer, create_server

class TestHandlers:
    """Test the MCP server handlers."""
    
    @pytest.mark.asyncio
    async def test_resource_handler(self):
        """Test the resource handler."""
        # Create a server
        mcp = create_server()
        
        # Get the resource URI
        uri = "hello://welcome"
        
        # Call the resource handler
        result = await mcp.read_resource(uri)
        
        # Verify the result
        assert len(result) == 1
        assert result[0].content == "Welcome to the Hello World MCP Server! This is a simple static resource."
    
    @pytest.mark.asyncio
    async def test_tool_handler(self):
        """Test the tool handler."""
        # Create a server
        mcp = create_server()
        
        # Call the tool handler
        result = await mcp.call_tool("hello", {"name": "Test User"})
        
        # Verify the result
        assert len(result) == 1
        assert result[0].text == "Hello, Test User! Welcome to the Hello World MCP Server."
        
        # Test with missing name argument
        with pytest.raises(Exception) as excinfo:
            await mcp.call_tool("hello", {})
        assert "Error executing tool hello" in str(excinfo.value)
        assert "Field required" in str(excinfo.value)
        
        # Test with unknown tool
        with pytest.raises(Exception) as excinfo:
            await mcp.call_tool("unknown", {})
        assert "Unknown tool: unknown" in str(excinfo.value)
    
    @pytest.mark.asyncio
    async def test_prompt_handler(self):
        """Test the prompt handler."""
        # Create a server
        mcp = create_server()
        
        # Call the prompt handler
        result = await mcp.get_prompt("greeting", {"name": "Test User"})
        
        # Verify the result
        assert len(result.messages) > 0
        assert result.messages[0].role == "user"
        assert result.messages[0].content.type == "text"
        assert "Hello there! You've chosen to use the greeting prompt with the name: Test User." in result.messages[0].content.text