""" Test configuration and fixtures for Lyra tests. """ import pytest import torch import numpy as np from pathlib import Path import tempfile import asyncio from unittest.mock import Mock, AsyncMock from typing import Dict, Any, Optional from lyra.config import LyraConfig from lyra.personality.matrix import PersonalityMatrix from lyra.personality.traits import OCEANTraits from lyra.emotions.system import EmotionalSystem, EmotionalState from lyra.core.self_evolution import SelfEvolutionEngine from lyra.core.thinking_agent import ThinkingAgent @pytest.fixture def device(): """Get appropriate device for testing.""" return torch.device("cpu") # Use CPU for tests to avoid GPU dependencies @pytest.fixture def mock_config(): """Mock configuration for testing.""" config = Mock(spec=LyraConfig) config.vocab_size = 1000 config.hidden_size = 128 config.num_layers = 2 config.num_heads = 2 config.context_length = 256 config.max_memory_gb = 1.0 config.personality_update_frequency = 10 config.emotion_decay_rate = 0.95 config.project_root = Path(tempfile.mkdtemp()) config.data_dir = config.project_root / "data" config.models_dir = config.project_root / "models" config.logs_dir = config.project_root / "logs" return config @pytest.fixture def sample_ocean_traits(): """Sample OCEAN personality traits for testing.""" return OCEANTraits( openness=0.7, conscientiousness=0.6, extraversion=0.8, agreeableness=0.9, neuroticism=0.3 ) @pytest.fixture def sample_emotional_state(): """Sample emotional state for testing.""" return EmotionalState( joy=0.7, trust=0.8, curiosity=0.9, emotional_intensity=0.6, emotional_stability=0.7 ) @pytest.fixture def personality_matrix(device): """Create personality matrix for testing.""" matrix = PersonalityMatrix(device=device, enable_self_modification=True) return matrix @pytest.fixture def emotional_system(device): """Create emotional system for testing.""" system = EmotionalSystem( input_dim=128, emotion_dim=19, memory_capacity=100, device=device ) return system @pytest.fixture def self_evolution_engine(device): """Create self-evolution engine for testing.""" engine = SelfEvolutionEngine( model_dim=128, evolution_rate=0.01, adaptation_threshold=0.7, device=device ) return engine @pytest.fixture def thinking_agent(device): """Create thinking agent for testing.""" agent = ThinkingAgent( model_dim=128, thought_types=8, max_thought_depth=3, device=device ) return agent @pytest.fixture def sample_context_embedding(device): """Sample context embedding tensor.""" return torch.randn(1, 10, 128, device=device) @pytest.fixture def sample_personality_tensor(device): """Sample personality state tensor.""" return torch.rand(1, 24, device=device) @pytest.fixture def sample_emotional_tensor(device): """Sample emotional state tensor.""" return torch.rand(1, 19, device=device) @pytest.fixture def sample_conversation_history(): """Sample conversation history for testing.""" return [ "Hello, how are you today?", "I'm doing well, thank you! How can I help you?", "I'm working on a project and feeling a bit stuck.", "I'd be happy to help! What kind of project are you working on?" ] @pytest.fixture def sample_user_message(): """Sample user message for testing.""" return "I'm really excited about this new AI project I'm working on!" @pytest.fixture def sample_book_content(): """Sample book content for knowledge processing tests.""" return """ The Art of Science Chapter 1: Introduction to Scientific Method Science is a systematic approach to understanding the natural world through observation, hypothesis formation, and experimentation. The scientific method has been the foundation of human progress for centuries. The key principles of scientific inquiry include: 1. Observation of natural phenomena 2. Formation of testable hypotheses 3. Design and execution of controlled experiments 4. Analysis of results and data 5. Drawing conclusions based on evidence Scientists throughout history have used these principles to make groundbreaking discoveries that have shaped our understanding of the universe. From Newton's laws of motion to Einstein's theory of relativity, scientific inquiry has revealed the fundamental principles governing our reality. Chapter 2: The Role of Hypothesis in Science A hypothesis is a proposed explanation for observed phenomena that can be tested through experimentation. Good hypotheses are specific, testable, and based on existing knowledge. """ @pytest.fixture async def mock_database_manager(): """Mock database manager for testing.""" manager = AsyncMock() manager.is_connected = True manager.async_session = AsyncMock() manager.create_user = AsyncMock() manager.get_user_by_discord_id = AsyncMock() manager.store_conversation = AsyncMock() manager.get_recent_conversations = AsyncMock(return_value=[]) manager.store_personality_state = AsyncMock() manager.store_emotional_memory = AsyncMock() manager.store_knowledge = AsyncMock() return manager @pytest.fixture def temp_directory(): """Create temporary directory for testing.""" with tempfile.TemporaryDirectory() as temp_dir: yield Path(temp_dir) @pytest.fixture def sample_gutenberg_book(): """Sample Gutenberg book data for testing.""" from lyra.knowledge.gutenberg_crawler import GutenbergBook return GutenbergBook( id=12345, title="Sample Public Domain Book", author="Test Author", language="en", category="Fiction", url="https://www.gutenberg.org/ebooks/12345", file_format="txt", download_url="https://www.gutenberg.org/files/12345/12345-0.txt", metadata={"test": True} ) class AsyncContextManager: """Helper for testing async context managers.""" def __init__(self, return_value=None): self.return_value = return_value async def __aenter__(self): return self.return_value async def __aexit__(self, exc_type, exc_val, exc_tb): pass @pytest.fixture def async_context_manager(): """Factory for creating async context managers.""" return AsyncContextManager # Event loop fixture for async tests @pytest.fixture(scope="session") def event_loop(): """Create an instance of the default event loop for the test session.""" loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() # Utility functions for tests def assert_tensor_shape(tensor: torch.Tensor, expected_shape: tuple, name: str = "tensor"): """Assert that a tensor has the expected shape.""" assert tensor.shape == expected_shape, ( f"{name} shape mismatch: expected {expected_shape}, got {tensor.shape}" ) def assert_tensor_range(tensor: torch.Tensor, min_val: float, max_val: float, name: str = "tensor"): """Assert that tensor values are within expected range.""" actual_min = tensor.min().item() actual_max = tensor.max().item() assert min_val <= actual_min, f"{name} minimum {actual_min} below expected {min_val}" assert actual_max <= max_val, f"{name} maximum {actual_max} above expected {max_val}" def create_mock_response(status: int = 200, text: str = "", json_data: Optional[Dict[str, Any]] = None): """Create a mock HTTP response.""" response = Mock() response.status = status response.text = AsyncMock(return_value=text) if json_data: response.json = AsyncMock(return_value=json_data) return response