Files
2026-08-14 01:16:50 +08:00

103 lines
3.1 KiB
Go

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",
"modelVersion": "silk-yolo-2026.08.1",
"isMock": true,
"status": "abnormal",
"abnormalProbability": 0.93,
"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 res.ModelVersion != "silk-yolo-2026.08.1" {
t.Errorf("modelVersion = %s, want silk-yolo-2026.08.1", res.ModelVersion)
}
if !res.IsMock {
t.Error("isMock 应解析为 true")
}
if res.Status != "abnormal" || res.AbnormalProbability != 0.93 {
t.Errorf("AI 语义字段解析不正确: %+v", res)
}
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 TestAIDetectionStatus(t *testing.T) {
if got := AIDetectionStatus(nil); got != "unknown" {
t.Errorf("空检测应为 unknown,实际 %s", got)
}
if got := AIDetectionStatus([]AIDetection{{ClassName: "healthy"}}); got != "healthy" {
t.Errorf("全健康应为 healthy,实际 %s", got)
}
if got := AIDetectionStatus([]AIDetection{{ClassName: "unknown"}}); got != "unknown" {
t.Errorf("unknown 应为 unknown,实际 %s", got)
}
if got := AIDetectionStatus([]AIDetection{{ClassName: "sick"}}); got != "abnormal" {
t.Errorf("异常类别应为 abnormal,实际 %s", got)
}
}
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 应返回错误")
}
}