|
12 | 12 | # See the License for the specific language governing permissions and |
13 | 13 | # limitations under the License. |
14 | 14 |
|
15 | | -"""Pytest fixtures for RenderTrust tests. |
| 15 | +"""Shared pytest fixtures for the RenderTrust test suite. |
16 | 16 |
|
17 | | -Provides async HTTP client and database session overrides |
18 | | -for isolated, repeatable testing. |
| 17 | +Provides: |
| 18 | +- ``test_engine`` -- session-scoped async SQLAlchemy engine (SQLite in-memory) |
| 19 | +- ``db_session`` -- per-test async session with automatic rollback isolation |
| 20 | +- ``client`` -- async HTTP client wired to a fresh FastAPI app instance |
| 21 | +- ``test_user`` -- pre-created ``User`` row available for auth tests |
| 22 | +- ``admin_user`` -- pre-created admin ``User`` row |
| 23 | +- ``auth_headers`` -- ``Authorization: Bearer <jwt>`` headers for the test user |
| 24 | +- ``admin_auth_headers`` -- same for admin user |
| 25 | +
|
| 26 | +All async fixtures use **pytest-asyncio** with ``asyncio_mode = "auto"`` |
| 27 | +(configured in ``pyproject.toml``). |
19 | 28 | """ |
20 | 29 |
|
21 | | -import os |
22 | | -from collections.abc import AsyncGenerator |
| 30 | +from __future__ import annotations |
23 | 31 |
|
24 | | -import pytest |
25 | | -from httpx import ASGITransport, AsyncClient |
| 32 | +import os |
26 | 33 |
|
27 | | -# Set test environment before importing app modules |
| 34 | +# --------------------------------------------------------------------------- |
| 35 | +# Environment overrides -- MUST come before any application imports so that |
| 36 | +# ``core.config.get_settings()`` picks up the test values. |
| 37 | +# --------------------------------------------------------------------------- |
28 | 38 | os.environ.setdefault("APP_ENV", "testing") |
29 | 39 | os.environ.setdefault("APP_DEBUG", "false") |
30 | 40 | os.environ.setdefault("SECRET_KEY", "test-secret-key-not-for-production") |
31 | 41 | os.environ.setdefault("JWT_SECRET_KEY", "test-jwt-secret-not-for-production") |
32 | 42 | os.environ.setdefault( |
33 | 43 | "DATABASE_URL", |
34 | | - "postgresql+asyncpg://rendertrust:rendertrust_dev@localhost:5432/rendertrust_test", |
| 44 | + "sqlite+aiosqlite:///:memory:", |
35 | 45 | ) |
36 | 46 | os.environ.setdefault("REDIS_URL", "redis://localhost:6379/1") |
| 47 | +os.environ.setdefault("STRIPE_SECRET_KEY", "sk_test_fake") |
| 48 | +os.environ.setdefault("STRIPE_WEBHOOK_SECRET", "whsec_test_fake") |
| 49 | + |
| 50 | +from collections.abc import AsyncGenerator # noqa: E402 |
| 51 | + |
| 52 | +import pytest # noqa: E402 |
| 53 | +from httpx import ASGITransport, AsyncClient # noqa: E402 |
| 54 | +from passlib.hash import bcrypt # noqa: E402 |
| 55 | +from sqlalchemy.ext.asyncio import ( # noqa: E402 |
| 56 | + AsyncSession, |
| 57 | + async_sessionmaker, |
| 58 | + create_async_engine, |
| 59 | +) |
| 60 | + |
| 61 | +from core.auth.jwt import create_access_token # noqa: E402 |
| 62 | +from core.database import Base, get_db_session # noqa: E402 |
| 63 | +from core.main import create_app # noqa: E402 |
| 64 | +from core.models.base import User # noqa: E402 |
| 65 | + |
| 66 | +# --------------------------------------------------------------------------- |
| 67 | +# Test database URL -- uses in-memory SQLite so no external DB server needed. |
| 68 | +# Override with ``TEST_DATABASE_URL`` env-var to point at a real Postgres |
| 69 | +# instance when running integration tests against a live database. |
| 70 | +# --------------------------------------------------------------------------- |
| 71 | +TEST_DATABASE_URL = os.environ.get( |
| 72 | + "TEST_DATABASE_URL", |
| 73 | + "sqlite+aiosqlite:///:memory:", |
| 74 | +) |
37 | 75 |
|
| 76 | +TEST_USER_PASSWORD = "testpassword123" # noqa: S105 -- test-only secret |
38 | 77 |
|
| 78 | + |
| 79 | +# --------------------------------------------------------------------------- |
| 80 | +# Session-scoped engine: created once, tables created once, torn down at end. |
| 81 | +# --------------------------------------------------------------------------- |
| 82 | +@pytest.fixture(scope="session") |
| 83 | +async def test_engine(): |
| 84 | + """Create a session-scoped async engine and bootstrap the schema.""" |
| 85 | + engine = create_async_engine(TEST_DATABASE_URL, echo=False) |
| 86 | + |
| 87 | + async with engine.begin() as conn: |
| 88 | + await conn.run_sync(Base.metadata.create_all) |
| 89 | + |
| 90 | + yield engine |
| 91 | + |
| 92 | + async with engine.begin() as conn: |
| 93 | + await conn.run_sync(Base.metadata.drop_all) |
| 94 | + await engine.dispose() |
| 95 | + |
| 96 | + |
| 97 | +# --------------------------------------------------------------------------- |
| 98 | +# Per-test session with savepoint rollback for full isolation. |
| 99 | +# --------------------------------------------------------------------------- |
39 | 100 | @pytest.fixture |
40 | | -async def client() -> AsyncGenerator[AsyncClient, None]: |
41 | | - """Async HTTP client for testing FastAPI endpoints. |
| 101 | +async def db_session( |
| 102 | + test_engine, |
| 103 | +) -> AsyncGenerator[AsyncSession, None]: |
| 104 | + """Yield a per-test database session that rolls back after each test.""" |
| 105 | + async with test_engine.connect() as connection: |
| 106 | + transaction = await connection.begin() |
| 107 | + session_factory = async_sessionmaker( |
| 108 | + bind=connection, |
| 109 | + class_=AsyncSession, |
| 110 | + expire_on_commit=False, |
| 111 | + ) |
| 112 | + |
| 113 | + async with session_factory() as session: |
| 114 | + yield session |
| 115 | + |
| 116 | + await transaction.rollback() |
42 | 117 |
|
43 | | - Creates a fresh app instance and provides an HTTPX AsyncClient |
44 | | - configured to talk to it via ASGI transport (no real HTTP). |
45 | | - """ |
46 | | - from core.main import create_app |
47 | 118 |
|
| 119 | +# --------------------------------------------------------------------------- |
| 120 | +# Async HTTP test client with dependency overrides. |
| 121 | +# --------------------------------------------------------------------------- |
| 122 | +@pytest.fixture |
| 123 | +async def client( |
| 124 | + db_session: AsyncSession, |
| 125 | +) -> AsyncGenerator[AsyncClient, None]: |
| 126 | + """Async HTTP client with database session override.""" |
48 | 127 | app = create_app() |
| 128 | + |
| 129 | + async def _override_db() -> AsyncGenerator[AsyncSession, None]: |
| 130 | + yield db_session |
| 131 | + |
| 132 | + app.dependency_overrides[get_db_session] = _override_db |
| 133 | + |
49 | 134 | transport = ASGITransport(app=app) |
50 | 135 | async with AsyncClient(transport=transport, base_url="http://test") as ac: |
51 | 136 | yield ac |
| 137 | + |
| 138 | + app.dependency_overrides.clear() |
| 139 | + |
| 140 | + |
| 141 | +# --------------------------------------------------------------------------- |
| 142 | +# Test user fixtures. |
| 143 | +# --------------------------------------------------------------------------- |
| 144 | +@pytest.fixture |
| 145 | +async def test_user(db_session: AsyncSession) -> User: |
| 146 | + """Insert and return a test user with a known password.""" |
| 147 | + user = User( |
| 148 | + email="test@rendertrust.com", |
| 149 | + name="Test User", |
| 150 | + hashed_password=bcrypt.hash(TEST_USER_PASSWORD), |
| 151 | + is_active=True, |
| 152 | + is_admin=False, |
| 153 | + ) |
| 154 | + db_session.add(user) |
| 155 | + await db_session.flush() |
| 156 | + return user |
| 157 | + |
| 158 | + |
| 159 | +@pytest.fixture |
| 160 | +async def admin_user(db_session: AsyncSession) -> User: |
| 161 | + """Insert and return an admin test user.""" |
| 162 | + user = User( |
| 163 | + email="admin@rendertrust.com", |
| 164 | + name="Admin User", |
| 165 | + hashed_password=bcrypt.hash(TEST_USER_PASSWORD), |
| 166 | + is_active=True, |
| 167 | + is_admin=True, |
| 168 | + ) |
| 169 | + db_session.add(user) |
| 170 | + await db_session.flush() |
| 171 | + return user |
| 172 | + |
| 173 | + |
| 174 | +# --------------------------------------------------------------------------- |
| 175 | +# JWT auth header fixtures. |
| 176 | +# --------------------------------------------------------------------------- |
| 177 | +@pytest.fixture |
| 178 | +def auth_headers(test_user: User) -> dict[str, str]: |
| 179 | + """Return ``Authorization: Bearer <token>`` headers for ``test_user``.""" |
| 180 | + token = create_access_token({"sub": str(test_user.id)}) |
| 181 | + return {"Authorization": f"Bearer {token}"} |
| 182 | + |
| 183 | + |
| 184 | +@pytest.fixture |
| 185 | +def admin_auth_headers(admin_user: User) -> dict[str, str]: |
| 186 | + """Return ``Authorization: Bearer <token>`` headers for ``admin_user``.""" |
| 187 | + token = create_access_token({"sub": str(admin_user.id)}) |
| 188 | + return {"Authorization": f"Bearer {token}"} |
0 commit comments