Files
mtusi2026lab2-fork/tests/conftest.py
T
2026-10-23 00:20:58 +03:00

154 lines
5.1 KiB
Python

"""Фикстуры для async-тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит).
Перед запуском: `make db-up` (postgres + база <DB_NAME>_test).
Переменные:
TEST_DATABASE_URL по умолчанию postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test
TEST_USE_MIGRATIONS=1 строить схему через `alembic upgrade head` вместо Base.metadata.create_all
Все тесты и async-фикстуры живут в ОДНОМ event loop (pytest.ini: loop_scope=session),
поэтому пул соединений, созданный в фикстуре, можно использовать в тестах.
"""
import asyncio
import os
from collections.abc import AsyncIterator, Callable
import httpx
import pytest
from alembic import command
from alembic.config import Config
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlalchemy.pool import NullPool
from app.core.config import Settings
from app.main import create_app
from app.models import Base
DEFAULT_TEST_DATABASE_URL = (
"postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test"
)
def _database_url() -> str:
return os.environ.get("TEST_DATABASE_URL", DEFAULT_TEST_DATABASE_URL)
def _alembic_config(url: str) -> Config:
config = Config("alembic.ini")
config.set_main_option("sqlalchemy.url", url.replace("%", "%%"))
return config
async def upgrade_head(url: str) -> None:
"""alembic command.upgrade внутри вызывает asyncio.run, поэтому — в отдельном потоке."""
await asyncio.to_thread(command.upgrade, _alembic_config(url), "head")
async def reset_schema(engine: AsyncEngine) -> None:
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.drop_all)
await connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
@pytest.fixture(scope="session")
def database_url() -> str:
return _database_url()
@pytest.fixture(scope="session")
async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
engine = create_async_engine(database_url, poolclass=NullPool)
try:
async with engine.connect() as connection:
await connection.execute(text("SELECT 1"))
except Exception as error: # noqa: BLE001
pytest.exit(
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
f"{type(error).__name__}. Выполните `make db-up`.",
returncode=2,
)
await reset_schema(engine)
if os.environ.get("TEST_USE_MIGRATIONS") == "1":
await upgrade_head(database_url)
else:
async with engine.begin() as connection:
await connection.run_sync(Base.metadata.create_all)
yield engine
await engine.dispose()
@pytest.fixture(autouse=True)
async def clean_db(db_engine: AsyncEngine) -> None:
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
if names:
async with db_engine.begin() as connection:
await connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
def build_settings(database_url: str, **overrides: object) -> Settings:
values: dict[str, object] = {
"app_host": "127.0.0.1",
"app_port": 8080,
"app_env": "test",
"max_messages": 1000,
"max_in_flight": 32,
"log_level": "CRITICAL",
"database_url": database_url,
"session_ttl_seconds": 300,
"db_pool_size": 10,
"db_max_overflow": 10,
}
values.update(overrides)
return Settings(_env_file=None, **values) # type: ignore[arg-type]
@pytest.fixture
def settings(database_url: str) -> Settings:
return build_settings(database_url)
@pytest.fixture
def make_settings(database_url: str) -> Callable[..., Settings]:
def factory(**overrides: object) -> Settings:
return build_settings(database_url, **overrides)
return factory
def make_client(app, *, raise_app_exceptions: bool = True, timeout: float = 30) -> httpx.AsyncClient:
"""ASGITransport не запускает lifespan, поэтому engine закрывает вызывающий (см. fixtures)."""
return httpx.AsyncClient(
transport=httpx.ASGITransport(app=app, raise_app_exceptions=raise_app_exceptions),
base_url="http://testserver",
timeout=timeout,
)
@pytest.fixture
def app(settings: Settings):
application = create_app(settings)
@application.get("/__test__/explode", include_in_schema=False)
async def explode() -> None:
raise RuntimeError("test-secret")
return application
@pytest.fixture
async def client(app) -> AsyncIterator[httpx.AsyncClient]:
async with make_client(app) as test_client:
yield test_client
await app.state.engine.dispose()
@pytest.fixture
async def client_no_raise(app) -> AsyncIterator[httpx.AsyncClient]:
async with make_client(app, raise_app_exceptions=False) as test_client:
yield test_client
await app.state.engine.dispose()