test_ballcontroller_import.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. BallController配置导入测试脚本
  5. 测试修复后的config_manager.py是否能正确导入BallController标准配置表.xlsx
  6. """
  7. import sys
  8. import os
  9. from pathlib import Path
  10. import json
  11. # 添加当前目录到Python路径
  12. sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
  13. try:
  14. import pandas as pd
  15. PANDAS_AVAILABLE = True
  16. except ImportError:
  17. PANDAS_AVAILABLE = False
  18. print("错误: pandas未安装,无法测试Excel导入功能")
  19. sys.exit(1)
  20. from config_manager import ConfigManagerGUI
  21. def test_ballcontroller_import():
  22. """测试BallController配置导入功能"""
  23. print("=== BallController配置导入测试 ===")
  24. # 创建配置管理器实例(不启动GUI)
  25. config_manager = ConfigManagerGUI()
  26. # 设置测试文件路径
  27. excel_file = Path("BallController标准配置表.xlsx")
  28. if not excel_file.exists():
  29. print(f"错误: 找不到测试文件 {excel_file}")
  30. return False
  31. print(f"测试文件: {excel_file}")
  32. # 模拟文件选择
  33. config_manager.selected_files = [str(excel_file)]
  34. config_manager._set_config_mapping_for_files()
  35. print(f"配置映射类型: {config_manager.current_mapping['format_type']}")
  36. print(f"支持的参数数量: {len(config_manager.current_mapping['param_types'])}")
  37. print(f"参数类型映射: {list(config_manager.current_mapping['param_types'].keys())}")
  38. # 测试Excel文件读取
  39. try:
  40. config_data = config_manager.read_excel_config(excel_file)
  41. if config_data:
  42. print(f"\n成功读取配置,共 {len(config_data)} 个参数:")
  43. for key, value in config_data.items():
  44. print(f" {key}: {value} ({type(value).__name__})")
  45. # 验证关键参数(使用Excel文件中的实际参数名)
  46. expected_params = [
  47. 'baseSpeed', 'maxReflectionRandomness', 'antiTrapTimeWindow', 'antiTrapHitThreshold',
  48. 'deflectionAttemptThreshold', 'antiTrapDeflectionMultiplier', 'FIRE_COOLDOWN', 'ballRadius',
  49. 'gravityScale', 'linearDamping', 'angularDamping', 'colliderGroup',
  50. 'colliderTag', 'friction', 'restitution', 'safeDistance',
  51. 'edgeOffset', 'sensor', 'maxAttempts'
  52. ]
  53. missing_params = [param for param in expected_params if param not in config_data]
  54. if missing_params:
  55. print(f"\n警告: 缺少以下参数: {missing_params}")
  56. else:
  57. print("\n✓ 所有预期参数都已正确读取")
  58. # 验证数据类型
  59. type_errors = []
  60. for param, expected_type in config_manager.current_mapping['param_types'].items():
  61. if param in config_data:
  62. actual_type = type(config_data[param])
  63. if expected_type == bool and actual_type != bool:
  64. type_errors.append(f"{param}: 期望 {expected_type.__name__}, 实际 {actual_type.__name__}")
  65. elif expected_type in [int, float] and actual_type not in [int, float]:
  66. type_errors.append(f"{param}: 期望 {expected_type.__name__}, 实际 {actual_type.__name__}")
  67. if type_errors:
  68. print(f"\n数据类型错误:")
  69. for error in type_errors:
  70. print(f" {error}")
  71. else:
  72. print("\n✓ 所有参数数据类型正确")
  73. # 生成JSON输出测试
  74. json_output = json.dumps(config_data, indent=2, ensure_ascii=False)
  75. print(f"\nJSON输出预览 (前200字符):")
  76. print(json_output[:200] + "..." if len(json_output) > 200 else json_output)
  77. return True
  78. else:
  79. print("错误: 未能读取到任何配置数据")
  80. return False
  81. except Exception as e:
  82. print(f"导入测试失败: {str(e)}")
  83. import traceback
  84. traceback.print_exc()
  85. return False
  86. if __name__ == "__main__":
  87. success = test_ballcontroller_import()
  88. if success:
  89. print("\n=== 测试通过 ===")
  90. print("BallController配置导入功能已修复,可以正常使用config_manager.py导入Excel配置")
  91. else:
  92. print("\n=== 测试失败 ===")
  93. print("BallController配置导入仍存在问题,需要进一步调试")
  94. sys.exit(0 if success else 1)