Spaces:
Runtime error
Runtime error
File size: 8,760 Bytes
330b6e4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | """
Shared pytest configuration and fixtures for all tests.
"""
import pytest
import os
import tempfile
import shutil
from unittest.mock import Mock, MagicMock, patch
from datetime import datetime, timedelta
# Test configuration
@pytest.fixture(scope="session")
def test_config():
"""Test configuration settings."""
return {
'database_url': 'sqlite:///:memory:',
'redis_url': 'redis://localhost:6379/15', # Use test database
'groq_api_key': 'test-api-key',
'session_timeout': 300, # 5 minutes for tests
'rate_limit_enabled': False,
'log_level': 'DEBUG'
}
# Database fixtures
@pytest.fixture(scope="function")
def temp_database():
"""Create temporary database for testing."""
temp_dir = tempfile.mkdtemp()
db_path = os.path.join(temp_dir, 'test_chat.db')
yield f'sqlite:///{db_path}'
# Cleanup
shutil.rmtree(temp_dir, ignore_errors=True)
# Mock fixtures
@pytest.fixture
def mock_groq_client():
"""Mock Groq client for testing."""
with patch('chat_agent.services.groq_client.GroqClient') as mock:
mock_instance = MagicMock()
# Default responses
mock_instance.generate_response.return_value = "This is a test response from the LLM."
mock_instance.stream_response.return_value = iter([
"This is ", "a test ", "streaming ", "response."
])
mock_instance.test_connection.return_value = True
mock.return_value = mock_instance
yield mock_instance
@pytest.fixture
def mock_redis():
"""Mock Redis client for testing."""
with patch('redis.from_url') as mock_redis:
mock_client = MagicMock()
# Mock Redis operations
mock_client.get.return_value = None
mock_client.set.return_value = True
mock_client.setex.return_value = True
mock_client.delete.return_value = 1
mock_client.ping.return_value = True
mock_redis.return_value = mock_client
yield mock_client
@pytest.fixture
def mock_database():
"""Mock database operations for testing."""
with patch('chat_agent.models.db') as mock_db:
mock_session = MagicMock()
mock_db.session = mock_session
# Mock database operations
mock_session.add.return_value = None
mock_session.commit.return_value = None
mock_session.rollback.return_value = None
mock_session.query.return_value = mock_session
mock_session.filter.return_value = mock_session
mock_session.first.return_value = None
mock_session.all.return_value = []
yield mock_session
# Service fixtures
@pytest.fixture
def session_manager(mock_database, mock_redis):
"""Create session manager with mocked dependencies."""
from chat_agent.services.session_manager import SessionManager
return SessionManager()
@pytest.fixture
def language_context_manager():
"""Create language context manager."""
from chat_agent.services.language_context import LanguageContextManager
return LanguageContextManager()
@pytest.fixture
def chat_history_manager(mock_database, mock_redis):
"""Create chat history manager with mocked dependencies."""
from chat_agent.services.chat_history import ChatHistoryManager
return ChatHistoryManager()
@pytest.fixture
def chat_agent(mock_groq_client, session_manager, language_context_manager, chat_history_manager):
"""Create chat agent with all dependencies."""
from chat_agent.services.chat_agent import ChatAgent
return ChatAgent(
groq_client=mock_groq_client,
session_manager=session_manager,
language_context_manager=language_context_manager,
chat_history_manager=chat_history_manager
)
# Test data fixtures
@pytest.fixture
def sample_user_id():
"""Sample user ID for testing."""
return "test-user-12345"
@pytest.fixture
def sample_session_data():
"""Sample session data for testing."""
return {
'session_id': 'test-session-12345',
'user_id': 'test-user-12345',
'language': 'python',
'created_at': datetime.utcnow(),
'last_active': datetime.utcnow(),
'message_count': 0,
'is_active': True,
'metadata': {}
}
@pytest.fixture
def sample_messages():
"""Sample chat messages for testing."""
return [
{
'id': 'msg-1',
'session_id': 'test-session-12345',
'role': 'user',
'content': 'What is Python?',
'language': 'python',
'timestamp': datetime.utcnow() - timedelta(minutes=5),
'metadata': {}
},
{
'id': 'msg-2',
'session_id': 'test-session-12345',
'role': 'assistant',
'content': 'Python is a high-level programming language.',
'language': 'python',
'timestamp': datetime.utcnow() - timedelta(minutes=4),
'metadata': {'tokens': 12}
},
{
'id': 'msg-3',
'session_id': 'test-session-12345',
'role': 'user',
'content': 'How do I create a list?',
'language': 'python',
'timestamp': datetime.utcnow() - timedelta(minutes=2),
'metadata': {}
}
]
# Flask app fixtures
@pytest.fixture
def app():
"""Create Flask app for testing."""
from flask import Flask
app = Flask(__name__)
app.config['TESTING'] = True
app.config['SECRET_KEY'] = 'test-secret-key'
app.config['WTF_CSRF_ENABLED'] = False
return app
@pytest.fixture
def client(app):
"""Create test client."""
return app.test_client()
@pytest.fixture
def auth_headers():
"""Authentication headers for API testing."""
return {
'X-User-ID': 'test-user-12345',
'Content-Type': 'application/json'
}
# Performance testing fixtures
@pytest.fixture
def performance_config():
"""Configuration for performance tests."""
return {
'light_load_users': 10,
'medium_load_users': 25,
'heavy_load_users': 50,
'messages_per_user': 3,
'max_response_time': 2.0,
'min_success_rate': 0.8
}
# Cleanup fixtures
@pytest.fixture(autouse=True)
def cleanup_test_data():
"""Automatically cleanup test data after each test."""
yield
# Cleanup logic here if needed
# For example, clear test caches, reset mocks, etc.
pass
# Markers for test categorization
def pytest_configure(config):
"""Configure pytest with custom markers."""
config.addinivalue_line(
"markers", "unit: Unit tests for individual components"
)
config.addinivalue_line(
"markers", "integration: Integration tests for component interactions"
)
config.addinivalue_line(
"markers", "e2e: End-to-end tests for complete workflows"
)
config.addinivalue_line(
"markers", "performance: Performance and load tests"
)
config.addinivalue_line(
"markers", "slow: Tests that take longer to run"
)
# Test collection customization
def pytest_collection_modifyitems(config, items):
"""Modify test collection to add markers automatically."""
for item in items:
# Add markers based on test file location
if "unit" in str(item.fspath):
item.add_marker(pytest.mark.unit)
elif "integration" in str(item.fspath):
item.add_marker(pytest.mark.integration)
elif "e2e" in str(item.fspath):
item.add_marker(pytest.mark.e2e)
elif "performance" in str(item.fspath):
item.add_marker(pytest.mark.performance)
item.add_marker(pytest.mark.slow)
# Skip conditions
def pytest_runtest_setup(item):
"""Setup conditions for running tests."""
# Skip performance tests in CI unless explicitly requested
if "performance" in item.keywords and not item.config.getoption("--run-performance", default=False):
pytest.skip("Performance tests skipped (use --run-performance to run)")
def pytest_addoption(parser):
"""Add custom command line options."""
parser.addoption(
"--run-performance",
action="store_true",
default=False,
help="Run performance tests"
)
parser.addoption(
"--run-slow",
action="store_true",
default=False,
help="Run slow tests"
) |