test_cd_integration.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #!/usr/bin/env python3
  2. """
  3. Cd预测集成测试脚本
  4. @description: 测试Cd预测功能是否正确集成到AcidMap系统中
  5. @author: AcidMap Team
  6. @version: 1.0.0
  7. """
  8. import os
  9. import sys
  10. import asyncio
  11. import logging
  12. from datetime import datetime
  13. # 添加app目录到Python路径
  14. sys.path.append(os.path.join(os.path.dirname(__file__), 'app'))
  15. # 设置日志
  16. logging.basicConfig(
  17. level=logging.INFO,
  18. format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
  19. )
  20. async def test_cd_prediction_integration():
  21. """
  22. 测试Cd预测功能集成
  23. @description: 验证配置、服务和包装器是否正常工作
  24. """
  25. logger = logging.getLogger(__name__)
  26. logger.info("开始测试Cd预测功能集成")
  27. try:
  28. # 测试1: 验证配置模块
  29. logger.info("测试1: 验证配置模块")
  30. from app.config.cd_prediction_config import cd_config
  31. logger.info(f"项目根目录: {cd_config.project_root}")
  32. logger.info(f"Cd系统路径: {cd_config.get_cd_system_path()}")
  33. logger.info(f"输出目录: {cd_config.get_output_dir()}")
  34. # 检查Cd系统是否存在
  35. cd_system_path = cd_config.get_cd_system_path()
  36. if not os.path.exists(cd_system_path):
  37. logger.error(f"Cd预测系统路径不存在: {cd_system_path}")
  38. return False
  39. logger.info("✅ 配置模块测试通过")
  40. # 测试2: 验证包装器
  41. logger.info("测试2: 验证包装器模块")
  42. from app.utils.cd_prediction_wrapper import CdPredictionWrapper
  43. wrapper = CdPredictionWrapper(cd_system_path)
  44. logger.info("✅ 包装器初始化成功")
  45. # 测试3: 验证服务类
  46. logger.info("测试3: 验证服务类")
  47. from app.services.cd_prediction_service import CdPredictionService
  48. service = CdPredictionService()
  49. logger.info("✅ 服务类初始化成功")
  50. # 测试4: 检查输出目录
  51. logger.info("测试4: 检查输出目录")
  52. figures_dir = cd_config.get_output_dir("figures")
  53. raster_dir = cd_config.get_output_dir("raster")
  54. logger.info(f"图片输出目录: {figures_dir}")
  55. logger.info(f"栅格输出目录: {raster_dir}")
  56. if os.path.exists(figures_dir) and os.path.exists(raster_dir):
  57. logger.info("✅ 输出目录创建成功")
  58. else:
  59. logger.warning("⚠️ 输出目录可能有问题")
  60. # 测试5: 检查Cd系统的关键文件
  61. logger.info("测试5: 检查Cd系统的关键文件")
  62. required_files = [
  63. "main.py",
  64. "config.py",
  65. "models",
  66. "analysis"
  67. ]
  68. missing_files = []
  69. for file_path in required_files:
  70. full_path = os.path.join(cd_system_path, file_path)
  71. if not os.path.exists(full_path):
  72. missing_files.append(file_path)
  73. if missing_files:
  74. logger.error(f"❌ Cd系统缺少关键文件: {missing_files}")
  75. return False
  76. else:
  77. logger.info("✅ Cd系统文件完整性检查通过")
  78. logger.info("🎉 所有测试通过!Cd预测功能集成成功!")
  79. return True
  80. except ImportError as e:
  81. logger.error(f"❌ 导入模块失败: {str(e)}")
  82. return False
  83. except Exception as e:
  84. logger.error(f"❌ 测试过程中发生错误: {str(e)}")
  85. return False
  86. def test_api_endpoints():
  87. """
  88. 测试API端点是否正确注册
  89. @description: 验证FastAPI应用是否正确包含Cd预测路由
  90. """
  91. logger = logging.getLogger(__name__)
  92. logger.info("测试API端点注册")
  93. try:
  94. from app.main import app
  95. # 获取所有路由
  96. routes = []
  97. for route in app.routes:
  98. if hasattr(route, 'path'):
  99. routes.append(route.path)
  100. # 检查Cd预测相关路由
  101. cd_routes = [route for route in routes if '/cd-prediction/' in route]
  102. expected_routes = [
  103. '/api/cd-prediction/crop-cd/generate-map',
  104. '/api/cd-prediction/effective-cd/generate-map',
  105. '/api/cd-prediction/crop-cd/download-map',
  106. '/api/cd-prediction/effective-cd/download-map',
  107. '/api/cd-prediction/crop-cd/download-histogram',
  108. '/api/cd-prediction/effective-cd/download-histogram'
  109. ]
  110. logger.info(f"发现的Cd预测路由: {cd_routes}")
  111. # 检查是否所有预期路由都存在
  112. found_routes = 0
  113. for expected_route in expected_routes:
  114. if any(expected_route in route for route in cd_routes):
  115. found_routes += 1
  116. logger.info(f"✅ 找到路由: {expected_route}")
  117. else:
  118. logger.warning(f"⚠️ 未找到路由: {expected_route}")
  119. if found_routes == len(expected_routes):
  120. logger.info("✅ 所有API端点注册成功")
  121. return True
  122. else:
  123. logger.warning(f"⚠️ 只找到 {found_routes}/{len(expected_routes)} 个预期路由")
  124. return False
  125. except Exception as e:
  126. logger.error(f"❌ API端点测试失败: {str(e)}")
  127. return False
  128. def main():
  129. """
  130. 主测试函数
  131. @description: 运行所有集成测试
  132. """
  133. print("=" * 60)
  134. print("🔬 Cd预测功能集成测试")
  135. print("=" * 60)
  136. # 运行异步测试
  137. integration_success = asyncio.run(test_cd_prediction_integration())
  138. # 运行API测试
  139. api_success = test_api_endpoints()
  140. print("\n" + "=" * 60)
  141. print("📊 测试结果汇总")
  142. print("=" * 60)
  143. if integration_success:
  144. print("✅ 集成功能测试: 通过")
  145. else:
  146. print("❌ 集成功能测试: 失败")
  147. if api_success:
  148. print("✅ API端点测试: 通过")
  149. else:
  150. print("❌ API端点测试: 失败")
  151. overall_success = integration_success and api_success
  152. if overall_success:
  153. print("\n🎉 恭喜!Cd预测功能已成功集成到AcidMap系统中!")
  154. print("\n📝 接下来您可以:")
  155. print(" 1. 启动FastAPI服务器: uvicorn app.main:app --reload")
  156. print(" 2. 访问API文档: http://localhost:8000/docs")
  157. print(" 3. 测试Cd预测接口")
  158. print(" 4. 参考 INTEGRATION_GUIDE.md 了解详细使用方法")
  159. else:
  160. print("\n❌ 集成存在问题,请检查错误信息并修复")
  161. print("\n🔧 常见问题排查:")
  162. print(" 1. 确保 Cd_Prediction_Integrated_System 文件夹存在且完整")
  163. print(" 2. 检查Python依赖是否安装完整")
  164. print(" 3. 验证文件路径和权限")
  165. print("=" * 60)
  166. return overall_success
  167. if __name__ == "__main__":
  168. success = main()
  169. sys.exit(0 if success else 1)