test_check_218.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 测试 /api/meta/check 接口 - 使用新服务器地址
  5. 服务器: http://192.168.3.218:18183
  6. """
  7. import requests
  8. import json
  9. from datetime import datetime
  10. import urllib.parse
  11. # 配置
  12. BASE_URL = "http://192.168.3.218:18183"
  13. CHECK_ENDPOINT = "/api/meta/check"
  14. def print_section(title, char="="):
  15. """打印分节标题"""
  16. print("\n" + char*70)
  17. print(f" {title}")
  18. print(char*70 + "\n")
  19. def test_check_interface():
  20. """测试检查接口"""
  21. print_section("测试 /api/meta/check 接口", "=")
  22. print(f"⏰ 测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  23. print(f"🌐 目标服务器: {BASE_URL}")
  24. print(f"📡 接口路径: {CHECK_ENDPOINT}")
  25. print(f"🔗 完整URL: {BASE_URL}{CHECK_ENDPOINT}")
  26. # 测试 1: 检查已存在的元数据
  27. print_section("测试 1: 检查已存在的元数据", "-")
  28. test_name_1 = "其他费用定额"
  29. url_1 = f"{BASE_URL}{CHECK_ENDPOINT}?name_zh={urllib.parse.quote(test_name_1)}"
  30. print(f"📝 测试元数据名: {test_name_1}")
  31. print(f"🔗 请求URL: {url_1}")
  32. print(f"📤 请求方法: GET")
  33. try:
  34. print("\n⏳ 发送请求...")
  35. response = requests.get(url_1, timeout=10)
  36. print(f"✅ 响应状态码: {response.status_code}")
  37. print(f"⚡ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  38. print(f"\n📦 响应内容:")
  39. try:
  40. data = response.json()
  41. print(json.dumps(data, indent=2, ensure_ascii=False))
  42. # 验证响应格式
  43. if response.status_code == 200:
  44. if data.get('code') == 200:
  45. exists = data.get('data', {}).get('exists')
  46. name_zh = data.get('data', {}).get('name_zh')
  47. msg = data.get('msg')
  48. print("\n✅ 响应格式正确")
  49. print(f"📊 返回字段:")
  50. print(f" ├─ code: {data.get('code')}")
  51. print(f" ├─ msg: {msg}")
  52. print(f" ├─ data.exists: {exists}")
  53. print(f" └─ data.name_zh: {name_zh}")
  54. if exists is not None:
  55. print(f"\n🎯 结果: 元数据 '{test_name_1}' {'✅ 存在' if exists else '❌ 不存在'}")
  56. print("🎉 测试 1 通过!")
  57. else:
  58. print("\n❌ 测试 1 失败: exists 字段为空")
  59. elif data.get('code') == 500:
  60. print(f"\n⚠️ 接口返回错误: {data.get('msg')}")
  61. print("这可能是正常的(例如:元数据不存在)")
  62. else:
  63. print(f"\n❌ 测试 1 失败: code={data.get('code')}, msg={data.get('msg')}")
  64. else:
  65. print(f"\n❌ 测试 1 失败: HTTP 状态码 {response.status_code}")
  66. print(f"响应内容: {response.text}")
  67. except ValueError as e:
  68. print(f"❌ 响应不是有效的 JSON: {str(e)}")
  69. print(f"原始响应: {response.text[:200]}")
  70. except requests.Timeout:
  71. print("❌ 请求超时(超过10秒)")
  72. print("💡 可能原因: 服务器响应慢或网络延迟")
  73. except requests.ConnectionError as e:
  74. print(f"❌ 连接失败: {str(e)}")
  75. print("\n💡 可能的原因:")
  76. print(" 1. 服务器未启动")
  77. print(" 2. 网络不可达")
  78. print(" 3. 防火墙阻止")
  79. print(" 4. IP 地址或端口错误")
  80. except Exception as e:
  81. print(f"❌ 请求失败: {str(e)}")
  82. # 测试 2: 检查不存在的元数据
  83. print_section("测试 2: 检查不存在的元数据", "-")
  84. import time
  85. test_name_2 = f"测试元数据_不存在_{int(time.time())}"
  86. url_2 = f"{BASE_URL}{CHECK_ENDPOINT}?name_zh={urllib.parse.quote(test_name_2)}"
  87. print(f"📝 测试元数据名: {test_name_2}")
  88. print(f"🔗 请求URL: {url_2}")
  89. print(f"📤 请求方法: GET")
  90. try:
  91. print("\n⏳ 发送请求...")
  92. response = requests.get(url_2, timeout=10)
  93. print(f"✅ 响应状态码: {response.status_code}")
  94. print(f"⚡ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  95. print(f"\n📦 响应内容:")
  96. data = response.json()
  97. print(json.dumps(data, indent=2, ensure_ascii=False))
  98. if response.status_code == 200:
  99. if data.get('code') == 200:
  100. exists = data.get('data', {}).get('exists')
  101. if exists == False:
  102. print(f"\n🎯 结果: 元数据 '{test_name_2}' 不存在(预期)")
  103. print("🎉 测试 2 通过!")
  104. elif exists == True:
  105. print(f"\n⚠️ 意外结果: 新创建的测试名称竟然已存在")
  106. else:
  107. print(f"\n❌ 测试 2 失败: exists={exists}")
  108. else:
  109. print(f"\n⚠️ 接口返回 code={data.get('code')}")
  110. else:
  111. print(f"\n❌ 测试 2 失败: HTTP 状态码 {response.status_code}")
  112. except Exception as e:
  113. print(f"❌ 请求失败: {str(e)}")
  114. # 测试 3: 缺少参数
  115. print_section("测试 3: 参数验证(缺少 name_zh)", "-")
  116. url_3 = f"{BASE_URL}{CHECK_ENDPOINT}"
  117. print(f"🔗 请求URL: {url_3}")
  118. print(f"📤 请求方法: GET")
  119. print("📝 参数: 无(故意不传 name_zh)")
  120. try:
  121. print("\n⏳ 发送请求...")
  122. response = requests.get(url_3, timeout=10)
  123. print(f"✅ 响应状态码: {response.status_code}")
  124. print(f"⚡ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  125. print(f"\n📦 响应内容:")
  126. data = response.json()
  127. print(json.dumps(data, indent=2, ensure_ascii=False))
  128. # 应该返回错误
  129. if data.get('code') != 200:
  130. msg = data.get('msg', '')
  131. if '缺少' in msg or 'name_zh' in msg:
  132. print(f"\n✅ 正确返回参数错误: {msg}")
  133. print("🎉 测试 3 通过!")
  134. else:
  135. print(f"\n⚠️ 返回了错误但错误信息不明确: {msg}")
  136. print("🎉 测试 3 通过(接口有参数验证)")
  137. else:
  138. print("\n❌ 测试 3 失败: 应该返回错误但返回了成功")
  139. except Exception as e:
  140. print(f"❌ 请求失败: {str(e)}")
  141. # 测试 4: 特殊字符处理
  142. print_section("测试 4: 特殊字符处理", "-")
  143. test_name_4 = "测试@#$%&*()中文名称"
  144. url_4 = f"{BASE_URL}{CHECK_ENDPOINT}?name_zh={urllib.parse.quote(test_name_4)}"
  145. print(f"📝 测试元数据名: {test_name_4}")
  146. print(f"🔐 URL编码后: {urllib.parse.quote(test_name_4)}")
  147. print(f"🔗 请求URL: {url_4}")
  148. try:
  149. print("\n⏳ 发送请求...")
  150. response = requests.get(url_4, timeout=10)
  151. print(f"✅ 响应状态码: {response.status_code}")
  152. print(f"⚡ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  153. print(f"\n📦 响应内容:")
  154. data = response.json()
  155. print(json.dumps(data, indent=2, ensure_ascii=False))
  156. if response.status_code == 200:
  157. if data.get('code') == 200:
  158. returned_name = data.get('data', {}).get('name_zh')
  159. if returned_name == test_name_4:
  160. print(f"\n✅ 特殊字符处理正确")
  161. print("🎉 测试 4 通过!")
  162. else:
  163. print(f"\n⚠️ 返回的名称不匹配:")
  164. print(f" 期望: {test_name_4}")
  165. print(f" 实际: {returned_name}")
  166. else:
  167. print(f"\n接口返回错误: {data.get('msg')}")
  168. print("(这可能是正常的)")
  169. else:
  170. print(f"\n❌ HTTP 状态码: {response.status_code}")
  171. except Exception as e:
  172. print(f"❌ 请求失败: {str(e)}")
  173. # 测试总结
  174. print_section("测试总结", "=")
  175. print("✅ 接口测试完成!")
  176. print("\n📊 测试覆盖:")
  177. print(" ✅ 测试 1: 检查已存在的元数据")
  178. print(" ✅ 测试 2: 检查不存在的元数据")
  179. print(" ✅ 测试 3: 参数验证")
  180. print(" ✅ 测试 4: 特殊字符处理")
  181. print("\n🎯 接口信息:")
  182. print(f" 🌐 服务器: {BASE_URL}")
  183. print(f" 📡 接口: {CHECK_ENDPOINT}")
  184. print(f" 🔗 完整地址: {BASE_URL}{CHECK_ENDPOINT}")
  185. print("\n💡 使用示例:")
  186. print(f" curl \"{BASE_URL}{CHECK_ENDPOINT}?name_zh=元数据名称\"")
  187. if __name__ == "__main__":
  188. try:
  189. test_check_interface()
  190. except KeyboardInterrupt:
  191. print("\n\n⚠️ 测试被用户中断")
  192. except Exception as e:
  193. print(f"\n\n❌ 测试过程中发生错误: {str(e)}")
  194. import traceback
  195. traceback.print_exc()