test_api.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. API 测试脚本
  5. 用于测试 /api/description 和 /api/title 两个端点
  6. """
  7. import requests
  8. import json
  9. import sys
  10. from typing import Dict, Any
  11. # API 基础配置
  12. BASE_URL = "http://60.165.238.181:5555" # 修改为你的服务地址
  13. def test_api_description():
  14. """测试商品描述生成接口"""
  15. print("=" * 80)
  16. print("测试 /api/description 接口")
  17. print("=" * 80)
  18. url = f"{BASE_URL}/api/description"
  19. data = {'img': 'https://img2.goelia.com.au/prod/product/1ENC6E220/material/main/Shopify/-1/72736752b0ad405382d5ed277dabc660.jpg',
  20. 'graphic_label': ['-100% Merino wool', '-With pockets', '-H-line fit'],
  21. 'spu': '1ENC6E220',
  22. 'plm_info': '1、手工流苏边设计   2、贴袋设计   3、金属纽扣'}
  23. print(f"\n请求 URL: {url}")
  24. print(f"请求数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
  25. try:
  26. response = requests.post(url, json=data, timeout=120)
  27. print(f"\n响应状态码: {response.status_code}")
  28. print(f"响应内容:")
  29. print(json.dumps(response.json(), ensure_ascii=False, indent=2))
  30. if response.status_code == 200:
  31. print("\n✅ 测试通过")
  32. return True
  33. else:
  34. print("\n❌ 测试失败")
  35. return False
  36. except requests.exceptions.ConnectionError:
  37. print("\n❌ 连接错误: 无法连接到服务器,请确保服务已启动")
  38. return False
  39. except requests.exceptions.Timeout:
  40. print("\n❌ 超时错误: 请求超时")
  41. return False
  42. except Exception as e:
  43. print(f"\n❌ 发生错误: {str(e)}")
  44. return False
  45. def test_api_title():
  46. """测试商品标题生成接口"""
  47. print("\n" + "=" * 80)
  48. print("测试 /api/title 接口")
  49. print("=" * 80)
  50. url = f"{BASE_URL}/api/title"
  51. data = {
  52. "spu": "TEST_SPU_002",
  53. "desc": "This maxi dress features unparalleled comfort and a unique texture with its tencel blend fabric. The square neckline and smocked bodice create a flattering silhouette, while the layered skirt adds romantic flair.",
  54. "tags": ["舒适", "优雅", "修身"],
  55. "reference_title": "Elegant Maxi Dress with Floral Pattern"
  56. }
  57. print(f"\n请求 URL: {url}")
  58. print(f"请求数据: {json.dumps(data, ensure_ascii=False, indent=2)}")
  59. try:
  60. response = requests.post(url, json=data, timeout=120)
  61. print(f"\n响应状态码: {response.status_code}")
  62. print(f"响应内容:")
  63. print(json.dumps(response.json(), ensure_ascii=False, indent=2))
  64. if response.status_code == 200:
  65. print("\n✅ 测试通过")
  66. return True
  67. else:
  68. print("\n❌ 测试失败")
  69. return False
  70. except requests.exceptions.ConnectionError:
  71. print("\n❌ 连接错误: 无法连接到服务器,请确保服务已启动")
  72. return False
  73. except requests.exceptions.Timeout:
  74. print("\n❌ 超时错误: 请求超时")
  75. return False
  76. except Exception as e:
  77. print(f"\n❌ 发生错误: {str(e)}")
  78. return False
  79. def test_error_cases():
  80. """测试错误情况"""
  81. print("\n" + "=" * 80)
  82. print("测试错误情况处理")
  83. print("=" * 80)
  84. # 测试缺少必需字段
  85. print("\n1. 测试缺少必需字段 (description)")
  86. url = f"{BASE_URL}/api/description"
  87. data = {
  88. "spu": "TEST_SPU_003",
  89. # 缺少 plm_info, img, graphic_label
  90. }
  91. try:
  92. response = requests.post(url, json=data, timeout=10)
  93. print(f"响应状态码: {response.status_code}")
  94. print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
  95. except Exception as e:
  96. print(f"发生错误: {str(e)}")
  97. # 测试无效的图片URL
  98. print("\n2. 测试无效的图片URL")
  99. data = {
  100. "spu": "TEST_SPU_004",
  101. "plm_info": "测试商品信息",
  102. "img": "https://invalid-url-test.com/nonexistent.jpg",
  103. "graphic_label": ["测试标签"]
  104. }
  105. try:
  106. response = requests.post(url, json=data, timeout=30)
  107. print(f"响应状态码: {response.status_code}")
  108. print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
  109. except Exception as e:
  110. print(f"发生错误: {str(e)}")
  111. def main():
  112. """主函数"""
  113. print("\n" + "=" * 80)
  114. print("开始 API 测试")
  115. print("=" * 80)
  116. # 检查服务器是否运行
  117. try:
  118. response = requests.get(f"{BASE_URL}/", timeout=5)
  119. print("✅ 服务器正在运行")
  120. except requests.exceptions.ConnectionError:
  121. print("⚠️ 警告: 无法连接到服务器")
  122. print("请确保 Flask 应用已启动 (app_v2.py)")
  123. response = input("\n是否继续测试? (y/n): ")
  124. if response.lower() != 'y':
  125. sys.exit(0)
  126. except Exception as e:
  127. print(f"⚠️ 警告: {str(e)}")
  128. results = []
  129. # 测试描述生成接口
  130. results.append(("Description API", test_api_description()))
  131. # 测试标题生成接口
  132. # results.append(("Title API", test_api_title()))
  133. # 测试错误情况
  134. # test_error_cases()
  135. # 打印测试总结
  136. print("\n" + "=" * 80)
  137. print("测试总结")
  138. print("=" * 80)
  139. for test_name, result in results:
  140. status = "✅ 通过" if result else "❌ 失败"
  141. print(f"{test_name}: {status}")
  142. passed = sum(1 for _, result in results if result)
  143. total = len(results)
  144. print(f"\n总计: {passed}/{total} 个测试通过")
  145. if __name__ == "__main__":
  146. main()