|
| 1 | +package handlers |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/mark3labs/mcp-go/mcp" |
| 9 | + "github.com/stretchr/testify/assert" |
| 10 | + "github.com/stretchr/testify/require" |
| 11 | + "go.uber.org/mock/gomock" |
| 12 | + |
| 13 | + "github.com/TuanKiri/weather-mcp-server/internal/server/services/mock" |
| 14 | +) |
| 15 | + |
| 16 | +func TestCurrentWeather(t *testing.T) { |
| 17 | + testCases := map[string]struct { |
| 18 | + arguments map[string]any |
| 19 | + errString string |
| 20 | + wait string |
| 21 | + setupWeatherService func(mocksWeather *mock.MockWeatherService) |
| 22 | + }{ |
| 23 | + "empty_city": { |
| 24 | + wait: "city must be a string", |
| 25 | + }, |
| 26 | + "city_not_found": { |
| 27 | + arguments: map[string]any{ |
| 28 | + "city": "Tokyo", |
| 29 | + }, |
| 30 | + errString: "weather API not available. Code: 400", |
| 31 | + setupWeatherService: func(mocksWeather *mock.MockWeatherService) { |
| 32 | + mocksWeather.EXPECT(). |
| 33 | + Current(context.Background(), "Tokyo"). |
| 34 | + Return("", errors.New("weather API not available. Code: 400")) |
| 35 | + }, |
| 36 | + }, |
| 37 | + "successful_request": { |
| 38 | + arguments: map[string]any{ |
| 39 | + "city": "London", |
| 40 | + }, |
| 41 | + wait: "<h1>London weather data</h1>", |
| 42 | + setupWeatherService: func(mocksWeather *mock.MockWeatherService) { |
| 43 | + mocksWeather.EXPECT(). |
| 44 | + Current(context.Background(), "London"). |
| 45 | + Return("<h1>London weather data</h1>", nil) |
| 46 | + }, |
| 47 | + }, |
| 48 | + } |
| 49 | + |
| 50 | + ctrl := gomock.NewController(t) |
| 51 | + defer ctrl.Finish() |
| 52 | + |
| 53 | + mocksWeather := mock.NewMockWeatherService(ctrl) |
| 54 | + |
| 55 | + svc := mock.NewMockServices(ctrl) |
| 56 | + svc.EXPECT().Weather().Return(mocksWeather).AnyTimes() |
| 57 | + |
| 58 | + handler := CurrentWeather(svc) |
| 59 | + |
| 60 | + for name, tc := range testCases { |
| 61 | + t.Run(name, func(t *testing.T) { |
| 62 | + if tc.setupWeatherService != nil { |
| 63 | + tc.setupWeatherService(mocksWeather) |
| 64 | + } |
| 65 | + |
| 66 | + var request mcp.CallToolRequest |
| 67 | + request.Params.Arguments = tc.arguments |
| 68 | + |
| 69 | + result, err := handler(context.Background(), request) |
| 70 | + if err != nil { |
| 71 | + assert.EqualError(t, err, tc.errString) |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + require.Len(t, result.Content, 1) |
| 76 | + content, ok := result.Content[0].(mcp.TextContent) |
| 77 | + require.True(t, ok) |
| 78 | + |
| 79 | + assert.Equal(t, tc.wait, content.Text) |
| 80 | + }) |
| 81 | + } |
| 82 | +} |
0 commit comments