"""Execution against mocked Radarr/Sonarr: planning, dry run, real run, failures.""" import json import respx from plexreaper.config import ArrConfig, Config, TmdbConfig from plexreaper.execute import build_plan, close_clients, load_indexes, open_clients, run_plan from plexreaper.ledger import Ledger from plexreaper.models import Breakdown, Candidate, Evidence from plexreaper.sources.tmdb import TmdbClient from tests.conftest import make_title RADARR = "http://radarr.test" SONARR = "http://sonarr.test" MOVIE = {"id": 11, "title": "Blood Diamond", "year": 2006, "tmdbId": 1372, "imdbId": "tt0450259", "monitored": True, "qualityProfileId": 1, "hasFile": True, "sizeOnDisk": 3_400_000_000, "movieFile": {"id": 501, "path": "/movies/Blood Diamond (2006)/bd.mkv", "size": 3_400_000_000, "quality": {"quality": {"name": "WEBDL-1080p", "resolution": 1080}}}} BIG = {"id": 12, "title": "The Great Flood", "year": 2020, "tmdbId": 777, "monitored": True, "qualityProfileId": 2, "hasFile": True, "sizeOnDisk": 18_000_000_000, "movieFile": {"id": 502, "path": "/movies/tgf.mkv", "size": 18_000_000_000, "quality": {"quality": {"name": "WEBDL-2160p", "resolution": 2160}}}} NOFILE = {"id": 13, "title": "Ghost", "year": 1990, "tmdbId": 251, "monitored": True, "qualityProfileId": 1, "hasFile": False} SERIES = {"id": 21, "title": "CSI: Vegas", "year": 2021, "tvdbId": 392256, "monitored": True, "qualityProfileId": 4, "status": "ended", "seasons": [{"seasonNumber": 1, "monitored": True}], "statistics": {"sizeOnDisk": 55_000_000_000, "episodeFileCount": 30, "totalEpisodeCount": 30}} EPFILES = [{"id": 901, "path": "/tv/csi/s01e01.mkv", "size": 2_000_000_000, "seasonNumber": 1}, {"id": 902, "path": "/tv/csi/s01e02.mkv", "size": 2_000_000_000, "seasonNumber": 1}] MIXED = {"id": 22, "title": "Westworld", "year": 2016, "tvdbId": 296762, "monitored": True, "qualityProfileId": 5, "status": "ended", "seasons": [{"seasonNumber": 1, "monitored": True}], "statistics": {"sizeOnDisk": 60_000_000_000, "episodeFileCount": 3, "totalEpisodeCount": 3}} MIXED_FILES = [ {"id": 911, "path": "/tv/ww/s01e01.mkv", "size": 20_000_000_000, "seasonNumber": 1, "quality": {"quality": {"name": "WEBDL-2160p", "resolution": 2160}}}, {"id": 912, "path": "/tv/ww/s01e02.mkv", "size": 20_000_000_000, "seasonNumber": 1, "quality": {"quality": {"name": "WEBDL-2160p", "resolution": 2160}}}, {"id": 913, "path": "/tv/ww/s01e03.mkv", "size": 3_000_000_000, "seasonNumber": 1, "quality": {"quality": {"name": "WEBDL-1080p", "resolution": 1080}}}, ] def _q(name, res, allowed=True): return {"allowed": allowed, "quality": {"id": hash(name) % 1000, "name": name, "resolution": res}} PROFILES_R = [ {"id": 1, "name": "HD-1080p", "items": [_q("WEBDL-1080p", 1080), _q("Bluray-1080p", 1080), _q("Remux-2160p", 2160, False)]}, {"id": 2, "name": "Ultra-HD", "items": [_q("WEBDL-2160p", 2160)]}, ] PROFILES_S = [ {"id": 4, "name": "HD-1080p", "items": [_q("WEBDL-1080p", 1080), {"allowed": True, "name": "WEB 720p", "items": [_q("WEBDL-720p", 720)]}]}, {"id": 5, "name": "Ultra-HD", "items": [_q("WEBDL-2160p", 2160)]}, ] def cfg_with_arr(tmp_path, downgrade="HD-1080p") -> Config: c = Config() c.arr = [ ArrConfig(name="radarr", type="radarr", url=RADARR, api_key="k", libraries=[2], downgrade_profile=downgrade), ArrConfig(name="sonarr", type="sonarr", url=SONARR, api_key="k", libraries=[3], downgrade={"Ultra-HD": "HD-1080p"}), ] c.state.ledger = str(tmp_path / "ledger.db") return c def cand(title, decision, protected=None): return Candidate(title=title, evidence=Evidence(), breakdown=Breakdown(), protected=protected, decision=decision) def mock_arrs(respx_mock): respx_mock.get(f"{RADARR}/api/v3/system/status").respond(json={"version": "5.0.0"}) respx_mock.get(f"{SONARR}/api/v3/system/status").respond(json={"version": "4.0.0"}) respx_mock.get(f"{RADARR}/api/v3/movie").respond(json=[MOVIE, BIG, NOFILE]) respx_mock.get(f"{RADARR}/api/v3/qualityprofile").respond(json=PROFILES_R) respx_mock.get(f"{SONARR}/api/v3/series").respond(json=[SERIES, MIXED]) respx_mock.get(f"{SONARR}/api/v3/episodefile", params__contains={"seriesId": "22"}).respond(json=MIXED_FILES) respx_mock.get(f"{SONARR}/api/v3/series/22").respond(json=MIXED) respx_mock.get(f"{SONARR}/api/v3/qualityprofile").respond(json=PROFILES_S) respx_mock.get(f"{SONARR}/api/v3/episodefile", params__contains={"seriesId": "21"}).respond(json=EPFILES) for m in (MOVIE, BIG, NOFILE): respx_mock.get(f"{RADARR}/api/v3/movie/{m['id']}").respond(json=m) respx_mock.get(f"{SONARR}/api/v3/series/21").respond(json=SERIES) writes = { "put_movie": respx_mock.put(url__regex=rf"{RADARR}/api/v3/movie/\d+").respond(202, json={}), "put_series": respx_mock.put(url__regex=rf"{SONARR}/api/v3/series/\d+").respond(202, json={}), "del_movie": respx_mock.delete(url__regex=rf"{RADARR}/api/v3/moviefile/\d+").respond(200), "del_ep": respx_mock.delete(url__regex=rf"{SONARR}/api/v3/episodefile/\d+").respond(200), "cmd_r": respx_mock.post(f"{RADARR}/api/v3/command").respond(201, json={}), "cmd_s": respx_mock.post(f"{SONARR}/api/v3/command").respond(201, json={}), "editor_s": respx_mock.put(f"{SONARR}/api/v3/series/editor").respond(202, json=[]), "editor_r": respx_mock.put(f"{RADARR}/api/v3/movie/editor").respond(202, json=[]), } return writes def titles(): return { "bd": make_title("plex://movie/bd", rating_key=1, title="Blood Diamond", library_id=2), "tgf": make_title("plex://movie/tgf", rating_key=2, title="The Great Flood", library_id=2), "csi": make_title("plex://show/csi", rating_key=3, kind="show", title="CSI: Vegas", library_id=3, library_name="TV Shows"), "ghost": make_title("plex://movie/ghost", rating_key=4, title="Ghost", library_id=2), "lost": make_title("plex://movie/lost", rating_key=5, title="Not In Radarr", library_id=2), "kids": make_title("plex://show/k", rating_key=6, kind="show", title="Kids Show", library_id=4, library_name="Kids"), } @respx.mock async def test_plan_resolution_and_dry_run(tmp_path, respx_mock): writes = mock_arrs(respx_mock) cfg = cfg_with_arr(tmp_path) t = titles() t["bd"].external_ids = {"tmdb": "1372"} t["tgf"].external_ids = {"imdb": "x"} # falls back to title + year? year differs → unresolved by id, title match t["tgf"].year = 2020 t["csi"].external_ids = {"tvdb": "392256"} t["ghost"].external_ids = {"tmdb": "251"} cands = [ cand(t["bd"], "reap"), cand(t["tgf"], "downgrade"), cand(t["csi"], "reap"), cand(t["ghost"], "reap"), cand(t["lost"], "reap"), cand(t["kids"], "reap"), cand(make_title("plex://movie/p", rating_key=9, title="P"), "reap", protected="genre 'Sport'"), cand(make_title("plex://movie/keep", rating_key=10), "keep"), ] clients = open_clients(cfg) try: indexes = await load_indexes(clients) plan = await build_plan(cfg, cands, clients, indexes) by = {p.title: p for p in plan} assert len(plan) == 7 # 'keep' is not executable assert by["Blood Diamond"].ok and by["Blood Diamond"].files[0]["id"] == 501 and by["Blood Diamond"].arr_id == 11 tgf = by["The Great Flood"] assert tgf.ok and (tgf.profile_from, tgf.profile_to) == ("Ultra-HD", "HD-1080p") assert by["CSI: Vegas"].ok and len(by["CSI: Vegas"].files) == 2 and by["CSI: Vegas"].size_bytes == 4_000_000_000 assert by["Ghost"].error == "no files on disk (nothing to do)" assert by["Not In Radarr"].error.startswith("not found in radarr") assert by["Kids Show"].error.startswith("no arr instance configured") assert by["P"].error.startswith("protected") ledger = Ledger(cfg.ledger_path) outcomes = await run_plan(plan, clients, indexes, ledger, dry_run=True) assert sum(o.ok for o in outcomes) == 3 assert all(not w.called for w in writes.values()) assert ledger.executions() == [] and len(ledger.executions(include_dry_runs=True)) == 3 finally: await close_clients(clients) @respx.mock async def test_real_run_acts_records_and_clears(tmp_path, respx_mock): # routes match in insertion order: the failing file must be registered before the catch-all respx_mock.delete(f"{SONARR}/api/v3/episodefile/902").respond(500) writes = mock_arrs(respx_mock) cfg = cfg_with_arr(tmp_path) t = titles() t["bd"].external_ids = {"tmdb": "1372"} t["tgf"].external_ids = {"tmdb": "777"} t["csi"].external_ids = {"tvdb": "392256"} ledger = Ledger(cfg.ledger_path) for k, action in (("bd", "reap"), ("tgf", "downgrade"), ("csi", "reap")): ledger.set(t[k].guid, action, kind=t[k].kind, title=t[k].title) cands = [cand(t["bd"], "reap"), cand(t["tgf"], "downgrade"), cand(t["csi"], "reap")] clients = open_clients(cfg) try: indexes = await load_indexes(clients) plan = await build_plan(cfg, cands, clients, indexes) outcomes = await run_plan(plan, clients, indexes, ledger, dry_run=False) finally: await close_clients(clients) by = {o.item.title: o for o in outcomes} assert by["Blood Diamond"].ok and by["The Great Flood"].ok assert not by["CSI: Vegas"].ok and "HTTPStatusError" in by["CSI: Vegas"].detail # reap: PUT monitored=false then DELETE moviefile put_bodies = [json.loads(c.request.content) for c in writes["put_movie"].calls] assert put_bodies[0]["id"] == 11 and put_bodies[0]["monitored"] is False assert put_bodies[1]["id"] == 12 and put_bodies[1]["qualityProfileId"] == 1 and put_bodies[1]["monitored"] is True series_body = json.loads(writes["put_series"].calls[0].request.content) assert series_body["monitored"] is False and all(not s["monitored"] for s in series_body["seasons"]) assert [c.request.url.path.rsplit("/", 1)[-1] for c in writes["del_movie"].calls] == ["501", "502"] assert writes["cmd_r"].called and not writes["cmd_s"].called assert writes["del_ep"].call_count == 1 # 901 succeeded, 902 hit the failing route # ledger: executed ones cleared, failed one kept assert ledger.decisions() == {t["csi"].guid: "reap"} rows = ledger.executions() assert {(r["title"], bool(r["ok"])) for r in rows} == {("Blood Diamond", True), ("The Great Flood", True), ("CSI: Vegas", False)} assert [r["action"] for r in ledger.conn.execute("SELECT action FROM log WHERE action='executed'")] == ["executed", "executed"] @respx.mock async def test_downgrade_profile_errors(tmp_path, respx_mock): mock_arrs(respx_mock) t = titles() t["bd"].external_ids = {"tmdb": "1372"} t["tgf"].external_ids = {"tmdb": "777"} cfg = cfg_with_arr(tmp_path, downgrade="SD-480p") clients = open_clients(cfg) try: indexes = await load_indexes(clients) plan = await build_plan(cfg, [cand(t["tgf"], "downgrade")], clients, indexes) assert plan[0].error == "profile 'SD-480p' not found in radarr" cfg.arr[0].downgrade_profile = "HD-1080p" # already on the target: enforce its ceiling; the 1080p file is not above it, so nothing to do plan = await build_plan(cfg, [cand(t["bd"], "downgrade")], clients, indexes) assert plan[0].error == "no files above 1080p (nothing to downgrade)" cfg.arr[0].downgrade_profile = "" # unmapped profile maps to itself: Ultra-HD's ceiling is 2160p, the 2160p file is not above it plan = await build_plan(cfg, [cand(t["tgf"], "downgrade")], clients, indexes) assert plan[0].error == "no files above 2160p (nothing to downgrade)" # explicit map wins and is case-insensitive cfg.arr[0].downgrade = {"ultra-hd": "HD-1080p"} plan = await build_plan(cfg, [cand(t["tgf"], "downgrade"), cand(t["bd"], "downgrade")], clients, indexes) assert plan[0].ok and plan[0].profile_to == "HD-1080p" and "profile Ultra-HD → HD-1080p" in plan[0].describe() assert plan[1].error == "no files above 1080p (nothing to downgrade)" finally: await close_clients(clients) def test_open_clients_skips_missing_keys(tmp_path): cfg = cfg_with_arr(tmp_path) cfg.arr[1].api_key = "" clients = open_clients(cfg) assert list(clients) == ["radarr"] @respx.mock async def test_tmdb_lookup(respx_mock): respx_mock.get("https://api.themoviedb.org/3/movie/1372").respond(json={ "vote_count": 9000, "vote_average": 7.9, "popularity": 42.5, "watch/providers": {"results": {"US": {"flatrate": [{"provider_name": "Netflix"}, {"provider_name": "Max"}]}}}, }) async with TmdbClient(TmdbConfig(api_key="k", region="US", providers=["netflix"])) as tmdb: info = await tmdb.lookup("movie", 1372) assert info == {"vote_count": 9000, "vote_average": 7.9, "popularity": 42.5, "providers": ["Max", "Netflix"], "subscribed": ["Netflix"]} def test_config_env_overlay(tmp_path): toml = tmp_path / "plex-reaper.toml" toml.write_text('[[arr]]\nname = "radarr-3d"\ntype = "radarr"\nurl = "http://x"\nlibraries = [1]\n') from plexreaper.config import load_config cfg = load_config(toml, env={"RADARR_3D_API_KEY": "abc", "RADARR_3D_URL": "http://y", "TMDB_API_KEY": "t"}) assert cfg.arr[0].api_key == "abc" and cfg.arr[0].url == "http://y" and cfg.tmdb.api_key == "t" assert cfg.arr_for_library(1).name == "radarr-3d" and cfg.arr_for_library(2) is None @respx.mock async def test_show_downgrade_deletes_only_files_above_target(tmp_path, respx_mock): writes = mock_arrs(respx_mock) cfg = cfg_with_arr(tmp_path) ww = make_title("plex://show/ww", rating_key=7, kind="show", title="Westworld", library_id=3, library_name="TV Shows") ww.external_ids = {"tvdb": "296762"} ledger = Ledger(cfg.ledger_path) clients = open_clients(cfg) try: indexes = await load_indexes(clients) assert indexes["sonarr"].max_resolution == {4: 1080, 5: 2160} plan = await build_plan(cfg, [cand(ww, "downgrade")], clients, indexes) p = plan[0] assert p.ok and [f["id"] for f in p.files] == [911, 912] and p.kept_files == 1 assert p.size_bytes == 40_000_000_000 and "keep 1 at/below target" in p.describe() await run_plan(plan, clients, indexes, ledger, dry_run=False) finally: await close_clients(clients) assert [c.request.url.path.rsplit("/", 1)[-1] for c in writes["del_ep"].calls] == ["911", "912"] body = json.loads(writes["put_series"].calls[0].request.content) assert body["qualityProfileId"] == 4 and body["monitored"] is True assert writes["cmd_s"].called @respx.mock async def test_profile_max_resolution_and_bulk_editor(tmp_path, respx_mock): from plexreaper.sources.arr import ArrClient, profile_max_resolution writes = mock_arrs(respx_mock) assert profile_max_resolution(PROFILES_R[0]) == 1080 # disallowed 2160p does not count assert profile_max_resolution(PROFILES_S[0]) == 1080 assert profile_max_resolution({"items": []}) == 0 cfg = cfg_with_arr(tmp_path) async with ArrClient(cfg.arr[1]) as s: await s.bulk_set_profile([21, 22], 4) assert json.loads(writes["editor_s"].calls[0].request.content) == {"seriesIds": [21, 22], "qualityProfileId": 4} @respx.mock async def test_enforce_ceiling_without_profile_swap(tmp_path, respx_mock): """A show already on the 1080p profile but holding 4K files: downgrade deletes the 4K files only.""" writes = mock_arrs(respx_mock) cfg = cfg_with_arr(tmp_path) cfg.arr[1].downgrade = {} on_target = dict(MIXED, qualityProfileId=4) respx_mock.get(f"{SONARR}/api/v3/series").respond(json=[SERIES, on_target]) respx_mock.get(f"{SONARR}/api/v3/series/22").respond(json=on_target) ww = make_title("plex://show/ww", rating_key=7, kind="show", title="Westworld", library_id=3, library_name="TV Shows") ww.external_ids = {"tvdb": "296762"} clients = open_clients(cfg) try: indexes = await load_indexes(clients) plan = await build_plan(cfg, [cand(ww, "downgrade")], clients, indexes) p = plan[0] assert p.ok and p.profile_from == p.profile_to == "HD-1080p" assert "enforce profile HD-1080p ceiling" in p.describe() and [f["id"] for f in p.files] == [911, 912] await run_plan(plan, clients, indexes, Ledger(cfg.ledger_path), dry_run=False) finally: await close_clients(clients) assert writes["del_ep"].call_count == 2 and writes["cmd_s"].called