68 lines
2.2 KiB
Python
68 lines
2.2 KiB
Python
"""Миграции: применение с нуля, идемпотентный повтор, совпадение со схемой моделей."""
|
|
|
|
import pytest
|
|
from alembic.autogenerate import compare_metadata
|
|
from alembic.migration import MigrationContext
|
|
from sqlalchemy import inspect, text
|
|
|
|
from app.models import Base
|
|
from conftest import reset_schema, upgrade_head
|
|
|
|
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "counters", "idempotency_keys", "attachments", "message_attachments", "upload_intents"}
|
|
|
|
|
|
@pytest.fixture
|
|
async def migrated_engine(database_url, db_engine):
|
|
await reset_schema(db_engine)
|
|
await upgrade_head(database_url)
|
|
yield db_engine
|
|
|
|
await reset_schema(db_engine)
|
|
async with db_engine.begin() as connection:
|
|
await connection.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
async def test_upgrade_creates_all_tables(migrated_engine):
|
|
async with migrated_engine.connect() as connection:
|
|
tables = await connection.run_sync(
|
|
lambda sync: set(inspect(sync).get_table_names())
|
|
)
|
|
assert EXPECTED_TABLES <= tables
|
|
|
|
|
|
async def test_upgrade_twice_is_idempotent_and_keeps_data(
|
|
migrated_engine, database_url
|
|
):
|
|
async with migrated_engine.begin() as connection:
|
|
await connection.execute(
|
|
text(
|
|
"INSERT INTO users (id, username, display_name, password_hash) "
|
|
"VALUES (gen_random_uuid(), 'keep_me', 'Keep', 'hash')"
|
|
)
|
|
)
|
|
|
|
await upgrade_head(database_url)
|
|
|
|
async with migrated_engine.connect() as connection:
|
|
count = (
|
|
await connection.execute(
|
|
text("SELECT count(*) FROM users WHERE username = 'keep_me'")
|
|
)
|
|
).scalar_one()
|
|
assert count == 1
|
|
|
|
|
|
async def test_models_and_migrations_are_in_sync(migrated_engine):
|
|
def compare(sync_connection):
|
|
context = MigrationContext.configure(
|
|
sync_connection, opts={"compare_type": True}
|
|
)
|
|
return compare_metadata(context, Base.metadata)
|
|
|
|
async with migrated_engine.connect() as connection:
|
|
diff = await connection.run_sync(compare)
|
|
|
|
assert diff == [], (
|
|
f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
|
)
|