69 lines
2.5 KiB
Python
69 lines
2.5 KiB
Python
"""Guard the baseline migration against the models.
|
|
|
|
Migration 0001 builds the schema from ``Base.metadata`` (see its docstring).
|
|
That is only safe if something checks it, so: migrate a scratch database, then
|
|
ask Alembic to autogenerate against it and assert the diff is empty.
|
|
|
|
This test keeps working after 0001 is replaced by explicit DDL, and it is what
|
|
catches "added a column to the model, forgot the migration" from Phase 2 on.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
from conftest import needs_db
|
|
|
|
pytestmark = [pytest.mark.db, needs_db]
|
|
|
|
|
|
def test_migrated_schema_matches_the_models():
|
|
from alembic.autogenerate import compare_metadata
|
|
from alembic.migration import MigrationContext
|
|
from sqlalchemy import create_engine, text
|
|
|
|
from poorbird.config import get_settings
|
|
from poorbird.db import engine
|
|
from poorbird.models import Base
|
|
|
|
scratch = "poorbird_schema_check"
|
|
|
|
# CREATE DATABASE cannot run inside a transaction block.
|
|
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
|
|
conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"'))
|
|
conn.execute(text(f'CREATE DATABASE "{scratch}"'))
|
|
|
|
url = get_settings().database_url
|
|
scratch_url = url.rsplit("/", 1)[0] + "/" + scratch
|
|
scratch_engine = create_engine(scratch_url)
|
|
|
|
try:
|
|
# Apply the real migration chain, exactly as `poorbird migrate` would.
|
|
with scratch_engine.begin() as conn:
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
|
|
cfg = Config()
|
|
cfg.set_main_option(
|
|
"script_location", str(Path(__file__).resolve().parents[1] / "migrations")
|
|
)
|
|
cfg.set_main_option("sqlalchemy.url", scratch_url)
|
|
cfg.attributes["connection"] = conn
|
|
command.upgrade(cfg, "head")
|
|
|
|
with scratch_engine.connect() as conn:
|
|
ctx = MigrationContext.configure(
|
|
conn,
|
|
opts={"compare_type": True, "compare_server_default": True},
|
|
)
|
|
diff = compare_metadata(ctx, Base.metadata)
|
|
|
|
# alembic_version is Alembic's own bookkeeping, not part of the models.
|
|
diff = [d for d in diff if "alembic_version" not in str(d)]
|
|
assert diff == [], f"schema has drifted from the models:\n{diff}"
|
|
finally:
|
|
scratch_engine.dispose()
|
|
with engine.connect().execution_options(isolation_level="AUTOCOMMIT") as conn:
|
|
conn.execute(text(f'DROP DATABASE IF EXISTS "{scratch}"'))
|