import importlib.util from pathlib import Path import pytest from sqlalchemy import create_engine,text from app.schema import schema_preflight,check_schema_revision def revision(name): path=Path(__file__).parents[1]/"alembic"/"versions"/name spec=importlib.util.spec_from_file_location(name,path) module=importlib.util.module_from_spec(spec);spec.loader.exec_module(module) return module def test_legacy_baseline_and_drift(): module=revision("001_legacy_baseline.py") meta=module.metadata();engine=create_engine("sqlite://") with engine.begin() as c: meta.create_all(c) assert len(meta.tables)==6 assert schema_preflight(c,meta).matches c.execute(text("DROP INDEX visual_jobs_dispatch")) assert not schema_preflight(c,meta).matches def test_upgrade_backfills_legacy_and_preserves_rows(tmp_path): from alembic.config import Config from alembic import command config=Config(str(Path(__file__).parents[1]/"alembic.ini")) db=tmp_path/"upgrade.sqlite" config.attributes["url"]="sqlite+aiosqlite:///"+str(db) command.upgrade(config,"001") engine=create_engine("sqlite:///"+str(db)) with engine.begin() as c: c.execute(text("INSERT INTO visual_users (id,username,display_name,password_hash,role,disabled,created_at) VALUES ('owner','legacy','Legacy','UNCHANGED','admin',0,CURRENT_TIMESTAMP)")) command.upgrade(config,"head") with engine.begin() as c: check_schema_revision(c,{"003"}) row=c.execute(text("SELECT password_hash,must_change_password FROM visual_users WHERE id='owner'")).one() assert row==("UNCHANGED",0) def test_unversioned_database_refuses_production(): with create_engine("sqlite://").begin() as c: with pytest.raises(RuntimeError,match="unversioned"):check_schema_revision(c,{"003"}) def test_mysql_reflection_normalizes_only_implicit_collation_and_boolean(): from sqlalchemy import String,Boolean from sqlalchemy.dialects.mysql import dialect,VARCHAR,TINYINT from app.schema import compatible_type mysql=dialect() assert compatible_type(String(32),VARCHAR(32,collation="utf8mb4_unicode_ci"),mysql) assert compatible_type(Boolean(),TINYINT(display_width=1),mysql) assert not compatible_type(String(32),VARCHAR(64,collation="utf8mb4_unicode_ci"),mysql) assert not compatible_type(String(32,collation="utf8mb4_bin"),VARCHAR(32,collation="utf8mb4_unicode_ci"),mysql) assert not compatible_type(Boolean(),TINYINT(display_width=4),mysql)