68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
"""Pytest fixtures shared across API v1 tests."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import AsyncGenerator
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from app.api.deps import get_cache_backend, get_db_session
|
|
from app.core.security import password_hasher
|
|
from app.main import create_app
|
|
from app.models import Base
|
|
from httpx import ASGITransport, AsyncClient
|
|
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
|
from tests.utils.fake_redis import InMemoryRedis
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def stub_password_hasher(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""Replace bcrypt-dependent hashing with deterministic helpers for tests."""
|
|
|
|
def fake_hash(password: str) -> str:
|
|
return f"hashed-{password}"
|
|
|
|
def fake_verify(password: str, hashed_password: str) -> bool:
|
|
return hashed_password == f"hashed-{password}"
|
|
|
|
monkeypatch.setattr(password_hasher, "hash", fake_hash)
|
|
monkeypatch.setattr(password_hasher, "verify", fake_verify)
|
|
|
|
|
|
@pytest_asyncio.fixture()
|
|
async def session_factory() -> AsyncGenerator[async_sessionmaker[AsyncSession], None]:
|
|
engine = create_async_engine("sqlite+aiosqlite:///:memory:", future=True)
|
|
async with engine.begin() as conn:
|
|
await conn.run_sync(Base.metadata.create_all)
|
|
factory = async_sessionmaker(engine, expire_on_commit=False)
|
|
yield factory
|
|
await engine.dispose()
|
|
|
|
|
|
@pytest_asyncio.fixture()
|
|
async def client(
|
|
session_factory: async_sessionmaker[AsyncSession],
|
|
cache_stub: InMemoryRedis,
|
|
) -> AsyncGenerator[AsyncClient, None]:
|
|
app = create_app()
|
|
|
|
async def _get_session_override() -> AsyncGenerator[AsyncSession, None]:
|
|
async with session_factory() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|
|
|
|
app.dependency_overrides[get_db_session] = _get_session_override
|
|
app.dependency_overrides[get_cache_backend] = lambda: cache_stub
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://testserver") as test_client:
|
|
yield test_client
|
|
|
|
|
|
@pytest.fixture()
|
|
def cache_stub() -> InMemoryRedis:
|
|
return InMemoryRedis()
|