Refactor: PHASE 6: Decoupling & Integration

This commit is contained in:
ziesorx 2025-09-12 15:57:51 +07:00
parent 6c7c4c5d9c
commit accefde8a1
8 changed files with 2344 additions and 86 deletions

197
validate_refactor.py Normal file
View file

@ -0,0 +1,197 @@
#!/usr/bin/env python3
"""
Validation script to test the refactored detector worker.
This script validates that:
1. All modules can be imported successfully
2. Singleton managers work correctly
3. Dependency injection container functions
4. Configuration system operates properly
"""
import sys
import traceback
import logging
def test_imports():
"""Test that all refactored modules can be imported."""
print("🔍 Testing module imports...")
try:
# Core modules
from detector_worker.core.config import get_config_manager
from detector_worker.core.singleton_managers import (
ModelStateManager, StreamStateManager, SessionStateManager
)
from detector_worker.core.dependency_injection import get_container
from detector_worker.core.exceptions import DetectionError
# Detection modules
from detector_worker.detection.detection_result import DetectionResult
from detector_worker.detection.yolo_detector import YOLODetector
# Pipeline modules
from detector_worker.pipeline.pipeline_executor import PipelineExecutor
from detector_worker.pipeline.action_executor import ActionExecutor
# Storage modules
from detector_worker.storage.database_manager import DatabaseManager
from detector_worker.storage.redis_client import RedisClientManager
# Communication modules
from detector_worker.communication.websocket_handler import WebSocketHandler
from detector_worker.communication.message_processor import MessageProcessor
# Utils
from detector_worker.utils.error_handler import ErrorHandler
from detector_worker.utils.system_monitor import get_system_metrics
print("✅ All imports successful!")
return True
except ImportError as e:
print(f"❌ Import failed: {e}")
traceback.print_exc()
return False
except Exception as e:
print(f"❌ Unexpected error during import: {e}")
traceback.print_exc()
return False
def test_singleton_managers():
"""Test that singleton managers work correctly."""
print("\n🔍 Testing singleton managers...")
try:
from detector_worker.core.singleton_managers import (
ModelStateManager, StreamStateManager, SessionStateManager,
CacheStateManager, CameraStateManager, PipelineStateManager
)
# Test that singletons return same instance
model1 = ModelStateManager()
model2 = ModelStateManager()
assert model1 is model2, "ModelStateManager not singleton"
stream1 = StreamStateManager()
stream2 = StreamStateManager()
assert stream1 is stream2, "StreamStateManager not singleton"
# Test basic functionality
model_manager = ModelStateManager()
stats = model_manager.get_stats()
assert isinstance(stats, dict), "Stats should be dict"
print("✅ Singleton managers working correctly!")
return True
except Exception as e:
print(f"❌ Singleton manager test failed: {e}")
traceback.print_exc()
return False
def test_dependency_injection():
"""Test dependency injection container."""
print("\n🔍 Testing dependency injection...")
try:
from detector_worker.core.dependency_injection import get_container
container = get_container()
stats = container.get_container().get_stats()
assert isinstance(stats, dict), "Container stats should be dict"
assert "registered_services" in stats, "Missing registered_services"
print(f"✅ Dependency injection working! Registered services: {stats['registered_services']}")
return True
except Exception as e:
print(f"❌ Dependency injection test failed: {e}")
traceback.print_exc()
return False
def test_configuration():
"""Test configuration management."""
print("\n🔍 Testing configuration system...")
try:
from detector_worker.core.config import get_config_manager, validate_config
config_manager = get_config_manager()
config = config_manager.get_all()
assert isinstance(config, dict), "Config should be dict"
assert "max_streams" in config, "Missing max_streams config"
# Test validation
errors = validate_config()
assert isinstance(errors, list), "Validation errors should be list"
print(f"✅ Configuration system working! Config keys: {len(config)}")
return True
except Exception as e:
print(f"❌ Configuration test failed: {e}")
traceback.print_exc()
return False
def test_error_handling():
"""Test error handling system."""
print("\n🔍 Testing error handling...")
try:
from detector_worker.utils.error_handler import ErrorHandler, ErrorContext, ErrorSeverity
handler = ErrorHandler("test_component")
context = ErrorContext(component="test", operation="test_op")
# Test error stats
stats = handler.get_error_stats()
assert isinstance(stats, dict), "Error stats should be dict"
print("✅ Error handling system working!")
return True
except Exception as e:
print(f"❌ Error handling test failed: {e}")
traceback.print_exc()
return False
def main():
"""Run all validation tests."""
print("🚀 Starting Detector Worker Refactor Validation")
print("=" * 50)
tests = [
test_imports,
test_singleton_managers,
test_dependency_injection,
test_configuration,
test_error_handling
]
passed = 0
total = len(tests)
for test in tests:
if test():
passed += 1
print("\n" + "=" * 50)
print(f"🎯 Validation Results: {passed}/{total} tests passed")
if passed == total:
print("🎉 All validation tests passed! Refactor is working correctly.")
return 0
else:
print("❌ Some validation tests failed. Please check the errors above.")
return 1
if __name__ == "__main__":
sys.exit(main())