init commit: create skeleton from lab1
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
"""Миграции с нуля: «миграции с нуля и повторный запуск без дублирования данных»."""
|
||||
|
||||
import pytest
|
||||
from alembic import command
|
||||
from alembic.autogenerate import compare_metadata
|
||||
from alembic.migration import MigrationContext
|
||||
from sqlalchemy import create_engine, inspect, text
|
||||
|
||||
from app.models import Base
|
||||
from tests.conftest import _alembic_config
|
||||
|
||||
EXPECTED_TABLES = {"users", "chats", "chat_members", "messages", "sessions"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def migrated_engine(database_url, db_engine):
|
||||
# db_engine гарантирует, что БД доступна; переключаем схему на «только миграции».
|
||||
engine = create_engine(database_url)
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
|
||||
command.upgrade(_alembic_config(database_url), "head")
|
||||
yield engine
|
||||
|
||||
Base.metadata.drop_all(engine)
|
||||
with engine.begin() as connection:
|
||||
connection.execute(text("DROP TABLE IF EXISTS alembic_version"))
|
||||
Base.metadata.create_all(engine) # вернуть схему для остальных тестов
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_upgrade_creates_all_tables(migrated_engine):
|
||||
assert EXPECTED_TABLES <= set(inspect(migrated_engine).get_table_names())
|
||||
|
||||
|
||||
def test_upgrade_twice_is_idempotent_and_keeps_data(migrated_engine, database_url):
|
||||
with migrated_engine.begin() as connection:
|
||||
connection.execute(
|
||||
text(
|
||||
"INSERT INTO users (id, username, display_name, password_hash) "
|
||||
"VALUES (gen_random_uuid(), 'keep_me', 'Keep', 'hash')"
|
||||
)
|
||||
)
|
||||
|
||||
command.upgrade(_alembic_config(database_url), "head") # повторный запуск
|
||||
|
||||
with migrated_engine.connect() as connection:
|
||||
count = connection.execute(
|
||||
text("SELECT count(*) FROM users WHERE username = 'keep_me'")
|
||||
).scalar_one()
|
||||
assert count == 1
|
||||
|
||||
|
||||
def test_models_and_migrations_are_in_sync(migrated_engine):
|
||||
"""Нет расхождений между ORM-моделями и схемой, созданной миграциями."""
|
||||
with migrated_engine.connect() as connection:
|
||||
context = MigrationContext.configure(connection, opts={"compare_type": True})
|
||||
diff = compare_metadata(context, Base.metadata)
|
||||
|
||||
assert diff == [], f"Создайте миграцию: alembic revision --autogenerate. Diff: {diff}"
|
||||
Reference in New Issue
Block a user