test_validation_improvements.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. #!/usr/bin/env python3
  2. """
  3. 测试 API 参数验证和错误处理改进
  4. 验证JSON格式错误处理和用户ID一致性校验
  5. """
  6. import requests
  7. import json
  8. def test_validation_improvements():
  9. """测试参数验证改进"""
  10. api_url = "http://localhost:8000/api/chat"
  11. print("🧪 开始测试 API 参数验证改进...")
  12. print("=" * 80)
  13. # 测试用例1: JSON格式错误 - 尾随逗号
  14. print(f"\n📋 测试用例1: JSON格式错误(尾随逗号)")
  15. malformed_json = '{ "question": "测试问题", "user_id": "wang01", "thread_id": "wang01:20250714102158117", }'
  16. try:
  17. response = requests.post(
  18. api_url,
  19. data=malformed_json, # 使用data而不是json,模拟原始JSON字符串
  20. headers={"Content-Type": "application/json"},
  21. timeout=10
  22. )
  23. print(f"📊 响应状态码: {response.status_code}")
  24. result = response.json()
  25. print(f"📝 响应内容: {json.dumps(result, ensure_ascii=False, indent=2)}")
  26. # 验证是否是400错误且有明确的错误信息
  27. if response.status_code == 400 and "JSON格式" in result.get("error", ""):
  28. print("✅ JSON格式错误处理正确")
  29. else:
  30. print("❌ JSON格式错误处理有问题")
  31. except Exception as e:
  32. print(f"❌ 测试JSON格式错误失败: {e}")
  33. # 测试用例2: 用户ID不一致 - thread_id
  34. print(f"\n📋 测试用例2: 用户ID不一致(thread_id)")
  35. test_case_2 = {
  36. "question": "测试用户ID不一致",
  37. "user_id": "alice",
  38. "thread_id": "bob:20250714120000001" # 用户ID不匹配
  39. }
  40. try:
  41. response = requests.post(
  42. api_url,
  43. json=test_case_2,
  44. headers={"Content-Type": "application/json"},
  45. timeout=10
  46. )
  47. print(f"📊 响应状态码: {response.status_code}")
  48. result = response.json()
  49. print(f"📝 响应内容: {json.dumps(result, ensure_ascii=False, indent=2)}")
  50. # 验证是否正确检测到用户ID不一致
  51. if response.status_code == 400 and "会话归属验证失败" in result.get("error", ""):
  52. print("✅ 用户ID一致性校验正确")
  53. else:
  54. print("❌ 用户ID一致性校验有问题")
  55. except Exception as e:
  56. print(f"❌ 测试用户ID一致性失败: {e}")
  57. # 测试用例3: 用户ID不一致 - conversation_id
  58. print(f"\n📋 测试用例3: 用户ID不一致(conversation_id)")
  59. test_case_3 = {
  60. "question": "测试conversation_id用户ID不一致",
  61. "user_id": "charlie",
  62. "conversation_id": "david:20250714120000002" # 用户ID不匹配
  63. }
  64. try:
  65. response = requests.post(
  66. api_url,
  67. json=test_case_3,
  68. headers={"Content-Type": "application/json"},
  69. timeout=10
  70. )
  71. print(f"📊 响应状态码: {response.status_code}")
  72. result = response.json()
  73. print(f"📝 响应内容: {json.dumps(result, ensure_ascii=False, indent=2)}")
  74. if response.status_code == 400 and "会话归属验证失败" in result.get("error", ""):
  75. print("✅ conversation_id用户ID一致性校验正确")
  76. else:
  77. print("❌ conversation_id用户ID一致性校验有问题")
  78. except Exception as e:
  79. print(f"❌ 测试conversation_id用户ID一致性失败: {e}")
  80. # 测试用例4: 会话ID格式错误
  81. print(f"\n📋 测试用例4: 会话ID格式错误(缺少冒号)")
  82. test_case_4 = {
  83. "question": "测试会话ID格式错误",
  84. "user_id": "eve",
  85. "thread_id": "eve20250714120000003" # 缺少冒号
  86. }
  87. try:
  88. response = requests.post(
  89. api_url,
  90. json=test_case_4,
  91. headers={"Content-Type": "application/json"},
  92. timeout=10
  93. )
  94. print(f"📊 响应状态码: {response.status_code}")
  95. result = response.json()
  96. print(f"📝 响应内容: {json.dumps(result, ensure_ascii=False, indent=2)}")
  97. if response.status_code == 400 and "会话ID格式无效" in result.get("error", ""):
  98. print("✅ 会话ID格式校验正确")
  99. else:
  100. print("❌ 会话ID格式校验有问题")
  101. except Exception as e:
  102. print(f"❌ 测试会话ID格式错误失败: {e}")
  103. # 测试用例5: 正常情况 - 验证修改不影响正常流程
  104. print(f"\n📋 测试用例5: 正常情况(验证修改不影响正常流程)")
  105. test_case_5 = {
  106. "question": "这是一个正常的测试问题",
  107. "user_id": "frank",
  108. "thread_id": "frank:20250714120000005"
  109. }
  110. try:
  111. response = requests.post(
  112. api_url,
  113. json=test_case_5,
  114. headers={"Content-Type": "application/json"},
  115. timeout=30
  116. )
  117. print(f"📊 响应状态码: {response.status_code}")
  118. if response.status_code == 200:
  119. result = response.json()
  120. print("✅ 正常请求处理成功")
  121. print(f" - conversation_id: {result.get('data', {}).get('conversation_id')}")
  122. print(f" - user_id: {result.get('data', {}).get('user_id')}")
  123. else:
  124. print(f"❌ 正常请求处理失败: {response.text}")
  125. except Exception as e:
  126. print(f"❌ 测试正常情况失败: {e}")
  127. # 测试用例6: guest用户不受限制
  128. print(f"\n📋 测试用例6: guest用户不受会话ID限制")
  129. test_case_6 = {
  130. "question": "guest用户测试",
  131. "user_id": "guest",
  132. "thread_id": "someuser:20250714120000006" # guest用户应该不受限制
  133. }
  134. try:
  135. response = requests.post(
  136. api_url,
  137. json=test_case_6,
  138. headers={"Content-Type": "application/json"},
  139. timeout=30
  140. )
  141. print(f"📊 响应状态码: {response.status_code}")
  142. if response.status_code == 200:
  143. print("✅ guest用户不受会话ID限制,处理正确")
  144. else:
  145. result = response.json()
  146. print(f"❌ guest用户处理有问题: {result}")
  147. except Exception as e:
  148. print(f"❌ 测试guest用户失败: {e}")
  149. print("\n" + "=" * 80)
  150. print("🎯 测试完成!")
  151. print("\n💡 预期结果总结:")
  152. print("1. JSON格式错误应该返回400错误,明确指出JSON格式问题")
  153. print("2. 用户ID与thread_id/conversation_id不一致应该返回400错误")
  154. print("3. 会话ID格式错误应该返回400错误")
  155. print("4. 正常请求应该不受影响")
  156. print("5. guest用户不受会话ID限制")
  157. def test_edge_cases():
  158. """测试边界情况"""
  159. api_url = "http://localhost:8000/api/chat"
  160. print("\n🔍 测试边界情况...")
  161. print("-" * 60)
  162. # 边界情况1: 复杂的会话ID格式
  163. test_edge_1 = {
  164. "question": "测试复杂会话ID",
  165. "user_id": "user:with:colons",
  166. "thread_id": "user:with:colons:20250714120000001:extra"
  167. }
  168. try:
  169. response = requests.post(api_url, json=test_edge_1, timeout=10)
  170. print(f"🔬 复杂会话ID测试 - 状态码: {response.status_code}")
  171. if response.status_code == 200:
  172. print("✅ 复杂会话ID处理正确")
  173. else:
  174. result = response.json()
  175. print(f"📝 错误信息: {result.get('error', '')}")
  176. except Exception as e:
  177. print(f"❌ 复杂会话ID测试失败: {e}")
  178. if __name__ == "__main__":
  179. test_validation_improvements()
  180. test_edge_cases()