forked from mtusi2026/mtusi2026lab2
200 lines
6.6 KiB
Python
200 lines
6.6 KiB
Python
"""Фикстуры async-тестов на реальных PostgreSQL и Redis.
|
|
|
|
Перед запуском: `make test-stand-up` (тестовый стенд и база <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
|
|
TEST_REDIS_HOST/PORT/PASSWORD/DB по умолчанию localhost:6379, база 15
|
|
DOCKER_TESTS=1 включить тесты, которые перезапускают контейнеры compose
|
|
"""
|
|
|
|
import asyncio
|
|
import os
|
|
from collections.abc import AsyncIterator, Callable
|
|
|
|
import httpx
|
|
import pytest
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
from fastapi import FastAPI
|
|
from redis.asyncio import Redis
|
|
from redis.exceptions import RedisError
|
|
from sqlalchemy import text
|
|
from sqlalchemy.exc import SQLAlchemyError
|
|
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
|
|
from sqlalchemy.pool import NullPool
|
|
|
|
from app.core.config import Settings
|
|
from app.core.redis import create_redis_client
|
|
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 _redis_settings() -> dict[str, object]:
|
|
return {
|
|
"redis_host": os.environ.get("TEST_REDIS_HOST", "localhost"),
|
|
"redis_port": int(os.environ.get("TEST_REDIS_PORT", "6379")),
|
|
"redis_password": os.environ.get("TEST_REDIS_PASSWORD") or None,
|
|
"redis_db": int(os.environ.get("TEST_REDIS_DB", "15")),
|
|
}
|
|
|
|
|
|
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"))
|
|
|
|
|
|
async def close_app(app: FastAPI) -> None:
|
|
"""ASGITransport не запускает lifespan, поэтому ресурсы приложения закрываются явно."""
|
|
await app.state.redis.aclose()
|
|
await app.state.engine.dispose()
|
|
|
|
|
|
@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 (SQLAlchemyError, OSError) as error:
|
|
pytest.exit(
|
|
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
|
|
f"{type(error).__name__}. Выполните `make test-stand-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(scope="session")
|
|
async def redis_client() -> AsyncIterator[Redis]:
|
|
settings = build_settings(_database_url())
|
|
if settings.redis_db == 0:
|
|
pytest.exit("TEST_REDIS_DB=0 запрещён: тесты очищают базу Redis.", returncode=2)
|
|
|
|
client = create_redis_client(settings)
|
|
try:
|
|
await client.ping()
|
|
except (RedisError, OSError) as error:
|
|
pytest.exit(
|
|
f"Redis недоступен: {type(error).__name__}. Выполните `make test-stand-up`.",
|
|
returncode=2,
|
|
)
|
|
|
|
yield client
|
|
await client.flushdb()
|
|
await client.aclose()
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
async def clean_db(db_engine: AsyncEngine, redis_client: Redis) -> 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"))
|
|
await redis_client.flushdb()
|
|
|
|
|
|
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,
|
|
**_redis_settings(),
|
|
}
|
|
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:
|
|
url = str(overrides.pop("database_url", database_url))
|
|
return build_settings(url, **overrides)
|
|
|
|
return factory
|
|
|
|
|
|
def make_client(
|
|
app, *, raise_app_exceptions: bool = True, timeout: float = 30
|
|
) -> httpx.AsyncClient:
|
|
"""ASGITransport не запускает lifespan, поэтому ресурсы закрывает вызывающий (close_app)."""
|
|
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 close_app(app)
|
|
|
|
|
|
@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 close_app(app)
|