from importlib.util import module_from_spec, spec_from_file_location from io import StringIO from pathlib import Path import pytest from alembic.migration import MigrationContext from alembic.operations import Operations from sqlalchemy import create_engine, inspect, text VERSIONS = Path(__file__).parents[2] / "mealie/alembic/versions" MIGRATIONS = [ ("2026-11-30-00.00.00_b742c6d50a10_add_step_ingredient_quantity.py", "recipe_ingredient_ref_link", "quantity"), ("2026-11-30-00.00.01_c981d7e62b11_add_step_cooking.py", "recipe_instructions", "cooking"), ] def load_migration(filename): spec = spec_from_file_location("step_metadata_migration", VERSIONS / filename) module = module_from_spec(spec) spec.loader.exec_module(module) return module @pytest.mark.parametrize(("filename", "table", "column"), MIGRATIONS) @pytest.mark.parametrize("dialect", ["sqlite", "postgresql"]) def test_additive_migration_sql(filename, table, column, dialect): output = StringIO() context = MigrationContext.configure(dialect_name=dialect, opts={"as_sql": True, "output_buffer": output}) with Operations.context(context): load_migration(filename).upgrade() sql = output.getvalue().upper() assert f"ALTER TABLE {table.upper()} ADD COLUMN {column.upper()}" in sql assert "NOT NULL" not in sql assert "DEFAULT" not in sql @pytest.mark.parametrize(("filename", "table", "column"), MIGRATIONS) def test_sqlite_upgrade_and_downgrade_preserve_rows(filename, table, column): engine = create_engine("sqlite://") with engine.begin() as connection: connection.execute(text(f"CREATE TABLE {table} (id INTEGER PRIMARY KEY, text VARCHAR)")) connection.execute(text(f"INSERT INTO {table} (id, text) VALUES (1, 'existing')")) migration = load_migration(filename) with Operations.context(MigrationContext.configure(connection)): migration.upgrade() assert next(col for col in inspect(connection).get_columns(table) if col["name"] == column)["nullable"] assert connection.execute(text(f"SELECT id, text, {column} FROM {table}")).one() == (1, "existing", None) migration.downgrade() assert connection.execute(text(f"SELECT id, text FROM {table}")).one() == (1, "existing") engine.dispose()