test_conversation_api.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #!/usr/bin/env python3
  2. """
  3. 测试新增的对话历史查询API
  4. """
  5. import requests
  6. import json
  7. import time
  8. import sys
  9. from typing import Dict, Any
  10. API_BASE = "http://localhost:8000"
  11. def test_health_check():
  12. """测试健康检查"""
  13. print("🔍 测试健康检查...")
  14. try:
  15. response = requests.get(f"{API_BASE}/health")
  16. result = response.json()
  17. if response.status_code == 200 and result.get("status") == "healthy":
  18. print("✅ 健康检查通过")
  19. return True
  20. else:
  21. print(f"❌ 健康检查失败: {result}")
  22. return False
  23. except Exception as e:
  24. print(f"❌ 健康检查异常: {e}")
  25. return False
  26. def create_test_conversations(user_id: str) -> list:
  27. """创建测试对话"""
  28. print(f"\n💬 为用户 {user_id} 创建测试对话...")
  29. test_questions = [
  30. "请问哪个高速服务区的档口数量最多?",
  31. "南城服务区有多少个餐饮档口?",
  32. "请查询收入最高的服务区",
  33. "你好,请介绍一下系统功能"
  34. ]
  35. thread_ids = []
  36. for i, question in enumerate(test_questions):
  37. print(f" 📝 创建对话 {i+1}: {question[:30]}...")
  38. try:
  39. response = requests.post(
  40. f"{API_BASE}/api/chat",
  41. json={
  42. "question": question,
  43. "user_id": user_id
  44. }
  45. )
  46. if response.status_code == 200:
  47. result = response.json()
  48. if result.get("success"):
  49. thread_id = result.get("thread_id")
  50. thread_ids.append(thread_id)
  51. print(f" ✅ 创建成功: {thread_id}")
  52. else:
  53. print(f" ❌ 创建失败: {result.get('error')}")
  54. else:
  55. print(f" ❌ HTTP错误: {response.status_code}")
  56. # 稍微延迟,确保时间戳不同
  57. time.sleep(1)
  58. except Exception as e:
  59. print(f" ❌ 异常: {e}")
  60. print(f"🎯 共创建了 {len(thread_ids)} 个测试对话")
  61. return thread_ids
  62. def test_get_user_conversations(user_id: str, limit: int = 5):
  63. """测试获取用户对话列表"""
  64. print(f"\n📋 测试获取用户 {user_id} 的对话列表 (limit={limit})...")
  65. try:
  66. response = requests.get(f"{API_BASE}/api/v0/react/users/{user_id}/conversations?limit={limit}")
  67. print(f" 状态码: {response.status_code}")
  68. if response.status_code == 200:
  69. result = response.json()
  70. if result.get("success"):
  71. data = result.get("data", {})
  72. conversations = data.get("conversations", [])
  73. print(f"✅ 成功获取 {len(conversations)} 个对话")
  74. print(f" 用户ID: {data.get('user_id')}")
  75. print(f" 总数量: {data.get('total_count')}")
  76. print(f" 限制数量: {data.get('limit')}")
  77. # 显示对话列表
  78. for i, conv in enumerate(conversations):
  79. print(f"\n 📝 对话 {i+1}:")
  80. print(f" Thread ID: {conv.get('thread_id')}")
  81. print(f" 时间戳: {conv.get('formatted_time')}")
  82. print(f" 消息数: {conv.get('message_count')}")
  83. print(f" 预览: {conv.get('conversation_preview')}")
  84. print(f" 最后消息: {conv.get('last_message', '')[:50]}...")
  85. return conversations
  86. else:
  87. print(f"❌ API返回错误: {result.get('error')}")
  88. return []
  89. else:
  90. print(f"❌ HTTP错误: {response.status_code}")
  91. try:
  92. error_detail = response.json()
  93. print(f" 错误详情: {error_detail}")
  94. except:
  95. print(f" 响应内容: {response.text}")
  96. return []
  97. except Exception as e:
  98. print(f"❌ 请求异常: {e}")
  99. return []
  100. def test_get_conversation_detail(user_id: str, thread_id: str):
  101. """测试获取对话详情"""
  102. print(f"\n📖 测试获取对话详情: {thread_id}...")
  103. try:
  104. response = requests.get(f"{API_BASE}/api/v0/react/users/{user_id}/conversations/{thread_id}")
  105. print(f" 状态码: {response.status_code}")
  106. if response.status_code == 200:
  107. result = response.json()
  108. if result.get("success"):
  109. data = result.get("data", {})
  110. messages = data.get("messages", [])
  111. print(f"✅ 成功获取对话详情")
  112. print(f" 用户ID: {data.get('user_id')}")
  113. print(f" Thread ID: {data.get('thread_id')}")
  114. print(f" 消息数量: {data.get('message_count')}")
  115. # 显示消息历史
  116. print(f"\n 📜 消息历史:")
  117. for i, msg in enumerate(messages):
  118. msg_type = msg.get('type', 'unknown')
  119. content = msg.get('content', '')
  120. # 限制显示长度
  121. display_content = content[:100] + "..." if len(content) > 100 else content
  122. print(f" [{i+1}] {msg_type.upper()}: {display_content}")
  123. # 如果有工具调用,显示相关信息
  124. if msg.get('tool_calls'):
  125. print(f" 🔧 包含工具调用")
  126. return data
  127. else:
  128. print(f"❌ API返回错误: {result.get('error')}")
  129. return None
  130. else:
  131. print(f"❌ HTTP错误: {response.status_code}")
  132. try:
  133. error_detail = response.json()
  134. print(f" 错误详情: {error_detail}")
  135. except:
  136. print(f" 响应内容: {response.text}")
  137. return None
  138. except Exception as e:
  139. print(f"❌ 请求异常: {e}")
  140. return None
  141. def test_invalid_cases(user_id: str):
  142. """测试无效情况的处理"""
  143. print(f"\n⚠️ 测试错误处理...")
  144. # 测试1: 不存在的用户
  145. print(" 测试不存在的用户...")
  146. response = requests.get(f"{API_BASE}/api/v0/react/users/nonexistent_user/conversations")
  147. print(f" 状态码: {response.status_code} (应该是200,返回空列表)")
  148. # 测试2: 不匹配的thread_id
  149. print(" 测试不匹配的thread_id...")
  150. response = requests.get(f"{API_BASE}/api/v0/react/users/{user_id}/conversations/wronguser:20250115103000001")
  151. print(f" 状态码: {response.status_code} (应该是400)")
  152. # 测试3: 超出限制的limit参数
  153. print(" 测试超出限制的limit参数...")
  154. response = requests.get(f"{API_BASE}/api/v0/react/users/{user_id}/conversations?limit=100")
  155. if response.status_code == 200:
  156. result = response.json()
  157. actual_limit = result.get("data", {}).get("limit", 0)
  158. print(f" 实际limit: {actual_limit} (应该被限制为50)")
  159. def main():
  160. """主测试流程"""
  161. print("🚀 开始测试对话历史查询API")
  162. print("=" * 60)
  163. # 1. 健康检查
  164. if not test_health_check():
  165. print("❌ 服务不可用,退出测试")
  166. sys.exit(1)
  167. # 2. 设置测试用户
  168. user_id = "test_user"
  169. print(f"\n🎯 使用测试用户: {user_id}")
  170. # 3. 创建测试对话
  171. thread_ids = create_test_conversations(user_id)
  172. if not thread_ids:
  173. print("❌ 未能创建测试对话,跳过后续测试")
  174. return
  175. # 4. 测试获取对话列表
  176. conversations = test_get_user_conversations(user_id, limit=3)
  177. # 5. 测试获取对话详情
  178. if conversations and len(conversations) > 0:
  179. test_thread_id = conversations[0].get("thread_id")
  180. test_get_conversation_detail(user_id, test_thread_id)
  181. # 6. 测试边界情况
  182. test_invalid_cases(user_id)
  183. print("\n🎉 测试完成!")
  184. print("=" * 60)
  185. if __name__ == "__main__":
  186. main()