add async with all functions
This commit is contained in:
+52
-32
@@ -1,28 +1,32 @@
|
||||
"""Фикстуры для тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит — см. README лабы).
|
||||
"""Фикстуры для async-тестов с РЕАЛЬНОЙ PostgreSQL (SQLite не подходит).
|
||||
|
||||
Перед запуском поднимите БД и создайте тестовую базу:
|
||||
make db-up # docker compose up -d postgres + createdb messenger_test
|
||||
Перед запуском: `make db-up` (postgres + база <DB_NAME>_test).
|
||||
Переменные:
|
||||
TEST_DATABASE_URL по умолчанию postgresql+psycopg://messenger:messenger@localhost:5432/messenger_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 Callable, Iterator
|
||||
from collections.abc import AsyncIterator, Callable
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.engine import Engine
|
||||
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+psycopg://messenger:messenger@localhost:5432/messenger_test"
|
||||
"postgresql+asyncpg://messenger:messenger@localhost:5432/messenger_test"
|
||||
)
|
||||
|
||||
|
||||
@@ -36,17 +40,28 @@ def _alembic_config(url: str) -> Config:
|
||||
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")
|
||||
def db_engine(database_url: str) -> Iterator[Engine]:
|
||||
engine = create_engine(database_url)
|
||||
async def db_engine(database_url: str) -> AsyncIterator[AsyncEngine]:
|
||||
engine = create_async_engine(database_url, poolclass=NullPool)
|
||||
try:
|
||||
with engine.connect() as connection:
|
||||
connection.execute(text("SELECT 1"))
|
||||
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)}: "
|
||||
@@ -54,28 +69,24 @@ def db_engine(database_url: str) -> Iterator[Engine]:
|
||||
returncode=2,
|
||||
)
|
||||
|
||||
# Чистая схема на старте сессии: тесты не зависят от прошлых запусков.
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
await reset_schema(engine)
|
||||
|
||||
if os.environ.get("TEST_USE_MIGRATIONS") == "1":
|
||||
command.upgrade(_alembic_config(database_url), "head")
|
||||
await upgrade_head(database_url)
|
||||
else:
|
||||
Base.metadata.create_all(engine)
|
||||
async with engine.begin() as connection:
|
||||
await connection.run_sync(Base.metadata.create_all)
|
||||
|
||||
yield engine
|
||||
engine.dispose()
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_db(db_engine: Engine) -> Iterator[None]:
|
||||
"""Пустые таблицы перед каждым тестом (приложение коммитит, откат не годится)."""
|
||||
async def clean_db(db_engine: AsyncEngine) -> None:
|
||||
names = ", ".join(f'"{table.name}"' for table in Base.metadata.sorted_tables)
|
||||
if names:
|
||||
with db_engine.begin() as connection:
|
||||
connection.execute(text(f"TRUNCATE {names} RESTART IDENTITY CASCADE"))
|
||||
yield
|
||||
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:
|
||||
@@ -102,32 +113,41 @@ def settings(database_url: str) -> Settings:
|
||||
|
||||
@pytest.fixture
|
||||
def make_settings(database_url: str) -> Callable[..., Settings]:
|
||||
"""Settings с переопределениями: make_settings(session_ttl_seconds=1)."""
|
||||
|
||||
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)
|
||||
def explode() -> None:
|
||||
async def explode() -> None:
|
||||
raise RuntimeError("test-secret")
|
||||
|
||||
return application
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(app) -> Iterator[TestClient]:
|
||||
with TestClient(app) as test_client:
|
||||
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
|
||||
def client_no_raise(app) -> Iterator[TestClient]:
|
||||
with TestClient(app, raise_server_exceptions=False) as test_client:
|
||||
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()
|
||||
|
||||
Reference in New Issue
Block a user