|
| 1 | +package weatherapi |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "os" |
| 8 | + "path/filepath" |
| 9 | + "testing" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | + |
| 13 | + "github.com/TuanKiri/weather-mcp-server/pkg/weatherapi/models" |
| 14 | +) |
| 15 | + |
| 16 | +func TestCurrentWeather(t *testing.T) { |
| 17 | + testCases := map[string]struct { |
| 18 | + city string |
| 19 | + errString string |
| 20 | + wait *models.CurrentResponse |
| 21 | + }{ |
| 22 | + "success_request": { |
| 23 | + city: "London", |
| 24 | + wait: &models.CurrentResponse{ |
| 25 | + Location: models.Location{ |
| 26 | + Name: "London", |
| 27 | + Country: "United Kingdom", |
| 28 | + }, |
| 29 | + Current: models.Current{ |
| 30 | + TempC: 18.4, |
| 31 | + WindKph: 4, |
| 32 | + Humidity: 45, |
| 33 | + Condition: models.Condition{ |
| 34 | + Text: "Sunny", |
| 35 | + Icon: "//cdn.weatherapi.com/weather/64x64/day/113.png", |
| 36 | + }, |
| 37 | + }, |
| 38 | + }, |
| 39 | + }, |
| 40 | + "bad_request": { |
| 41 | + errString: "weather API not available. Code: 400", |
| 42 | + }, |
| 43 | + } |
| 44 | + |
| 45 | + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 46 | + q := r.URL.Query().Get("q") |
| 47 | + if q == "" { |
| 48 | + http.Error(w, "", http.StatusBadRequest) |
| 49 | + return |
| 50 | + } |
| 51 | + |
| 52 | + path := filepath.Join("mock", "current.json") |
| 53 | + |
| 54 | + data, err := os.ReadFile(path) |
| 55 | + if err != nil { |
| 56 | + http.Error(w, "", http.StatusInternalServerError) |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + w.Header().Set("Content-Type", "application/json") |
| 61 | + w.Write(data) |
| 62 | + })) |
| 63 | + defer server.Close() |
| 64 | + |
| 65 | + weatherAPI := &WeatherAPI{ |
| 66 | + key: "test-key", |
| 67 | + baseURL: server.URL, |
| 68 | + client: server.Client(), |
| 69 | + } |
| 70 | + |
| 71 | + for name, tc := range testCases { |
| 72 | + t.Run(name, func(t *testing.T) { |
| 73 | + result, err := weatherAPI.Current(context.Background(), tc.city) |
| 74 | + if err != nil { |
| 75 | + assert.EqualError(t, err, tc.errString) |
| 76 | + } |
| 77 | + |
| 78 | + assert.Equal(t, tc.wait, result) |
| 79 | + }) |
| 80 | + } |
| 81 | +} |
0 commit comments