import json from sqlalchemy import create_engine, inspect, text from app import models # noqa: F401 - enregistre les modeles SQLAlchemy from app.conf_store import AppConfig, config_path, write_raw_config from app.database import Base from app.migrations import ( CONF_MIGRATIONS, current_conf_version, migrate_conf_file, run_db_migrations, ) def test_db_migration_from_legacy_schema(tmp_path) -> None: """Une base 'legacy' (colonnes v1 absentes) est migree, sans perdre les donnees, et la migration n'est jouee qu'une seule fois.""" engine = create_engine(f"sqlite:///{tmp_path / 'legacy.db'}") with engine.begin() as conn: conn.execute( text( """ CREATE TABLE iso_movies ( id INTEGER PRIMARY KEY, radarr_movie_id INTEGER, radarr_movie_file_id INTEGER, title TEXT, path TEXT, status TEXT, last_seen_at DATETIME ) """ ) ) conn.execute( text( "INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id," " title, path, status) VALUES (10, 20, 'ISO Movie', '/x.iso', 'detected')" ) ) applied = run_db_migrations(engine) assert applied == [ "iso_movies: colonnes de suivi des conversions", "iso_movies: colonnes created_at/last_seen_at sur les bases anciennes", ] columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")} assert { "processed_at", "completed_at", "failed_step", "last_error", "poster_url", "radarr_linked", "created_at", } <= columns # Les donnees existantes sont conservees. with engine.connect() as conn: rows = list(conn.execute(text("SELECT title, radarr_linked FROM iso_movies"))) assert rows == [("ISO Movie", 1)] # Les versions sont tracees et les migrations ne sont pas rejouees. with engine.connect() as conn: recorded = list(conn.execute(text("SELECT version FROM schema_migrations"))) assert [row[0] for row in recorded] == [1, 2] assert run_db_migrations(engine) == [] def test_db_migration_fresh_database(tmp_path) -> None: """Sur une base vierge, create_all cree deja le schema complet: la migration v1 est inoffensive mais reste tracee.""" engine = create_engine(f"sqlite:///{tmp_path / 'fresh.db'}") Base.metadata.create_all(bind=engine) applied = run_db_migrations(engine) assert applied == [ "iso_movies: colonnes de suivi des conversions", "iso_movies: colonnes created_at/last_seen_at sur les bases anciennes", ] assert run_db_migrations(engine) == [] def test_conf_file_stamped_with_version() -> None: """Un conf.json d'avant le systeme (sans cle version) est charge tel quel et estampille avec la version courante.""" write_raw_config( { "radarr": {"url": "http://radarr:7878", "api_key": "k"}, "sonarr": {"url": "http://sonarr:8989", "api_key": "k"}, "jellyfin": {"url": "http://jf:8096"}, } ) applied = migrate_conf_file() # v1 -> v2 retire les services hors perimetre, puis etampille la version. assert applied == ["conf.json v1 -> v2"] raw = json.loads(config_path().read_text(encoding="utf-8")) assert raw["version"] == current_conf_version() assert raw["radarr"]["url"] == "http://radarr:7878" assert raw["radarr"]["api_key"] == "k" assert "sonarr" not in raw assert "jellyfin" not in raw # Deja a jour: plus rien a appliquer. assert migrate_conf_file() == [] def test_conf_migration_transforms_content(monkeypatch) -> None: """Une migration conf.json transforme le contenu et incremente la version, en chaine jusqu'a la version courante.""" def v1_to_v2(data: dict) -> dict: data["jellyfin"] = data.pop("jellyfin_old", {}) return data def v2_to_v3(data: dict) -> dict: data["prowlarr"] = {"url": None} return data monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", [v1_to_v2, v2_to_v3]) assert current_conf_version() == 3 write_raw_config({"version": 1, "jellyfin_old": {"url": "http://jf:8096"}}) applied = migrate_conf_file() assert applied == ["conf.json v1 -> v2", "conf.json v2 -> v3"] raw = json.loads(config_path().read_text(encoding="utf-8")) assert raw["version"] == 3 assert raw["jellyfin"] == {"url": "http://jf:8096"} assert "jellyfin_old" not in raw assert raw["prowlarr"] == {"url": None} # Deja a jour: plus aucune migration a appliquer. assert migrate_conf_file() == [] def test_appconfig_version_matches_registry(monkeypatch) -> None: """Invariant: la version par defaut d'AppConfig suit le registre de migrations conf.json.""" monkeypatch.setattr("app.migrations.CONF_MIGRATIONS", CONF_MIGRATIONS) assert AppConfig().version == current_conf_version() def test_db_migration_adds_created_at_on_very_old_database(tmp_path) -> None: """Une base d'epoque, sans created_at/last_seen_at, est reparee par la migration v2 et redevient utilisable par l'application.""" from sqlalchemy import create_engine, inspect, text from app.database import Base from app.migrations import run_db_migrations engine = create_engine(f"sqlite:///{tmp_path / 'old.db'}") with engine.begin() as conn: conn.execute( text( """ CREATE TABLE iso_movies ( id INTEGER PRIMARY KEY, radarr_movie_id INTEGER, radarr_movie_file_id INTEGER, title TEXT, year INTEGER, path TEXT, size INTEGER, status TEXT ) """ ) ) conn.execute( text( "INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id," " title, status) VALUES (1, 2, 'Vieux Film', 'detected')" ) ) run_db_migrations(engine) columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")} assert {"created_at", "last_seen_at", "radarr_linked", "last_error"} <= columns with engine.connect() as conn: rows = list(conn.execute(text("SELECT title, status FROM iso_movies"))) assert rows == [("Vieux Film", "detected")] # La table est conforme au modele: create_all ne change rien. Base.metadata.create_all(bind=engine)