|
| 1 | +"""Pytest configuration and fixtures.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from typing import AsyncGenerator, Generator |
| 5 | + |
| 6 | +import pytest |
| 7 | +from fastapi.testclient import TestClient |
| 8 | +from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker |
| 9 | + |
| 10 | +from app.main import app |
| 11 | +from app.models.base import Base |
| 12 | +from app.db.session import get_db |
| 13 | +from app.core.config import get_settings |
| 14 | + |
| 15 | + |
| 16 | +# Test database URL |
| 17 | +TEST_DATABASE_URL = "postgresql+asyncpg://postgres:password@localhost:5432/log_analysis_test_db" |
| 18 | + |
| 19 | + |
| 20 | +@pytest.fixture(scope="session") |
| 21 | +def event_loop() -> Generator: |
| 22 | + """Create event loop for async tests.""" |
| 23 | + loop = asyncio.get_event_loop_policy().new_event_loop() |
| 24 | + yield loop |
| 25 | + loop.close() |
| 26 | + |
| 27 | + |
| 28 | +@pytest.fixture(scope="session") |
| 29 | +async def test_engine(): |
| 30 | + """Create test database engine.""" |
| 31 | + engine = create_async_engine(TEST_DATABASE_URL, echo=False) |
| 32 | + |
| 33 | + async with engine.begin() as conn: |
| 34 | + await conn.run_sync(Base.metadata.create_all) |
| 35 | + |
| 36 | + yield engine |
| 37 | + |
| 38 | + async with engine.begin() as conn: |
| 39 | + await conn.run_sync(Base.metadata.drop_all) |
| 40 | + |
| 41 | + await engine.dispose() |
| 42 | + |
| 43 | + |
| 44 | +@pytest.fixture |
| 45 | +async def test_db(test_engine) -> AsyncGenerator[AsyncSession, None]: |
| 46 | + """Create test database session.""" |
| 47 | + async_session = async_sessionmaker( |
| 48 | + test_engine, |
| 49 | + class_=AsyncSession, |
| 50 | + expire_on_commit=False, |
| 51 | + ) |
| 52 | + |
| 53 | + async with async_session() as session: |
| 54 | + yield session |
| 55 | + |
| 56 | + |
| 57 | +@pytest.fixture |
| 58 | +def client(test_db) -> TestClient: |
| 59 | + """Create test client with database override.""" |
| 60 | + |
| 61 | + async def override_get_db(): |
| 62 | + yield test_db |
| 63 | + |
| 64 | + app.dependency_overrides[get_db] = override_get_db |
| 65 | + |
| 66 | + with TestClient(app) as c: |
| 67 | + yield c |
| 68 | + |
| 69 | + app.dependency_overrides.clear() |
| 70 | + |
| 71 | + |
| 72 | +@pytest.fixture |
| 73 | +def mock_jwt_token() -> str: |
| 74 | + """Create mock JWT token for testing.""" |
| 75 | + from app.core.security import SecurityManager |
| 76 | + |
| 77 | + security_manager = SecurityManager() |
| 78 | + token = security_manager.create_access_token( |
| 79 | + data={"sub": "test_user", "role": "admin"} |
| 80 | + ) |
| 81 | + return token |
0 commit comments