package tool import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "strings" "testing" "time" "example.com/ueino/pkg/model" ) func TestForecastDates(t *testing.T) { // UTC 尚未跨年,北京时间已是下一年的第一天。 now := time.Date(2026, 12, 31, 16, 30, 0, 0, time.UTC) for _, tt := range []struct { name, start, end, wantEnd string invalid bool }{ {name: "默认今天", wantEnd: "2027-01-01"}, {name: "单日", start: "2027-01-02", wantEnd: "2027-01-02"}, {name: "整个窗口", start: "2027-01-01", end: "2027-01-16", wantEnd: "2027-01-16"}, {name: "缺少开始日期", end: "2027-01-02", invalid: true}, {name: "相对日期", start: "明天", invalid: true}, {name: "无效日期", start: "2027-02-30", invalid: true}, {name: "无效结束", start: "2027-01-02", end: "周末", invalid: true}, {name: "过去日期", start: "2026-12-31", invalid: true}, {name: "超出窗口", start: "2027-01-16", end: "2027-01-17", invalid: true}, {name: "反向范围", start: "2027-01-02", end: "2027-01-01", invalid: true}, } { t.Run(tt.name, func(t *testing.T) { start, end, err := forecastDates(model.WeatherArguments{StartDate: tt.start, EndDate: tt.end}, now) if tt.invalid { if err == nil { t.Fatal("预期参数错误") } return } wantStart := tt.start if wantStart == "" { wantStart = "2027-01-01" } if err != nil || start.Format(time.DateOnly) != wantStart || end.Format(time.DateOnly) != tt.wantEnd { t.Fatalf("日期范围 = %s 至 %s,错误 = %v", start, end, err) } }) } } func TestWeatherForecast(t *testing.T) { today := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)) for _, days := range []int{1, 2} { t.Run(fmt.Sprintf("%d天", days), func(t *testing.T) { start := today.AddDate(0, 0, 1).Format(time.DateOnly) end := today.AddDate(0, 0, days).Format(time.DateOnly) calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ if r.Method != http.MethodGet { t.Error("应使用 GET") } query := r.URL.Query() if r.URL.Path == "/search" { if query.Get("name") != "北京 海淀/?&" || query.Get("count") != "1" || query.Get("language") != "zh" { t.Errorf("地点查询编码错误: %v", query) } fmt.Fprint(w, `{"results":[{"name":"北京","admin1":"北京市","country":"中国","latitude":39.9,"longitude":116.4}]}`) return } if r.URL.Path != "/forecast" || query.Get("latitude") != "39.9" || query.Get("longitude") != "116.4" || query.Get("start_date") != start || query.Get("end_date") != end || query.Get("timezone") != "Asia/Shanghai" || query.Get("daily") != "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max" { t.Errorf("预报请求错误: %s", r.URL) } // 返回乱序日期及额外日期,必须按请求范围提取排序。 json.NewEncoder(w).Encode(map[string]any{"daily": map[string]any{ "time": []string{today.AddDate(0, 0, 2).Format(time.DateOnly), start, today.Format(time.DateOnly)}, "weather_code": []int{61, 0, 3}, "temperature_2m_max": []float64{12, 18, 15}, "temperature_2m_min": []float64{3, 8, 6}, "precipitation_probability_max": []float64{80, 0, 30}, }}) })) defer server.Close() weather := NewWeather() weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast" args := model.WeatherArguments{Location: " 北京 海淀/?& ", StartDate: start} if days == 2 { args.EndDate = end } arguments, _ := json.Marshal(args) result, err := weather.Execute(context.Background(), string(arguments)) 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 || forecast.Location != "北京 北京市 中国" || forecast.Timezone != "Asia/Shanghai" || len(forecast.Days) != days { t.Fatalf("预报结果 = %+v,调用次数 = %d", forecast, calls) } first := forecast.Days[0] if first.Date != start || first.Condition != "晴" || first.MinTemperatureC != 8 || first.MaxTemperatureC != 18 || first.PrecipitationChancePct != 0 { t.Fatalf("单日数据错误: %+v", first) } if days == 2 && (forecast.Days[1].Date != end || forecast.Days[1].Condition != "小雨") { t.Fatalf("日期顺序错误: %+v", forecast.Days) } }) } } func TestForecastInvalidArguments(t *testing.T) { calls := 0 server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { calls++ })) defer server.Close() weather := NewWeather() weather.geocodingURL = server.URL for _, args := range []string{ `{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`, `{"location":"北京","end_date":"2026-11-20"}`, `{"location":"北京","start_date":"明天"}`, `{"location":"北京","start_date":"2000-01-01"}`, `{"location":"北京","start_date":"2999-01-01"}`, `{"start_date":"2026-11-19"}`, `{"location":"北京","start_date":123}`, } { if _, err := weather.Execute(context.Background(), args); err == nil { t.Errorf("参数 %s 应返回错误", args) } } if calls != 0 { t.Fatalf("无效参数请求了接口 %d 次", calls) } } func TestForecastResponseErrors(t *testing.T) { date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly) for _, mode := range []string{"查无城市", "搜索失败", "预报失败", "错误JSON", "缺少日期", "缺少字段", "字段为空"} { t.Run(mode, func(t *testing.T) { calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ if r.URL.Path == "/search" { switch mode { case "查无城市": fmt.Fprint(w, `{}`) case "搜索失败": w.WriteHeader(http.StatusServiceUnavailable) case "错误JSON": fmt.Fprint(w, "{") default: fmt.Fprint(w, `{"results":[{"name":"北京","latitude":39.9,"longitude":116.4}]}`) } return } if mode == "预报失败" { w.WriteHeader(http.StatusServiceUnavailable) return } daily := map[string]any{ "time": []string{date}, "weather_code": []int{0}, "temperature_2m_max": []float64{18}, "temperature_2m_min": []float64{8}, "precipitation_probability_max": []float64{0}, } switch mode { case "缺少日期": daily["time"] = []string{} case "缺少字段": delete(daily, "temperature_2m_min") case "字段为空": daily["weather_code"] = []any{nil} } json.NewEncoder(w).Encode(map[string]any{"daily": daily}) })) defer server.Close() weather := NewWeather() weather.geocodingURL, weather.forecastURL = server.URL+"/search", server.URL+"/forecast" args := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date) if _, err := weather.Execute(context.Background(), args); err == nil { t.Fatal("接口异常应返回错误") } if (mode == "查无城市" || mode == "搜索失败" || mode == "错误JSON") && calls != 1 { t.Fatal("城市查询失败后不应请求预报") } }) } } func TestForecastCancellationAndTimeout(t *testing.T) { date := time.Now().In(time.FixedZone("Asia/Shanghai", 8*60*60)).Format(time.DateOnly) arguments := fmt.Sprintf(`{"location":"北京","start_date":%q}`, date) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) defer server.Close() weather := NewWeather() weather.geocodingURL = server.URL ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := weather.Execute(ctx, arguments); !errors.Is(err, context.Canceled) { t.Fatalf("取消错误 = %v", err) } weather.client.Timeout = 20 * time.Millisecond if _, err := weather.Execute(context.Background(), arguments); err == nil || !strings.Contains(err.Error(), "Client.Timeout") { t.Fatalf("超时错误 = %v", err) } }