231 lines
8.2 KiB
Python
231 lines
8.2 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Test d'intégration des utilitaires d'entrée avec l'orchestrateur
|
|
"""
|
|
|
|
import sys
|
|
from pathlib import Path
|
|
from unittest.mock import Mock, patch, MagicMock
|
|
import tempfile
|
|
import shutil
|
|
|
|
# Ajouter le répertoire au path
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
|
|
print("Test d'Intégration - InputUtils + Orchestrateur")
|
|
print("=" * 60)
|
|
|
|
# Créer des répertoires temporaires
|
|
temp_dir = tempfile.mkdtemp()
|
|
profiles_dir = Path(temp_dir) / "profiles"
|
|
logs_dir = Path(temp_dir) / "logs"
|
|
index_dir = Path(temp_dir) / "index"
|
|
keys_dir = Path(temp_dir) / "keys"
|
|
|
|
profiles_dir.mkdir(parents=True, exist_ok=True)
|
|
logs_dir.mkdir(parents=True, exist_ok=True)
|
|
index_dir.mkdir(parents=True, exist_ok=True)
|
|
keys_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
try:
|
|
# Test 1: Import des modules
|
|
print("\n1. Import des modules...")
|
|
with patch.dict('sys.modules', {'pyautogui': MagicMock()}):
|
|
from geniusia2.core.utils.input_utils import InputUtils, ActionType
|
|
from geniusia2.core.orchestrator import Orchestrator
|
|
from geniusia2.core.learning_manager import LearningManager
|
|
from geniusia2.core.utils.vision_utils import VisionUtils
|
|
from geniusia2.core.llm_manager import LLMManager
|
|
from geniusia2.core.logger import Logger
|
|
from geniusia2.core.embeddings_manager import EmbeddingsManager
|
|
from geniusia2.core.config import get_config
|
|
|
|
print(" ✓ Tous les modules importés")
|
|
|
|
# Test 2: Création des composants
|
|
print("\n2. Création des composants...")
|
|
|
|
logger = Logger(log_dir=str(logs_dir), key_path=str(keys_dir))
|
|
print(" ✓ Logger créé")
|
|
|
|
embeddings_manager = EmbeddingsManager(
|
|
model_name="ViT-B-32",
|
|
index_path=str(index_dir),
|
|
device="cpu"
|
|
)
|
|
print(" ✓ EmbeddingsManager créé")
|
|
|
|
config = get_config()
|
|
learning_manager = LearningManager(
|
|
embeddings_manager,
|
|
logger,
|
|
config,
|
|
profiles_path=str(profiles_dir)
|
|
)
|
|
print(" ✓ LearningManager créé")
|
|
|
|
vision_utils = VisionUtils(config)
|
|
print(" ✓ VisionUtils créé")
|
|
|
|
llm_manager = LLMManager(logger=logger, fallback_to_vision=True)
|
|
print(" ✓ LLMManager créé")
|
|
|
|
with patch.dict('sys.modules', {'pyautogui': MagicMock()}):
|
|
input_utils = InputUtils(logger, config)
|
|
print(" ✓ InputUtils créé")
|
|
|
|
# Test 3: Création de l'orchestrateur avec InputUtils
|
|
print("\n3. Création de l'orchestrateur...")
|
|
|
|
with patch.dict('sys.modules', {'pyautogui': MagicMock()}):
|
|
orchestrator = Orchestrator(
|
|
learning_manager=learning_manager,
|
|
vision_utils=vision_utils,
|
|
llm_manager=llm_manager,
|
|
logger=logger,
|
|
gui=None,
|
|
config=config,
|
|
input_utils=input_utils
|
|
)
|
|
print(" ✓ Orchestrateur créé avec InputUtils")
|
|
print(f" ✓ InputUtils intégré: {orchestrator.input_utils is not None}")
|
|
|
|
# Test 4: Vérifier les méthodes de l'orchestrateur
|
|
print("\n4. Vérification des méthodes de l'orchestrateur...")
|
|
|
|
methods = [
|
|
"execute_action",
|
|
"rollback_last_actions",
|
|
"get_status"
|
|
]
|
|
|
|
for method in methods:
|
|
if hasattr(orchestrator, method):
|
|
print(f" ✓ {method}()")
|
|
else:
|
|
print(f" ✗ {method}() - MANQUANT")
|
|
|
|
# Test 5: Test du statut avec historique d'actions
|
|
print("\n5. Test du statut avec historique...")
|
|
|
|
status = orchestrator.get_status()
|
|
print(f" ✓ Statut obtenu")
|
|
print(f" ✓ Mode: {status['mode']}")
|
|
print(f" ✓ Running: {status['running']}")
|
|
print(f" ✓ Action history size: {status.get('action_history_size', 0)}")
|
|
|
|
# Test 6: Simulation d'exécution d'action (avec mock)
|
|
print("\n6. Simulation d'exécution d'action...")
|
|
|
|
with patch.dict('sys.modules', {'pyautogui': MagicMock()}):
|
|
from geniusia2.core.models import Action
|
|
from datetime import datetime
|
|
import numpy as np
|
|
|
|
# Créer une action de test
|
|
test_action = Action(
|
|
action_type="click",
|
|
target_element="test_button",
|
|
bbox=(100, 100, 50, 30),
|
|
confidence=0.95,
|
|
embedding=np.random.rand(512).astype(np.float32),
|
|
timestamp=datetime.now(),
|
|
window_title="Test Window",
|
|
parameters={"button": "left"}
|
|
)
|
|
|
|
# Créer une décision
|
|
decision = {
|
|
"action": test_action,
|
|
"confidence": 0.95,
|
|
"task_id": "test_task"
|
|
}
|
|
|
|
# Mock de execute_action pour éviter l'exécution réelle
|
|
with patch.object(orchestrator.input_utils, 'execute_action', return_value=True):
|
|
orchestrator.execute_action(decision)
|
|
print(" ✓ Action exécutée (simulée)")
|
|
print(f" ✓ Actions exécutées: {orchestrator.metrics['actions_executed']}")
|
|
|
|
# Test 7: Test de rollback (avec mock)
|
|
print("\n7. Test de rollback...")
|
|
|
|
with patch.dict('sys.modules', {'pyautogui': MagicMock()}):
|
|
# Ajouter quelques actions à l'historique
|
|
with patch.object(orchestrator.input_utils, 'execute_action', return_value=True):
|
|
orchestrator.input_utils.action_history = [
|
|
{"type": "click", "x": 100, "y": 100},
|
|
{"type": "type", "text": "test", "length": 4},
|
|
{"type": "scroll", "direction": "down", "amount": 3}
|
|
]
|
|
|
|
print(f" ✓ Historique: {len(orchestrator.input_utils.action_history)} actions")
|
|
|
|
# Mock execute_inverse_action
|
|
with patch.object(orchestrator.input_utils, 'execute_inverse_action', return_value=True):
|
|
orchestrator.rollback_last_actions(count=3)
|
|
print(" ✓ Rollback exécuté (simulé)")
|
|
|
|
# Test 8: Vérifier l'intégration complète
|
|
print("\n8. Vérification de l'intégration complète...")
|
|
|
|
integration_checks = [
|
|
("InputUtils dans Orchestrator", orchestrator.input_utils is not None),
|
|
("Méthode execute_action", hasattr(orchestrator, 'execute_action')),
|
|
("Méthode rollback_last_actions", hasattr(orchestrator, 'rollback_last_actions')),
|
|
("Logger partagé", orchestrator.input_utils.logger is logger),
|
|
("Config partagée", orchestrator.input_utils.config is config),
|
|
]
|
|
|
|
all_checks_passed = True
|
|
for check_name, check_result in integration_checks:
|
|
status_icon = "✓" if check_result else "✗"
|
|
print(f" {status_icon} {check_name}")
|
|
if not check_result:
|
|
all_checks_passed = False
|
|
|
|
# Test 9: Test de la chaîne complète (mock)
|
|
print("\n9. Test de la chaîne complète...")
|
|
|
|
with patch.dict('sys.modules', {'pyautogui': MagicMock()}):
|
|
# Simuler une décision d'action
|
|
test_decision = {
|
|
"action": test_action,
|
|
"confidence": 0.95,
|
|
"task_id": "integration_test"
|
|
}
|
|
|
|
# Mock toutes les opérations
|
|
with patch.object(orchestrator.input_utils, 'execute_action', return_value=True):
|
|
with patch.object(orchestrator.learning_manager, 'record_execution'):
|
|
# Exécuter
|
|
orchestrator.execute_action(test_decision)
|
|
print(" ✓ Chaîne complète exécutée")
|
|
print(" ✓ Action → InputUtils → Logger → LearningManager")
|
|
|
|
print("\n" + "=" * 60)
|
|
if all_checks_passed:
|
|
print("✓ TOUS LES TESTS D'INTÉGRATION RÉUSSIS!")
|
|
print("✓ InputUtils est correctement intégré avec l'Orchestrateur.")
|
|
else:
|
|
print("⚠ Certains tests d'intégration ont échoué.")
|
|
|
|
print("\nRésumé de l'intégration:")
|
|
print(" - InputUtils créé et intégré")
|
|
print(" - Orchestrateur peut exécuter des actions")
|
|
print(" - Rollback fonctionnel")
|
|
print(" - Logging complet")
|
|
print(" - Chaîne complète validée")
|
|
|
|
print("\n✓ Tests d'intégration terminés!")
|
|
|
|
except Exception as e:
|
|
print(f"\n✗ ERREUR: {e}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|
|
finally:
|
|
# Nettoyer
|
|
shutil.rmtree(temp_dir)
|
|
print("\n✓ Fichiers temporaires nettoyés")
|