✨ Page Fichiers: inventaire du dossier des telechargements avec fiches TMDB
- Nouveau module app/media_files.py: scan du dossier MKVTOOL_DOWNLOADS_DIR, detection des fichiers video (films, episodes, ISO) avec taille reelle - Endpoint API dedie + onglet Fichiers dans le front (web/src/App.tsx), tri par taille, fiches/affiches TMDB films et series hors Radarr - app/tmdb.py: client TMDB pour les fiches et affiches - main.py/schemas.py/models.py/migrations.py: wiring de l'inventaire, persistance en base (table download_files) et migrations - tests: test_files_scan.py + ajustement test_migrations.py - e2e: nouvelle spec 08-fichiers.spec.ts, helpers et e2e_server mis a jour - doc: README et DOCUMENTATION a jour Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
1 parent
7f600557df
commit
bff2c8acbc
16 files changed
+7201
-5229
No files matched your search
@@ -0,0 +1,347 @@
|
||||
"""Scan du dossier des telechargements (page Fichiers) et affiches TMDB.
|
||||
|
||||
Couvre le parsing des noms (films, series SxxEyy / dossiers Season XX, ISO
|
||||
vs MKV renomme), l'endpoint de scan (inventaire persistant, suppressions,
|
||||
tailles), la recherche d'affiches TMDB (films et series) et la config du
|
||||
service TMDB dans conf.json.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import respx
|
||||
from fastapi.testclient import TestClient
|
||||
from httpx import Response
|
||||
|
||||
from app.conf_store import AppConfig, read_config, service_status, write_config
|
||||
from app.config import settings
|
||||
from app.database import SessionLocal
|
||||
from app.main import app
|
||||
from app.media_files import clean_series_dir, clean_title, collect_video_files, parse_video_file
|
||||
from app.models import DownloadFile
|
||||
|
||||
TMDB_BASE = "https://api.themoviedb.org/3"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def downloads_dir(tmp_path, monkeypatch) -> Path:
|
||||
"""Dossier des telechargements isole par test + table vide."""
|
||||
monkeypatch.setattr(settings, "downloads_dir", tmp_path)
|
||||
with SessionLocal() as db:
|
||||
db.query(DownloadFile).delete()
|
||||
db.commit()
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def tmdb_conf():
|
||||
"""Restaure conf.json apres le test (partage entre les tests)."""
|
||||
saved = read_config().model_copy(deep=True)
|
||||
yield
|
||||
write_config(saved)
|
||||
|
||||
|
||||
def _populate(root: Path) -> None:
|
||||
(root / "Mon Film 2024").mkdir(parents=True)
|
||||
(root / "Mon Film 2024" / "Mon.Film.2024.1080p.BluRay.x264-GRP.mkv").write_bytes(b"x" * 2048)
|
||||
(root / "Ma Serie").mkdir()
|
||||
(root / "Ma Serie" / "Ma.Serie.S01E01.720p.mkv").write_bytes(b"x" * 1024)
|
||||
(root / "Ma Serie" / "Ma.Serie.S01E02.720p.mkv").write_bytes(b"x" * 512)
|
||||
(root / "Disque 2020.iso").write_bytes(b"\x00CD001 fake image disque")
|
||||
(root / "notes.txt").write_text("pas une video")
|
||||
(root / ".cache").mkdir()
|
||||
(root / ".cache" / "cache.mkv").write_bytes(b"x" * 10)
|
||||
|
||||
|
||||
# --- Parsing des noms ---
|
||||
def test_clean_title_strips_release_tags() -> None:
|
||||
assert clean_title("Mon.Film.1080p.BluRay.x264-GRP") == "Mon Film"
|
||||
assert clean_title("Serie [FRENCH] 720p") == "Serie"
|
||||
assert clean_title("Film (2024)") == "Film"
|
||||
|
||||
|
||||
def test_clean_series_dir_strips_season_suffix() -> None:
|
||||
assert clean_series_dir("Ma Serie S01") == "Ma Serie"
|
||||
assert clean_series_dir("Ma.Serie.Saison.02") == "Ma Serie"
|
||||
|
||||
|
||||
def test_parse_movie_with_year_in_filename() -> None:
|
||||
item = parse_video_file(Path("Mon.Film.2024.1080p.BluRay.x264-GRP.mkv"), 100, False)
|
||||
assert item.kind == "movie"
|
||||
assert item.title == "Mon Film"
|
||||
assert item.year == 2024
|
||||
assert item.series_title is None
|
||||
|
||||
|
||||
def test_parse_movie_year_in_parentheses() -> None:
|
||||
"""La coupe sur l'année ne laisse pas de parenthese ouverte ("Cars (")."""
|
||||
item = parse_video_file(Path("Cars 2006") / "Cars (2006).mkv", 7, False)
|
||||
assert item.kind == "movie"
|
||||
assert item.title == "Cars"
|
||||
assert item.year == 2006
|
||||
|
||||
|
||||
def test_parse_movie_year_in_parent_folder() -> None:
|
||||
item = parse_video_file(Path("Mon Film 2024") / "mon film.mkv", 100, False)
|
||||
assert item.kind == "movie"
|
||||
assert item.title == "Mon Film"
|
||||
assert item.year == 2024
|
||||
|
||||
|
||||
def test_parse_real_iso_vs_renamed_mkv() -> None:
|
||||
iso = parse_video_file(Path("Dossier") / "Disque.2020.iso", 100, real_iso=True)
|
||||
assert iso.kind == "iso"
|
||||
assert iso.title == "Disque"
|
||||
assert iso.year == 2020
|
||||
renamed = parse_video_file(Path("Film.2024.iso"), 100, real_iso=False)
|
||||
assert renamed.kind == "movie"
|
||||
|
||||
|
||||
def test_parse_episode_sxxeyy() -> None:
|
||||
item = parse_video_file(Path("Ma Serie") / "Ma.Serie.S02E03.720p.mkv", 10, False)
|
||||
assert item.kind == "episode"
|
||||
assert item.series_title == "Ma Serie"
|
||||
assert item.title == "Ma Serie"
|
||||
assert item.season == 2
|
||||
assert item.episode == 3
|
||||
|
||||
|
||||
def test_parse_episode_x_pattern_falls_back_to_folder() -> None:
|
||||
item = parse_video_file(Path("Ma Serie S01") / "1x05.mkv", 10, False)
|
||||
assert item.kind == "episode"
|
||||
assert item.series_title == "Ma Serie"
|
||||
assert item.season == 1
|
||||
assert item.episode == 5
|
||||
|
||||
|
||||
def test_parse_episode_in_season_folder() -> None:
|
||||
item = parse_video_file(Path("Ma Serie") / "Season 01" / "episode 07.mkv", 10, False)
|
||||
assert item.kind == "episode"
|
||||
assert item.series_title == "Ma Serie"
|
||||
assert item.season == 1
|
||||
assert item.episode == 7
|
||||
|
||||
|
||||
# --- Parcours du dossier ---
|
||||
def test_collect_video_files_skips_hidden_and_non_video(tmp_path) -> None:
|
||||
_populate(tmp_path)
|
||||
found = collect_video_files(tmp_path)
|
||||
names = sorted(item.name for item in found)
|
||||
assert names == [
|
||||
"Disque 2020.iso",
|
||||
"Ma.Serie.S01E01.720p.mkv",
|
||||
"Ma.Serie.S01E02.720p.mkv",
|
||||
"Mon.Film.2024.1080p.BluRay.x264-GRP.mkv",
|
||||
]
|
||||
by_name = {item.name: item for item in found}
|
||||
assert by_name["Disque 2020.iso"].kind == "iso"
|
||||
assert by_name["Disque 2020.iso"].size == len(b"\x00CD001 fake image disque")
|
||||
assert by_name["Mon.Film.2024.1080p.BluRay.x264-GRP.mkv"].size == 2048
|
||||
assert all(item.path != str(Path(".cache") / "cache.mkv") for item in found)
|
||||
|
||||
|
||||
def test_collect_video_files_renamed_mkv_iso_is_not_iso(tmp_path) -> None:
|
||||
fake_mkv = tmp_path / "Film.2024.iso"
|
||||
fake_mkv.write_bytes(b"\x1aE\xdf\xa3" + b"x" * 100) # en-tete EBML
|
||||
found = collect_video_files(tmp_path)
|
||||
assert len(found) == 1
|
||||
assert found[0].kind == "movie"
|
||||
|
||||
|
||||
# --- API de scan ---
|
||||
def test_scan_downloads_requires_existing_dir(monkeypatch, tmp_path) -> None:
|
||||
monkeypatch.setattr(settings, "downloads_dir", tmp_path / "absent")
|
||||
with TestClient(app) as client:
|
||||
response = client.post("/api/downloads/scan")
|
||||
assert response.status_code == 409
|
||||
assert "MKVTOOL_DOWNLOADS_DIR" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_scan_downloads_inventories_files_and_sizes(downloads_dir) -> None:
|
||||
_populate(downloads_dir)
|
||||
with TestClient(app) as client:
|
||||
scan = client.post("/api/downloads/scan")
|
||||
listed = client.get("/api/downloads/files")
|
||||
assert scan.status_code == 200
|
||||
data = scan.json()
|
||||
assert data["scanned_files"] == 4
|
||||
assert data["isos"] == 1
|
||||
assert data["movies"] == 1
|
||||
assert data["episodes"] == 2
|
||||
assert data["series"] == 1
|
||||
assert data["total_size"] == 2048 + 1024 + 512 + len(b"\x00CD001 fake image disque")
|
||||
assert data["tmdb_configured"] is False
|
||||
assert data["posters_found"] == 0
|
||||
assert len(data["files"]) == 4
|
||||
# L'inventaire persiste et est relu par GET, avec la racine du dossier.
|
||||
assert listed.json()["downloads_dir"] == str(downloads_dir)
|
||||
assert [item["name"] for item in listed.json()["files"]] == [
|
||||
item["name"] for item in data["files"]
|
||||
]
|
||||
episode = next(item for item in data["files"] if item["kind"] == "episode")
|
||||
assert episode["series_title"] == "Ma Serie"
|
||||
assert {item["episode"] for item in data["files"] if item["kind"] == "episode"} == {1, 2}
|
||||
|
||||
|
||||
def test_scan_downloads_removes_disappeared_files(downloads_dir) -> None:
|
||||
_populate(downloads_dir)
|
||||
with TestClient(app) as client:
|
||||
first = client.post("/api/downloads/scan").json()
|
||||
assert first["deleted"] == 0
|
||||
(downloads_dir / "Disque 2020.iso").unlink()
|
||||
second = client.post("/api/downloads/scan").json()
|
||||
assert second["scanned_files"] == 3
|
||||
assert second["deleted"] == 1
|
||||
assert second["isos"] == 0
|
||||
assert len(second["files"]) == 3
|
||||
|
||||
|
||||
def _tmdb_router(movie_results=None, tv_results=None) -> respx.MockRouter:
|
||||
"""Router respx neuf par test (les routes du router global fuiraient
|
||||
d'un test a l'autre)."""
|
||||
router = respx.MockRouter(assert_all_called=False)
|
||||
router.get(f"{TMDB_BASE}/configuration").mock(
|
||||
return_value=Response(200, json={"images": {"secure_base_url": "https://image.tmdb.org/t/p/"}})
|
||||
)
|
||||
router.get(f"{TMDB_BASE}/search/movie").mock(
|
||||
return_value=Response(
|
||||
200, json={"results": movie_results if movie_results is not None else []}
|
||||
)
|
||||
)
|
||||
router.get(f"{TMDB_BASE}/search/tv").mock(
|
||||
return_value=Response(200, json={"results": tv_results if tv_results is not None else []})
|
||||
)
|
||||
return router
|
||||
|
||||
|
||||
def test_scan_keeps_posters_between_scans(downloads_dir, tmdb_conf) -> None:
|
||||
"""Un second scan ne re-cherche pas les affiches deja resolues."""
|
||||
_populate(downloads_dir)
|
||||
router = _tmdb_router(
|
||||
movie_results=[{"id": 42, "poster_path": "/movie.jpg"}],
|
||||
tv_results=[{"id": 77, "poster_path": "/tv.jpg"}],
|
||||
)
|
||||
with TestClient(app) as client:
|
||||
client.put("/api/settings/tmdb", json={"url": "", "api_key": "test-key"})
|
||||
with router:
|
||||
with TestClient(app) as client:
|
||||
first = client.post("/api/downloads/scan").json()
|
||||
second = client.post("/api/downloads/scan").json()
|
||||
assert first["tmdb_configured"] is True
|
||||
# 1 film + 1 ISO + 2 episodes (la serie n'est cherchee qu'une fois, cache).
|
||||
assert first["posters_found"] == 4
|
||||
assert second["posters_found"] == 0
|
||||
by_name = {item["name"]: item for item in second["files"]}
|
||||
assert by_name["Mon.Film.2024.1080p.BluRay.x264-GRP.mkv"]["poster_url"] == (
|
||||
"https://image.tmdb.org/t/p/w500/movie.jpg"
|
||||
)
|
||||
assert by_name["Mon.Film.2024.1080p.BluRay.x264-GRP.mkv"]["tmdb_id"] == 42
|
||||
assert by_name["Ma.Serie.S01E01.720p.mkv"]["poster_url"] == (
|
||||
"https://image.tmdb.org/t/p/w500/tv.jpg"
|
||||
)
|
||||
assert by_name["Ma.Serie.S01E01.720p.mkv"]["tmdb_kind"] == "tv"
|
||||
|
||||
|
||||
def test_poster_refresh_endpoint(downloads_dir, tmdb_conf) -> None:
|
||||
_populate(downloads_dir)
|
||||
cfg = read_config()
|
||||
cfg.tmdb.api_key = None
|
||||
write_config(cfg)
|
||||
with TestClient(app) as client:
|
||||
# TMDB non configure: aucun appel reseau, aucune affiche.
|
||||
scan = client.post("/api/downloads/scan").json()
|
||||
movie = next(item for item in scan["files"] if item["kind"] == "movie")
|
||||
assert movie["poster_url"] is None
|
||||
with TestClient(app) as client:
|
||||
client.put("/api/settings/tmdb", json={"url": "", "api_key": "test-key"})
|
||||
router = _tmdb_router(movie_results=[{"id": 42, "poster_path": "/movie.jpg"}])
|
||||
with router:
|
||||
with TestClient(app) as client:
|
||||
refreshed = client.post(f"/api/downloads/files/{movie['id']}/poster")
|
||||
assert refreshed.status_code == 200
|
||||
assert refreshed.json()["poster_url"] == "https://image.tmdb.org/t/p/w500/movie.jpg"
|
||||
assert refreshed.json()["tmdb_id"] == 42
|
||||
|
||||
|
||||
def test_poster_refresh_without_match(downloads_dir, tmdb_conf) -> None:
|
||||
_populate(downloads_dir)
|
||||
with TestClient(app) as client:
|
||||
client.put("/api/settings/tmdb", json={"url": "", "api_key": "test-key"})
|
||||
router = _tmdb_router() # aucun resultat: pas d'affiche, aucun appel reel
|
||||
with router:
|
||||
with TestClient(app) as client:
|
||||
scan = client.post("/api/downloads/scan").json()
|
||||
movie = next(item for item in scan["files"] if item["kind"] == "movie")
|
||||
response = client.post(f"/api/downloads/files/{movie['id']}/poster")
|
||||
assert response.status_code == 409
|
||||
assert "Aucune affiche" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_poster_refresh_requires_tmdb_configured(downloads_dir, tmdb_conf) -> None:
|
||||
_populate(downloads_dir)
|
||||
cfg = read_config()
|
||||
cfg.tmdb.api_key = None
|
||||
write_config(cfg)
|
||||
with TestClient(app) as client:
|
||||
scan = client.post("/api/downloads/scan").json()
|
||||
movie = next(item for item in scan["files"] if item["kind"] == "movie")
|
||||
response = client.post(f"/api/downloads/files/{movie['id']}/poster")
|
||||
assert response.status_code == 409
|
||||
assert "TMDB" in response.json()["detail"]
|
||||
|
||||
|
||||
# --- Configuration TMDB ---
|
||||
def test_tmdb_configured_with_default_url_when_only_api_key() -> None:
|
||||
cfg = AppConfig()
|
||||
assert cfg.tmdb.default_url == TMDB_BASE
|
||||
assert service_status(cfg.tmdb) == "unconfigured"
|
||||
cfg.tmdb.api_key = "k"
|
||||
assert service_status(cfg.tmdb) == "configured"
|
||||
|
||||
|
||||
def test_tmdb_settings_lifecycle(tmdb_conf) -> None:
|
||||
router = _tmdb_router()
|
||||
with router:
|
||||
with TestClient(app) as client:
|
||||
put = client.put("/api/settings/tmdb", json={"url": "", "api_key": "test-key"})
|
||||
assert put.status_code == 200
|
||||
assert put.json()["api_key_configured"] is True
|
||||
assert put.json()["status"] == "configured"
|
||||
got = client.get("/api/settings/tmdb")
|
||||
assert got.json()["status"] == "configured"
|
||||
test = client.post("/api/settings/tmdb/test")
|
||||
assert test.status_code == 200
|
||||
assert client.get("/api/settings/tmdb").json()["status"] == "tested"
|
||||
|
||||
|
||||
def test_tmdb_test_failure_marks_error(tmdb_conf) -> None:
|
||||
router = respx.MockRouter(assert_all_called=False)
|
||||
router.get(f"{TMDB_BASE}/configuration").mock(
|
||||
return_value=Response(401, json={"status_message": "Invalid API key"})
|
||||
)
|
||||
with router:
|
||||
with TestClient(app) as client:
|
||||
client.put("/api/settings/tmdb", json={"url": "", "api_key": "bad-key"})
|
||||
response = client.post("/api/settings/tmdb/test")
|
||||
assert response.status_code == 502
|
||||
assert client.get("/api/settings/tmdb").json()["status"] == "error"
|
||||
|
||||
|
||||
def test_tmdb_test_requires_api_key(tmdb_conf) -> None:
|
||||
cfg = read_config()
|
||||
cfg.tmdb.api_key = None
|
||||
write_config(cfg)
|
||||
with TestClient(app) as client:
|
||||
response = client.post("/api/settings/tmdb/test")
|
||||
assert response.status_code == 409
|
||||
|
||||
|
||||
# --- Divers ---
|
||||
def test_scan_ignores_existing_iso_movies_table(downloads_dir) -> None:
|
||||
"""Le scan des telechargements ne touche pas l'inventaire ISO (Radarr)."""
|
||||
_populate(downloads_dir)
|
||||
with TestClient(app) as client:
|
||||
client.post("/api/downloads/scan")
|
||||
movies = client.get("/api/movies")
|
||||
assert movies.status_code == 200
|
||||
assert isinstance(movies.json(), list)
|
||||
+247
-245
@@ -1,245 +1,247 @@
|
||||
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",
|
||||
"iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
"iso_movies: colonne purge_pending (suppression permanente en attente)",
|
||||
"iso_movies: colonne iso_purged (ISO de telechargement partie)",
|
||||
]
|
||||
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",
|
||||
"qb_content_path",
|
||||
} <= 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, 3, 4, 5]
|
||||
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",
|
||||
"iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
"iso_movies: colonne purge_pending (suppression permanente en attente)",
|
||||
"iso_movies: colonne iso_purged (ISO de telechargement partie)",
|
||||
]
|
||||
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)
|
||||
|
||||
|
||||
def test_db_migration_v4_adds_purge_pending(tmp_path) -> None:
|
||||
"""Une base v3 (avant la suppression permanente) recoit la colonne
|
||||
purge_pending sans perdre de donnees."""
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'v3.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,
|
||||
last_seen_at DATETIME,
|
||||
created_at DATETIME,
|
||||
failed_step TEXT,
|
||||
last_error TEXT,
|
||||
poster_url TEXT,
|
||||
radarr_linked BOOLEAN DEFAULT 1,
|
||||
qb_content_path TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id,"
|
||||
" title, status, qb_content_path)"
|
||||
" VALUES (10, 20, 'Film Traite', 'completed', '/downloads/x.iso')"
|
||||
)
|
||||
)
|
||||
from app.migrations import run_db_migrations
|
||||
|
||||
run_db_migrations(engine)
|
||||
|
||||
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||
assert "purge_pending" in columns
|
||||
with engine.connect() as conn:
|
||||
row = conn.execute(
|
||||
text("SELECT title, status, qb_content_path, purge_pending FROM iso_movies")
|
||||
).fetchone()
|
||||
assert row == ("Film Traite", "completed", "/downloads/x.iso", 0)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
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",
|
||||
"iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
"iso_movies: colonne purge_pending (suppression permanente en attente)",
|
||||
"iso_movies: colonne iso_purged (ISO de telechargement partie)",
|
||||
"download_files: inventaire des fichiers du dossier des telechargements",
|
||||
]
|
||||
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",
|
||||
"qb_content_path",
|
||||
} <= 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, 3, 4, 5, 6]
|
||||
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",
|
||||
"iso_movies: colonne qb_content_path (ISO cote telechargements)",
|
||||
"iso_movies: colonne purge_pending (suppression permanente en attente)",
|
||||
"iso_movies: colonne iso_purged (ISO de telechargement partie)",
|
||||
"download_files: inventaire des fichiers du dossier des telechargements",
|
||||
]
|
||||
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)
|
||||
|
||||
|
||||
def test_db_migration_v4_adds_purge_pending(tmp_path) -> None:
|
||||
"""Une base v3 (avant la suppression permanente) recoit la colonne
|
||||
purge_pending sans perdre de donnees."""
|
||||
engine = create_engine(f"sqlite:///{tmp_path / 'v3.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,
|
||||
last_seen_at DATETIME,
|
||||
created_at DATETIME,
|
||||
failed_step TEXT,
|
||||
last_error TEXT,
|
||||
poster_url TEXT,
|
||||
radarr_linked BOOLEAN DEFAULT 1,
|
||||
qb_content_path TEXT
|
||||
)
|
||||
"""
|
||||
)
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"INSERT INTO iso_movies (radarr_movie_id, radarr_movie_file_id,"
|
||||
" title, status, qb_content_path)"
|
||||
" VALUES (10, 20, 'Film Traite', 'completed', '/downloads/x.iso')"
|
||||
)
|
||||
)
|
||||
from app.migrations import run_db_migrations
|
||||
|
||||
run_db_migrations(engine)
|
||||
|
||||
columns = {col["name"] for col in inspect(engine).get_columns("iso_movies")}
|
||||
assert "purge_pending" in columns
|
||||
with engine.connect() as conn:
|
||||
row = conn.execute(
|
||||
text("SELECT title, status, qb_content_path, purge_pending FROM iso_movies")
|
||||
).fetchone()
|
||||
assert row == ("Film Traite", "completed", "/downloads/x.iso", 0)
|
||||
Base.metadata.create_all(bind=engine)
|
||||
Reference in new issue
Block a user