api_test.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292
  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. // SearchRequest 定义搜索请求结构
  622. type SearchRequest struct {
  623. Query string `json:"query"`
  624. NResults int `json:"n_results"`
  625. }
  626. // SearchResponse 定义搜索响应结构
  627. type SearchResponse struct {
  628. Results []SearchResult `json:"results"`
  629. Total int `json:"total"`
  630. Query string `json:"query"`
  631. }
  632. // SearchResult 定义搜索结果结构
  633. type SearchResult struct {
  634. ID string `json:"id"`
  635. Title string `json:"title"`
  636. Content string `json:"content"`
  637. Score float64 `json:"score"`
  638. Metadata map[string]interface{} `json:"metadata,omitempty"`
  639. }
  640. // TestSearchAPI 测试搜索功能接口
  641. func TestSearchAPI(t *testing.T) {
  642. // 加载测试配置
  643. config := LoadConfig()
  644. baseURL := config.SearchBaseURL
  645. testCases := []struct {
  646. name string
  647. query string
  648. nResults int
  649. }{
  650. {
  651. name: "技术搜索测试",
  652. query: "技术",
  653. nResults: 3,
  654. },
  655. {
  656. name: "编程搜索测试",
  657. query: "编程",
  658. nResults: 5,
  659. },
  660. {
  661. name: "AI搜索测试",
  662. query: "人工智能",
  663. nResults: 2,
  664. },
  665. }
  666. for _, tc := range testCases {
  667. t.Run(tc.name, func(t *testing.T) {
  668. // 构建搜索请求
  669. request := SearchRequest{
  670. Query: tc.query,
  671. NResults: tc.nResults,
  672. }
  673. jsonData, err := json.Marshal(request)
  674. if err != nil {
  675. t.Fatalf("序列化搜索请求失败: %v", err)
  676. }
  677. // 发送POST请求到搜索端点
  678. resp, err := http.Post(
  679. fmt.Sprintf("%s/search", baseURL),
  680. "application/json",
  681. bytes.NewBuffer(jsonData),
  682. )
  683. if err != nil {
  684. t.Fatalf("搜索请求失败: %v", err)
  685. }
  686. defer resp.Body.Close()
  687. // 读取响应内容
  688. body, err := io.ReadAll(resp.Body)
  689. if err != nil {
  690. t.Fatalf("读取搜索响应失败: %v", err)
  691. }
  692. t.Logf("搜索响应状态码: %d", resp.StatusCode)
  693. t.Logf("搜索查询: %s", tc.query)
  694. t.Logf("请求结果数量: %d", tc.nResults)
  695. // 验证响应状态码
  696. if resp.StatusCode != http.StatusOK {
  697. t.Errorf("搜索请求失败,期望状态码200,实际状态码: %d", resp.StatusCode)
  698. if len(body) < 500 {
  699. t.Logf("错误响应内容: %s", string(body))
  700. }
  701. return
  702. }
  703. // 验证响应内容不为空
  704. if len(body) == 0 {
  705. t.Error("搜索响应内容为空")
  706. return
  707. }
  708. // 尝试解析JSON响应
  709. var searchResponse SearchResponse
  710. if err := json.Unmarshal(body, &searchResponse); err != nil {
  711. t.Logf("⚠️ 搜索响应不是标准JSON格式: %v", err)
  712. t.Logf("响应内容: %s", string(body))
  713. // 尝试解析为简单的map结构
  714. var simpleResponse map[string]interface{}
  715. if err := json.Unmarshal(body, &simpleResponse); err == nil {
  716. t.Logf("✅ 搜索返回简单JSON格式: %+v", simpleResponse)
  717. } else {
  718. t.Logf("搜索返回非JSON格式响应")
  719. }
  720. return
  721. }
  722. // 验证搜索结果
  723. t.Logf("✅ 搜索成功!")
  724. t.Logf("查询: %s", searchResponse.Query)
  725. t.Logf("总结果数: %d", searchResponse.Total)
  726. t.Logf("返回结果数: %d", len(searchResponse.Results))
  727. // 验证结果数量
  728. if len(searchResponse.Results) > tc.nResults {
  729. t.Logf("⚠️ 返回结果数量(%d)超过请求数量(%d)", len(searchResponse.Results), tc.nResults)
  730. }
  731. // 显示搜索结果详情
  732. for i, result := range searchResponse.Results {
  733. t.Logf("结果 %d:", i+1)
  734. t.Logf(" ID: %s", result.ID)
  735. t.Logf(" 标题: %s", result.Title)
  736. t.Logf(" 内容: %s", truncateString(result.Content, 100))
  737. t.Logf(" 评分: %.4f", result.Score)
  738. if len(result.Metadata) > 0 {
  739. t.Logf(" 元数据: %+v", result.Metadata)
  740. }
  741. }
  742. })
  743. }
  744. }
  745. // truncateString 截断字符串到指定长度
  746. func truncateString(s string, maxLen int) string {
  747. if len(s) <= maxLen {
  748. return s
  749. }
  750. return s[:maxLen] + "..."
  751. }
  752. // TTSRequest 定义TTS请求结构
  753. type TTSRequest struct {
  754. Text string `json:"text"`
  755. }
  756. // TestTTSStreamAPI 测试TTS流式接口
  757. func TestTTSStreamAPI(t *testing.T) {
  758. // 加载测试配置
  759. config := LoadConfig()
  760. baseURL := config.TTSBaseURL
  761. testCases := []struct {
  762. name string
  763. text string
  764. }{
  765. {
  766. name: "短文本测试",
  767. text: "你好,这是一个语音合成测试。",
  768. },
  769. {
  770. name: "中等长度文本测试",
  771. text: "答案依据:《汽车加油站雷电防护装置检测报告综述表》委托单位随检人员在雷电防护装置检测过程中承担着关键的协同与监督职责。",
  772. },
  773. {
  774. name: "长文本测试",
  775. text: "答案依据:《汽车加油站雷电防护装置检测报告综述表》委托单位随检人员在雷电防护装置检测过程中承担着关键的协同与监督职责,其参与过程对检测报告的完整性与合规性具有直接影响。作为检测工作的现场对接方和责任主体之一,委托单位随检人员需全程参与检测实施,确保检测工作在真实、可控的现场环境下开展,有效保障检测数据的真实性与代表性。",
  776. },
  777. }
  778. for _, tc := range testCases {
  779. t.Run(tc.name, func(t *testing.T) {
  780. // 构建TTS请求
  781. request := TTSRequest{
  782. Text: tc.text,
  783. }
  784. jsonData, err := json.Marshal(request)
  785. if err != nil {
  786. t.Fatalf("序列化TTS请求失败: %v", err)
  787. }
  788. t.Logf("发送的TTS请求: %s", string(jsonData))
  789. t.Logf("请求URL: %s/tts/voice", baseURL)
  790. // 创建HTTP客户端,设置较长的超时时间(TTS可能需要较长时间)
  791. client := &http.Client{
  792. Timeout: 60 * time.Second,
  793. }
  794. // 发送POST请求
  795. resp, err := client.Post(
  796. fmt.Sprintf("%s/tts/voice", baseURL),
  797. "application/json",
  798. bytes.NewBuffer(jsonData),
  799. )
  800. if err != nil {
  801. t.Fatalf("发送TTS请求失败: %v", err)
  802. }
  803. defer resp.Body.Close()
  804. t.Logf("TTS响应状态码: %d", resp.StatusCode)
  805. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  806. t.Logf("Content-Length: %s", resp.Header.Get("Content-Length"))
  807. // 验证响应状态码
  808. if resp.StatusCode != http.StatusOK {
  809. body, _ := io.ReadAll(resp.Body)
  810. t.Fatalf("TTS请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(body))
  811. }
  812. // 检查Content-Type是否为音频格式
  813. contentType := resp.Header.Get("Content-Type")
  814. if contentType != "" {
  815. t.Logf("响应Content-Type: %s", contentType)
  816. // WAV格式通常为 "audio/wav" 或 "audio/wave"
  817. if !strings.Contains(contentType, "audio") && !strings.Contains(contentType, "wav") {
  818. t.Logf("⚠️ 警告: Content-Type不是预期的音频格式")
  819. }
  820. }
  821. // 读取流式音频数据
  822. t.Logf("开始接收流式音频数据...")
  823. var audioData bytes.Buffer
  824. totalBytes := 0
  825. chunkCount := 0
  826. // 分块读取数据
  827. buffer := make([]byte, 4096) // 4KB缓冲区
  828. for {
  829. n, err := resp.Body.Read(buffer)
  830. if n > 0 {
  831. audioData.Write(buffer[:n])
  832. totalBytes += n
  833. chunkCount++
  834. // 每读取10个块输出一次进度
  835. if chunkCount%10 == 0 {
  836. t.Logf("已接收 %d 字节音频数据 (块数: %d)", totalBytes, chunkCount)
  837. }
  838. }
  839. if err == io.EOF {
  840. t.Logf("音频数据接收完成")
  841. break
  842. }
  843. if err != nil {
  844. t.Fatalf("读取音频数据失败: %v", err)
  845. }
  846. }
  847. t.Logf("✅ TTS流式响应成功!")
  848. t.Logf("请求文本: %s", tc.text)
  849. t.Logf("文本长度: %d 字符", len(tc.text))
  850. t.Logf("音频数据总大小: %d 字节", totalBytes)
  851. t.Logf("接收块数: %d", chunkCount)
  852. // 验证音频数据不为空
  853. if totalBytes == 0 {
  854. t.Error("音频数据为空")
  855. return
  856. }
  857. // 验证音频数据大小合理性(至少应该有WAV文件头)
  858. if totalBytes < 44 {
  859. t.Errorf("音频数据太小,可能不是有效的WAV文件: %d 字节", totalBytes)
  860. }
  861. // 验证WAV文件头(RIFF格式)
  862. audioBytes := audioData.Bytes()
  863. if len(audioBytes) >= 12 {
  864. // 检查RIFF头
  865. if string(audioBytes[0:4]) == "RIFF" {
  866. t.Logf("✅ 检测到有效的RIFF格式音频文件")
  867. if len(audioBytes) >= 8 {
  868. fileSize := int(audioBytes[4]) | int(audioBytes[5])<<8 | int(audioBytes[6])<<16 | int(audioBytes[7])<<24
  869. t.Logf("WAV文件大小字段: %d 字节", fileSize)
  870. }
  871. if len(audioBytes) >= 12 && string(audioBytes[8:12]) == "WAVE" {
  872. t.Logf("✅ 检测到WAVE格式")
  873. }
  874. } else {
  875. t.Logf("⚠️ 警告: 音频数据不是标准的RIFF格式")
  876. t.Logf("文件头: %x", audioBytes[:min(16, len(audioBytes))])
  877. }
  878. }
  879. // 保存音频文件到本地进行验证
  880. outputFilename := fmt.Sprintf("tts_test_%s.wav", strings.ReplaceAll(tc.name, " ", "_"))
  881. outputFile, err := os.Create(outputFilename)
  882. if err != nil {
  883. t.Fatalf("创建音频输出文件失败: %v", err)
  884. }
  885. defer outputFile.Close()
  886. _, err = outputFile.Write(audioBytes)
  887. if err != nil {
  888. t.Fatalf("写入音频文件失败: %v", err)
  889. }
  890. t.Logf("✅ 音频文件已保存: %s", outputFilename)
  891. t.Logf("文件大小: %d 字节", totalBytes)
  892. // 验证文件是否成功创建
  893. if stat, err := os.Stat(outputFilename); err == nil {
  894. t.Logf("✅ 文件验证成功,实际大小: %d 字节", stat.Size())
  895. if stat.Size() != int64(totalBytes) {
  896. t.Errorf("文件大小不匹配: 期望 %d, 实际 %d", totalBytes, stat.Size())
  897. }
  898. } else {
  899. t.Errorf("文件验证失败: %v", err)
  900. }
  901. })
  902. }
  903. }
  904. // min 返回两个整数中的较小值
  905. func min(a, b int) int {
  906. if a < b {
  907. return a
  908. }
  909. return b
  910. }
  911. // TestTTSConnectivity 测试TTS接口连通性
  912. func TestTTSConnectivity(t *testing.T) {
  913. // 加载测试配置
  914. config := LoadConfig()
  915. baseURL := config.TTSBaseURL
  916. t.Run("TTS接口连通性测试", func(t *testing.T) {
  917. client := &http.Client{
  918. Timeout: 30 * time.Second,
  919. }
  920. t.Logf("测试TTS接口连通性: %s/tts/voice", baseURL)
  921. // 构建简单的测试请求
  922. request := TTSRequest{
  923. Text: "测试",
  924. }
  925. jsonData, err := json.Marshal(request)
  926. if err != nil {
  927. t.Fatalf("序列化测试请求失败: %v", err)
  928. }
  929. // 发送POST请求
  930. resp, err := client.Post(
  931. fmt.Sprintf("%s/tts/voice", baseURL),
  932. "application/json",
  933. bytes.NewBuffer(jsonData),
  934. )
  935. if err != nil {
  936. t.Logf("❌ TTS接口连接失败: %v", err)
  937. t.Logf("可能的原因:")
  938. t.Logf(" - TTS服务未启动")
  939. t.Logf(" - 网络不可达")
  940. t.Logf(" - 端口不正确")
  941. t.Logf(" - 防火墙阻止")
  942. t.Fatalf("TTS接口连通性测试失败: %v", err)
  943. }
  944. defer resp.Body.Close()
  945. t.Logf("✅ TTS接口HTTP连接成功")
  946. t.Logf("响应状态码: %d", resp.StatusCode)
  947. t.Logf("Content-Type: %s", resp.Header.Get("Content-Type"))
  948. // 验证响应状态码
  949. if resp.StatusCode != http.StatusOK {
  950. body, _ := io.ReadAll(resp.Body)
  951. t.Logf("⚠️ TTS服务不可用,状态码: %d", resp.StatusCode)
  952. t.Logf("响应内容: %s", string(body))
  953. // 根据状态码提供具体的错误信息
  954. switch resp.StatusCode {
  955. case 502:
  956. t.Logf("❌ 502 Bad Gateway - TTS后端服务可能未启动或配置错误")
  957. case 503:
  958. t.Logf("❌ 503 Service Unavailable - TTS服务暂时不可用")
  959. case 404:
  960. t.Logf("❌ 404 Not Found - TTS接口路径不存在")
  961. case 500:
  962. t.Logf("❌ 500 Internal Server Error - TTS服务内部错误")
  963. default:
  964. t.Logf("❌ 未知错误状态码: %d", resp.StatusCode)
  965. }
  966. } else {
  967. t.Logf("✅ TTS服务响应正常")
  968. // 读取少量数据验证是否为音频格式
  969. buffer := make([]byte, 1024)
  970. n, err := resp.Body.Read(buffer)
  971. if err != nil && err != io.EOF {
  972. t.Logf("读取响应数据失败: %v", err)
  973. } else if n > 0 {
  974. t.Logf("✅ 成功接收 %d 字节数据", n)
  975. // 检查是否为WAV格式
  976. if n >= 12 {
  977. if string(buffer[0:4]) == "RIFF" {
  978. t.Logf("✅ 检测到WAV格式音频数据")
  979. } else {
  980. t.Logf("⚠️ 数据格式可能不是WAV: %x", buffer[:min(16, n)])
  981. }
  982. }
  983. }
  984. }
  985. })
  986. }
  987. // TestHealthAndSearchIntegration 集成测试:先检查健康状态,再进行搜索
  988. func TestHealthAndSearchIntegration(t *testing.T) {
  989. // 加载测试配置
  990. config := LoadConfig()
  991. baseURL := config.HealthBaseURL
  992. t.Run("健康检查和搜索集成测试", func(t *testing.T) {
  993. client := &http.Client{
  994. Timeout: 15 * time.Second,
  995. }
  996. // 第一步:健康检查
  997. t.Logf("步骤1: 执行健康检查...")
  998. t.Logf("请求URL: %s/health", baseURL)
  999. healthResp, err := client.Post(fmt.Sprintf("%s/health", baseURL), "application/json", nil)
  1000. if err != nil {
  1001. t.Logf("❌ 健康检查请求失败: %v", err)
  1002. t.Logf("错误类型: %T", err)
  1003. // 检查是否是网络相关错误
  1004. if netErr, ok := err.(interface{ Timeout() bool }); ok && netErr.Timeout() {
  1005. t.Logf("⚠️ 这是超时错误")
  1006. }
  1007. // 尝试更详细的错误信息
  1008. if urlErr, ok := err.(*url.Error); ok {
  1009. t.Logf("URL错误详情: %+v", urlErr)
  1010. if urlErr.Err != nil {
  1011. t.Logf("底层错误: %v", urlErr.Err)
  1012. }
  1013. }
  1014. t.Fatalf("健康检查失败: %v", err)
  1015. }
  1016. defer healthResp.Body.Close()
  1017. // 读取响应内容
  1018. healthBody, err := io.ReadAll(healthResp.Body)
  1019. if err != nil {
  1020. t.Logf("读取健康检查响应失败: %v", err)
  1021. }
  1022. t.Logf("健康检查响应状态码: %d", healthResp.StatusCode)
  1023. t.Logf("响应头: %+v", healthResp.Header)
  1024. if len(healthBody) > 0 {
  1025. t.Logf("响应内容: %s", string(healthBody))
  1026. }
  1027. if healthResp.StatusCode != http.StatusOK {
  1028. t.Fatalf("健康检查失败,状态码: %d", healthResp.StatusCode)
  1029. }
  1030. t.Logf("✅ 健康检查通过")
  1031. // 第二步:执行搜索
  1032. t.Logf("步骤2: 执行搜索测试...")
  1033. searchRequest := SearchRequest{
  1034. Query: "技术",
  1035. NResults: 3,
  1036. }
  1037. jsonData, err := json.Marshal(searchRequest)
  1038. if err != nil {
  1039. t.Fatalf("序列化搜索请求失败: %v", err)
  1040. }
  1041. searchResp, err := client.Post(
  1042. fmt.Sprintf("%s/search", baseURL),
  1043. "application/json",
  1044. bytes.NewBuffer(jsonData),
  1045. )
  1046. if err != nil {
  1047. t.Fatalf("搜索请求失败: %v", err)
  1048. }
  1049. defer searchResp.Body.Close()
  1050. body, err := io.ReadAll(searchResp.Body)
  1051. if err != nil {
  1052. t.Fatalf("读取搜索响应失败: %v", err)
  1053. }
  1054. if searchResp.StatusCode != http.StatusOK {
  1055. t.Errorf("搜索失败,状态码: %d", searchResp.StatusCode)
  1056. if len(body) < 200 {
  1057. t.Logf("错误响应: %s", string(body))
  1058. }
  1059. } else {
  1060. t.Logf("✅ 搜索功能正常")
  1061. t.Logf("响应长度: %d 字节", len(body))
  1062. }
  1063. t.Logf("✅ 集成测试完成")
  1064. })
  1065. }
  1066. // TestNetworkConnectivity 测试网络连通性
  1067. func TestNetworkConnectivity(t *testing.T) {
  1068. // 加载测试配置
  1069. config := LoadConfig()
  1070. baseURL := config.HealthBaseURL
  1071. t.Run("网络连通性测试", func(t *testing.T) {
  1072. // 解析URL
  1073. parsedURL, err := url.Parse(baseURL)
  1074. if err != nil {
  1075. t.Fatalf("解析URL失败: %v", err)
  1076. }
  1077. t.Logf("测试目标: %s", baseURL)
  1078. t.Logf("协议: %s", parsedURL.Scheme)
  1079. t.Logf("主机: %s", parsedURL.Host)
  1080. t.Logf("端口: %s", parsedURL.Port())
  1081. // 测试TCP连接
  1082. conn, err := net.DialTimeout("tcp", parsedURL.Host, 5*time.Second)
  1083. if err != nil {
  1084. t.Logf("❌ TCP连接失败: %v", err)
  1085. t.Logf("可能的原因:")
  1086. t.Logf(" - 服务器未启动")
  1087. t.Logf(" - 防火墙阻止")
  1088. t.Logf(" - 网络不可达")
  1089. t.Logf(" - 端口不正确")
  1090. } else {
  1091. t.Logf("✅ TCP连接成功")
  1092. conn.Close()
  1093. }
  1094. // 测试HTTP连接
  1095. client := &http.Client{
  1096. Timeout: 10 * time.Second,
  1097. }
  1098. // 尝试简单的HEAD请求
  1099. resp, err := client.Head(baseURL)
  1100. if err != nil {
  1101. t.Logf("❌ HTTP HEAD请求失败: %v", err)
  1102. } else {
  1103. t.Logf("✅ HTTP连接成功,状态码: %d", resp.StatusCode)
  1104. resp.Body.Close()
  1105. }
  1106. // 尝试POST请求到根路径
  1107. resp, err = client.Post(baseURL, "application/json", nil)
  1108. if err != nil {
  1109. t.Logf("❌ HTTP POST请求失败: %v", err)
  1110. } else {
  1111. t.Logf("✅ HTTP POST连接成功,状态码: %d", resp.StatusCode)
  1112. resp.Body.Close()
  1113. }
  1114. })
  1115. }