"""The Alembic migration must produce exactly the schema the ORM models describe.""" import asyncio import os import pytest from alembic import command from alembic.autogenerate import compare_metadata from alembic.config import Config from alembic.migration import MigrationContext from sqlalchemy.ext.asyncio import create_async_engine from estimator.infra.db import Base, normalize_dsn PG = os.getenv("TEST_PG_DSN") def _alembic(dsn: str, *cmd) -> None: cfg = Config("alembic.ini") cfg.cmd_opts = type("O", (), {"x": [f"dsn={dsn}"]})() getattr(command, cmd[0])(cfg, *cmd[1:]) async def _diff(dsn: str): engine = create_async_engine(normalize_dsn(dsn)) try: async with engine.connect() as conn: def run(sync_conn): ctx = MigrationContext.configure(sync_conn, opts={"compare_type": True}) return compare_metadata(ctx, Base.metadata) return await conn.run_sync(run) finally: await engine.dispose() async def _tables(dsn: str) -> set[str]: engine = create_async_engine(normalize_dsn(dsn)) try: async with engine.connect() as conn: from sqlalchemy import inspect return set(await conn.run_sync(lambda c: inspect(c).get_table_names())) finally: await engine.dispose() def _drop_pg(dsn): import psycopg with psycopg.connect(dsn, autocommit=True) as c: c.execute("drop table if exists estimate_versions, estimates, alembic_version cascade") @pytest.fixture(params=["sqlite", "postgres"]) def fresh_dsn(request, tmp_path): if request.param == "postgres": if not PG: pytest.skip("set TEST_PG_DSN to run on PostgreSQL") _drop_pg(PG) yield PG _drop_pg(PG) else: yield f"sqlite:///{tmp_path / 'mig.db'}" async def test_upgrade_matches_models_and_downgrade_is_clean(fresh_dsn): await asyncio.to_thread(_alembic, fresh_dsn, "upgrade", "head") assert {"estimates", "estimate_versions"} <= await _tables(fresh_dsn) assert await _diff(fresh_dsn) == [] # no drift between migration and models await asyncio.to_thread(_alembic, fresh_dsn, "downgrade", "base") assert await _tables(fresh_dsn) <= {"alembic_version"} async def test_upgrade_is_idempotent(fresh_dsn): await asyncio.to_thread(_alembic, fresh_dsn, "upgrade", "head") await asyncio.to_thread(_alembic, fresh_dsn, "upgrade", "head") assert await _diff(fresh_dsn) == []