Files
MyGolandRelease/internal/ai/llm_test.go
T
zerorigin f401c3de85 feat: 补全文档中文翻译(LLM,OpenAI 兼容接口)
补全列表底部的英文 godoc 翻译成中文:
- internal/ai: OpenAI 兼容最小客户端 + TranslateDoc(保留代码标识符)
- app 层 docTranslation: 内存+磁盘缓存、inflight 去重、失败哨兵防重复请求
- 自定义补全面板渲染(RenderCompletions 钩子),文档区异步换译文,
  不重送候选列表、不打断选择状态
- 设置新增「文档翻译」:开关 + 接口地址/API Key/模型 三件套,
  兼容 DeepSeek/GLM/Ollama/OpenAI 等,没配齐时静默关闭
2026-11-04 17:10:05 +08:00

109 lines
3.2 KiB
Go

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("缺模型不应可用")
}
}