test_check_interface_only.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 独立测试 /api/meta/check 接口
  5. 直接通过 HTTP 请求测试,不依赖 Flask test_client
  6. """
  7. import requests
  8. import json
  9. from datetime import datetime
  10. import urllib.parse
  11. # 配置
  12. BASE_URL = "http://192.168.3.143:5000"
  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. else:
  60. print(f"\n❌ 测试 1 失败: code={data.get('code')}, msg={data.get('msg')}")
  61. else:
  62. print(f"\n❌ 测试 1 失败: HTTP 状态码 {response.status_code}")
  63. except ValueError as e:
  64. print(f"❌ 响应不是有效的 JSON: {str(e)}")
  65. print(f"原始响应: {response.text}")
  66. except requests.Timeout:
  67. print("❌ 请求超时(超过10秒)")
  68. except requests.ConnectionError as e:
  69. print(f"❌ 连接失败: {str(e)}")
  70. print("\n可能的原因:")
  71. print(" 1. 服务器未启动")
  72. print(" 2. 网络不可达")
  73. print(" 3. 防火墙阻止")
  74. print(" 4. IP 地址或端口错误")
  75. except Exception as e:
  76. print(f"❌ 请求失败: {str(e)}")
  77. # 测试 2: 检查不存在的元数据
  78. print_section("测试 2: 检查不存在的元数据", "-")
  79. import time
  80. test_name_2 = f"测试元数据_不存在_{int(time.time())}"
  81. url_2 = f"{BASE_URL}{CHECK_ENDPOINT}?name_zh={urllib.parse.quote(test_name_2)}"
  82. print(f"测试元数据名: {test_name_2}")
  83. print(f"请求URL: {url_2}")
  84. print(f"请求方法: GET")
  85. try:
  86. print("\n发送请求...")
  87. response = requests.get(url_2, timeout=10)
  88. print(f"✅ 响应状态码: {response.status_code}")
  89. print(f"✅ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  90. print(f"\n响应内容:")
  91. data = response.json()
  92. print(json.dumps(data, indent=2, ensure_ascii=False))
  93. if response.status_code == 200:
  94. if data.get('code') == 200:
  95. exists = data.get('data', {}).get('exists')
  96. if exists == False:
  97. print(f"\n🎯 结果: 元数据 '{test_name_2}' 不存在(预期)")
  98. print("✅ 测试 2 通过")
  99. elif exists == True:
  100. print(f"\n⚠️ 意外结果: 新创建的测试名称竟然已存在")
  101. else:
  102. print(f"\n❌ 测试 2 失败: exists={exists}")
  103. else:
  104. print(f"\n❌ 测试 2 失败: code={data.get('code')}")
  105. else:
  106. print(f"\n❌ 测试 2 失败: HTTP 状态码 {response.status_code}")
  107. except Exception as e:
  108. print(f"❌ 请求失败: {str(e)}")
  109. # 测试 3: 缺少参数
  110. print_section("测试 3: 参数验证(缺少 name_zh)", "-")
  111. url_3 = f"{BASE_URL}{CHECK_ENDPOINT}"
  112. print(f"请求URL: {url_3}")
  113. print(f"请求方法: GET")
  114. print("参数: 无(故意不传 name_zh)")
  115. try:
  116. print("\n发送请求...")
  117. response = requests.get(url_3, timeout=10)
  118. print(f"✅ 响应状态码: {response.status_code}")
  119. print(f"✅ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  120. print(f"\n响应内容:")
  121. data = response.json()
  122. print(json.dumps(data, indent=2, ensure_ascii=False))
  123. # 应该返回错误
  124. if data.get('code') != 200:
  125. msg = data.get('msg', '')
  126. if '缺少' in msg or 'name_zh' in msg:
  127. print(f"\n✅ 正确返回参数错误: {msg}")
  128. print("✅ 测试 3 通过")
  129. else:
  130. print(f"\n⚠️ 返回了错误但错误信息不明确: {msg}")
  131. else:
  132. print("\n❌ 测试 3 失败: 应该返回错误但返回了成功")
  133. except Exception as e:
  134. print(f"❌ 请求失败: {str(e)}")
  135. # 测试 4: 特殊字符处理
  136. print_section("测试 4: 特殊字符处理", "-")
  137. test_name_4 = "测试@#$%&*()中文名称"
  138. url_4 = f"{BASE_URL}{CHECK_ENDPOINT}?name_zh={urllib.parse.quote(test_name_4)}"
  139. print(f"测试元数据名: {test_name_4}")
  140. print(f"URL编码后: {urllib.parse.quote(test_name_4)}")
  141. print(f"请求URL: {url_4}")
  142. try:
  143. print("\n发送请求...")
  144. response = requests.get(url_4, timeout=10)
  145. print(f"✅ 响应状态码: {response.status_code}")
  146. print(f"✅ 响应时间: {response.elapsed.total_seconds():.3f} 秒")
  147. print(f"\n响应内容:")
  148. data = response.json()
  149. print(json.dumps(data, indent=2, ensure_ascii=False))
  150. if response.status_code == 200:
  151. if data.get('code') == 200:
  152. returned_name = data.get('data', {}).get('name_zh')
  153. if returned_name == test_name_4:
  154. print(f"\n✅ 特殊字符处理正确")
  155. print("✅ 测试 4 通过")
  156. else:
  157. print(f"\n⚠️ 返回的名称不匹配:")
  158. print(f" 期望: {test_name_4}")
  159. print(f" 实际: {returned_name}")
  160. else:
  161. print(f"\n接口返回错误: {data.get('msg')}")
  162. else:
  163. print(f"\n❌ HTTP 状态码: {response.status_code}")
  164. except Exception as e:
  165. print(f"❌ 请求失败: {str(e)}")
  166. # 测试总结
  167. print_section("测试总结", "=")
  168. print("✅ 接口测试完成!")
  169. print("\n测试覆盖:")
  170. print(" ✅ 测试 1: 检查已存在的元数据")
  171. print(" ✅ 测试 2: 检查不存在的元数据")
  172. print(" ✅ 测试 3: 参数验证")
  173. print(" ✅ 测试 4: 特殊字符处理")
  174. print("\n如果所有测试都通过,说明接口工作正常!")
  175. print(f"\n接口地址: {BASE_URL}{CHECK_ENDPOINT}")
  176. print("状态: 可用")
  177. if __name__ == "__main__":
  178. try:
  179. test_check_interface()
  180. except KeyboardInterrupt:
  181. print("\n\n⚠️ 测试被用户中断")
  182. except Exception as e:
  183. print(f"\n\n❌ 测试过程中发生错误: {str(e)}")
  184. import traceback
  185. traceback.print_exc()