1251 lines
48 KiB
Python
1251 lines
48 KiB
Python
import errno
|
|
import json
|
|
import shutil
|
|
import time
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
import httpx
|
|
import respx
|
|
from fastapi.testclient import TestClient
|
|
from httpx import Response
|
|
|
|
from app.config import settings
|
|
from app.converter import extract_mkv
|
|
from app.database import SessionLocal
|
|
from app.main import app
|
|
from app.models import IsoMovie
|
|
from tests.test_api import configure_radarr
|
|
|
|
FILM_FOLDER = "ISO Movie (2025)"
|
|
ISO_NAME = "ISO Movie (2025).iso"
|
|
MKV_NAME = "ISO Movie (2025).mkv"
|
|
|
|
|
|
def reset_state() -> None:
|
|
"""Isole chaque test: vide la base et les dossiers films/telechargements."""
|
|
with SessionLocal() as db:
|
|
db.query(IsoMovie).delete()
|
|
db.commit()
|
|
for folder in (settings.films_dir, settings.downloads_dir):
|
|
shutil.rmtree(folder, ignore_errors=True)
|
|
|
|
|
|
def film_dir() -> Path:
|
|
return settings.films_dir / FILM_FOLDER
|
|
|
|
|
|
def radarr_movie(path: str) -> dict:
|
|
return {
|
|
"id": 10,
|
|
"title": "ISO Movie",
|
|
"year": 2025,
|
|
"path": path,
|
|
"images": [{"coverType": "poster", "remoteUrl": "https://img/poster.jpg"}],
|
|
"movieFile": {
|
|
"id": 20,
|
|
"relativePath": ISO_NAME,
|
|
"size": 42_000_000_000,
|
|
},
|
|
}
|
|
|
|
|
|
def mock_radarr(path: str) -> None:
|
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
|
return_value=Response(200, json=[radarr_movie(path)])
|
|
)
|
|
|
|
|
|
def create_film_folder() -> Path:
|
|
folder = film_dir()
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
(folder / ISO_NAME).write_bytes(b"fake iso")
|
|
(folder / "poster.jpg").write_bytes(b"junk")
|
|
extra = folder / "extras"
|
|
extra.mkdir(exist_ok=True)
|
|
(extra / "trailer.mkv").write_bytes(b"junk")
|
|
return folder
|
|
|
|
|
|
def wait_for_status(client: TestClient, expected: str, timeout: float = 10.0) -> dict:
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
movie = client.get("/api/movies").json()[0]
|
|
if movie["status"] == expected:
|
|
return movie
|
|
time.sleep(0.05)
|
|
raise AssertionError(f"Statut {expected} jamais atteint (dernier: {movie['status']})")
|
|
|
|
|
|
@respx.mock
|
|
def test_conversion_order_and_radarr_file_name() -> None:
|
|
reset_state()
|
|
folder = create_film_folder()
|
|
# Radarr rapporte les chemins dans son referentiel; les fichiers physiques
|
|
# vivent sous films_dir (montage /films dans le conteneur).
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
scan = client.post("/api/scans")
|
|
assert scan.status_code == 200
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
|
|
convert = client.post(f"/api/movies/{movie_id}/convert")
|
|
assert convert.status_code == 200
|
|
|
|
movie = wait_for_status(client, "validating")
|
|
assert movie["poster_url"] == "https://img/poster.jpg"
|
|
assert movie["radarr_linked"] is True
|
|
|
|
# Ordre voulu: le dossier du film a ete nettoye (poster, extras)
|
|
# sauf l'ISO, gardee jusqu'a la validation manuelle. Le MKV lie
|
|
# reprend le nom du fichier Radarr (seule l'extension change).
|
|
entries = sorted(entry.name for entry in folder.iterdir())
|
|
assert entries == [ISO_NAME, MKV_NAME]
|
|
|
|
rescan_route = respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
|
assert validate.status_code == 200
|
|
assert validate.json()["status"] == "completed"
|
|
# La validation enfile rescan puis renommage Radarr: il adopte le
|
|
# MKV lie comme fichier du film, puis le renomme selon sa config
|
|
# Media Management.
|
|
commands = [
|
|
json.loads(call.request.content) for call in rescan_route.calls
|
|
]
|
|
assert commands == [
|
|
{"name": "RescanMovie", "movieId": 10},
|
|
{"name": "RenameMovie", "movieId": 10},
|
|
]
|
|
|
|
# Validation: l'ISO est supprimee, seul le MKV reste.
|
|
entries = sorted(entry.name for entry in folder.iterdir())
|
|
assert entries == [MKV_NAME]
|
|
# Le MKV brut du dossier de travail est conserve (meme inode que le
|
|
# lien): la fiche du film traite en affiche le chemin.
|
|
workspace = settings.downloads_dir / "ISO Movie 2025"
|
|
raw = workspace / MKV_NAME
|
|
assert raw.is_file()
|
|
assert raw.stat().st_ino == (folder / MKV_NAME).stat().st_ino
|
|
|
|
# La fiche detaillee du film traite expose les deux chemins.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["status"] == "completed"
|
|
assert fiche["linked_mkv_path"] == str(folder / MKV_NAME)
|
|
assert fiche["work_mkv_path"] == str(raw)
|
|
|
|
|
|
@respx.mock
|
|
def test_cancel_conversion_restores_detected() -> None:
|
|
reset_state()
|
|
folder = create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
|
|
client.post(f"/api/movies/{movie_id}/convert")
|
|
wait_for_status(client, "validating")
|
|
|
|
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
|
assert cancel.status_code == 200
|
|
assert cancel.json()["status"] == "detected"
|
|
|
|
# Annulation: lien et MKV de travail supprimes, l'ISO est intacte.
|
|
entries = sorted(entry.name for entry in folder.iterdir())
|
|
assert entries == [ISO_NAME]
|
|
assert not list(settings.downloads_dir.iterdir())
|
|
|
|
# Le film reste supprimable quand il n'est pas en conversion.
|
|
delete = client.delete(f"/api/movies/{movie_id}")
|
|
assert delete.status_code == 200
|
|
assert client.get("/api/movies").json() == []
|
|
|
|
|
|
@respx.mock
|
|
def test_scan_marks_missing_radarr_files_as_unlinked() -> None:
|
|
"""La pastille "Radarr lie" suit la presence du fichier cote Radarr."""
|
|
reset_state()
|
|
create_film_folder()
|
|
radarr_path = str(settings.radarr_films_dir / FILM_FOLDER)
|
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
|
return_value=Response(200, json=[radarr_movie(radarr_path)])
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie = client.get("/api/movies").json()[0]
|
|
assert movie["radarr_linked"] is True
|
|
|
|
# Le film disparait de Radarr (fichier supprime): il reste en base
|
|
# mais passe a non lie.
|
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
|
return_value=Response(200, json=[])
|
|
)
|
|
client.post("/api/scans")
|
|
movie = client.get("/api/movies").json()[0]
|
|
assert movie["radarr_linked"] is False
|
|
assert movie["status"] == "detected"
|
|
|
|
|
|
class FakePopen:
|
|
"""Remplace subprocess.Popen pour les tests: sortie en flux + code retour."""
|
|
|
|
def __init__(self, lines: list[str], returncode: int) -> None:
|
|
self.stdout = iter(line if line.endswith("\n") else line + "\n" for line in lines)
|
|
self._returncode = returncode
|
|
|
|
def __enter__(self) -> "FakePopen":
|
|
return self
|
|
|
|
def __exit__(self, *args: object) -> bool:
|
|
return False
|
|
|
|
def wait(self) -> int:
|
|
return self._returncode
|
|
|
|
|
|
SHAREWARE_OUTPUT = [
|
|
"This functionality is shareware. You may evaluate it for 30 days "
|
|
"after what you would need to purchase an activation key.",
|
|
"Do you want to start evaluation period now?",
|
|
"Evaluation version, 30 day(s) out of 30 remaining",
|
|
]
|
|
|
|
|
|
def test_extract_fails_with_activation_error_when_makemkv_unactivated(
|
|
monkeypatch, tmp_path
|
|
) -> None:
|
|
"""Sans cle MakeMKV (message shareware), l'erreur guide vers l'activation."""
|
|
monkeypatch.setattr(settings, "simulate_conversion", False)
|
|
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
|
monkeypatch.setattr(
|
|
"app.converter.subprocess.Popen",
|
|
lambda args, **kwargs: FakePopen(SHAREWARE_OUTPUT, 10),
|
|
)
|
|
movie = IsoMovie(
|
|
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
|
|
)
|
|
try:
|
|
extract_mkv(movie, tmp_path / "out" / "movie.mkv")
|
|
except RuntimeError as error:
|
|
assert "MakeMKV n'est pas activé" in str(error)
|
|
assert "MAKEMKV_KEY" in str(error)
|
|
else:
|
|
raise AssertionError("RuntimeError attendue")
|
|
|
|
|
|
def test_extract_reports_signal_kill(monkeypatch, tmp_path) -> None:
|
|
"""Un processus tue par signal (ex: OOM) est identifie dans l'erreur."""
|
|
monkeypatch.setattr(settings, "simulate_conversion", False)
|
|
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
|
monkeypatch.setattr(
|
|
"app.converter.subprocess.Popen",
|
|
lambda args, **kwargs: FakePopen([], -9),
|
|
)
|
|
movie = IsoMovie(
|
|
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
|
|
)
|
|
try:
|
|
extract_mkv(movie, tmp_path / "out" / "movie.mkv")
|
|
except RuntimeError as error:
|
|
assert "SIGKILL" in str(error)
|
|
else:
|
|
raise AssertionError("RuntimeError attendue")
|
|
|
|
|
|
def test_extract_picks_longest_title_and_streams_log(monkeypatch, tmp_path) -> None:
|
|
"""Le titre extrait est le plus long, et la sortie est diffusee en flux."""
|
|
robot_info = [
|
|
'MSG:1005,0,1,"MakeMKV started"',
|
|
'TINFO:0,9,0,"0:02:30"',
|
|
'TINFO:1,9,0,"1:57:00"',
|
|
'TINFO:2,9,0,"0:24:13"',
|
|
]
|
|
seen_lines: list[str] = []
|
|
|
|
def fake_popen(args, **kwargs):
|
|
if "--robot" in args:
|
|
return FakePopen(robot_info, 0)
|
|
assert args[3] == "1", f"titre attendu: 1, commande: {args}"
|
|
out = tmp_path / "out"
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
(out / "movie.mkv").write_text("mkv")
|
|
return FakePopen(["Saving 1 titles", "1 titles saved"], 0)
|
|
|
|
monkeypatch.setattr(settings, "simulate_conversion", False)
|
|
monkeypatch.setattr("app.converter.shutil.which", lambda _: "/usr/bin/makemkvcon")
|
|
monkeypatch.setattr("app.converter.subprocess.Popen", fake_popen)
|
|
movie = IsoMovie(
|
|
radarr_movie_id=1, radarr_movie_file_id=2, title="ISO Movie", path="/x.iso"
|
|
)
|
|
extract_mkv(
|
|
movie, tmp_path / "out" / "movie.mkv", lambda line: seen_lines.append(line)
|
|
)
|
|
assert (tmp_path / "out" / "movie.mkv").exists()
|
|
# Les lignes des deux commandes (info + mkv) ont ete diffusees.
|
|
assert any("TINFO" in line for line in seen_lines)
|
|
assert "1 titles saved" in seen_lines
|
|
|
|
|
|
def test_looks_like_iso_rejects_renamed_mkv() -> None:
|
|
"""Un fichier .iso dont l'en-tete est EBML est un MKV renomme: ecarte."""
|
|
from app.converter import EBML_MAGIC, looks_like_iso
|
|
|
|
iso_file = settings.films_dir / "Dossier"
|
|
iso_file.mkdir(parents=True, exist_ok=True)
|
|
real_iso = iso_file / "Film (2025).iso"
|
|
fake_iso = iso_file / "Renomme (2025).iso"
|
|
real_iso.write_bytes(b"\x00CD001 fake image")
|
|
fake_iso.write_bytes(EBML_MAGIC + b"matroska data")
|
|
|
|
assert looks_like_iso(str(settings.radarr_films_dir / "Dossier" / "Film (2025).iso"))
|
|
assert not looks_like_iso(
|
|
str(settings.radarr_films_dir / "Dossier" / "Renomme (2025).iso")
|
|
)
|
|
# Extension non iso: refuse.
|
|
assert not looks_like_iso("/quelque/chose.mkv")
|
|
# Fichier introuvable dans le conteneur: refuse (montage a corriger),
|
|
# sinon MakeMKV echouerait d'un « File does not exist » imcomprehensible.
|
|
assert not looks_like_iso(str(settings.radarr_films_dir / "Dossier" / "Absent.iso"))
|
|
|
|
|
|
@respx.mock
|
|
def test_scan_skips_mkv_renamed_as_iso() -> None:
|
|
"""Le scan n'importe pas les MKV renommes en .iso (contenu EBML)."""
|
|
reset_state()
|
|
folder = film_dir()
|
|
folder.mkdir(parents=True, exist_ok=True)
|
|
(folder / ISO_NAME).write_bytes(b"\x00CD001 vraie image")
|
|
(folder / "FAKE.iso").write_bytes(b"\x1aE\xdf\xa3 mkv renomme")
|
|
movies = [
|
|
radarr_movie(str(settings.radarr_films_dir / FILM_FOLDER)),
|
|
{
|
|
"id": 11,
|
|
"title": "Renomme",
|
|
"year": 2024,
|
|
"path": str(settings.radarr_films_dir / FILM_FOLDER),
|
|
"movieFile": {"id": 21, "relativePath": "FAKE.iso", "size": 42},
|
|
},
|
|
]
|
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
|
return_value=Response(200, json=movies)
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
scan = client.post("/api/scans")
|
|
assert scan.json()["iso_files"] == 1
|
|
titles = [movie["title"] for movie in client.get("/api/movies").json()]
|
|
assert titles == ["ISO Movie"]
|
|
|
|
|
|
@respx.mock
|
|
def test_convert_tolerates_stray_space_in_stored_path() -> None:
|
|
"""Reprise du cas reel « Coco »: le chemin stocke (issu de Radarr) porte
|
|
une espace parasite en tete — MakeMKV cherchait un fichier inexistant.
|
|
La traduction nettoie l'espace, la conversion part sur le vrai fichier."""
|
|
reset_state()
|
|
create_film_folder()
|
|
# Ligne en base avec l'espace, ISO presente au chemin propre.
|
|
with SessionLocal() as db:
|
|
movie = IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="ISO Movie",
|
|
year=2025,
|
|
path=f" {settings.radarr_films_dir / FILM_FOLDER / ISO_NAME}",
|
|
status="detected",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
db.add(movie)
|
|
db.commit()
|
|
movie_id = movie.id
|
|
with TestClient(app) as client:
|
|
converted = client.post(f"/api/movies/{movie_id}/convert")
|
|
assert converted.status_code == 200
|
|
assert converted.json()["status"] == "queued"
|
|
# La conversion simulee aboutit jusqu'a la validation.
|
|
movie = wait_for_status(client, "validating")
|
|
assert movie["status"] == "validating"
|
|
|
|
|
|
@respx.mock
|
|
def test_convert_refuses_iso_invisible_in_container() -> None:
|
|
"""L'ISO rapportee par Radarr mais introuvable dans le conteneur (montage
|
|
mal regle) est refusee avec un message explicite — MakeMKV n'y verrait
|
|
qu'un « File does not exist » incomprehensible."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
# L'ISO disparait du referentiel du conteneur (remontage ratte).
|
|
iso = film_dir() / ISO_NAME
|
|
iso.unlink()
|
|
|
|
refused = client.post(f"/api/movies/{movie_id}/convert")
|
|
assert refused.status_code == 409
|
|
assert "n'est pas visible dans le conteneur" in refused.json()["detail"]
|
|
|
|
|
|
@respx.mock
|
|
def test_convert_blocked_by_workspace_leftovers() -> None:
|
|
"""Des restes dans le dossier de travail bloquent la conversion jusqu'a
|
|
confirmation; force=true les supprime et reprend."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
workspace = settings.downloads_dir / "ISO Movie 2025"
|
|
workspace.mkdir(parents=True, exist_ok=True)
|
|
(workspace / "ancien_titre.mkv").write_bytes(b"restes")
|
|
(workspace / "partial.mkv").write_bytes(b"restes")
|
|
|
|
blocked = client.post(f"/api/movies/{movie_id}/convert")
|
|
assert blocked.status_code == 409
|
|
detail = blocked.json()["detail"]
|
|
assert detail["code"] == "workspace_not_empty"
|
|
assert sorted(detail["files"]) == ["ancien_titre.mkv", "partial.mkv"]
|
|
|
|
# La fiche detaillee expose aussi l'etat du dossier.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["workspace_files"] == ["ancien_titre.mkv", "partial.mkv"]
|
|
|
|
forced = client.post(f"/api/movies/{movie_id}/convert?force=true")
|
|
assert forced.status_code == 200
|
|
assert forced.json()["status"] == "queued"
|
|
# Le nettoyage a supprime les restes. Le MKV fraichement produit par
|
|
# le worker peut deja etre present: course avec le worker (rapide en
|
|
# mode simulation), on ne verifie que l'absence des anciens fichiers.
|
|
remaining = workspace_files_dir(workspace)
|
|
assert "ancien_titre.mkv" not in remaining
|
|
assert "partial.mkv" not in remaining
|
|
|
|
movie = wait_for_status(client, "validating")
|
|
assert movie["status"] == "validating"
|
|
|
|
|
|
def workspace_files_dir(folder: Path) -> list[str]:
|
|
return sorted(entry.name for entry in folder.iterdir())
|
|
|
|
|
|
@respx.mock
|
|
def test_cancel_only_at_validating_and_tolerates_missing_files() -> None:
|
|
"""L'annulation n'est possible qu'a l'etat "a valider". Un MKV deja
|
|
disparu est tolere: l'annulation reste valable, retour a "detecte"."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
|
|
# Hors "a valider": refus (le MKV converti n'existe pas avant).
|
|
early = client.post(f"/api/movies/{movie_id}/cancel")
|
|
assert early.status_code == 409
|
|
|
|
convert = client.post(f"/api/movies/{movie_id}/convert")
|
|
assert convert.status_code == 200
|
|
|
|
# Apres conversion, on supprime physiquement le MKV et son lien
|
|
# pour simuler des fichiers deja disparus.
|
|
wait_for_status(client, "validating")
|
|
folder = film_dir()
|
|
for entry in folder.iterdir():
|
|
if entry.suffix == ".mkv":
|
|
entry.unlink()
|
|
workspace = settings.downloads_dir / "ISO Movie 2025"
|
|
if workspace.is_dir():
|
|
shutil.rmtree(workspace)
|
|
|
|
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
|
assert cancel.status_code == 200
|
|
assert cancel.json()["status"] == "detected"
|
|
|
|
|
|
@respx.mock
|
|
def test_cancel_reports_permission_error(monkeypatch) -> None:
|
|
"""Une erreur de droits pendant l'annulation remonte un message
|
|
explicite (via notification) et le film reste "a valider"."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
import app.converter as converter_module
|
|
|
|
def refuse_unlink(path: Path) -> None:
|
|
# Comme le vrai unlink_if_exists: l'OSError est traduite en message
|
|
# explicite avant de remonter.
|
|
raise converter_module.file_error(
|
|
PermissionError(errno.EACCES, "Permission denied", str(path)),
|
|
"Suppression",
|
|
path,
|
|
)
|
|
|
|
monkeypatch.setattr(converter_module, "unlink_if_exists", refuse_unlink)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
convert = client.post(f"/api/movies/{movie_id}/convert")
|
|
assert convert.status_code == 200
|
|
wait_for_status(client, "validating")
|
|
|
|
cancel = client.post(f"/api/movies/{movie_id}/cancel")
|
|
assert cancel.status_code == 409
|
|
assert "erreur de droits" in cancel.json()["detail"]
|
|
assert "Annulation impossible" in cancel.json()["detail"]
|
|
|
|
movie = client.get("/api/movies").json()[0]
|
|
assert movie["status"] == "validating"
|
|
|
|
|
|
@respx.mock
|
|
def test_validate_survives_radarr_rescan_failure() -> None:
|
|
"""Un echec du rescan Radarr n'invalide pas la validation: le film passe
|
|
quand meme en "termine" et l'avertissement remonte a l'interface."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
client.post(f"/api/movies/{movie_id}/convert")
|
|
wait_for_status(client, "validating")
|
|
|
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(500, text="boom")
|
|
)
|
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
|
assert validate.status_code == 200
|
|
body = validate.json()
|
|
assert body["status"] == "completed"
|
|
assert body["rescan_warning"] is not None
|
|
assert "mise à jour Radarr impossible" in body["rescan_warning"]
|
|
|
|
|
|
@respx.mock
|
|
def test_radarr_rename_only_for_processed_movies() -> None:
|
|
"""Le renommage Radarr unitaire n'accepte que les films termines."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
|
|
# Film non termine: refus.
|
|
refused = client.post(f"/api/movies/{movie_id}/radarr-rename")
|
|
assert refused.status_code == 409
|
|
|
|
client.post(f"/api/movies/{movie_id}/convert")
|
|
wait_for_status(client, "validating")
|
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
client.post(f"/api/movies/{movie_id}/validate")
|
|
wait_for_status(client, "completed")
|
|
|
|
# Film termine: rescan + renommage Radarr.
|
|
command_route = respx.post("http://radarr:7878/api/v3/command")
|
|
response = client.post(f"/api/movies/{movie_id}/radarr-rename")
|
|
assert response.status_code == 200
|
|
assert response.json()["status"] == "completed"
|
|
commands = [json.loads(call.request.content) for call in command_route.calls]
|
|
# Deux appels de plus depuis le rattrapage: Rescan puis Rename.
|
|
assert commands[-2:] == [
|
|
{"name": "RescanMovie", "movieId": 10},
|
|
{"name": "RenameMovie", "movieId": 10},
|
|
]
|
|
|
|
|
|
@respx.mock
|
|
def test_radarr_rename_processed_bulk_reports_failures() -> None:
|
|
"""Le renommage global traite tous les films termines et collecte les
|
|
echecs sans interrompre la serie."""
|
|
reset_state()
|
|
create_film_folder()
|
|
with SessionLocal() as db:
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film A",
|
|
path="/films/a.iso",
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=11,
|
|
radarr_movie_file_id=21,
|
|
title="Film B",
|
|
path="/films/b.iso",
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.commit()
|
|
|
|
def command_response(request: httpx.Request) -> Response:
|
|
body = json.loads(request.content)
|
|
if body["movieId"] == 11:
|
|
return Response(500, text="boom")
|
|
return Response(201, json={"id": 1})
|
|
|
|
respx.post("http://radarr:7878/api/v3/command").mock(side_effect=command_response)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
result = client.post("/api/radarr/rename-processed")
|
|
|
|
assert result.status_code == 200
|
|
body = result.json()
|
|
assert body["renamed"] == 1
|
|
assert len(body["failures"]) == 1
|
|
assert body["failures"][0]["title"] == "Film B"
|
|
assert "500" in body["failures"][0]["error"]
|
|
|
|
|
|
@respx.mock
|
|
def test_scan_refreshes_paths_of_processed_movies() -> None:
|
|
"""Radarr pointe desormais le MKV des films traites: le scan met a jour
|
|
le chemin stocke (rattrapage des traitements anterieurs), repasse le
|
|
film "Radarr lie" et ne cree pas de ligne pour les films MKV inconnus."""
|
|
reset_state()
|
|
with SessionLocal() as db:
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Traite",
|
|
path="/films/film_traite.iso",
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.commit()
|
|
radarr_movies = [
|
|
{
|
|
"id": 10,
|
|
"title": "Film Traité",
|
|
"year": 2020,
|
|
"path": "/movies/Film Traité (2020)",
|
|
"movieFile": {
|
|
"id": 99, # nouvel id Radarr: le MKV n'est pas l'ISO d'origine
|
|
"path": "/movies/Film Traité (2020)/Film Traité (2020).mkv",
|
|
"size": 42_000_000_000,
|
|
},
|
|
},
|
|
{
|
|
"id": 11, # film MKV jamais inventorie: aucune ligne a creer
|
|
"title": "Film Externe",
|
|
"year": 2021,
|
|
"path": "/movies/Film Externe (2021)",
|
|
"movieFile": {"id": 31, "path": "/movies/Film Externe (2021).mkv"},
|
|
},
|
|
]
|
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
|
return_value=Response(200, json=radarr_movies)
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
scan = client.post("/api/scans")
|
|
|
|
assert scan.status_code == 200
|
|
body = scan.json()
|
|
assert body["iso_files"] == 0
|
|
assert body["created"] == 0
|
|
assert body["refreshed"] == 1
|
|
with SessionLocal() as db:
|
|
rows = db.query(IsoMovie).order_by(IsoMovie.id).all()
|
|
assert len(rows) == 1 # le film externe n'a pas ete inventorie
|
|
row = rows[0]
|
|
assert row.status == "completed"
|
|
assert row.radarr_linked is True
|
|
assert row.path == "/movies/Film Traité (2020)/Film Traité (2020).mkv"
|
|
assert row.size == 42_000_000_000
|
|
|
|
|
|
@respx.mock
|
|
def test_validation_removes_torrent_without_files() -> None:
|
|
"""La validation retire le torrent qBittorrent SANS ses donnees: l'ISO
|
|
est deja supprimee par nom et le MKV converti vit dans le meme dossier —
|
|
qBittorrent ne doit pouvoir y toucher en aucun cas."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
# qBittorrent configure (cle API): le torrent de l'ISO existe.
|
|
torrents_route = respx.get("http://qbit:8080/api/v2/torrents/info").mock(
|
|
return_value=Response(
|
|
200,
|
|
json=[
|
|
{
|
|
"hash": "abc123",
|
|
"name": ISO_NAME,
|
|
"content_path": f"/qbittorrentdownloads/{ISO_NAME}",
|
|
}
|
|
],
|
|
)
|
|
)
|
|
delete_route = respx.post("http://qbit:8080/api/v2/torrents/delete").mock(
|
|
return_value=Response(200)
|
|
)
|
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.put(
|
|
"/api/settings/qbittorrent",
|
|
json={"url": "http://qbit:8080", "port": 8080, "api_key": "qbt_key"},
|
|
)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
client.post(f"/api/movies/{movie_id}/convert")
|
|
wait_for_status(client, "validating")
|
|
|
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
|
assert validate.status_code == 200
|
|
assert validate.json()["status"] == "completed"
|
|
|
|
# Le torrent correspondant a l'ISO a ete retire...
|
|
assert torrents_route.called
|
|
assert delete_route.called
|
|
body = delete_route.calls.last.request.content.decode()
|
|
assert "hashes=abc123" in body
|
|
# ...sans ses donnees: le MKV du dossier du film est hors de portee.
|
|
assert "deleteFiles=false" in body
|
|
assert "deleteFiles=true" not in body
|
|
|
|
# Le MKV lie survit a la validation.
|
|
assert (film_dir() / MKV_NAME).is_file()
|
|
|
|
|
|
@respx.mock
|
|
def test_validation_captures_qbittorrent_download_path() -> None:
|
|
"""A la validation, le chemin de l'ISO cote telechargements qBittorrent
|
|
est capture et stocke: aucune suppression ISO n'a lieu a ce moment."""
|
|
reset_state()
|
|
create_film_folder()
|
|
mock_radarr(str(settings.radarr_films_dir / FILM_FOLDER))
|
|
# L'ISO cote telechargements existe physiquement dans l'environnement
|
|
# de test: le tag "ISO a supprimer" doit s'activer apres validation.
|
|
qb_download_dir = settings.downloads_dir / FILM_FOLDER
|
|
qb_download_dir.mkdir(parents=True, exist_ok=True)
|
|
qb_download_iso = qb_download_dir / ISO_NAME
|
|
qb_download_iso.write_bytes(b"iso telecharge")
|
|
respx.get("http://qbit:8080/api/v2/torrents/info").mock(
|
|
return_value=Response(
|
|
200,
|
|
json=[{"hash": "abc", "name": ISO_NAME,
|
|
"content_path": str(qb_download_iso)}],
|
|
)
|
|
)
|
|
respx.post("http://qbit:8080/api/v2/torrents/delete").mock(return_value=Response(200))
|
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
client.put(
|
|
"/api/settings/qbittorrent",
|
|
json={"url": "http://qbit:8080", "port": 8080, "api_key": "qbt_key"},
|
|
)
|
|
client.post("/api/scans")
|
|
movie_id = client.get("/api/movies").json()[0]["id"]
|
|
client.post(f"/api/movies/{movie_id}/convert")
|
|
wait_for_status(client, "validating")
|
|
|
|
validate = client.post(f"/api/movies/{movie_id}/validate")
|
|
assert validate.status_code == 200
|
|
|
|
from app.database import SessionLocal
|
|
|
|
with SessionLocal() as db:
|
|
movie = db.get(IsoMovie, movie_id)
|
|
assert movie.qb_content_path == str(qb_download_iso)
|
|
# Aucune suppression ISO a la validation: le fichier cote telechargements
|
|
# reste present, la fiche porte le tag.
|
|
assert qb_download_iso.is_file()
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["iso_to_delete"] is True
|
|
|
|
# Suppression manuelle: le tag retombe.
|
|
deleted = client.post(f"/api/movies/{movie_id}/delete-iso")
|
|
assert deleted.status_code == 200
|
|
assert not qb_download_iso.exists()
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["iso_to_delete"] is False
|
|
|
|
|
|
@respx.mock
|
|
def test_scan_refreshes_stale_qb_content_path() -> None:
|
|
"""Changement de montage (passage au volume unique): le chemin de
|
|
telechargement capture a la validation ne pointe plus sur le fichier.
|
|
Le scan le retrouve par son nom sous la racine des telechargements —
|
|
le torrent etant deja retire, qBittorrent ne peut pas aider."""
|
|
reset_state()
|
|
# ISO encore presente dans les telechargements, referentiel actuel.
|
|
iso = settings.downloads_dir / "Film Casse 2020" / "FILM.iso"
|
|
iso.parent.mkdir(parents=True, exist_ok=True)
|
|
iso.write_bytes(b"iso telecharge")
|
|
with SessionLocal() as db:
|
|
movie = IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Casse",
|
|
year=2020,
|
|
path=str(settings.radarr_films_dir / "Film Casse (2020)" / "FILM.iso"),
|
|
status="completed",
|
|
# Chemin de l'ANCIEN montage: plus resolu apres remontage.
|
|
qb_content_path="/ancien-montage/Film Casse 2020/FILM.iso",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
db.add(movie)
|
|
db.commit()
|
|
movie_id = movie.id
|
|
# Radarr ne retourne rien: le rattrapage est independant de l'inventaire.
|
|
respx.get("http://radarr:7878/api/v3/movie?includeMovieFile=true").mock(
|
|
return_value=Response(200, json=[])
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
# Avant rattrapage: l'ancien chemin est muet, pas de tag.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["iso_to_delete"] is False
|
|
|
|
scan = client.post("/api/scans")
|
|
assert scan.status_code == 200
|
|
|
|
# Apres rattrapage: chemin actuel, tag de suppression actif.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["qb_content_path"] == str(iso)
|
|
assert fiche["iso_to_delete"] is True
|
|
|
|
# La suppression manuelle fonctionne sur le chemin rattape.
|
|
deleted = client.post(f"/api/movies/{movie_id}/delete-iso")
|
|
assert deleted.status_code == 200
|
|
assert not iso.exists()
|
|
|
|
|
|
def _seed_purged_movie(title: str, folder: str, movie_id: int = 10, file_id: int = 20) -> int:
|
|
"""Film traite et purge: ISO de telechargement deja supprimee."""
|
|
with SessionLocal() as db:
|
|
movie = IsoMovie(
|
|
radarr_movie_id=movie_id,
|
|
radarr_movie_file_id=file_id,
|
|
title=title,
|
|
year=2020,
|
|
path=str(settings.radarr_films_dir / folder / "FILM.iso"),
|
|
status="completed",
|
|
qb_content_path=str(settings.downloads_dir / folder / "FILM.iso"),
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
db.add(movie)
|
|
db.commit()
|
|
return movie.id
|
|
|
|
|
|
@respx.mock
|
|
def test_purge_removes_mkv_folder_and_row() -> None:
|
|
"""Suppression permanente d'un traite purge: MKV et dossier du film
|
|
retires, ligne supprimee de l'inventaire."""
|
|
reset_state()
|
|
movie_id = _seed_purged_movie("Film Purge", "Film Purge (2020)")
|
|
film_folder = settings.films_dir / "Film Purge (2020)"
|
|
film_folder.mkdir(parents=True)
|
|
(film_folder / "Film.Purge.2020.mkv").write_text("mkv lie")
|
|
with TestClient(app) as client:
|
|
# Le film apparait comme traite ET purge.
|
|
movies = client.get("/api/movies").json()
|
|
assert movies[0]["purged"] is True
|
|
|
|
purged = client.post(f"/api/movies/{movie_id}/purge")
|
|
assert purged.status_code == 200
|
|
assert purged.json()["folder_kept"] is False
|
|
# MKV et dossier disparus, ligne retiree.
|
|
assert not film_folder.exists()
|
|
assert client.get(f"/api/files/{movie_id}").status_code == 404
|
|
|
|
|
|
@respx.mock
|
|
def test_purge_keeps_folder_then_confirmation_removes_it() -> None:
|
|
"""Dossier du film avec d'autres fichiers: le MKV est supprime, le
|
|
dossier conserve (warning), la ligne garde le tag « non complète »;
|
|
la seconde confirmation retire le dossier et la ligne."""
|
|
reset_state()
|
|
movie_id = _seed_purged_movie("Film Garde", "Film Garde (2020)")
|
|
film_folder = settings.films_dir / "Film Garde (2020)"
|
|
film_folder.mkdir(parents=True)
|
|
(film_folder / "Film.Garde.2020.mkv").write_text("mkv lie")
|
|
(film_folder / "poster.jpg").write_bytes(b"affiche")
|
|
(film_folder / "bonus.mkv").write_bytes(b"bonus")
|
|
with TestClient(app) as client:
|
|
first = client.post(f"/api/movies/{movie_id}/purge")
|
|
assert first.status_code == 200
|
|
result = first.json()
|
|
assert result["folder_kept"] is True
|
|
assert "conservé" in result["message"]
|
|
# Le MKV est supprime, les autres fichiers restent.
|
|
assert not (film_folder / "Film.Garde.2020.mkv").exists()
|
|
assert (film_folder / "poster.jpg").is_file()
|
|
# La ligne reste, taggee « non complète ».
|
|
assert result["movie"]["purge_pending"] is True
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["purge_pending"] is True
|
|
assert fiche["purged"] is True
|
|
|
|
# Seconde confirmation: dossier et ligne retires.
|
|
second = client.post(f"/api/movies/{movie_id}/purge?force_folder=true")
|
|
assert second.status_code == 200
|
|
assert second.json()["folder_kept"] is False
|
|
assert not film_folder.exists()
|
|
assert client.get(f"/api/files/{movie_id}").status_code == 404
|
|
|
|
|
|
@respx.mock
|
|
def test_purge_guards() -> None:
|
|
"""La suppression permanente exige un film traite dont l'ISO de
|
|
telechargement est deja partie."""
|
|
reset_state()
|
|
# Film traite mais ISO encore presente: refuse.
|
|
with SessionLocal() as db:
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film ISO Presente",
|
|
year=2020,
|
|
path=str(settings.radarr_films_dir / "Film ISO Presente (2020)" / "FILM.iso"),
|
|
status="completed",
|
|
qb_content_path=str(settings.downloads_dir / "iso.iso"),
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=11,
|
|
radarr_movie_file_id=21,
|
|
title="Film Detecte",
|
|
year=2021,
|
|
path=str(settings.radarr_films_dir / "Film Detecte (2021)" / "FILM.iso"),
|
|
status="detected",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.commit()
|
|
iso = settings.downloads_dir / "iso.iso"
|
|
iso.parent.mkdir(parents=True, exist_ok=True)
|
|
iso.write_bytes(b"iso")
|
|
with TestClient(app) as client:
|
|
movies = {m["title"]: m["id"] for m in client.get("/api/movies").json()}
|
|
with_iso = client.post(f"/api/movies/{movies['Film ISO Presente']}/purge")
|
|
assert with_iso.status_code == 409
|
|
assert "ISO de téléchargement" in with_iso.json()["detail"]
|
|
detected = client.post(f"/api/movies/{movies['Film Detecte']}/purge")
|
|
assert detected.status_code == 409
|
|
# Un traite purge sans dossier du film: juste la ligne, sans erreur.
|
|
gone = _seed_purged_movie("Film Fantome", "Film Fantome (2020)", 12, 22)
|
|
nothing = client.post(f"/api/movies/{gone}/purge")
|
|
assert nothing.status_code == 200
|
|
assert "Rien à supprimer" in nothing.json()["message"]
|
|
assert client.get(f"/api/files/{gone}").status_code == 404
|
|
|
|
|
|
@respx.mock
|
|
def test_delete_download_iso_manual_with_safety_guards() -> None:
|
|
"""Suppression manuelle de l'ISO sur l'etat traite: fichier supprime,
|
|
dossier du film retire s'il devient vide, racine des telechargements et
|
|
chemins hors zone intouchables."""
|
|
reset_state()
|
|
with SessionLocal() as db:
|
|
iso_dir = settings.downloads_dir / "Film Telecharge (2020)"
|
|
iso_dir.mkdir(parents=True, exist_ok=True)
|
|
iso_file = iso_dir / "FILM.iso"
|
|
iso_file.write_bytes(b"iso")
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Telecharge",
|
|
path="/films/film.iso",
|
|
status="completed",
|
|
qb_content_path=str(iso_file),
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
# Film traite dont l'ISO est hors de la racine des telechargements.
|
|
outside = Path("/tmp/iso-hors-zone.iso")
|
|
outside.write_bytes(b"iso")
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=11,
|
|
radarr_movie_file_id=21,
|
|
title="Film Hors Zone",
|
|
path="/films/hors.iso",
|
|
status="completed",
|
|
qb_content_path=str(outside),
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
# Film traite sans chemin connu.
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=12,
|
|
radarr_movie_file_id=22,
|
|
title="Film Sans Chemin",
|
|
path="/films/sans.iso",
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
# Film non traite avec un chemin connu: refus.
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=13,
|
|
radarr_movie_file_id=23,
|
|
title="Film En Cours",
|
|
path="/films/enroute.iso",
|
|
status="validating",
|
|
qb_content_path=str(iso_file),
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.commit()
|
|
ids = {
|
|
row.title: row.id
|
|
for row in db.query(IsoMovie).all()
|
|
}
|
|
|
|
with TestClient(app) as client:
|
|
# Hors etat traite: refuse.
|
|
assert client.post(f"/api/movies/{ids['Film En Cours']}/delete-iso").status_code == 409
|
|
# Sans chemin connu: refuse.
|
|
assert client.post(f"/api/movies/{ids['Film Sans Chemin']}/delete-iso").status_code == 409
|
|
# Hors de la racine des telechargements: refuse par securite,
|
|
# le fichier hors zone reste intact.
|
|
refused = client.post(f"/api/movies/{ids['Film Hors Zone']}/delete-iso")
|
|
assert refused.status_code == 409
|
|
assert "sécurité" in refused.json()["detail"]
|
|
assert outside.exists()
|
|
|
|
# Chemin legitime: fichier supprime, dossier vide retire,
|
|
# racine des telechargements intacte.
|
|
ok = client.post(f"/api/movies/{ids['Film Telecharge']}/delete-iso")
|
|
assert ok.status_code == 200
|
|
assert not iso_file.exists()
|
|
assert not iso_dir.exists()
|
|
assert settings.downloads_dir.is_dir()
|
|
|
|
# Idempotent: un second appel reussit (deja supprimee).
|
|
again = client.post(f"/api/movies/{ids['Film Telecharge']}/delete-iso")
|
|
assert again.status_code == 200
|
|
|
|
# La fiche ne porte plus le tag.
|
|
fiche = client.get(f"/api/files/{ids['Film Telecharge']}").json()
|
|
assert fiche["iso_to_delete"] is False
|
|
|
|
|
|
@respx.mock
|
|
def test_repair_link_recreates_hardlink_with_radarr_name() -> None:
|
|
"""Lien casse (brut present, lien absent): la reparation recree un lien
|
|
dur au nom attendu par Radarr, meme inode, et rescanne Radarr."""
|
|
reset_state()
|
|
with SessionLocal() as db:
|
|
movie = IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Casse",
|
|
year=2020,
|
|
path=str(settings.radarr_films_dir / "Film Casse (2020)" / "FILM.iso"),
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
db.add(movie)
|
|
db.commit()
|
|
movie_id = movie.id
|
|
# MKV brut present dans le dossier de travail, dossier du film vide.
|
|
brut = settings.downloads_dir / "Film Casse 2020" / "Film Casse (2020).mkv"
|
|
brut.parent.mkdir(parents=True, exist_ok=True)
|
|
brut.write_text("donnees du mkv")
|
|
film_folder = settings.films_dir / "Film Casse (2020)"
|
|
film_folder.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Radarr connait le nom attendu (apres renommage Media Management).
|
|
respx.get("http://radarr:7878/api/v3/movie/10").mock(
|
|
return_value=Response(
|
|
200,
|
|
json={"id": 10, "movieFile": {
|
|
"id": 99,
|
|
"path": "/movies/Film Casse (2020)/Film.Casse.2020.1080p.BluRay.mkv",
|
|
}},
|
|
)
|
|
)
|
|
rescan_route = respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
# La fiche detecte le lien casse.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["link_broken"] is True
|
|
|
|
repair = client.post(f"/api/movies/{movie_id}/repair-link")
|
|
assert repair.status_code == 200
|
|
message = repair.json()["message"]
|
|
assert "Lien du MKV recréé" in message
|
|
|
|
# Le lien porte le nom attendu par Radarr et partage l'inode du brut.
|
|
linked = film_folder / "Film.Casse.2020.1080p.BluRay.mkv"
|
|
assert linked.is_file()
|
|
assert linked.stat().st_ino == brut.stat().st_ino
|
|
assert linked.read_text() == "donnees du mkv"
|
|
# Rescan Radarr declenche.
|
|
assert rescan_route.called
|
|
# La fiche ne signale plus de lien casse.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["link_broken"] is False
|
|
assert fiche["linked_mkv_path"] == str(linked)
|
|
|
|
|
|
@respx.mock
|
|
def test_repair_link_replaces_symbolic_link() -> None:
|
|
"""Vieux lien symbolique (chemin interne au conteneur, illisible depuis
|
|
Jellyfin/Radarr): la fiche le signale et la reparation le remplace par
|
|
un vrai fichier, meme inode que le brut."""
|
|
reset_state()
|
|
with SessionLocal() as db:
|
|
movie = IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Sym",
|
|
year=2020,
|
|
path=str(settings.radarr_films_dir / "Film Sym (2020)" / "FILM.iso"),
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
db.add(movie)
|
|
db.commit()
|
|
movie_id = movie.id
|
|
brut = settings.downloads_dir / "Film Sym 2020" / "Film Sym (2020).mkv"
|
|
brut.parent.mkdir(parents=True, exist_ok=True)
|
|
brut.write_text("donnees du mkv")
|
|
film_folder = settings.films_dir / "Film Sym (2020)"
|
|
film_folder.mkdir(parents=True, exist_ok=True)
|
|
# Ancien comportement: lien symbolique absolu, deja au nom attendu.
|
|
linked = film_folder / "Film.Sym.2020.1080p.BluRay.mkv"
|
|
linked.symlink_to(brut)
|
|
|
|
respx.get("http://radarr:7878/api/v3/movie/10").mock(
|
|
return_value=Response(
|
|
200,
|
|
json={"id": 10, "movieFile": {
|
|
"id": 99,
|
|
"path": "/movies/Film Sym (2020)/Film.Sym.2020.1080p.BluRay.mkv",
|
|
}},
|
|
)
|
|
)
|
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
# La fiche signale le lien symbolique (fragile), pas un lien casse.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["link_symbolic"] is True
|
|
assert fiche["link_broken"] is False
|
|
|
|
repair = client.post(f"/api/movies/{movie_id}/repair-link")
|
|
assert repair.status_code == 200
|
|
assert "(lien)" in repair.json()["message"]
|
|
|
|
# Le lien symbolique est remplace par un vrai fichier.
|
|
assert linked.is_file()
|
|
assert not linked.is_symlink()
|
|
assert linked.stat().st_ino == brut.stat().st_ino
|
|
# La fiche ne signale plus rien.
|
|
fiche = client.get(f"/api/files/{movie_id}").json()
|
|
assert fiche["link_symbolic"] is False
|
|
assert fiche["link_broken"] is False
|
|
|
|
|
|
@respx.mock
|
|
def test_repair_link_requires_brut_and_completed() -> None:
|
|
"""La reparation exige un MKV brut present et un film traite."""
|
|
reset_state()
|
|
with SessionLocal() as db:
|
|
db.add(
|
|
IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Sans Brut",
|
|
year=2021,
|
|
path=str(settings.radarr_films_dir / "Film Sans Brut (2021)" / "x.iso"),
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
)
|
|
db.commit()
|
|
with TestClient(app) as client:
|
|
movies = client.get("/api/movies").json()
|
|
movie_id = movies[0]["id"]
|
|
missing = client.post(f"/api/movies/{movie_id}/repair-link")
|
|
assert missing.status_code == 409
|
|
assert "MKV brut introuvable" in missing.json()["detail"]
|
|
|
|
|
|
@respx.mock
|
|
def test_repair_link_finds_renamed_brut() -> None:
|
|
"""Radarr a pu renommer le brut dans le dossier de travail: la reparation
|
|
retombe sur n'importe quel MKV du dossier, meme sous un autre nom."""
|
|
reset_state()
|
|
with SessionLocal() as db:
|
|
movie = IsoMovie(
|
|
radarr_movie_id=10,
|
|
radarr_movie_file_id=20,
|
|
title="Film Renomme",
|
|
year=2020,
|
|
path=str(settings.radarr_films_dir / "Film Renomme (2020)" / "FILM.iso"),
|
|
status="completed",
|
|
last_seen_at=datetime(2026, 1, 1),
|
|
)
|
|
db.add(movie)
|
|
db.commit()
|
|
movie_id = movie.id
|
|
# Le brut a ete renomme par Radarr: l'ancien nom n'existe plus.
|
|
brut_renamed = settings.downloads_dir / "Film Renomme 2020" / "Film.Renomme.2020.1080p.mkv"
|
|
brut_renamed.parent.mkdir(parents=True, exist_ok=True)
|
|
brut_renamed.write_text("donnees")
|
|
|
|
respx.get("http://radarr:7878/api/v3/movie/10").mock(
|
|
return_value=Response(
|
|
200,
|
|
json={"id": 10, "movieFile": {
|
|
"id": 99, "path": "/movies/Film Renomme (2020)/Film.Renomme.2020.1080p.mkv",
|
|
}},
|
|
)
|
|
)
|
|
respx.post("http://radarr:7878/api/v3/command").mock(
|
|
return_value=Response(201, json={"id": 1})
|
|
)
|
|
with TestClient(app) as client:
|
|
configure_radarr(client)
|
|
repair = client.post(f"/api/movies/{movie_id}/repair-link")
|
|
assert repair.status_code == 200
|
|
|
|
linked = settings.films_dir / "Film Renomme (2020)" / "Film.Renomme.2020.1080p.mkv"
|
|
assert linked.is_file()
|
|
assert linked.read_text() == "donnees"
|
|
assert linked.stat().st_ino == brut_renamed.stat().st_ino
|