Files
mxivideo/examples/test_refactored_modules.py
2025-07-12 13:44:57 +08:00

249 lines
7.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Test Refactored Modules
测试重构后的模块
验证重构后的场景检测模块是否正常工作
"""
import sys
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
from python_core.scene_detection import (
SceneDetector,
DetectorType,
OutputFormat,
SceneInfo,
DetectionResult,
SceneDetectionWorkflowState
)
def test_imports():
"""测试模块导入"""
print("🧪 测试模块导入...")
try:
# 测试类型导入
assert DetectorType.CONTENT == "content"
assert OutputFormat.JSON == "json"
print("✅ 类型导入成功")
# 测试数据模型
scene = SceneInfo(0, 0.0, 5.0, 5.0)
assert scene.index == 0
assert scene.duration == 5.0
print("✅ 数据模型导入成功")
# 测试主接口类
detector = SceneDetector()
assert detector is not None
assert hasattr(detector, 'detect_scenes')
assert hasattr(detector, 'detect_with_workflow')
print("✅ 主接口类导入成功")
return True
except Exception as e:
print(f"❌ 导入测试失败: {e}")
return False
def test_basic_functionality():
"""测试基础功能"""
print("\n🧪 测试基础功能...")
try:
detector = SceneDetector()
# 测试视频信息获取
video_path = Path("assets/1/1752032011698.mp4")
if video_path.exists():
info_result = detector.get_video_info(video_path)
if info_result["success"]:
print("✅ 视频信息获取成功")
print(f" 分辨率: {info_result['info']['resolution']}")
print(f" 时长: {info_result['info']['duration']:.2f}")
else:
print(f"⚠️ 视频信息获取失败: {info_result['error']}")
else:
print("⚠️ 测试视频文件不存在,跳过视频信息测试")
# 测试JSON-RPC方法注册
detector.register_jsonrpc_methods()
print("✅ JSON-RPC方法注册成功")
return True
except Exception as e:
print(f"❌ 基础功能测试失败: {e}")
import traceback
print(f"详细错误: {traceback.format_exc()}")
return False
def test_services():
"""测试服务层"""
print("\n🧪 测试服务层...")
try:
from python_core.scene_detection.services import (
SceneDetectorService,
VideoInfoService,
AIAnalysisService
)
# 测试检测服务
detector_service = SceneDetectorService()
assert len(detector_service.supported_formats) > 0
print("✅ 场景检测服务初始化成功")
# 测试视频信息服务
video_info_service = VideoInfoService()
assert hasattr(video_info_service, 'extract_video_info')
print("✅ 视频信息服务初始化成功")
# 测试AI分析服务
ai_service = AIAnalysisService()
assert hasattr(ai_service, 'analyze_detection_result')
print(f"✅ AI分析服务初始化成功 (AI启用: {ai_service.ai_enabled})")
return True
except Exception as e:
print(f"❌ 服务层测试失败: {e}")
return False
def test_workflows():
"""测试工作流"""
print("\n🧪 测试工作流...")
try:
from python_core.scene_detection.workflows import (
SceneDetectionWorkflowManager,
WorkflowNodes
)
# 测试工作流管理器
workflow_manager = SceneDetectionWorkflowManager()
assert hasattr(workflow_manager, 'create_detection_workflow')
print("✅ 工作流管理器初始化成功")
# 测试工作流节点
nodes = WorkflowNodes()
assert hasattr(nodes, 'validate_input')
assert hasattr(nodes, 'detect_scenes')
assert hasattr(nodes, 'finalize_results')
print("✅ 工作流节点初始化成功")
# 测试工作流创建
workflow = workflow_manager.create_detection_workflow()
if workflow:
print("✅ LangGraph工作流创建成功")
else:
print("⚠️ LangGraph工作流创建失败可能是依赖问题")
return True
except Exception as e:
print(f"❌ 工作流测试失败: {e}")
return False
def test_utils():
"""测试工具类"""
print("\n🧪 测试工具类...")
try:
from python_core.scene_detection.utils import (
ResultSaver,
InputValidator
)
# 测试结果保存器
saver = ResultSaver()
assert hasattr(saver, 'save_results')
print("✅ 结果保存器初始化成功")
# 测试输入验证器
validator = InputValidator({'.mp4', '.avi'})
assert hasattr(validator, 'validate_video_path')
print("✅ 输入验证器初始化成功")
return True
except Exception as e:
print(f"❌ 工具类测试失败: {e}")
return False
def test_cli_integration():
"""测试CLI集成"""
print("\n🧪 测试CLI集成...")
try:
# 测试新的CLI模块
from python_core.cli.scene_detect_new import app
assert app is not None
print("✅ 新CLI模块导入成功")
return True
except Exception as e:
print(f"❌ CLI集成测试失败: {e}")
return False
def main():
"""主测试函数"""
print("🚀 开始测试重构后的场景检测模块")
print("=" * 60)
tests = [
("模块导入", test_imports),
("基础功能", test_basic_functionality),
("服务层", test_services),
("工作流", test_workflows),
("工具类", test_utils),
("CLI集成", test_cli_integration),
]
passed = 0
total = len(tests)
for test_name, test_func in tests:
try:
if test_func():
passed += 1
print(f"{test_name} - 通过")
else:
print(f"{test_name} - 失败")
except Exception as e:
print(f"{test_name} - 异常: {e}")
print("\n" + "=" * 60)
print(f"🎉 测试完成: {passed}/{total} 通过")
if passed == total:
print("🎊 所有测试都通过了!重构成功!")
print("\n📋 重构后的模块结构:")
print("├── types/ # 类型定义和数据模型")
print("├── services/ # 核心业务逻辑服务")
print("├── workflows/ # LangGraph工作流")
print("├── utils/ # 工具类和辅助函数")
print("└── scene_detector.py # 主接口类")
else:
print("⚠️ 部分测试失败,请检查重构实现")
return passed == total
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)