package service import ( "strings" "testing" ) func TestParseAnalysisResponse(t *testing.T) { cases := []struct { name string in string wantRetry bool wantErr bool }{ {"纯JSON", `{"retryable": true, "reason": "限流"}`, true, false}, {"带json代码块", "```json\n{\"retryable\": false, \"reason\": \"参数错误\"}\n```", false, false}, {"带前后文字", `分析结果: {"retryable": true, "reason": "瞬时故障"} 完毕`, true, false}, {"非法响应", `抱歉,我无法分析`, false, true}, {"空串", ``, false, true}, } for _, c := range cases { retry, _, err := parseAnalysisResponse(c.in) if c.wantErr { if err == nil { t.Fatalf("[%s] 期望错误, got retry=%v", c.name, retry) } continue } if err != nil { t.Fatalf("[%s] 不应报错: %v", c.name, err) } if retry != c.wantRetry { t.Fatalf("[%s] retryable = %v, want %v", c.name, retry, c.wantRetry) } } } func TestParseAnalysisResponseReason(t *testing.T) { _, reason, err := parseAnalysisResponse(`{"retryable": true, "reason": "服务过载"}`) if err != nil { t.Fatalf("unexpected err: %v", err) } if reason != "服务过载" { t.Fatalf("reason = %q, want 服务过载", reason) } } func TestBuildAnalysisBody(t *testing.T) { body := buildAnalysisBody("doubao-lite", "429", "too many", strings.Repeat("x", 5000)) msg := body["messages"].([]map[string]string)[1] if len(msg["content"]) >= 2000+len("429")+len("too many")+100 { t.Fatalf("响应体应被截断到2000字符, got %d", len(msg["content"])) } if body["model"] != "doubao-lite" { t.Fatalf("model 字段错误") } if body["temperature"] != 0 { t.Fatalf("temperature 应为0") } } func TestTruncateStr(t *testing.T) { if truncateStr("abc", 5) != "abc" { t.Fatalf("短串不应截断") } if truncateStr("abcdef", 3) != "abc" { t.Fatalf("截断错误") } }