package tool import ( "context" "encoding/json" "fmt" "net/http" "net/http/httptest" "testing" "time" "example.com/ueino/pkg/model" ) func TestWeatherDefaultsToToday(t *testing.T) { today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly) calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ if r.URL.Path == "/search" { if r.URL.Query().Get("name") != "北京" { t.Errorf("地点参数错误: %s", r.URL) } fmt.Fprint(w, `{"results":[{"name":"北京","country":"中国","latitude":39.9,"longitude":116.4}]}`) return } if r.URL.Path != "/forecast" || r.URL.Query().Get("start_date") != today || r.URL.Query().Get("end_date") != today { t.Errorf("未指定日期时应查询北京时间今天: %s", r.URL) } json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{ "time": []string{today}, "weather_code": []int{0}, "temperature_2m_min": []int{10}, "temperature_2m_max": []int{20}, "precipitation_probability_max": []int{0}, }}) })) defer server.Close() weather := NewWeather() weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast" result, err := weather.Execute(context.Background(), `{"location":" 北京 "}`) if err != nil { t.Fatal(err) } var forecast model.WeatherForecast if err := json.Unmarshal([]byte(result), &forecast); err != nil { t.Fatal(err) } if calls != 2 || len(forecast.Days) != 1 || forecast.Days[0].Date != today || forecast.Days[0].Condition != "晴" { t.Fatalf("默认查询结果不正确: %+v,请求次数=%d", forecast, calls) } }