api_test.go.backup 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868
  1. package tests
  2. import (
  3. "bufio"
  4. "bytes"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "image"
  9. "image/color"
  10. "image/draw"
  11. "image/jpeg"
  12. "io"
  13. "net"
  14. "net/http"
  15. "net/url"
  16. "os"
  17. "strings"
  18. "testing"
  19. "time"
  20. )
  21. // Qwen3ChatRequest 定义Qwen3聊天请求结构
  22. type Qwen3ChatRequest struct {
  23. Model string `json:"model"`
  24. Messages []ChatMessage `json:"messages"`
  25. Stream bool `json:"stream"`
  26. Temperature float64 `json:"temperature,omitempty"`
  27. }
  28. // ChatMessage 定义聊天消息结构
  29. type ChatMessage struct {
  30. Role string `json:"role"`
  31. Content string `json:"content"`
  32. }
  33. // Qwen3ChatResponse 定义Qwen3聊天响应结构(非流式)
  34. type Qwen3ChatResponse struct {
  35. ID string `json:"id"`
  36. Object string `json:"object"`
  37. Created int64 `json:"created"`
  38. Model string `json:"model"`
  39. Choices []struct {
  40. Index int `json:"index"`
  41. Message struct {
  42. Role string `json:"role"`
  43. Content string `json:"content"`
  44. Refusal *string `json:"refusal"`
  45. Annotations *string `json:"annotations"`
  46. Audio *string `json:"audio"`
  47. FunctionCall *string `json:"function_call"`
  48. ToolCalls []interface{} `json:"tool_calls"`
  49. ReasoningContent *string `json:"reasoning_content"`
  50. } `json:"message"`
  51. Logprobs *string `json:"logprobs"`
  52. FinishReason string `json:"finish_reason"`
  53. StopReason *string `json:"stop_reason"`
  54. } `json:"choices"`
  55. ServiceTier *string `json:"service_tier"`
  56. SystemFingerprint *string `json:"system_fingerprint"`
  57. Usage struct {
  58. PromptTokens int `json:"prompt_tokens"`
  59. TotalTokens int `json:"total_tokens"`
  60. CompletionTokens int `json:"completion_tokens"`
  61. PromptTokensDetails *string `json:"prompt_tokens_details"`
  62. } `json:"usage"`
  63. PromptLogprobs *string `json:"prompt_logprobs"`
  64. KvTransferParams *string `json:"kv_transfer_params"`
  65. }
  66. // Qwen3StreamResponse 定义Qwen3流式响应结构
  67. type Qwen3StreamResponse struct {
  68. ID string `json:"id"`
  69. Object string `json:"object"`
  70. Created int64 `json:"created"`
  71. Model string `json:"model"`
  72. SystemFingerprint string `json:"system_fingerprint,omitempty"`
  73. Choices []struct {
  74. Index int `json:"index"`
  75. Delta struct {
  76. Role string `json:"role,omitempty"`
  77. Content string `json:"content,omitempty"`
  78. ToolCalls []struct {
  79. Index int `json:"index"`
  80. ID string `json:"id"`
  81. Type string `json:"type"`
  82. Function struct {
  83. Name string `json:"name"`
  84. Arguments string `json:"arguments"`
  85. } `json:"function"`
  86. } `json:"tool_calls,omitempty"`
  87. } `json:"delta"`
  88. Logprobs interface{} `json:"logprobs"`
  89. FinishReason *string `json:"finish_reason"`
  90. StopReason *string `json:"stop_reason,omitempty"`
  91. } `json:"choices"`
  92. }
  93. // TestQwen3ChatAPI 测试Qwen3聊天接口
  94. func TestQwen3ChatAPI(t *testing.T) {
  95. // 加载测试配置
  96. config := LoadConfig()
  97. baseURL := config.Qwen3BaseURL
  98. model := config.Qwen3Model
  99. testCases := []struct {
  100. name string
  101. message string
  102. }{
  103. {
  104. name: "基础问候测试",
  105. message: "你好,请介绍一下你自己。",
  106. },
  107. {
  108. name: "技术问题测试",
  109. message: "请解释一下什么是编程?",
  110. },
  111. }
  112. for _, tc := range testCases {
  113. t.Run(tc.name, func(t *testing.T) {
  114. // 构建非流式请求
  115. request := Qwen3ChatRequest{
  116. Model: model,
  117. Stream: false,
  118. Messages: []ChatMessage{
  119. {
  120. Role: "system",
  121. Content: "你是一个乐于助人的助手。",
  122. },
  123. {
  124. Role: "user",
  125. Content: tc.message,
  126. },
  127. },
  128. }
  129. jsonData, err := json.Marshal(request)
  130. if err != nil {
  131. t.Fatalf("序列化请求失败: %v", err)
  132. }
  133. t.Logf("发送的请求: %s", string(jsonData))
  134. // 发送POST请求
  135. resp, err := http.Post(
  136. fmt.Sprintf("%s/v1/chat/completions", baseURL),
  137. "application/json",
  138. bytes.NewBuffer(jsonData),
  139. )
  140. if err != nil {
  141. t.Fatalf("发送请求失败: %v", err)
  142. }
  143. defer resp.Body.Close()
  144. t.Logf("响应状态码: %d", resp.StatusCode)
  145. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  146. if resp.StatusCode != http.StatusOK {
  147. body, _ := io.ReadAll(resp.Body)
  148. t.Fatalf("请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(body))
  149. }
  150. // 读取完整的响应内容
  151. body, err := io.ReadAll(resp.Body)
  152. if err != nil {
  153. t.Fatalf("读取响应失败: %v", err)
  154. }
  155. t.Logf("响应长度: %d", len(body))
  156. // 解析JSON响应
  157. var response Qwen3ChatResponse
  158. if err := json.Unmarshal(body, &response); err != nil {
  159. t.Fatalf("解析JSON响应失败: %v", err)
  160. }
  161. // 验证响应
  162. if response.ID == "" {
  163. t.Error("响应ID为空")
  164. }
  165. if len(response.Choices) == 0 {
  166. t.Error("响应中没有选择项")
  167. }
  168. t.Logf("✅ 非流式响应成功!")
  169. t.Logf("请求: %s", tc.message)
  170. t.Logf("响应ID: %s", response.ID)
  171. t.Logf("模型: %s", response.Model)
  172. t.Logf("完整响应: %s", response.Choices[0].Message.Content)
  173. })
  174. }
  175. }
  176. // TestQwen3StreamAPI 测试Qwen3流式聊天接口
  177. func TestQwen3StreamAPI(t *testing.T) {
  178. // 加载测试配置
  179. config := LoadConfig()
  180. baseURL := config.Qwen3BaseURL
  181. model := config.Qwen3Model
  182. testCases := []struct {
  183. name string
  184. message string
  185. }{
  186. {
  187. name: "流式基础问候测试",
  188. message: "你好,请介绍一下你自己。",
  189. },
  190. {
  191. name: "流式技术问题测试",
  192. message: "请解释一下什么是编程?",
  193. },
  194. }
  195. for _, tc := range testCases {
  196. t.Run(tc.name, func(t *testing.T) {
  197. // 构建流式请求
  198. request := Qwen3ChatRequest{
  199. Model: model,
  200. Stream: false,
  201. Temperature: 0.7,
  202. Messages: []ChatMessage{
  203. {
  204. Role: "system",
  205. Content: "你是一个乐于助人的助手。",
  206. },
  207. {
  208. Role: "user",
  209. Content: tc.message,
  210. },
  211. },
  212. }
  213. jsonData, err := json.Marshal(request)
  214. if err != nil {
  215. t.Fatalf("序列化请求失败: %v", err)
  216. }
  217. // 发送POST请求
  218. resp, err := http.Post(
  219. fmt.Sprintf("%s/v1/chat/completions", baseURL),
  220. "application/json",
  221. bytes.NewBuffer(jsonData),
  222. )
  223. if err != nil {
  224. t.Fatalf("发送请求失败: %v", err)
  225. }
  226. defer resp.Body.Close()
  227. t.Logf("响应状态码: %d", resp.StatusCode)
  228. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  229. if resp.StatusCode != http.StatusOK {
  230. body, _ := io.ReadAll(resp.Body)
  231. t.Fatalf("请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(body))
  232. }
  233. t.Logf("响应长度: %d", resp.ContentLength)
  234. if request.Stream {
  235. // 处理流式响应
  236. scanner := bufio.NewScanner(resp.Body)
  237. var fullContent strings.Builder
  238. var responseID string
  239. var firstChunk = true
  240. t.Logf("开始接收流式响应...")
  241. chunkCount := 0
  242. for scanner.Scan() {
  243. line := scanner.Text()
  244. chunkCount++
  245. // 跳过空行和data:前缀
  246. if line == "" || !strings.HasPrefix(line, "data: ") {
  247. continue
  248. }
  249. // 移除"data: "前缀
  250. data := strings.TrimPrefix(line, "data: ")
  251. // 检查是否是结束标记
  252. if data == "[DONE]" {
  253. t.Logf("收到结束标记")
  254. break
  255. }
  256. // 解析JSON数据
  257. var streamResp Qwen3StreamResponse
  258. if err := json.Unmarshal([]byte(data), &streamResp); err != nil {
  259. t.Logf("解析流式响应失败: %v, 数据: %s", err, data)
  260. continue
  261. }
  262. // 记录第一个块的ID
  263. if firstChunk {
  264. responseID = streamResp.ID
  265. t.Logf("响应ID: %s", responseID)
  266. t.Logf("模型: %s", streamResp.Model)
  267. firstChunk = false
  268. }
  269. // 处理choices中的内容
  270. if len(streamResp.Choices) > 0 {
  271. choice := streamResp.Choices[0]
  272. if choice.Delta.Content != "" {
  273. fullContent.WriteString(choice.Delta.Content)
  274. t.Logf("收到内容块: %s", choice.Delta.Content)
  275. }
  276. // 检查是否完成
  277. if choice.FinishReason != nil {
  278. t.Logf("完成原因: %s", *choice.FinishReason)
  279. break
  280. }
  281. }
  282. }
  283. if err := scanner.Err(); err != nil {
  284. t.Fatalf("读取流式响应失败: %v", err)
  285. }
  286. // 验证结果
  287. finalContent := fullContent.String()
  288. if finalContent == "" {
  289. t.Error("流式响应内容为空")
  290. } else {
  291. t.Logf("✅ 流式响应成功!")
  292. t.Logf("请求: %s", tc.message)
  293. t.Logf("响应ID: %s", responseID)
  294. t.Logf("总块数: %d", chunkCount)
  295. t.Logf("完整响应: %s", finalContent)
  296. }
  297. } else {
  298. // 处理非流式响应
  299. body, err := io.ReadAll(resp.Body)
  300. if err != nil {
  301. t.Fatalf("读取响应失败: %v", err)
  302. }
  303. t.Logf("开始解析非流式响应...")
  304. // 解析JSON响应
  305. var response Qwen3ChatResponse
  306. if err := json.Unmarshal(body, &response); err != nil {
  307. t.Fatalf("解析JSON响应失败: %v", err)
  308. }
  309. // 验证响应
  310. if response.ID == "" {
  311. t.Error("响应ID为空")
  312. }
  313. if len(response.Choices) == 0 {
  314. t.Error("响应中没有选择项")
  315. }
  316. t.Logf("✅ 非流式响应成功!")
  317. t.Logf("请求: %s", tc.message)
  318. t.Logf("响应ID: %s", response.ID)
  319. t.Logf("模型: %s", response.Model)
  320. t.Logf("完整响应: %s", response.Choices[0].Message.Content)
  321. }
  322. })
  323. }
  324. }
  325. // TestYOLOPredictAPI 测试YOLO图像识别接口
  326. func TestYOLOPredictAPI(t *testing.T) {
  327. // 加载测试配置
  328. config := LoadConfig()
  329. baseURL := config.YOLOBaseURL
  330. testCase := struct {
  331. modeltype string
  332. image string
  333. conf_threshold float32
  334. }{
  335. modeltype: "gas_station",
  336. image: "test_images/1.jpg",
  337. conf_threshold: 0.5,
  338. }
  339. // 使用单个测试用例,不需要循环
  340. tc := testCase
  341. // 检查图像文件是否存在
  342. if _, err := os.Stat(tc.image); os.IsNotExist(err) {
  343. t.Skipf("测试图像文件不存在: %s", tc.image)
  344. }
  345. // 读取图像文件并转换为base64
  346. imageData, err := os.ReadFile(tc.image)
  347. if err != nil {
  348. t.Fatalf("读取图像文件失败: %v", err)
  349. }
  350. // 解码图像用于后续处理
  351. img, _, err := image.Decode(bytes.NewReader(imageData))
  352. if err != nil {
  353. t.Fatalf("解码图像失败: %v", err)
  354. }
  355. // 将图像数据转换为base64
  356. imageBase64 := base64.StdEncoding.EncodeToString(imageData)
  357. // 构建JSON请求体
  358. requestBody := map[string]interface{}{
  359. "modeltype": tc.modeltype,
  360. "image": imageBase64,
  361. "conf_threshold": tc.conf_threshold,
  362. }
  363. jsonData, err := json.Marshal(requestBody)
  364. if err != nil {
  365. t.Fatalf("序列化请求体失败: %v", err)
  366. }
  367. resp, err := http.Post(
  368. fmt.Sprintf("%s/predict", baseURL),
  369. "application/json",
  370. bytes.NewBuffer(jsonData),
  371. )
  372. if err != nil {
  373. t.Fatalf("发送请求失败: %v", err)
  374. }
  375. defer resp.Body.Close()
  376. body, err := io.ReadAll(resp.Body)
  377. if err != nil {
  378. t.Fatalf("读取响应失败: %v", err)
  379. }
  380. if resp.StatusCode != http.StatusOK {
  381. t.Errorf("请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(body))
  382. }
  383. if len(body) == 0 {
  384. t.Error("响应内容为空")
  385. }
  386. t.Logf("响应状态码: %d", resp.StatusCode)
  387. t.Logf("响应内容: %s", string(body))
  388. // 解析YOLO响应
  389. var yoloResp YOLOResponse
  390. if err := json.Unmarshal(body, &yoloResp); err != nil {
  391. t.Fatalf("解析YOLO响应失败: %v", err)
  392. }
  393. t.Logf("解析成功: 检测到 %d 个对象", len(yoloResp.Labels))
  394. t.Logf("开始绘制边界框...")
  395. // 在原始图像上绘制边界框
  396. annotatedImg := drawBoundingBox(img, yoloResp.Boxes, yoloResp.Labels, yoloResp.Scores)
  397. t.Logf("边界框绘制完成")
  398. t.Logf("开始保存图像...")
  399. // 保存标注后的图像
  400. outputPath := "test_images/annotated_1.jpg"
  401. outputFile, err := os.Create(outputPath)
  402. if err != nil {
  403. t.Fatalf("创建输出文件失败: %v", err)
  404. }
  405. defer outputFile.Close()
  406. if err := jpeg.Encode(outputFile, annotatedImg, &jpeg.Options{Quality: 95}); err != nil {
  407. t.Fatalf("保存图像失败: %v", err)
  408. }
  409. t.Logf("✅ 已保存标注后的图像到: %s", outputPath)
  410. t.Logf("识别结果: 检测到 %d 个对象", len(yoloResp.Labels))
  411. for i, label := range yoloResp.Labels {
  412. if i < len(yoloResp.Scores) {
  413. t.Logf(" - %s: 置信度 %.2f%%", label, yoloResp.Scores[i]*100)
  414. }
  415. }
  416. // 强制输出日志
  417. t.Logf("测试完成,图像已保存")
  418. }
  419. // TestAPIEndpoints 测试API端点连通性
  420. func TestAPIEndpoints(t *testing.T) {
  421. // 加载测试配置
  422. config := LoadConfig()
  423. endpoints := []struct {
  424. name string
  425. url string
  426. }{
  427. {"Qwen3聊天接口", config.GetQwen3ChatURL()},
  428. {"YOLO预测接口", config.GetYOLOPredictURL()},
  429. {"TTS流式接口", config.GetTTSStreamURL()},
  430. }
  431. for _, endpoint := range endpoints {
  432. t.Run(endpoint.name, func(t *testing.T) {
  433. client := &http.Client{
  434. Timeout: 10 * time.Second,
  435. }
  436. resp, err := client.Head(endpoint.url)
  437. if err != nil {
  438. t.Logf("端点 %s 不可达: %v", endpoint.name, err)
  439. return
  440. }
  441. defer resp.Body.Close()
  442. t.Logf("端点 %s 可达,状态码: %d", endpoint.name, resp.StatusCode)
  443. })
  444. }
  445. }
  446. // BenchmarkQwen3ChatAPI 性能测试Qwen3聊天接口
  447. func BenchmarkQwen3ChatAPI(b *testing.B) {
  448. // 加载测试配置
  449. config := LoadConfig()
  450. baseURL := config.Qwen3BaseURL
  451. model := config.Qwen3Model
  452. request := Qwen3ChatRequest{
  453. Model: model,
  454. Messages: []ChatMessage{
  455. {
  456. Role: "user",
  457. Content: "你好",
  458. },
  459. },
  460. }
  461. jsonData, _ := json.Marshal(request)
  462. b.ResetTimer()
  463. for i := 0; i < b.N; i++ {
  464. resp, err := http.Post(
  465. fmt.Sprintf("%s/v1/chat/completions", baseURL),
  466. "application/json",
  467. bytes.NewBuffer(jsonData),
  468. )
  469. if err != nil {
  470. b.Fatalf("请求失败: %v", err)
  471. }
  472. resp.Body.Close()
  473. }
  474. }
  475. // YOLOResponse 定义YOLO响应结构
  476. type YOLOResponse struct {
  477. Boxes [][]float64 `json:"boxes"`
  478. Labels []string `json:"labels"`
  479. Scores []float64 `json:"scores"`
  480. ModelType string `json:"model_type"`
  481. }
  482. // drawBoundingBox 在图像上绘制边界框和标签
  483. func drawBoundingBox(img image.Image, boxes [][]float64, labels []string, scores []float64) image.Image {
  484. // 创建可绘制的图像副本
  485. bounds := img.Bounds()
  486. drawableImg := image.NewRGBA(bounds)
  487. draw.Draw(drawableImg, bounds, img, image.Point{}, draw.Src)
  488. // 红色边界框
  489. red := image.NewUniform(color.RGBA{255, 0, 0, 255})
  490. fmt.Printf("图像边界: %v\n", bounds)
  491. for i, box := range boxes {
  492. if len(box) >= 4 {
  493. x1, y1, x2, y2 := int(box[0]), int(box[1]), int(box[2]), int(box[3])
  494. fmt.Printf("边界框 %d: [%d, %d, %d, %d]\n", i, x1, y1, x2, y2)
  495. // 绘制边界框
  496. drawRect(drawableImg, x1, y1, x2, y2, red)
  497. // 绘制标签和置信度(暂时注释掉,避免白色区域)
  498. // if i < len(labels) && i < len(scores) {
  499. // label := fmt.Sprintf("%s: %.2f", labels[i], scores[i])
  500. // drawLabel(drawableImg, x1, y1-20, label)
  501. // }
  502. }
  503. }
  504. return drawableImg
  505. }
  506. // drawRect 绘制矩形
  507. func drawRect(img *image.RGBA, x1, y1, x2, y2 int, color *image.Uniform) {
  508. bounds := img.Bounds()
  509. fmt.Printf("绘制矩形: [%d, %d, %d, %d], 图像边界: %v\n", x1, y1, x2, y2, bounds)
  510. // 确保坐标在图像边界内
  511. if x1 < bounds.Min.X {
  512. x1 = bounds.Min.X
  513. }
  514. if y1 < bounds.Min.Y {
  515. y1 = bounds.Min.Y
  516. }
  517. if x2 >= bounds.Max.X {
  518. x2 = bounds.Max.X - 1
  519. }
  520. if y2 >= bounds.Max.Y {
  521. y2 = bounds.Max.Y - 1
  522. }
  523. fmt.Printf("调整后坐标: [%d, %d, %d, %d]\n", x1, y1, x2, y2)
  524. // 绘制四条边
  525. for x := x1; x <= x2; x++ {
  526. img.Set(x, y1, color)
  527. img.Set(x, y2, color)
  528. }
  529. for y := y1; y <= y2; y++ {
  530. img.Set(x1, y, color)
  531. img.Set(x2, y, color)
  532. }
  533. fmt.Printf("矩形绘制完成\n")
  534. }
  535. // drawLabel 绘制标签文本(简化版本,只绘制背景矩形)
  536. func drawLabel(img *image.RGBA, x, y int, text string) {
  537. fmt.Printf("绘制标签: '%s' 在位置 [%d, %d]\n", text, x, y)
  538. // 绘制白色背景矩形
  539. white := image.NewUniform(color.RGBA{255, 255, 255, 255})
  540. labelWidth := len(text) * 8 // 估算文本宽度
  541. labelHeight := 16
  542. // 确保标签在图像边界内
  543. bounds := img.Bounds()
  544. if x < bounds.Min.X {
  545. x = bounds.Min.X
  546. }
  547. if y < bounds.Min.Y {
  548. y = bounds.Min.Y
  549. }
  550. if x+labelWidth >= bounds.Max.X {
  551. labelWidth = bounds.Max.X - x - 1
  552. }
  553. if y+labelHeight >= bounds.Max.Y {
  554. labelHeight = bounds.Max.Y - y - 1
  555. }
  556. fmt.Printf("标签尺寸: %dx%d\n", labelWidth, labelHeight)
  557. // 绘制背景矩形
  558. for dx := 0; dx < labelWidth; dx++ {
  559. for dy := 0; dy < labelHeight; dy++ {
  560. if x+dx < bounds.Max.X && y+dy < bounds.Max.Y && x+dx >= bounds.Min.X && y+dy >= bounds.Min.Y {
  561. img.Set(x+dx, y+dy, white)
  562. }
  563. }
  564. }
  565. fmt.Printf("标签绘制完成\n")
  566. }
  567. // TestHealthCheck 测试健康检查接口
  568. func TestHealthCheck(t *testing.T) {
  569. // 加载测试配置
  570. config := LoadConfig()
  571. baseURL := config.HealthBaseURL
  572. t.Run("健康检查测试", func(t *testing.T) {
  573. client := &http.Client{
  574. Timeout: 10 * time.Second,
  575. }
  576. // 发送POST请求到健康检查端点
  577. t.Logf("请求URL: %s/health", baseURL)
  578. resp, err := client.Post(fmt.Sprintf("%s/health", baseURL), "application/json", nil)
  579. if err != nil {
  580. t.Logf("❌ 健康检查请求失败: %v", err)
  581. t.Logf("错误类型: %T", err)
  582. // 检查是否是网络相关错误
  583. if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
  584. t.Logf("⚠️ 这是超时错误")
  585. }
  586. // 尝试更详细的错误信息
  587. if urlErr, ok := err.(*url.Error); ok {
  588. t.Logf("URL错误详情: %+v", urlErr)
  589. if urlErr.Err != nil {
  590. t.Logf("底层错误: %v", urlErr.Err)
  591. }
  592. }
  593. t.Fatalf("健康检查请求失败: %v", err)
  594. }
  595. defer resp.Body.Close()
  596. // 读取响应内容
  597. body, err := io.ReadAll(resp.Body)
  598. if err != nil {
  599. t.Logf("读取响应失败: %v", err)
  600. }
  601. t.Logf("健康检查响应状态码: %d", resp.StatusCode)
  602. t.Logf("响应头: %+v", resp.Header)
  603. t.Logf("响应内容: %s", string(body))
  604. // 验证响应状态码
  605. if resp.StatusCode != http.StatusOK {
  606. t.Errorf("健康检查失败,期望状态码200,实际状态码: %d", resp.StatusCode)
  607. }
  608. // 验证响应内容(通常健康检查返回简单的状态信息)
  609. if len(body) == 0 {
  610. t.Error("健康检查响应内容为空")
  611. }
  612. // 尝试解析JSON响应(如果返回的是JSON格式)
  613. var healthResponse map[string]interface{}
  614. if err := json.Unmarshal(body, &healthResponse); err == nil {
  615. t.Logf("✅ 健康检查返回JSON格式响应: %+v", healthResponse)
  616. } else {
  617. t.Logf("健康检查返回非JSON格式响应: %s", string(body))
  618. }
  619. })
  620. }
  621. // ShudaoWorkflowRequest 定义蜀道集团工作流请求结构
  622. type ShudaoWorkflowRequest struct {
  623. WorkflowID string `json:"workflow_id"`
  624. Inputs map[string]interface{} `json:"inputs"`
  625. ResponseMode string `json:"response_mode"`
  626. User string `json:"user"`
  627. }
  628. // ShudaoWorkflowResponse 定义蜀道集团工作流响应结构
  629. type ShudaoWorkflowResponse struct {
  630. TaskID string `json:"task_id"`
  631. WorkflowRunID string `json:"workflow_run_id"`
  632. Data struct {
  633. ID string `json:"id"`
  634. WorkflowID string `json:"workflow_id"`
  635. Status string `json:"status"`
  636. Outputs struct {
  637. JSON []struct {
  638. Answer *string `json:"answer"`
  639. FollowUpQuestions *string `json:"follow_up_questions"`
  640. Images []string `json:"images"`
  641. Query string `json:"query"`
  642. RequestID string `json:"request_id"`
  643. ResponseTime float64 `json:"response_time"`
  644. Results []struct {
  645. Content string `json:"content"`
  646. RawContent *string `json:"raw_content"`
  647. Score float64 `json:"score"`
  648. Title string `json:"title"`
  649. URL string `json:"url"`
  650. } `json:"results"`
  651. } `json:"json"`
  652. } `json:"outputs"`
  653. Error string `json:"error"`
  654. ElapsedTime float64 `json:"elapsed_time"`
  655. TotalTokens int `json:"total_tokens"`
  656. TotalSteps int `json:"total_steps"`
  657. CreatedAt int64 `json:"created_at"`
  658. FinishedAt int64 `json:"finished_at"`
  659. } `json:"data"`
  660. }
  661. // TestShudaoWorkflowConnectivity 测试蜀道集团工作流接口连通性
  662. func TestShudaoWorkflowConnectivity(t *testing.T) {
  663. // 加载测试配置
  664. config := LoadConfig()
  665. baseURL := config.GetShudaoWorkflowURL()
  666. authToken := config.ShuDaoAuthToken
  667. workflowID := config.ShuDaoWorkflowID
  668. t.Run("蜀道集团工作流接口连通性测试", func(t *testing.T) {
  669. client := &http.Client{
  670. Timeout: 60 * time.Second, // 工作流可能需要更长时间
  671. }
  672. t.Logf("测试蜀道集团工作流接口连通性: %s", baseURL)
  673. t.Logf("使用工作流ID: %s", workflowID)
  674. t.Logf("使用认证令牌: %s", authToken)
  675. // 构建测试请求
  676. request := ShudaoWorkflowRequest{
  677. WorkflowID: workflowID,
  678. Inputs: map[string]interface{}{
  679. "keywords": "蜀道集团",
  680. "num": 5, // 减少结果数量以加快测试
  681. },
  682. ResponseMode: "blocking",
  683. User: "test_user_001",
  684. }
  685. jsonData, err := json.Marshal(request)
  686. if err != nil {
  687. t.Fatalf("序列化测试请求失败: %v", err)
  688. }
  689. // 创建HTTP请求
  690. req, err := http.NewRequest("POST", baseURL, bytes.NewBuffer(jsonData))
  691. if err != nil {
  692. t.Fatalf("创建HTTP请求失败: %v", err)
  693. }
  694. // 设置请求头
  695. req.Header.Set("Authorization", "Bearer "+authToken)
  696. req.Header.Set("Content-Type", "application/json")
  697. // 发送请求
  698. resp, err := client.Do(req)
  699. if err != nil {
  700. t.Logf("❌ 蜀道集团工作流接口连接失败: %v", err)
  701. t.Logf("可能的原因:")
  702. t.Logf(" - 工作流服务未启动")
  703. t.Logf(" - 网络不可达")
  704. t.Logf(" - 端口不正确")
  705. t.Logf(" - 防火墙阻止")
  706. t.Logf(" - 认证令牌无效")
  707. t.Fatalf("蜀道集团工作流接口连通性测试失败: %v", err)
  708. }
  709. defer resp.Body.Close()
  710. t.Logf("✅ 蜀道集团工作流接口HTTP连接成功")
  711. t.Logf("响应状态码: %d", resp.StatusCode)
  712. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  713. // 读取响应体
  714. body, err := io.ReadAll(resp.Body)
  715. if err != nil {
  716. t.Fatalf("读取响应体失败: %v", err)
  717. }
  718. // 验证响应状态码
  719. if resp.StatusCode != http.StatusOK {
  720. t.Logf("⚠️ 蜀道集团工作流服务返回非200状态码: %d", resp.StatusCode)
  721. t.Logf("响应内容: %s", string(body))
  722. t.Fatalf("蜀道集团工作流接口返回错误状态码: %d", resp.StatusCode)
  723. }
  724. // 解析响应JSON
  725. var response ShudaoWorkflowResponse
  726. if err := json.Unmarshal(body, &response); err != nil {
  727. t.Logf("⚠️ 响应JSON解析失败: %v", err)
  728. t.Logf("原始响应: %s", string(body))
  729. t.Fatalf("无法解析蜀道集团工作流响应: %v", err)
  730. }
  731. t.Logf("✅ 蜀道集团工作流服务响应正常")
  732. t.Logf("任务ID: %s", response.TaskID)
  733. t.Logf("工作流运行ID: %s", response.WorkflowRunID)
  734. t.Logf("工作流状态: %s", response.Data.Status)
  735. t.Logf("执行耗时: %.3f秒", response.Data.ElapsedTime)
  736. // 验证工作流执行状态
  737. if response.Data.Status != "succeeded" {
  738. t.Logf("⚠️ 工作流执行状态异常: %s", response.Data.Status)
  739. if response.Data.Error != "" {
  740. t.Logf("错误信息: %s", response.Data.Error)
  741. }
  742. t.Fatalf("工作流执行失败,状态: %s", response.Data.Status)
  743. }
  744. // 验证返回结果
  745. if len(response.Data.Outputs.JSON) == 0 {
  746. t.Fatalf("工作流未返回任何结果")
  747. }
  748. jsonResult := response.Data.Outputs.JSON[0]
  749. t.Logf("查询关键词: %s", jsonResult.Query)
  750. t.Logf("检索耗时: %.3f秒", jsonResult.ResponseTime)
  751. t.Logf("返回结果数量: %d", len(jsonResult.Results))
  752. // 验证结果质量
  753. if len(jsonResult.Results) == 0 {
  754. t.Fatalf("未返回任何检索结果")
  755. }
  756. // 显示前3个结果的基本信息
  757. for i, result := range jsonResult.Results {
  758. if i >= 3 {
  759. break
  760. }
  761. t.Logf("结果 %d:", i+1)
  762. t.Logf(" 标题: %s", result.Title)
  763. t.Logf(" 相关性得分: %.4f", result.Score)
  764. t.Logf(" URL: %s", result.URL)
  765. t.Logf(" 内容摘要: %s...", truncateString(result.Content, 100))
  766. }
  767. // 验证结果质量(相关性得分)
  768. highScoreCount := 0
  769. for _, result := range jsonResult.Results {
  770. if result.Score > 0.7 {
  771. highScoreCount++
  772. }
  773. }
  774. t.Logf("高质量结果数量 (得分>0.7): %d/%d", highScoreCount, len(jsonResult.Results))
  775. if highScoreCount == 0 {
  776. t.Logf("⚠️ 警告: 没有高质量结果 (得分>0.7)")
  777. }
  778. t.Logf("✅ 蜀道集团工作流接口测试完成")
  779. })
  780. }
  781. // truncateString 截断字符串到指定长度
  782. func truncateString(s string, maxLen int) string {
  783. if len(s) <= maxLen {
  784. return s
  785. }
  786. return s[:maxLen]
  787. }
  788. // SearchRequest 定义搜索请求结构
  789. type SearchRequest struct {
  790. Query string `json:"query"`
  791. NResults int `json:"n_results"`
  792. }
  793. // SearchResponse 定义搜索响应结构
  794. type SearchResponse struct {
  795. Results []SearchResult `json:"results"`
  796. Total int `json:"total"`
  797. Query string `json:"query"`
  798. }
  799. // SearchResult 定义搜索结果结构
  800. type SearchResult struct {
  801. ID string `json:"id"`
  802. Title string `json:"title"`
  803. Content string `json:"content"`
  804. Score float64 `json:"score"`
  805. Metadata map[string]interface{} `json:"metadata,omitempty"`
  806. }
  807. // TestSearchAPI 测试搜索功能接口
  808. func TestSearchAPI(t *testing.T) {
  809. // 加载测试配置
  810. config := LoadConfig()
  811. baseURL := config.SearchBaseURL
  812. testCases := []struct {
  813. name string
  814. query string
  815. nResults int
  816. }{
  817. {
  818. name: "技术搜索测试",
  819. query: "技术",
  820. nResults: 3,
  821. },
  822. {
  823. name: "编程搜索测试",
  824. query: "编程",
  825. nResults: 5,
  826. },
  827. {
  828. name: "AI搜索测试",
  829. query: "人工智能",
  830. nResults: 2,
  831. },
  832. }
  833. for _, tc := range testCases {
  834. t.Run(tc.name, func(t *testing.T) {
  835. // 构建搜索请求
  836. request := SearchRequest{
  837. Query: tc.query,
  838. NResults: tc.nResults,
  839. }
  840. jsonData, err := json.Marshal(request)
  841. if err != nil {
  842. t.Fatalf("序列化搜索请求失败: %v", err)
  843. }
  844. // 发送POST请求到搜索端点
  845. resp, err := http.Post(
  846. fmt.Sprintf("%s/search", baseURL),
  847. "application/json",
  848. bytes.NewBuffer(jsonData),
  849. )
  850. if err != nil {
  851. t.Fatalf("搜索请求失败: %v", err)
  852. }
  853. defer resp.Body.Close()
  854. // 读取响应内容
  855. body, err := io.ReadAll(resp.Body)
  856. if err != nil {
  857. t.Fatalf("读取搜索响应失败: %v", err)
  858. }
  859. t.Logf("搜索响应状态码: %d", resp.StatusCode)
  860. t.Logf("搜索查询: %s", tc.query)
  861. t.Logf("请求结果数量: %d", tc.nResults)
  862. // 验证响应状态码
  863. if resp.StatusCode != http.StatusOK {
  864. t.Errorf("搜索请求失败,期望状态码200,实际状态码: %d", resp.StatusCode)
  865. if len(body) < 500 {
  866. t.Logf("错误响应内容: %s", string(body))
  867. }
  868. return
  869. }
  870. // 验证响应内容不为空
  871. if len(body) == 0 {
  872. t.Error("搜索响应内容为空")
  873. return
  874. }
  875. // 尝试解析JSON响应
  876. var searchResponse SearchResponse
  877. if err := json.Unmarshal(body, &searchResponse); err != nil {
  878. t.Logf("⚠️ 搜索响应不是标准JSON格式: %v", err)
  879. t.Logf("响应内容: %s", string(body))
  880. // 尝试解析为简单的map结构
  881. var simpleResponse map[string]interface{}
  882. if err := json.Unmarshal(body, &simpleResponse); err == nil {
  883. t.Logf("✅ 搜索返回简单JSON格式: %+v", simpleResponse)
  884. } else {
  885. t.Logf("搜索返回非JSON格式响应")
  886. }
  887. return
  888. }
  889. // 验证搜索结果
  890. t.Logf("✅ 搜索成功!")
  891. t.Logf("查询: %s", searchResponse.Query)
  892. t.Logf("总结果数: %d", searchResponse.Total)
  893. t.Logf("返回结果数: %d", len(searchResponse.Results))
  894. // 验证结果数量
  895. if len(searchResponse.Results) > tc.nResults {
  896. t.Logf("⚠️ 返回结果数量(%d)超过请求数量(%d)", len(searchResponse.Results), tc.nResults)
  897. }
  898. // 显示搜索结果详情
  899. for i, result := range searchResponse.Results {
  900. t.Logf("结果 %d:", i+1)
  901. t.Logf(" ID: %s", result.ID)
  902. t.Logf(" 标题: %s", result.Title)
  903. t.Logf(" 内容: %s", truncateString(result.Content, 100))
  904. t.Logf(" 评分: %.4f", result.Score)
  905. if len(result.Metadata) > 0 {
  906. t.Logf(" 元数据: %+v", result.Metadata)
  907. }
  908. }
  909. })
  910. }
  911. }
  912. // truncateString 截断字符串到指定长度
  913. func truncateString(s string, maxLen int) string {
  914. if len(s) <= maxLen {
  915. return s
  916. }
  917. return s[:maxLen] + "..."
  918. }
  919. // TTSRequest 定义TTS请求结构
  920. type TTSRequest struct {
  921. Text string `json:"text"`
  922. }
  923. // TestTTSStreamAPI 测试TTS流式接口
  924. func TestTTSStreamAPI(t *testing.T) {
  925. // 加载测试配置
  926. config := LoadConfig()
  927. baseURL := config.TTSBaseURL
  928. testCases := []struct {
  929. name string
  930. text string
  931. }{
  932. {
  933. name: "短文本测试",
  934. text: "你好,这是一个语音合成测试。",
  935. },
  936. {
  937. name: "中等长度文本测试",
  938. text: "答案依据:《汽车加油站雷电防护装置检测报告综述表》委托单位随检人员在雷电防护装置检测过程中承担着关键的协同与监督职责。",
  939. },
  940. {
  941. name: "长文本测试",
  942. text: "答案依据:《汽车加油站雷电防护装置检测报告综述表》委托单位随检人员在雷电防护装置检测过程中承担着关键的协同与监督职责,其参与过程对检测报告的完整性与合规性具有直接影响。作为检测工作的现场对接方和责任主体之一,委托单位随检人员需全程参与检测实施,确保检测工作在真实、可控的现场环境下开展,有效保障检测数据的真实性与代表性。",
  943. },
  944. }
  945. for _, tc := range testCases {
  946. t.Run(tc.name, func(t *testing.T) {
  947. // 构建TTS请求
  948. request := TTSRequest{
  949. Text: tc.text,
  950. }
  951. jsonData, err := json.Marshal(request)
  952. if err != nil {
  953. t.Fatalf("序列化TTS请求失败: %v", err)
  954. }
  955. t.Logf("发送的TTS请求: %s", string(jsonData))
  956. t.Logf("请求URL: %s/tts/voice", baseURL)
  957. // 创建HTTP客户端,设置较长的超时时间(TTS可能需要较长时间)
  958. client := &http.Client{
  959. Timeout: 60 * time.Second,
  960. }
  961. // 发送POST请求
  962. resp, err := client.Post(
  963. fmt.Sprintf("%s/tts/voice", baseURL),
  964. "application/json",
  965. bytes.NewBuffer(jsonData),
  966. )
  967. if err != nil {
  968. t.Fatalf("发送TTS请求失败: %v", err)
  969. }
  970. defer resp.Body.Close()
  971. t.Logf("TTS响应状态码: %d", resp.StatusCode)
  972. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  973. t.Logf("Content-Length: %s", resp.Header.Get("Content-Length"))
  974. // 验证响应状态码
  975. if resp.StatusCode != http.StatusOK {
  976. body, _ := io.ReadAll(resp.Body)
  977. t.Fatalf("TTS请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(body))
  978. }
  979. // 检查Content-Type是否为音频格式
  980. contentType := resp.Header.Get("Content-Type")
  981. if contentType != "" {
  982. t.Logf("响应Content-Type: %s", contentType)
  983. // WAV格式通常为 "audio/wav" 或 "audio/wave"
  984. if !strings.Contains(contentType, "audio") && !strings.Contains(contentType, "wav") {
  985. t.Logf("⚠️ 警告: Content-Type不是预期的音频格式")
  986. }
  987. }
  988. // 读取流式音频数据
  989. t.Logf("开始接收流式音频数据...")
  990. var audioData bytes.Buffer
  991. totalBytes := 0
  992. chunkCount := 0
  993. // 分块读取数据
  994. buffer := make([]byte, 4096) // 4KB缓冲区
  995. for {
  996. n, err := resp.Body.Read(buffer)
  997. if n > 0 {
  998. audioData.Write(buffer[:n])
  999. totalBytes += n
  1000. chunkCount++
  1001. // 每读取10个块输出一次进度
  1002. if chunkCount%10 == 0 {
  1003. t.Logf("已接收 %d 字节音频数据 (块数: %d)", totalBytes, chunkCount)
  1004. }
  1005. }
  1006. if err == io.EOF {
  1007. t.Logf("音频数据接收完成")
  1008. break
  1009. }
  1010. if err != nil {
  1011. t.Fatalf("读取音频数据失败: %v", err)
  1012. }
  1013. }
  1014. t.Logf("✅ TTS流式响应成功!")
  1015. t.Logf("请求文本: %s", tc.text)
  1016. t.Logf("文本长度: %d 字符", len(tc.text))
  1017. t.Logf("音频数据总大小: %d 字节", totalBytes)
  1018. t.Logf("接收块数: %d", chunkCount)
  1019. // 验证音频数据不为空
  1020. if totalBytes == 0 {
  1021. t.Error("音频数据为空")
  1022. return
  1023. }
  1024. // 验证音频数据大小合理性(至少应该有WAV文件头)
  1025. if totalBytes < 44 {
  1026. t.Errorf("音频数据太小,可能不是有效的WAV文件: %d 字节", totalBytes)
  1027. }
  1028. // 验证WAV文件头(RIFF格式)
  1029. audioBytes := audioData.Bytes()
  1030. if len(audioBytes) >= 12 {
  1031. // 检查RIFF头
  1032. if string(audioBytes[0:4]) == "RIFF" {
  1033. t.Logf("✅ 检测到有效的RIFF格式音频文件")
  1034. if len(audioBytes) >= 8 {
  1035. fileSize := int(audioBytes[4]) | int(audioBytes[5])<<8 | int(audioBytes[6])<<16 | int(audioBytes[7])<<24
  1036. t.Logf("WAV文件大小字段: %d 字节", fileSize)
  1037. }
  1038. if len(audioBytes) >= 12 && string(audioBytes[8:12]) == "WAVE" {
  1039. t.Logf("✅ 检测到WAVE格式")
  1040. }
  1041. } else {
  1042. t.Logf("⚠️ 警告: 音频数据不是标准的RIFF格式")
  1043. t.Logf("文件头: %x", audioBytes[:min(16, len(audioBytes))])
  1044. }
  1045. }
  1046. // 保存音频文件到本地进行验证
  1047. outputFilename := fmt.Sprintf("tts_test_%s.wav", strings.ReplaceAll(tc.name, " ", "_"))
  1048. outputFile, err := os.Create(outputFilename)
  1049. if err != nil {
  1050. t.Fatalf("创建音频输出文件失败: %v", err)
  1051. }
  1052. defer outputFile.Close()
  1053. _, err = outputFile.Write(audioBytes)
  1054. if err != nil {
  1055. t.Fatalf("写入音频文件失败: %v", err)
  1056. }
  1057. t.Logf("✅ 音频文件已保存: %s", outputFilename)
  1058. t.Logf("文件大小: %d 字节", totalBytes)
  1059. // 验证文件是否成功创建
  1060. if stat, err := os.Stat(outputFilename); err == nil {
  1061. t.Logf("✅ 文件验证成功,实际大小: %d 字节", stat.Size())
  1062. if stat.Size() != int64(totalBytes) {
  1063. t.Errorf("文件大小不匹配: 期望 %d, 实际 %d", totalBytes, stat.Size())
  1064. }
  1065. } else {
  1066. t.Errorf("文件验证失败: %v", err)
  1067. }
  1068. })
  1069. }
  1070. }
  1071. // min 返回两个整数中的较小值
  1072. func min(a, b int) int {
  1073. if a < b {
  1074. return a
  1075. }
  1076. return b
  1077. }
  1078. // TestTTSConnectivity 测试TTS接口连通性
  1079. func TestTTSConnectivity(t *testing.T) {
  1080. // 加载测试配置
  1081. config := LoadConfig()
  1082. baseURL := config.TTSBaseURL
  1083. t.Run("TTS接口连通性测试", func(t *testing.T) {
  1084. client := &http.Client{
  1085. Timeout: 30 * time.Second,
  1086. }
  1087. t.Logf("测试TTS接口连通性: %s/tts/voice", baseURL)
  1088. // 构建简单的测试请求
  1089. request := TTSRequest{
  1090. Text: "测试",
  1091. }
  1092. jsonData, err := json.Marshal(request)
  1093. if err != nil {
  1094. t.Fatalf("序列化测试请求失败: %v", err)
  1095. }
  1096. // 发送POST请求
  1097. resp, err := client.Post(
  1098. fmt.Sprintf("%s/tts/voice", baseURL),
  1099. "application/json",
  1100. bytes.NewBuffer(jsonData),
  1101. )
  1102. if err != nil {
  1103. t.Logf("❌ TTS接口连接失败: %v", err)
  1104. t.Logf("可能的原因:")
  1105. t.Logf(" - TTS服务未启动")
  1106. t.Logf(" - 网络不可达")
  1107. t.Logf(" - 端口不正确")
  1108. t.Logf(" - 防火墙阻止")
  1109. t.Fatalf("TTS接口连通性测试失败: %v", err)
  1110. }
  1111. defer resp.Body.Close()
  1112. t.Logf("✅ TTS接口HTTP连接成功")
  1113. t.Logf("响应状态码: %d", resp.StatusCode)
  1114. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  1115. // 验证响应状态码
  1116. if resp.StatusCode != http.StatusOK {
  1117. body, _ := io.ReadAll(resp.Body)
  1118. t.Logf("⚠️ TTS服务不可用,状态码: %d", resp.StatusCode)
  1119. t.Logf("响应内容: %s", string(body))
  1120. // 根据状态码提供具体的错误信息
  1121. switch resp.StatusCode {
  1122. case 502:
  1123. t.Logf("❌ 502 Bad Gateway - TTS后端服务可能未启动或配置错误")
  1124. case 503:
  1125. t.Logf("❌ 503 Service Unavailable - TTS服务暂时不可用")
  1126. case 404:
  1127. t.Logf("❌ 404 Not Found - TTS接口路径不存在")
  1128. case 500:
  1129. t.Logf("❌ 500 Internal Server Error - TTS服务内部错误")
  1130. default:
  1131. t.Logf("❌ 未知错误状态码: %d", resp.StatusCode)
  1132. }
  1133. } else {
  1134. t.Logf("✅ TTS服务响应正常")
  1135. // 读取少量数据验证是否为音频格式
  1136. buffer := make([]byte, 1024)
  1137. n, err := resp.Body.Read(buffer)
  1138. if err != nil && err != io.EOF {
  1139. t.Logf("读取响应数据失败: %v", err)
  1140. } else if n > 0 {
  1141. t.Logf("✅ 成功接收 %d 字节数据", n)
  1142. // 检查是否为WAV格式
  1143. if n >= 12 {
  1144. if string(buffer[0:4]) == "RIFF" {
  1145. t.Logf("✅ 检测到WAV格式音频数据")
  1146. } else {
  1147. t.Logf("⚠️ 数据格式可能不是WAV: %x", buffer[:min(16, n)])
  1148. }
  1149. }
  1150. }
  1151. }
  1152. })
  1153. }
  1154. // ShudaoWorkflowRequest 定义蜀道集团工作流请求结构
  1155. type ShudaoWorkflowRequest struct {
  1156. WorkflowID string `json:"workflow_id"`
  1157. Inputs map[string]interface{} `json:"inputs"`
  1158. ResponseMode string `json:"response_mode"`
  1159. User string `json:"user"`
  1160. }
  1161. // ShudaoWorkflowResponse 定义蜀道集团工作流响应结构
  1162. type ShudaoWorkflowResponse struct {
  1163. TaskID string `json:"task_id"`
  1164. WorkflowRunID string `json:"workflow_run_id"`
  1165. Data struct {
  1166. ID string `json:"id"`
  1167. WorkflowID string `json:"workflow_id"`
  1168. Status string `json:"status"`
  1169. Outputs struct {
  1170. JSON []struct {
  1171. Answer *string `json:"answer"`
  1172. FollowUpQuestions *string `json:"follow_up_questions"`
  1173. Images []string `json:"images"`
  1174. Query string `json:"query"`
  1175. RequestID string `json:"request_id"`
  1176. ResponseTime float64 `json:"response_time"`
  1177. Results []struct {
  1178. Content string `json:"content"`
  1179. RawContent *string `json:"raw_content"`
  1180. Score float64 `json:"score"`
  1181. Title string `json:"title"`
  1182. URL string `json:"url"`
  1183. } `json:"results"`
  1184. } `json:"json"`
  1185. } `json:"outputs"`
  1186. Error string `json:"error"`
  1187. ElapsedTime float64 `json:"elapsed_time"`
  1188. TotalTokens int `json:"total_tokens"`
  1189. TotalSteps int `json:"total_steps"`
  1190. CreatedAt int64 `json:"created_at"`
  1191. FinishedAt int64 `json:"finished_at"`
  1192. } `json:"data"`
  1193. }
  1194. // TestShudaoWorkflowConnectivity 测试蜀道集团工作流接口连通性
  1195. func TestShudaoWorkflowConnectivity(t *testing.T) {
  1196. // 加载测试配置
  1197. config := LoadConfig()
  1198. baseURL := config.GetShudaoWorkflowURL()
  1199. authToken := config.ShuDaoAuthToken
  1200. workflowID := config.ShuDaoWorkflowID
  1201. t.Run("蜀道集团工作流接口连通性测试", func(t *testing.T) {
  1202. client := &http.Client{
  1203. Timeout: 60 * time.Second, // 工作流可能需要更长时间
  1204. }
  1205. t.Logf("测试蜀道集团工作流接口连通性: %s", baseURL)
  1206. t.Logf("使用工作流ID: %s", workflowID)
  1207. t.Logf("使用认证令牌: %s", authToken)
  1208. // 构建测试请求
  1209. request := ShudaoWorkflowRequest{
  1210. WorkflowID: workflowID,
  1211. Inputs: map[string]interface{}{
  1212. "keywords": "蜀道集团",
  1213. "num": 5, // 减少结果数量以加快测试
  1214. },
  1215. ResponseMode: "blocking",
  1216. User: "test_user_001",
  1217. }
  1218. jsonData, err := json.Marshal(request)
  1219. if err != nil {
  1220. t.Fatalf("序列化测试请求失败: %v", err)
  1221. }
  1222. // 创建HTTP请求
  1223. req, err := http.NewRequest("POST", baseURL, bytes.NewBuffer(jsonData))
  1224. if err != nil {
  1225. t.Fatalf("创建HTTP请求失败: %v", err)
  1226. }
  1227. // 设置请求头
  1228. req.Header.Set("Authorization", "Bearer "+authToken)
  1229. req.Header.Set("Content-Type", "application/json")
  1230. // 发送请求
  1231. resp, err := client.Do(req)
  1232. if err != nil {
  1233. t.Logf("❌ 蜀道集团工作流接口连接失败: %v", err)
  1234. t.Logf("可能的原因:")
  1235. t.Logf(" - 工作流服务未启动")
  1236. t.Logf(" - 网络不可达")
  1237. t.Logf(" - 端口不正确")
  1238. t.Logf(" - 防火墙阻止")
  1239. t.Logf(" - 认证令牌无效")
  1240. t.Fatalf("蜀道集团工作流接口连通性测试失败: %v", err)
  1241. }
  1242. defer resp.Body.Close()
  1243. t.Logf("✅ 蜀道集团工作流接口HTTP连接成功")
  1244. t.Logf("响应状态码: %d", resp.StatusCode)
  1245. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  1246. // 读取响应体
  1247. body, err := io.ReadAll(resp.Body)
  1248. if err != nil {
  1249. t.Fatalf("读取响应体失败: %v", err)
  1250. }
  1251. // 验证响应状态码
  1252. if resp.StatusCode != http.StatusOK {
  1253. t.Logf("⚠️ 蜀道集团工作流服务返回非200状态码: %d", resp.StatusCode)
  1254. t.Logf("响应内容: %s", string(body))
  1255. t.Fatalf("蜀道集团工作流接口返回错误状态码: %d", resp.StatusCode)
  1256. }
  1257. // 解析响应JSON
  1258. var response ShudaoWorkflowResponse
  1259. if err := json.Unmarshal(body, &response); err != nil {
  1260. t.Logf("⚠️ 响应JSON解析失败: %v", err)
  1261. t.Logf("原始响应: %s", string(body))
  1262. t.Fatalf("无法解析蜀道集团工作流响应: %v", err)
  1263. }
  1264. t.Logf("✅ 蜀道集团工作流服务响应正常")
  1265. t.Logf("任务ID: %s", response.TaskID)
  1266. t.Logf("工作流运行ID: %s", response.WorkflowRunID)
  1267. t.Logf("工作流状态: %s", response.Data.Status)
  1268. t.Logf("执行耗时: %.3f秒", response.Data.ElapsedTime)
  1269. // 验证工作流执行状态
  1270. if response.Data.Status != "succeeded" {
  1271. t.Logf("⚠️ 工作流执行状态异常: %s", response.Data.Status)
  1272. if response.Data.Error != "" {
  1273. t.Logf("错误信息: %s", response.Data.Error)
  1274. }
  1275. t.Fatalf("工作流执行失败,状态: %s", response.Data.Status)
  1276. }
  1277. // 验证返回结果
  1278. if len(response.Data.Outputs.JSON) == 0 {
  1279. t.Fatalf("工作流未返回任何结果")
  1280. }
  1281. jsonResult := response.Data.Outputs.JSON[0]
  1282. t.Logf("查询关键词: %s", jsonResult.Query)
  1283. t.Logf("检索耗时: %.3f秒", jsonResult.ResponseTime)
  1284. t.Logf("返回结果数量: %d", len(jsonResult.Results))
  1285. // 验证结果质量
  1286. if len(jsonResult.Results) == 0 {
  1287. t.Fatalf("未返回任何检索结果")
  1288. }
  1289. // 显示前3个结果的基本信息
  1290. for i, result := range jsonResult.Results {
  1291. if i >= 3 {
  1292. break
  1293. }
  1294. t.Logf("结果 %d:", i+1)
  1295. t.Logf(" 标题: %s", result.Title)
  1296. t.Logf(" 相关性得分: %.4f", result.Score)
  1297. t.Logf(" URL: %s", result.URL)
  1298. t.Logf(" 内容摘要: %s...", truncateString(result.Content, 100))
  1299. }
  1300. // 验证结果质量(相关性得分)
  1301. highScoreCount := 0
  1302. for _, result := range jsonResult.Results {
  1303. if result.Score > 0.7 {
  1304. highScoreCount++
  1305. }
  1306. }
  1307. t.Logf("高质量结果数量 (得分>0.7): %d/%d", highScoreCount, len(jsonResult.Results))
  1308. if highScoreCount == 0 {
  1309. t.Logf("⚠️ 警告: 没有高质量结果 (得分>0.7)")
  1310. }
  1311. t.Logf("✅ 蜀道集团工作流接口测试完成")
  1312. })
  1313. }
  1314. // truncateString 截断字符串到指定长度
  1315. func truncateString(s string, maxLen int) string {
  1316. if len(s) <= maxLen {
  1317. return s
  1318. }
  1319. return s[:maxLen]
  1320. }
  1321. // TestHealthAndSearchIntegration 集成测试:先检查健康状态,再进行搜索
  1322. func TestHealthAndSearchIntegration(t *testing.T) {
  1323. // 加载测试配置
  1324. config := LoadConfig()
  1325. baseURL := config.HealthBaseURL
  1326. t.Run("健康检查和搜索集成测试", func(t *testing.T) {
  1327. client := &http.Client{
  1328. Timeout: 15 * time.Second,
  1329. }
  1330. // 第一步:健康检查
  1331. t.Logf("步骤1: 执行健康检查...")
  1332. t.Logf("请求URL: %s/health", baseURL)
  1333. healthResp, err := client.Post(fmt.Sprintf("%s/health", baseURL), "application/json", nil)
  1334. if err != nil {
  1335. t.Logf("❌ 健康检查请求失败: %v", err)
  1336. t.Logf("错误类型: %T", err)
  1337. // 检查是否是网络相关错误
  1338. if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
  1339. t.Logf("⚠️ 这是超时错误")
  1340. }
  1341. // 尝试更详细的错误信息
  1342. if urlErr, ok := err.(*url.Error); ok {
  1343. t.Logf("URL错误详情: %+v", urlErr)
  1344. if urlErr.Err != nil {
  1345. t.Logf("底层错误: %v", urlErr.Err)
  1346. }
  1347. }
  1348. t.Fatalf("健康检查失败: %v", err)
  1349. }
  1350. defer healthResp.Body.Close()
  1351. // 读取响应内容
  1352. healthBody, err := io.ReadAll(healthResp.Body)
  1353. if err != nil {
  1354. t.Logf("读取健康检查响应失败: %v", err)
  1355. }
  1356. t.Logf("健康检查响应状态码: %d", healthResp.StatusCode)
  1357. t.Logf("响应头: %+v", healthResp.Header)
  1358. if len(healthBody) > 0 {
  1359. t.Logf("响应内容: %s", string(healthBody))
  1360. }
  1361. if healthResp.StatusCode != http.StatusOK {
  1362. t.Fatalf("健康检查失败,状态码: %d", healthResp.StatusCode)
  1363. }
  1364. t.Logf("✅ 健康检查通过")
  1365. // 第二步:执行搜索
  1366. t.Logf("步骤2: 执行搜索测试...")
  1367. searchRequest := SearchRequest{
  1368. Query: "技术",
  1369. NResults: 3,
  1370. }
  1371. jsonData, err := json.Marshal(searchRequest)
  1372. if err != nil {
  1373. t.Fatalf("序列化搜索请求失败: %v", err)
  1374. }
  1375. searchResp, err := client.Post(
  1376. fmt.Sprintf("%s/search", baseURL),
  1377. "application/json",
  1378. bytes.NewBuffer(jsonData),
  1379. )
  1380. if err != nil {
  1381. t.Fatalf("搜索请求失败: %v", err)
  1382. }
  1383. defer searchResp.Body.Close()
  1384. body, err := io.ReadAll(searchResp.Body)
  1385. if err != nil {
  1386. t.Fatalf("读取搜索响应失败: %v", err)
  1387. }
  1388. if searchResp.StatusCode != http.StatusOK {
  1389. t.Errorf("搜索失败,状态码: %d", searchResp.StatusCode)
  1390. if len(body) < 200 {
  1391. t.Logf("错误响应: %s", string(body))
  1392. }
  1393. } else {
  1394. t.Logf("✅ 搜索功能正常")
  1395. t.Logf("响应长度: %d 字节", len(body))
  1396. }
  1397. t.Logf("✅ 集成测试完成")
  1398. })
  1399. }
  1400. // TestNetworkConnectivity 测试网络连通性
  1401. func TestNetworkConnectivity(t *testing.T) {
  1402. // 加载测试配置
  1403. config := LoadConfig()
  1404. baseURL := config.HealthBaseURL
  1405. t.Run("网络连通性测试", func(t *testing.T) {
  1406. // 解析URL
  1407. parsedURL, err := url.Parse(baseURL)
  1408. if err != nil {
  1409. t.Fatalf("解析URL失败: %v", err)
  1410. }
  1411. t.Logf("测试目标: %s", baseURL)
  1412. t.Logf("协议: %s", parsedURL.Scheme)
  1413. t.Logf("主机: %s", parsedURL.Host)
  1414. t.Logf("端口: %s", parsedURL.Port())
  1415. // 测试TCP连接
  1416. conn, err := net.DialTimeout("tcp", parsedURL.Host, 5*time.Second)
  1417. if err != nil {
  1418. t.Logf("❌ TCP连接失败: %v", err)
  1419. t.Logf("可能的原因:")
  1420. t.Logf(" - 服务器未启动")
  1421. t.Logf(" - 防火墙阻止")
  1422. t.Logf(" - 网络不可达")
  1423. t.Logf(" - 端口不正确")
  1424. } else {
  1425. t.Logf("✅ TCP连接成功")
  1426. conn.Close()
  1427. }
  1428. // 测试HTTP连接
  1429. client := &http.Client{
  1430. Timeout: 10 * time.Second,
  1431. }
  1432. // 尝试简单的HEAD请求
  1433. resp, err := client.Head(baseURL)
  1434. if err != nil {
  1435. t.Logf("❌ HTTP HEAD请求失败: %v", err)
  1436. } else {
  1437. t.Logf("✅ HTTP连接成功,状态码: %d", resp.StatusCode)
  1438. resp.Body.Close()
  1439. }
  1440. // 尝试POST请求到根路径
  1441. resp, err = client.Post(baseURL, "application/json", nil)
  1442. if err != nil {
  1443. t.Logf("❌ HTTP POST请求失败: %v", err)
  1444. } else {
  1445. t.Logf("✅ HTTP POST连接成功,状态码: %d", resp.StatusCode)
  1446. resp.Body.Close()
  1447. }
  1448. })
  1449. }
  1450. // ShudaoWorkflowRequest 定义蜀道集团工作流请求结构
  1451. type ShudaoWorkflowRequest struct {
  1452. WorkflowID string `json:"workflow_id"`
  1453. Inputs map[string]interface{} `json:"inputs"`
  1454. ResponseMode string `json:"response_mode"`
  1455. User string `json:"user"`
  1456. }
  1457. // ShudaoWorkflowResponse 定义蜀道集团工作流响应结构
  1458. type ShudaoWorkflowResponse struct {
  1459. TaskID string `json:"task_id"`
  1460. WorkflowRunID string `json:"workflow_run_id"`
  1461. Data struct {
  1462. ID string `json:"id"`
  1463. WorkflowID string `json:"workflow_id"`
  1464. Status string `json:"status"`
  1465. Outputs struct {
  1466. JSON []struct {
  1467. Answer *string `json:"answer"`
  1468. FollowUpQuestions *string `json:"follow_up_questions"`
  1469. Images []string `json:"images"`
  1470. Query string `json:"query"`
  1471. RequestID string `json:"request_id"`
  1472. ResponseTime float64 `json:"response_time"`
  1473. Results []struct {
  1474. Content string `json:"content"`
  1475. RawContent *string `json:"raw_content"`
  1476. Score float64 `json:"score"`
  1477. Title string `json:"title"`
  1478. URL string `json:"url"`
  1479. } `json:"results"`
  1480. } `json:"json"`
  1481. } `json:"outputs"`
  1482. Error string `json:"error"`
  1483. ElapsedTime float64 `json:"elapsed_time"`
  1484. TotalTokens int `json:"total_tokens"`
  1485. TotalSteps int `json:"total_steps"`
  1486. CreatedAt int64 `json:"created_at"`
  1487. FinishedAt int64 `json:"finished_at"`
  1488. } `json:"data"`
  1489. }
  1490. // TestShudaoWorkflowConnectivity 测试蜀道集团工作流接口连通性
  1491. func TestShudaoWorkflowConnectivity(t *testing.T) {
  1492. // 加载测试配置
  1493. config := LoadConfig()
  1494. baseURL := config.GetShudaoWorkflowURL()
  1495. authToken := config.ShuDaoAuthToken
  1496. workflowID := config.ShuDaoWorkflowID
  1497. t.Run("蜀道集团工作流接口连通性测试", func(t *testing.T) {
  1498. client := &http.Client{
  1499. Timeout: 60 * time.Second, // 工作流可能需要更长时间
  1500. }
  1501. t.Logf("测试蜀道集团工作流接口连通性: %s", baseURL)
  1502. t.Logf("使用工作流ID: %s", workflowID)
  1503. t.Logf("使用认证令牌: %s", authToken)
  1504. // 构建测试请求
  1505. request := ShudaoWorkflowRequest{
  1506. WorkflowID: workflowID,
  1507. Inputs: map[string]interface{}{
  1508. "keywords": "蜀道集团",
  1509. "num": 5, // 减少结果数量以加快测试
  1510. },
  1511. ResponseMode: "blocking",
  1512. User: "test_user_001",
  1513. }
  1514. jsonData, err := json.Marshal(request)
  1515. if err != nil {
  1516. t.Fatalf("序列化测试请求失败: %v", err)
  1517. }
  1518. // 创建HTTP请求
  1519. req, err := http.NewRequest("POST", baseURL, bytes.NewBuffer(jsonData))
  1520. if err != nil {
  1521. t.Fatalf("创建HTTP请求失败: %v", err)
  1522. }
  1523. // 设置请求头
  1524. req.Header.Set("Authorization", "Bearer "+authToken)
  1525. req.Header.Set("Content-Type", "application/json")
  1526. // 发送请求
  1527. resp, err := client.Do(req)
  1528. if err != nil {
  1529. t.Logf("❌ 蜀道集团工作流接口连接失败: %v", err)
  1530. t.Logf("可能的原因:")
  1531. t.Logf(" - 工作流服务未启动")
  1532. t.Logf(" - 网络不可达")
  1533. t.Logf(" - 端口不正确")
  1534. t.Logf(" - 防火墙阻止")
  1535. t.Logf(" - 认证令牌无效")
  1536. t.Fatalf("蜀道集团工作流接口连通性测试失败: %v", err)
  1537. }
  1538. defer resp.Body.Close()
  1539. t.Logf("✅ 蜀道集团工作流接口HTTP连接成功")
  1540. t.Logf("响应状态码: %d", resp.StatusCode)
  1541. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  1542. // 读取响应体
  1543. body, err := io.ReadAll(resp.Body)
  1544. if err != nil {
  1545. t.Fatalf("读取响应体失败: %v", err)
  1546. }
  1547. // 验证响应状态码
  1548. if resp.StatusCode != http.StatusOK {
  1549. t.Logf("⚠️ 蜀道集团工作流服务返回非200状态码: %d", resp.StatusCode)
  1550. t.Logf("响应内容: %s", string(body))
  1551. t.Fatalf("蜀道集团工作流接口返回错误状态码: %d", resp.StatusCode)
  1552. }
  1553. // 解析响应JSON
  1554. var response ShudaoWorkflowResponse
  1555. if err := json.Unmarshal(body, &response); err != nil {
  1556. t.Logf("⚠️ 响应JSON解析失败: %v", err)
  1557. t.Logf("原始响应: %s", string(body))
  1558. t.Fatalf("无法解析蜀道集团工作流响应: %v", err)
  1559. }
  1560. t.Logf("✅ 蜀道集团工作流服务响应正常")
  1561. t.Logf("任务ID: %s", response.TaskID)
  1562. t.Logf("工作流运行ID: %s", response.WorkflowRunID)
  1563. t.Logf("工作流状态: %s", response.Data.Status)
  1564. t.Logf("执行耗时: %.3f秒", response.Data.ElapsedTime)
  1565. // 验证工作流执行状态
  1566. if response.Data.Status != "succeeded" {
  1567. t.Logf("⚠️ 工作流执行状态异常: %s", response.Data.Status)
  1568. if response.Data.Error != "" {
  1569. t.Logf("错误信息: %s", response.Data.Error)
  1570. }
  1571. t.Fatalf("工作流执行失败,状态: %s", response.Data.Status)
  1572. }
  1573. // 验证返回结果
  1574. if len(response.Data.Outputs.JSON) == 0 {
  1575. t.Fatalf("工作流未返回任何结果")
  1576. }
  1577. jsonResult := response.Data.Outputs.JSON[0]
  1578. t.Logf("查询关键词: %s", jsonResult.Query)
  1579. t.Logf("检索耗时: %.3f秒", jsonResult.ResponseTime)
  1580. t.Logf("返回结果数量: %d", len(jsonResult.Results))
  1581. // 验证结果质量
  1582. if len(jsonResult.Results) == 0 {
  1583. t.Fatalf("未返回任何检索结果")
  1584. }
  1585. // 显示前3个结果的基本信息
  1586. for i, result := range jsonResult.Results {
  1587. if i >= 3 {
  1588. break
  1589. }
  1590. t.Logf("结果 %d:", i+1)
  1591. t.Logf(" 标题: %s", result.Title)
  1592. t.Logf(" 相关性得分: %.4f", result.Score)
  1593. t.Logf(" URL: %s", result.URL)
  1594. t.Logf(" 内容摘要: %s...", truncateString(result.Content, 100))
  1595. }
  1596. // 验证结果质量(相关性得分)
  1597. highScoreCount := 0
  1598. for _, result := range jsonResult.Results {
  1599. if result.Score > 0.7 {
  1600. highScoreCount++
  1601. }
  1602. }
  1603. t.Logf("高质量结果数量 (得分>0.7): %d/%d", highScoreCount, len(jsonResult.Results))
  1604. if highScoreCount == 0 {
  1605. t.Logf("⚠️ 警告: 没有高质量结果 (得分>0.7)")
  1606. }
  1607. t.Logf("✅ 蜀道集团工作流接口测试完成")
  1608. })
  1609. }
  1610. // truncateString 截断字符串到指定长度
  1611. func truncateString(s string, maxLen int) string {
  1612. if len(s) <= maxLen {
  1613. return s
  1614. }
  1615. return s[:maxLen]
  1616. }