-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconftest.py
More file actions
380 lines (328 loc) · 10.3 KB
/
conftest.py
File metadata and controls
380 lines (328 loc) · 10.3 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
"""
Global pytest configuration for Python microservices.
Provides shared fixtures, test environment setup, and common utilities.
"""
import asyncio
import os
import pytest
import pytest_asyncio
from typing import AsyncGenerator, Dict, Any
from unittest.mock import AsyncMock, MagicMock
import httpx
import asyncpg
import redis.asyncio as redis
from testcontainers.postgres import PostgresContainer
from testcontainers.redis import RedisContainer
from testcontainers.compose import DockerCompose
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Test environment configuration
TEST_ENV = os.getenv("TEST_ENV", "unit")
CI = os.getenv("CI", "false").lower() == "true"
@pytest.fixture(scope="session")
def event_loop():
"""Create an instance of the default event loop for the test session."""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
yield loop
loop.close()
@pytest.fixture(scope="session")
def postgres_container():
"""Provide PostgreSQL container for integration tests."""
if TEST_ENV == "unit":
yield None
return
with PostgresContainer(
"postgres:16-alpine",
username="test",
password="test",
dbname="test_db"
) as postgres:
# Wait for container to be ready
postgres.get_connection_url()
yield postgres
@pytest.fixture(scope="session")
def redis_container():
"""Provide Redis container for integration tests."""
if TEST_ENV == "unit":
yield None
return
with RedisContainer("redis:7-alpine") as redis_c:
yield redis_c
@pytest.fixture(scope="session")
async def test_database_url(postgres_container):
"""Provide database URL for tests."""
if postgres_container is None:
return "sqlite:///:memory:"
return postgres_container.get_connection_url().replace("postgresql://", "postgresql+asyncpg://")
@pytest.fixture(scope="session")
def test_redis_url(redis_container):
"""Provide Redis URL for tests."""
if redis_container is None:
return None
return redis_container.get_connection_url()
@pytest.fixture
async def db_connection(test_database_url: str) -> AsyncGenerator[asyncpg.Connection, None]:
"""Provide a database connection for tests."""
if "sqlite" in test_database_url:
yield None
return
# Extract connection params from URL
import urllib.parse
parsed = urllib.parse.urlparse(test_database_url)
conn = await asyncpg.connect(
host=parsed.hostname,
port=parsed.port,
user=parsed.username,
password=parsed.password,
database=parsed.path.lstrip('/')
)
try:
yield conn
finally:
await conn.close()
@pytest.fixture
async def redis_client(test_redis_url: str) -> AsyncGenerator[redis.Redis, None]:
"""Provide a Redis client for tests."""
if test_redis_url is None:
yield None
return
client = redis.Redis.from_url(test_redis_url)
try:
await client.ping()
yield client
finally:
await client.aclose()
@pytest.fixture
async def http_client() -> AsyncGenerator[httpx.AsyncClient, None]:
"""Provide an HTTP client for API testing."""
async with httpx.AsyncClient(timeout=30.0) as client:
yield client
@pytest.fixture
def mock_airtable_api():
"""Provide mock for Airtable API."""
mock = AsyncMock()
# Default responses
mock.get_base.return_value = {
"id": "appTest123",
"name": "Test Base",
"permissionLevel": "create"
}
mock.list_tables.return_value = {
"tables": [
{
"id": "tblTest123",
"name": "Test Table",
"primaryFieldId": "fldTest123",
"fields": [
{
"id": "fldTest123",
"name": "Name",
"type": "singleLineText"
}
]
}
]
}
mock.list_records.return_value = {
"records": [
{
"id": "recTest123",
"fields": {
"Name": "Test Record"
},
"createdTime": "2024-01-01T00:00:00.000Z"
}
]
}
return mock
@pytest.fixture
def mock_llm_client():
"""Provide mock for LLM clients (OpenAI, Anthropic, etc.)."""
mock = AsyncMock()
# Default chat completion response
mock.chat.completions.create.return_value = MagicMock(
choices=[
MagicMock(
message=MagicMock(
content="Mock AI response",
role="assistant"
),
finish_reason="stop"
)
],
usage=MagicMock(
prompt_tokens=10,
completion_tokens=5,
total_tokens=15
)
)
return mock
@pytest.fixture
def mock_auth_service():
"""Provide mock for authentication service."""
mock = AsyncMock()
# Default user data
test_user = {
"id": "test-user-id",
"email": "test@example.com",
"name": "Test User",
"role": "user",
"tenant_id": "test-tenant-id"
}
mock.verify_token.return_value = test_user
mock.get_user.return_value = test_user
mock.create_user.return_value = test_user
return mock
@pytest.fixture(autouse=True)
async def cleanup_database(db_connection):
"""Clean database before and after each test."""
if db_connection is None:
yield
return
# Get all table names
tables_query = """
SELECT tablename FROM pg_tables
WHERE schemaname = 'public'
AND tablename NOT LIKE 'alembic_%'
"""
try:
# Clean before test
await db_connection.execute("BEGIN")
tables = await db_connection.fetch(tables_query)
for table in tables:
await db_connection.execute(f"TRUNCATE TABLE {table['tablename']} CASCADE")
await db_connection.execute("COMMIT")
yield
# Clean after test
await db_connection.execute("BEGIN")
tables = await db_connection.fetch(tables_query)
for table in tables:
await db_connection.execute(f"TRUNCATE TABLE {table['tablename']} CASCADE")
await db_connection.execute("COMMIT")
except Exception as e:
logger.warning(f"Database cleanup failed: {e}")
await db_connection.execute("ROLLBACK")
yield
@pytest.fixture(autouse=True)
async def cleanup_redis(redis_client):
"""Clean Redis before and after each test."""
if redis_client is None:
yield
return
try:
# Clean before test
await redis_client.flushdb()
yield
# Clean after test
await redis_client.flushdb()
except Exception as e:
logger.warning(f"Redis cleanup failed: {e}")
yield
@pytest.fixture
def test_settings():
"""Provide test-specific settings."""
return {
"DATABASE_URL": "sqlite:///:memory:",
"REDIS_URL": "redis://localhost:6379/1",
"SECRET_KEY": "test-secret-key",
"JWT_SECRET": "test-jwt-secret",
"ENVIRONMENT": "test",
"LOG_LEVEL": "DEBUG",
"RATE_LIMIT_ENABLED": False,
"CACHE_TTL": 60,
"API_TIMEOUT": 30,
}
@pytest.fixture
def test_headers():
"""Provide common test headers."""
return {
"Authorization": "Bearer test-token",
"Content-Type": "application/json",
"User-Agent": "PyAirtable-Test/1.0",
"X-Tenant-ID": "test-tenant-id",
}
@pytest.fixture
def sample_user_data():
"""Provide sample user data for tests."""
return {
"id": "test-user-id",
"email": "test@example.com",
"name": "Test User",
"role": "user",
"tenant_id": "test-tenant-id",
"is_active": True,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
}
@pytest.fixture
def sample_workspace_data():
"""Provide sample workspace data for tests."""
return {
"id": "test-workspace-id",
"name": "Test Workspace",
"description": "A test workspace",
"tenant_id": "test-tenant-id",
"owner_id": "test-user-id",
"is_active": True,
"settings": {
"auto_sync": True,
"sync_interval": 300
},
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
}
# Pytest markers for different test types
def pytest_configure(config):
"""Configure pytest with custom markers."""
markers = [
"unit: Unit tests",
"integration: Integration tests",
"e2e: End-to-end tests",
"slow: Slow tests (> 1s)",
"external: Tests requiring external services",
"database: Tests requiring database",
"redis: Tests requiring Redis",
"rabbitmq: Tests requiring RabbitMQ",
"auth: Authentication tests",
"api: API tests",
"performance: Performance tests",
"security: Security tests",
"smoke: Smoke tests",
]
for marker in markers:
config.addinivalue_line("markers", marker)
def pytest_collection_modifyitems(config, items):
"""Modify test collection to add automatic markers."""
for item in items:
# Add markers based on test 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)
# Add slow marker for tests that take > 1 second
if hasattr(item, "function"):
if getattr(item.function, "_slow", False):
item.add_marker(pytest.mark.slow)
# Helper functions
def mark_slow(func):
"""Decorator to mark tests as slow."""
func._slow = True
return func
# Skip conditions
skip_if_no_docker = pytest.mark.skipif(
not os.path.exists("/var/run/docker.sock"),
reason="Docker not available"
)
skip_if_unit_test = pytest.mark.skipif(
TEST_ENV == "unit",
reason="Integration test environment not available"
)
skip_if_ci = pytest.mark.skipif(
CI,
reason="Skipped in CI environment"
)