package service import ( "context" "encoding/json" "net/http" "net/http/httptest" "testing" ) func TestAIClientDetectParsesResult(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { t.Errorf("method = %s, want POST", r.Method) } if r.URL.Path != "/detect" { t.Errorf("path = %s, want /detect", r.URL.Path) } if err := r.ParseMultipartForm(10 << 20); err != nil { t.Errorf("multipart 解析失败: %v", err) } if _, _, err := r.FormFile("file"); err != nil { t.Errorf("缺少 file 字段: %v", err) } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]any{ "model": "mock", "detections": []map[string]any{ {"bbox": map[string]float64{"x": 1, "y": 2, "w": 3, "h": 4}, "class": "sick", "confidence": 0.93}, }, }) })) defer srv.Close() client := NewAIClient(srv.URL) res, err := client.Detect(context.Background(), []byte("image-bytes"), "a.png") if err != nil { t.Fatalf("Detect 返回错误: %v", err) } if res.Model != "mock" { t.Errorf("model = %s, want mock", res.Model) } if len(res.Detections) != 1 { t.Fatalf("detections 数量 = %d, want 1", len(res.Detections)) } d := res.Detections[0] if d.ClassName != "sick" || d.Confidence != 0.93 || d.BBox.W != 3 { t.Errorf("解析结果不正确: %+v", d) } } func TestAIClientDetectServerError(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "boom", http.StatusInternalServerError) })) defer srv.Close() _, err := NewAIClient(srv.URL).Detect(context.Background(), []byte("x"), "a.png") if err == nil { t.Error("服务端 500 应返回错误") } } func TestAIClientDetectInvalidJSON(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("{bad")) })) defer srv.Close() _, err := NewAIClient(srv.URL).Detect(context.Background(), []byte("x"), "a.png") if err == nil { t.Error("非法 JSON 应返回错误") } }