add tests

This commit is contained in:
2026-10-26 23:02:39 +03:00
parent 3082b84f61
commit 8ad0bb6947
22 changed files with 1042 additions and 121 deletions
+60 -14
View File
@@ -1,12 +1,11 @@
"""Фикстуры для async-тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит).
"""Фикстуры async-тестов на реальных PostgreSQL и Redis.
Перед запуском: `make db-up` (postgres + база <DB_NAME>_test).
Перед запуском: `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
Все тесты и async-фикстуры живут в ОДНОМ event loop (pytest.ini: loop_scope=session),
поэтому пул соединений, созданный в фикстуре, можно использовать в тестах.
TEST_REDIS_HOST/PORT/PASSWORD/DB по умолчанию localhost:6379, база 15
DOCKER_TESTS=1 включить тесты, которые перезапускают контейнеры compose
"""
import asyncio
@@ -17,11 +16,16 @@ 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
@@ -34,6 +38,15 @@ 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("%", "%%"))
@@ -51,6 +64,12 @@ async def reset_schema(engine: AsyncEngine) -> None:
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()
@@ -62,10 +81,10 @@ async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
try:
async with engine.connect() as connection:
await connection.execute(text("SELECT 1"))
except Exception as error: # noqa: BLE001
except (SQLAlchemyError, OSError) as error:
pytest.exit(
f"PostgreSQL недоступна по {engine.url.render_as_string(hide_password=True)}: "
f"{type(error).__name__}. Выполните `make db-up`.",
f"{type(error).__name__}. Выполните `make test-stand-up`.",
returncode=2,
)
@@ -81,12 +100,33 @@ async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
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) -> None:
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:
@@ -101,6 +141,7 @@ def build_settings(database_url: str, **overrides: object) -> Settings:
"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]
@@ -114,15 +155,20 @@ def settings(database_url: str) -> Settings:
@pytest.fixture
def make_settings(database_url: str) -> Callable[..., Settings]:
def factory(**overrides: object) -> Settings:
return build_settings(database_url, **overrides)
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, поэтому engine закрывает вызывающий (см. fixtures)."""
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),
transport=httpx.ASGITransport(
app=app, raise_app_exceptions=raise_app_exceptions
),
base_url="http://testserver",
timeout=timeout,
)
@@ -143,11 +189,11 @@ def app(settings: Settings):
async def client(app) -> AsyncIterator[httpx.AsyncClient]:
async with make_client(app) as test_client:
yield test_client
await app.state.engine.dispose()
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 app.state.engine.dispose()
await close_app(app)