|
| 1 | +from pathlib import Path |
| 2 | +from typing import Optional, Type |
| 3 | +from unittest import mock |
| 4 | + |
| 5 | +import pytest |
| 6 | +from sqlalchemy import select |
| 7 | +from sqlalchemy.exc import OperationalError |
| 8 | +from sqlalchemy.orm import ( |
| 9 | + DeclarativeBase, |
| 10 | + Mapped, |
| 11 | + MappedAsDataclass, |
| 12 | + declared_attr, |
| 13 | + mapped_column, |
| 14 | +) |
| 15 | + |
| 16 | +import reflex.constants |
| 17 | +import reflex.model |
| 18 | +from reflex.model import Model, ModelRegistry, sqla_session |
| 19 | + |
| 20 | + |
| 21 | +@pytest.mark.filterwarnings( |
| 22 | + "ignore:This declarative base already contains a class with the same class name", |
| 23 | +) |
| 24 | +def test_automigration( |
| 25 | + tmp_working_dir: Path, |
| 26 | + monkeypatch: pytest.MonkeyPatch, |
| 27 | + model_registry: Type[ModelRegistry], |
| 28 | +): |
| 29 | + """Test alembic automigration with add and drop table and column. |
| 30 | +
|
| 31 | + Args: |
| 32 | + tmp_working_dir: directory where database and migrations are stored |
| 33 | + monkeypatch: pytest fixture to overwrite attributes |
| 34 | + model_registry: clean reflex ModelRegistry |
| 35 | + """ |
| 36 | + alembic_ini = tmp_working_dir / "alembic.ini" |
| 37 | + versions = tmp_working_dir / "alembic" / "versions" |
| 38 | + monkeypatch.setattr(reflex.constants, "ALEMBIC_CONFIG", str(alembic_ini)) |
| 39 | + |
| 40 | + config_mock = mock.Mock() |
| 41 | + config_mock.db_url = f"sqlite:///{tmp_working_dir}/reflex.db" |
| 42 | + monkeypatch.setattr(reflex.model, "get_config", mock.Mock(return_value=config_mock)) |
| 43 | + |
| 44 | + assert alembic_ini.exists() is False |
| 45 | + assert versions.exists() is False |
| 46 | + Model.alembic_init() |
| 47 | + assert alembic_ini.exists() |
| 48 | + assert versions.exists() |
| 49 | + |
| 50 | + class Base(DeclarativeBase): |
| 51 | + @declared_attr.directive |
| 52 | + def __tablename__(cls) -> str: |
| 53 | + return cls.__name__.lower() |
| 54 | + |
| 55 | + assert model_registry.register(Base) |
| 56 | + |
| 57 | + class ModelBase(Base, MappedAsDataclass): |
| 58 | + __abstract__ = True |
| 59 | + id: Mapped[Optional[int]] = mapped_column(primary_key=True, default=None) |
| 60 | + |
| 61 | + # initial table |
| 62 | + class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] |
| 63 | + t1: Mapped[str] = mapped_column(default="") |
| 64 | + |
| 65 | + with Model.get_db_engine().connect() as connection: |
| 66 | + assert Model.alembic_autogenerate( |
| 67 | + connection=connection, message="Initial Revision" |
| 68 | + ) |
| 69 | + assert Model.migrate() |
| 70 | + version_scripts = list(versions.glob("*.py")) |
| 71 | + assert len(version_scripts) == 1 |
| 72 | + assert version_scripts[0].name.endswith("initial_revision.py") |
| 73 | + |
| 74 | + with sqla_session() as session: |
| 75 | + session.add(AlembicThing(t1="foo")) |
| 76 | + session.commit() |
| 77 | + |
| 78 | + model_registry.get_metadata().clear() |
| 79 | + |
| 80 | + # Create column t2, mark t1 as optional with default |
| 81 | + class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] |
| 82 | + t1: Mapped[Optional[str]] = mapped_column(default="default") |
| 83 | + t2: Mapped[str] = mapped_column(default="bar") |
| 84 | + |
| 85 | + assert Model.migrate(autogenerate=True) |
| 86 | + assert len(list(versions.glob("*.py"))) == 2 |
| 87 | + |
| 88 | + with sqla_session() as session: |
| 89 | + session.add(AlembicThing(t2="baz")) |
| 90 | + session.commit() |
| 91 | + result = session.scalars(select(AlembicThing)).all() |
| 92 | + assert len(result) == 2 |
| 93 | + assert result[0].t1 == "foo" |
| 94 | + assert result[0].t2 == "bar" |
| 95 | + assert result[1].t1 == "default" |
| 96 | + assert result[1].t2 == "baz" |
| 97 | + |
| 98 | + model_registry.get_metadata().clear() |
| 99 | + |
| 100 | + # Drop column t1 |
| 101 | + class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] |
| 102 | + t2: Mapped[str] = mapped_column(default="bar") |
| 103 | + |
| 104 | + assert Model.migrate(autogenerate=True) |
| 105 | + assert len(list(versions.glob("*.py"))) == 3 |
| 106 | + |
| 107 | + with sqla_session() as session: |
| 108 | + result = session.scalars(select(AlembicThing)).all() |
| 109 | + assert len(result) == 2 |
| 110 | + assert result[0].t2 == "bar" |
| 111 | + assert result[1].t2 == "baz" |
| 112 | + |
| 113 | + # Add table |
| 114 | + class AlembicSecond(ModelBase): |
| 115 | + a: Mapped[int] = mapped_column(default=42) |
| 116 | + b: Mapped[float] = mapped_column(default=4.2) |
| 117 | + |
| 118 | + assert Model.migrate(autogenerate=True) |
| 119 | + assert len(list(versions.glob("*.py"))) == 4 |
| 120 | + |
| 121 | + with reflex.model.session() as session: |
| 122 | + session.add(AlembicSecond(id=None)) |
| 123 | + session.commit() |
| 124 | + result = session.scalars(select(AlembicSecond)).all() |
| 125 | + assert len(result) == 1 |
| 126 | + assert result[0].a == 42 |
| 127 | + assert result[0].b == 4.2 |
| 128 | + |
| 129 | + # No-op |
| 130 | + # assert Model.migrate(autogenerate=True) |
| 131 | + # assert len(list(versions.glob("*.py"))) == 4 |
| 132 | + |
| 133 | + # drop table (AlembicSecond) |
| 134 | + model_registry.get_metadata().clear() |
| 135 | + |
| 136 | + class AlembicThing(ModelBase): # pyright: ignore[reportGeneralTypeIssues] |
| 137 | + t2: Mapped[str] = mapped_column(default="bar") |
| 138 | + |
| 139 | + assert Model.migrate(autogenerate=True) |
| 140 | + assert len(list(versions.glob("*.py"))) == 5 |
| 141 | + |
| 142 | + with reflex.model.session() as session: |
| 143 | + with pytest.raises(OperationalError) as errctx: |
| 144 | + _ = session.scalars(select(AlembicSecond)).all() |
| 145 | + assert errctx.match(r"no such table: alembicsecond") |
| 146 | + # first table should still exist |
| 147 | + result = session.scalars(select(AlembicThing)).all() |
| 148 | + assert len(result) == 2 |
| 149 | + assert result[0].t2 == "bar" |
| 150 | + assert result[1].t2 == "baz" |
| 151 | + |
| 152 | + model_registry.get_metadata().clear() |
| 153 | + |
| 154 | + class AlembicThing(ModelBase): |
| 155 | + # changing column type not supported by default |
| 156 | + t2: Mapped[int] = mapped_column(default=42) |
| 157 | + |
| 158 | + assert Model.migrate(autogenerate=True) |
| 159 | + assert len(list(versions.glob("*.py"))) == 5 |
| 160 | + |
| 161 | + # clear all metadata to avoid influencing subsequent tests |
| 162 | + model_registry.get_metadata().clear() |
| 163 | + |
| 164 | + # drop remaining tables |
| 165 | + assert Model.migrate(autogenerate=True) |
| 166 | + assert len(list(versions.glob("*.py"))) == 6 |
0 commit comments