package tool import ( "context" "errors" "fmt" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" ) func TestWeatherExecute(t *testing.T) { location := "北京 海淀/?&" calls := 0 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ if r.Method != http.MethodGet || r.URL.EscapedPath() != "/"+url.PathEscape(location) { t.Errorf("地点编码不正确: %s", r.URL) } query := r.URL.Query() if query.Get("format") != "3" || query.Get("lang") != "zh" || !query.Has("m") { t.Errorf("查询参数不正确: %v", query) } fmt.Fprint(w, "北京: 晴 +20°C\n") })) defer server.Close() weather := NewWeather() weather.baseURL = server.URL got, err := weather.Execute(context.Background(), `{"location":" 北京 海淀/?& "}`) if err != nil || got != "北京: 晴 +20°C" { t.Fatalf("天气 = %q,错误 = %v", got, err) } for _, arguments := range []string{`{`, `{}`, `null`, `{"location":" "}`, `{"location":123}`} { if _, err := weather.Execute(context.Background(), arguments); err == nil { t.Fatalf("参数 %s 应报错", arguments) } } if calls != 1 { t.Fatalf("无效参数不应请求接口,实际请求 %d 次", calls) } definition := weather.Definition() if definition.Type != "function" || definition.Function.Name != "get_weather" { t.Fatalf("工具定义不正确: %+v", definition) } } func TestWeatherResponseErrors(t *testing.T) { for _, tt := range []struct { name string status int body string }{ {name: "接口错误", status: 503, body: "unavailable"}, {name: "空结果", status: 200, body: " \n"}, } { t.Run(tt.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(tt.status); fmt.Fprint(w, tt.body) })) defer server.Close() weather := NewWeather() weather.baseURL = server.URL if _, err := weather.Execute(context.Background(), `{"location":"北京"}`); err == nil { t.Fatal("期望返回错误") } }) } } func TestWeatherCancellationAndTimeout(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { <-r.Context().Done() })) defer server.Close() weather := NewWeather() weather.baseURL = server.URL ctx, cancel := context.WithCancel(context.Background()) cancel() if _, err := weather.Execute(ctx, `{"location":"北京"}`); !errors.Is(err, context.Canceled) { t.Fatalf("取消错误 = %v", err) } weather.client.Timeout = 50 * time.Millisecond if _, err := weather.Execute(context.Background(), `{"location":"北京"}`); err == nil || !strings.Contains(err.Error(), "Client.Timeout") { t.Fatalf("超时错误 = %v", err) } }