470 lines
18 KiB
Python
470 lines
18 KiB
Python
import errno
|
|
import json
|
|
import shutil
|
|
import time
|
|
from pathlib import Path
|
|
|
|
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 dossier de travail dans les telechargements est nettoye.
|
|
assert not list(settings.downloads_dir.iterdir())
|
|
|
|
|
|
@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 illisible mais extension iso: accepte par defaut.
|
|
assert 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_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"]
|