package ai import ( "context" "encoding/json" "net/http" "net/http/httptest" "strings" "testing" ) // TestChatOK 用 httptest 模拟 OpenAI 兼容服务,验证请求装配与响应解析。 func TestChatOK(t *testing.T) { var gotPath, gotAuth, gotBody string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotPath = r.URL.Path gotAuth = r.Header.Get("Authorization") b := make([]byte, r.ContentLength) _, _ = r.Body.Read(b) gotBody = string(b) _ = json.NewEncoder(w).Encode(map[string]any{ "choices": []map[string]any{ {"message": map[string]string{"role": "assistant", "content": "操作数"}}, }, }) })) defer srv.Close() cfg := Config{BaseURL: srv.URL + "/v1", APIKey: "sk-test", Model: "test-chat"} out, err := Chat(context.Background(), cfg, "sys", "hello") if err != nil { t.Fatalf("Chat: %v", err) } if out != "操作数" { t.Fatalf("回复 = %q, want 操作数", out) } if gotPath != "/v1/chat/completions" { t.Fatalf("路径 = %q", gotPath) } if gotAuth != "Bearer sk-test" { t.Fatalf("鉴权头 = %q", gotAuth) } var req chatRequest if err := json.Unmarshal([]byte(gotBody), &req); err != nil { t.Fatalf("请求体解析: %v", err) } if req.Model != "test-chat" || req.Stream || len(req.Messages) != 2 { t.Fatalf("请求体不对: %+v", req) } if req.Messages[0].Role != "system" || req.Messages[1].Content != "hello" { t.Fatalf("消息不对: %+v", req.Messages) } } // TestChatAPIError 服务端返回 error 结构时应当透出它的消息。 func TestChatAPIError(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) _ = json.NewEncoder(w).Encode(map[string]any{ "error": map[string]string{"message": "Invalid API key"}, }) })) defer srv.Close() cfg := Config{BaseURL: srv.URL, APIKey: "bad", Model: "m"} _, err := Chat(context.Background(), cfg, "s", "u") if err == nil || !strings.Contains(err.Error(), "Invalid API key") { t.Fatalf("应透出服务端错误消息,实际: %v", err) } } // TestTranslateDocPrompt 确认翻译走的是 Chat 且带上了原文。 func TestTranslateDocPrompt(t *testing.T) { var userContent string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var req chatRequest _ = json.NewDecoder(r.Body).Decode(&req) if len(req.Messages) == 2 { userContent = req.Messages[1].Content } _ = json.NewEncoder(w).Encode(map[string]any{ "choices": []map[string]any{ {"message": map[string]string{"content": "译文"}}, }, }) })) defer srv.Close() cfg := Config{BaseURL: srv.URL, APIKey: "k", Model: "m"} out, err := TranslateDoc(context.Background(), cfg, "Append formats using...") if err != nil { t.Fatalf("TranslateDoc: %v", err) } if out != "译文" || userContent != "Append formats using..." { t.Fatalf("out=%q user=%q", out, userContent) } } // TestReady 配置不齐时应判为不可用。 func TestReady(t *testing.T) { full := Config{BaseURL: "x", APIKey: "y", Model: "z"} if !full.Ready() { t.Fatal("完整配置应可用") } if (Config{BaseURL: "x", APIKey: "y"}).Ready() { t.Fatal("缺模型不应可用") } }