Nenhuma descrição
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

session_messages_test.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. package main
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "testing"
  10. "time"
  11. "git.x2erp.com/qdy/go-svc-code/internal/opencode"
  12. )
  13. // TestDirectOpenCodeMessages 直接调用opencode API (8787端口) 获取会话消息
  14. func TestDirectOpenCodeMessages(t *testing.T) {
  15. // 外部已启动的OpenCode服务端口
  16. externalOpenCodePort := 8787
  17. opencodeURL := fmt.Sprintf("http://127.0.0.1:%d", externalOpenCodePort)
  18. // 检查OpenCode服务是否运行
  19. if !isServiceRunningForMessages(t, opencodeURL) {
  20. t.Skipf("OpenCode服务未运行在 %s,跳过测试", opencodeURL)
  21. }
  22. t.Logf("🚀 开始测试直接调用OpenCode API获取消息")
  23. t.Logf("OpenCode URL: %s", opencodeURL)
  24. // 使用现有的测试会话ID
  25. sessionID := "ses_3aa9a94dfffeLIdWcLHCG97m7z"
  26. t.Logf("测试会话ID: %s", sessionID)
  27. // 1. 使用DirectClient调用(测试SDK接口)
  28. t.Run("SDKClient", func(t *testing.T) {
  29. testDirectClientMessages(t, externalOpenCodePort, sessionID)
  30. })
  31. // 2. 直接HTTP调用(测试原始API)
  32. t.Run("RawHTTP", func(t *testing.T) {
  33. testRawHTTPMessages(t, opencodeURL, sessionID)
  34. })
  35. }
  36. // testDirectClientMessages 使用DirectClient测试获取消息
  37. func testDirectClientMessages(t *testing.T, port int, sessionID string) {
  38. // 创建客户端
  39. client, err := opencode.NewDirectClient(port)
  40. if err != nil {
  41. t.Fatalf("❌ 创建OpenCode客户端失败: %v", err)
  42. }
  43. t.Logf("✅ 创建OpenCode客户端成功,基础URL: %s", client.GetBaseURL())
  44. ctx := context.Background()
  45. // 测试不带limit参数
  46. t.Log("📝 测试获取消息(不带limit)")
  47. messages, err := client.GetSessionMessages(ctx, sessionID, 0)
  48. if err != nil {
  49. t.Errorf("❌ 获取会话消息失败: %v", err)
  50. return
  51. }
  52. t.Logf("✅ 获取到 %d 条消息", len(messages))
  53. // 打印消息摘要
  54. for i, msg := range messages {
  55. t.Logf(" 消息[%d]: ID=%s, 角色=%s", i+1, extractMessageID(msg), extractMessageRole(msg))
  56. if i < 3 && len(messages) > 3 { // 只打印前3条
  57. if content := extractMessageContent(msg); content != "" {
  58. t.Logf(" 内容预览: %.100s...", content)
  59. }
  60. }
  61. }
  62. // 测试带limit参数
  63. t.Log("📝 测试获取消息(limit=5)")
  64. messagesLimited, err := client.GetSessionMessages(ctx, sessionID, 5)
  65. if err != nil {
  66. t.Errorf("❌ 获取限制数量的会话消息失败: %v", err)
  67. return
  68. }
  69. t.Logf("✅ 获取到 %d 条消息(限制5条)", len(messagesLimited))
  70. if len(messages) > 0 && len(messagesLimited) > 0 {
  71. if len(messagesLimited) > 5 {
  72. t.Errorf("❌ 消息数量超过限制: %d > 5", len(messagesLimited))
  73. }
  74. }
  75. }
  76. // testRawHTTPMessages 直接HTTP调用测试获取消息
  77. func testRawHTTPMessages(t *testing.T, baseURL, sessionID string) {
  78. // 构造URL
  79. url := fmt.Sprintf("%s/session/%s/message", baseURL, sessionID)
  80. t.Logf("📡 调用原始API: %s", url)
  81. // 发送HTTP请求
  82. client := &http.Client{Timeout: 10 * time.Second}
  83. req, err := http.NewRequest("GET", url, nil)
  84. if err != nil {
  85. t.Fatalf("❌ 创建请求失败: %v", err)
  86. }
  87. req.Header.Set("Accept", "application/json")
  88. resp, err := client.Do(req)
  89. if err != nil {
  90. t.Fatalf("❌ HTTP请求失败: %v", err)
  91. }
  92. defer resp.Body.Close()
  93. t.Logf("📊 响应状态码: %d", resp.StatusCode)
  94. if resp.StatusCode != http.StatusOK {
  95. body, _ := io.ReadAll(resp.Body)
  96. t.Fatalf("❌ 获取会话消息失败,状态码: %d, 响应体: %s", resp.StatusCode, string(body))
  97. }
  98. // 解析响应
  99. body, err := io.ReadAll(resp.Body)
  100. if err != nil {
  101. t.Fatalf("❌ 读取响应体失败: %v", err)
  102. }
  103. // 尝试解析为SessionMessage数组
  104. var messages []opencode.SessionMessage
  105. if err := json.Unmarshal(body, &messages); err != nil {
  106. t.Errorf("❌ 解析消息响应失败: %v", err)
  107. t.Logf("原始响应: %s", string(body[:minForMessagesTest(500, len(body))]))
  108. return
  109. }
  110. t.Logf("✅ 解析成功,获取到 %d 条消息", len(messages))
  111. // 验证消息结构
  112. for i, msg := range messages {
  113. if extractMessageID(msg) == "" {
  114. t.Errorf("❌ 消息[%d]缺少ID", i)
  115. }
  116. if extractMessageRole(msg) == "" {
  117. t.Errorf("❌ 消息[%d]缺少角色", i)
  118. }
  119. }
  120. // 测试带limit参数
  121. urlWithLimit := fmt.Sprintf("%s?limit=3", url)
  122. t.Logf("📡 调用带limit的API: %s", urlWithLimit)
  123. reqLimit, err := http.NewRequest("GET", urlWithLimit, nil)
  124. if err != nil {
  125. t.Errorf("❌ 创建带limit的请求失败: %v", err)
  126. return
  127. }
  128. reqLimit.Header.Set("Accept", "application/json")
  129. respLimit, err := client.Do(reqLimit)
  130. if err != nil {
  131. t.Errorf("❌ HTTP请求(带limit)失败: %v", err)
  132. return
  133. }
  134. defer respLimit.Body.Close()
  135. if respLimit.StatusCode == http.StatusOK {
  136. bodyLimit, _ := io.ReadAll(respLimit.Body)
  137. var messagesLimit []opencode.SessionMessage
  138. if err := json.Unmarshal(bodyLimit, &messagesLimit); err == nil {
  139. t.Logf("✅ 带limit获取到 %d 条消息", len(messagesLimit))
  140. if len(messagesLimit) > 3 {
  141. t.Errorf("❌ 带limit的消息数量超过限制: %d > 3", len(messagesLimit))
  142. }
  143. }
  144. }
  145. }
  146. // TestSvcCodeMessagesAPI 通过svc-code API (8020端口) 获取会话消息
  147. func TestSvcCodeMessagesAPI(t *testing.T) {
  148. // svc-code服务地址
  149. svcCodeURL := "http://localhost:8020"
  150. // 检查svc-code服务是否运行
  151. if !isServiceRunningForMessages(t, svcCodeURL) {
  152. t.Skipf("svc-code服务未运行在 %s,跳过测试", svcCodeURL)
  153. }
  154. t.Logf("🚀 开始测试通过svc-code API获取消息")
  155. t.Logf("svc-code URL: %s", svcCodeURL)
  156. // 使用现有的测试会话ID
  157. sessionID := "ses_3aa9a94dfffeLIdWcLHCG97m7z"
  158. t.Logf("测试会话ID: %s", sessionID)
  159. // 1. 用户登录获取token
  160. token, err := loginAndGetTokenForMessagesTest(t, svcCodeURL)
  161. if err != nil {
  162. t.Fatalf("❌ 登录失败: %v", err)
  163. }
  164. t.Logf("✅ 获取到Token: %s...", token[:minForMessagesTest(20, len(token))])
  165. // 2. 测试不带limit参数
  166. t.Run("WithoutLimit", func(t *testing.T) {
  167. testSvcCodeMessages(t, svcCodeURL, token, sessionID, 0)
  168. })
  169. // 3. 测试带limit参数
  170. t.Run("WithLimit", func(t *testing.T) {
  171. testSvcCodeMessages(t, svcCodeURL, token, sessionID, 10)
  172. })
  173. // 4. 测试无效token
  174. t.Run("InvalidToken", func(t *testing.T) {
  175. testInvalidTokenForMessages(t, svcCodeURL, sessionID)
  176. })
  177. // 5. 测试无效sessionID
  178. t.Run("InvalidSessionID", func(t *testing.T) {
  179. testInvalidSessionIDForMessages(t, svcCodeURL, token)
  180. })
  181. }
  182. // testSvcCodeMessages 测试svc-code获取消息API
  183. func testSvcCodeMessages(t *testing.T, baseURL, token, sessionID string, limit int) {
  184. // 构造URL
  185. url := fmt.Sprintf("%s/api/session/messages", baseURL)
  186. // 创建请求
  187. req, err := http.NewRequest("GET", url, nil)
  188. if err != nil {
  189. t.Fatalf("❌ 创建请求失败: %v", err)
  190. }
  191. // 添加查询参数
  192. q := req.URL.Query()
  193. q.Add("sessionID", sessionID)
  194. if limit > 0 {
  195. q.Add("limit", fmt.Sprintf("%d", limit))
  196. }
  197. req.URL.RawQuery = q.Encode()
  198. // 添加认证头
  199. req.Header.Set("Authorization", "Bearer "+token)
  200. req.Header.Set("Accept", "application/json")
  201. t.Logf("📡 调用svc-code API: %s", req.URL.String())
  202. // 发送请求
  203. client := &http.Client{Timeout: 10 * time.Second}
  204. resp, err := client.Do(req)
  205. if err != nil {
  206. t.Fatalf("❌ HTTP请求失败: %v", err)
  207. }
  208. defer resp.Body.Close()
  209. t.Logf("📊 响应状态码: %d", resp.StatusCode)
  210. body, err := io.ReadAll(resp.Body)
  211. if err != nil {
  212. t.Fatalf("❌ 读取响应体失败: %v", err)
  213. }
  214. // 解析响应
  215. var result struct {
  216. Success bool `json:"success"`
  217. Message string `json:"message"`
  218. Data struct {
  219. Messages []opencode.SessionMessage `json:"messages"`
  220. Count int `json:"count"`
  221. } `json:"data"`
  222. }
  223. if err := json.Unmarshal(body, &result); err != nil {
  224. t.Errorf("❌ 解析响应失败: %v", err)
  225. t.Logf("原始响应: %s", string(body[:minForMessagesTest(500, len(body))]))
  226. return
  227. }
  228. if !result.Success {
  229. t.Errorf("❌ API调用失败: %s", result.Message)
  230. return
  231. }
  232. t.Logf("✅ 获取成功!消息数量: %d, 总计: %d",
  233. len(result.Data.Messages), result.Data.Count)
  234. // 验证数据一致性
  235. if result.Data.Count != len(result.Data.Messages) {
  236. t.Errorf("❌ 数据不一致: Count=%d, Messages长度=%d",
  237. result.Data.Count, len(result.Data.Messages))
  238. }
  239. // 打印消息摘要
  240. for i, msg := range result.Data.Messages {
  241. t.Logf(" 消息[%d]: ID=%s, 角色=%s", i+1, extractMessageID(msg), extractMessageRole(msg))
  242. if i < 2 && len(result.Data.Messages) > 2 {
  243. if content := extractMessageContent(msg); content != "" {
  244. t.Logf(" 内容预览: %.100s...", content)
  245. }
  246. }
  247. }
  248. // 验证limit参数效果
  249. if limit > 0 && len(result.Data.Messages) > limit {
  250. t.Errorf("❌ 消息数量超过限制: %d > %d", len(result.Data.Messages), limit)
  251. }
  252. }
  253. // testInvalidTokenForMessages 测试无效token
  254. func testInvalidTokenForMessages(t *testing.T, baseURL, sessionID string) {
  255. url := fmt.Sprintf("%s/api/session/messages?sessionID=%s", baseURL, sessionID)
  256. req, err := http.NewRequest("GET", url, nil)
  257. if err != nil {
  258. t.Fatalf("创建请求失败: %v", err)
  259. }
  260. // 使用无效token
  261. req.Header.Set("Authorization", "Bearer invalid_token_12345")
  262. client := &http.Client{Timeout: 5 * time.Second}
  263. resp, err := client.Do(req)
  264. if err != nil {
  265. t.Fatalf("HTTP请求失败: %v", err)
  266. }
  267. defer resp.Body.Close()
  268. // 应该返回401或403
  269. if resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden {
  270. t.Errorf("预期认证错误状态码(401/403),实际: %d", resp.StatusCode)
  271. body, _ := io.ReadAll(resp.Body)
  272. t.Logf("响应体: %s", string(body))
  273. } else {
  274. t.Logf("✅ 无效token测试通过,返回状态码: %d", resp.StatusCode)
  275. }
  276. }
  277. // testInvalidSessionIDForMessages 测试无效sessionID
  278. func testInvalidSessionIDForMessages(t *testing.T, baseURL, token string) {
  279. invalidSessionID := "ses_invalid_12345"
  280. url := fmt.Sprintf("%s/api/session/messages?sessionID=%s", baseURL, invalidSessionID)
  281. req, err := http.NewRequest("GET", url, nil)
  282. if err != nil {
  283. t.Fatalf("创建请求失败: %v", err)
  284. }
  285. req.Header.Set("Authorization", "Bearer "+token)
  286. client := &http.Client{Timeout: 5 * time.Second}
  287. resp, err := client.Do(req)
  288. if err != nil {
  289. t.Fatalf("HTTP请求失败: %v", err)
  290. }
  291. defer resp.Body.Close()
  292. body, err := io.ReadAll(resp.Body)
  293. if err != nil {
  294. t.Fatalf("读取响应体失败: %v", err)
  295. }
  296. var result struct {
  297. Success bool `json:"success"`
  298. Message string `json:"message"`
  299. }
  300. if err := json.Unmarshal(body, &result); err != nil {
  301. t.Errorf("解析响应失败: %v", err)
  302. return
  303. }
  304. if result.Success {
  305. t.Errorf("无效sessionID应该返回失败,实际成功")
  306. } else {
  307. t.Logf("✅ 无效sessionID测试通过,错误信息: %s", result.Message)
  308. }
  309. }
  310. // loginAndGetTokenForMessagesTest 登录获取token
  311. func loginAndGetTokenForMessagesTest(t *testing.T, baseURL string) (string, error) {
  312. loginURL := baseURL + "/api/auth/login"
  313. loginData := map[string]string{
  314. "user_id": "test-user-001",
  315. "password": "password123",
  316. }
  317. jsonData, _ := json.Marshal(loginData)
  318. resp, err := http.Post(loginURL, "application/json", bytes.NewBuffer(jsonData))
  319. if err != nil {
  320. return "", fmt.Errorf("登录请求失败: %v", err)
  321. }
  322. defer resp.Body.Close()
  323. if resp.StatusCode != http.StatusOK {
  324. bodyBytes, _ := io.ReadAll(resp.Body)
  325. return "", fmt.Errorf("登录失败 (状态码 %d): %s", resp.StatusCode, string(bodyBytes))
  326. }
  327. var result struct {
  328. Success bool `json:"success"`
  329. Data string `json:"data"`
  330. Message string `json:"message"`
  331. }
  332. bodyBytes, _ := io.ReadAll(resp.Body)
  333. if err := json.Unmarshal(bodyBytes, &result); err != nil {
  334. return "", fmt.Errorf("解析响应失败: %v", err)
  335. }
  336. if !result.Success {
  337. return "", fmt.Errorf("登录失败: %s", result.Message)
  338. }
  339. return result.Data, nil
  340. }
  341. // isServiceRunningForMessages 检查服务是否运行
  342. func isServiceRunningForMessages(t *testing.T, url string) bool {
  343. client := &http.Client{Timeout: 3 * time.Second}
  344. // 尝试多个端点
  345. endpoints := []string{
  346. "/global/health", // opencode健康检查
  347. "/api/auth/health", // svc-code健康检查
  348. "/api/health", // 其他健康检查
  349. "", // 根路径
  350. }
  351. for _, endpoint := range endpoints {
  352. fullURL := url + endpoint
  353. resp, err := client.Get(fullURL)
  354. if err == nil {
  355. resp.Body.Close()
  356. if resp.StatusCode == http.StatusOK {
  357. t.Logf("✅ 服务运行正常: %s (状态码: %d)", fullURL, resp.StatusCode)
  358. return true
  359. }
  360. }
  361. }
  362. return false
  363. }
  364. // extractMessageID 从SessionMessage提取消息ID
  365. func extractMessageID(msg opencode.SessionMessage) string {
  366. if msg.Info != nil {
  367. if id, ok := msg.Info["id"].(string); ok {
  368. return id
  369. }
  370. }
  371. return ""
  372. }
  373. // extractMessageRole 从SessionMessage提取消息角色
  374. func extractMessageRole(msg opencode.SessionMessage) string {
  375. if msg.Info != nil {
  376. if role, ok := msg.Info["role"].(string); ok {
  377. return role
  378. }
  379. }
  380. return ""
  381. }
  382. // extractMessageContent 从SessionMessage提取消息内容
  383. func extractMessageContent(msg opencode.SessionMessage) string {
  384. if len(msg.Parts) > 0 {
  385. for _, part := range msg.Parts {
  386. if text, ok := part["text"].(string); ok && text != "" {
  387. return text
  388. }
  389. }
  390. }
  391. return ""
  392. }
  393. // minForMessagesTest 返回两个整数的最小值
  394. func minForMessagesTest(a, b int) int {
  395. if a < b {
  396. return a
  397. }
  398. return b
  399. }