package service import ( "context" "net/http" "net/http/httptest" "testing" ) func TestWeatherServiceConfigured(t *testing.T) { if NewWeatherService("", "").Configured() { t.Error("空配置应返回 false") } if !NewWeatherService("key", "101010100").Configured() { t.Error("有配置应返回 true") } } func TestWeatherFetchNow(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/v7/weather/now" { t.Errorf("path = %s", r.URL.Path) } if r.URL.Query().Get("key") != "key1" || r.URL.Query().Get("location") == "" { t.Errorf("参数不正确: %v", r.URL.Query()) } _, _ = w.Write([]byte(`{"code":"200","now":{"temp":"28","text":"小雨","humidity":"85"}}`)) })) defer srv.Close() s := NewWeatherService("key1", "116.41,39.92") s.baseURL = srv.URL now, err := s.FetchNow(context.Background()) if err != nil { t.Fatalf("FetchNow 错误: %v", err) } if now.Temp != 28 || now.Humidity != 85 || now.Text != "小雨" { t.Errorf("解析结果不正确: %+v", now) } } func TestWeatherFetchDaily(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"code":"200","daily":[{"fxDate":"2026-08-12","textDay":"小雨","textNight":"阴","tempMax":"30","tempMin":"24","humidity":"78"}]}`)) })) defer srv.Close() s := NewWeatherService("key1", "101010100") s.baseURL = srv.URL daily, err := s.FetchDaily(context.Background()) if err != nil { t.Fatalf("FetchDaily 错误: %v", err) } if len(daily) != 1 || daily[0].TextDay != "小雨" || daily[0].TempMax != 30 { t.Errorf("解析结果不正确: %+v", daily) } } func TestWeatherFetchErrorCode(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(`{"code":"401","message":"invalid key"}`)) })) defer srv.Close() s := NewWeatherService("bad", "101010100") s.baseURL = srv.URL if _, err := s.FetchNow(context.Background()); err == nil { t.Error("code!=200 应返回错误") } }