mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* fix(scan): delete screenshots and media a rescan leaves unreferenced A complete rescan keeps the stored artwork, so two kinds of file stayed on disk with nothing pointing at them: - screenshots indexed past a shorter new list, since files are named by position and only the indexes in range were rewritten - media of a type removed from the preferences, since providers record no path for it and stale media was compared over the preferred types only get_rom_screenshots now deletes the indexes past the new list, and remove_stale_media compares every media type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): split scan_rom's merge into named steps scan_rom held seeding the row, following Demozoo links, splicing scene summaries, resetting rematched sources, the scene lock, rehash cleanup, priority merges for fields, tags and artwork, and the SteamGridDB pass in one body. Each step is now its own helper, the SteamGridDB lookup a _RomLookups method, and the providers' answers a dict keyed by source instead of fourteen locals. The Pouet and CSDb link follows share one helper. Behaviour is unchanged. McCabe complexity of scan_rom goes from 68 to 13, and the function from 664 to 215 lines. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(scan): trim remove_stale_media's docstring per Greptile review Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): move the scan vocabulary, lookups and merge into handler/scan scan_handler.py held the scan types and metadata sources, the per-source lookups, the merge of their answers and the orchestration in one 2,000-line module. It now builds on a handler/scan package: - sources.py: ScanType, MetadataSource, the tag constants, RESCAN_RULES, should_consult, stored_match_id and the priority ordering - lookups.py: RomLookups, the LaunchBox and Steam resolvers and get_main_platform_igdb_id - merge.py: the pure steps that merge the sources' answers into a rom's columns scan_handler.py keeps scan_platform, scan_rom, the asset scans and the media downloads. Importers point at the module that now defines each name, and the helpers that crossed a module boundary lost their leading underscore. clear_rehash_misses takes the attempted sources instead of the lookups, so merge does not depend on lookups. Behaviour is unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(ci): import ScanType from handler.scan.sources in the e2e seed script Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(scan): harden leftover screenshot cleanup (pr-ready: code-review) List the screenshots folder once, use isdecimal() for the index test, and log rather than raise when a leftover can't be removed. Point three comments at handler/scan instead of scan_handler. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(scan): tidy the merge helpers and patch paths (pr-ready: simplify) - fetch_sgdb_rom refetches by stored_id and builds the SGDB name list itself, so the name sources stay private to lookups. - follow_demozoo_link checks the source is enabled; scan_rom loops over Pouët and CSDb. - order_merge_sources holds the one ordering pass, and build_metadata_handlers adds the empty SGDB entry. - Leftover screenshots go through the quiet-delete helper, renamed _discard_file. - Tests patch rom lookups through handler.scan.lookups. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(scan): never leave a recorded media or screenshot path without its file - remove_stale_media only deletes a file whose owner or source changed when that new owner stores the type again in this pass. A file nothing records is still deleted. - Screenshots past a shorter list are pruned by remove_screenshots_past once the new paths are saved, in both download_rom_resources and update_rom, so a failed cover or manual leaves them in place. - The release-notes schema diff watches scan_handler.py beside scan/sources.py, for ranges that span the move. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
387 lines
13 KiB
Python
387 lines
13 KiB
Python
"""Tests for the libretro thumbnails metadata handler."""
|
|
|
|
import hashlib
|
|
import json
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import pytest
|
|
|
|
from adapters.services.libretro_thumbnails import LibretroThumbnailsService
|
|
from adapters.services.libretro_thumbnails_types import LibretroArtType
|
|
from config.config_manager import MetadataMediaType
|
|
from handler.metadata.base_handler import MAME_XML_KEY
|
|
from handler.metadata.libretro_handler import (
|
|
LIBRETRO_PLATFORM_LIST,
|
|
LibretroHandler,
|
|
_strip_paren_tags,
|
|
libretro_id_for,
|
|
)
|
|
|
|
# Sample directory listing for Sony - PlayStation
|
|
PSX_LISTING = [
|
|
"Castlevania - Symphony of the Night (USA).png",
|
|
"Castlevania - Symphony of the Night (Europe).png",
|
|
"Castlevania - Symphony of the Night (Japan).png",
|
|
"Final Fantasy VII (USA).png",
|
|
"Final Fantasy VII (Europe).png",
|
|
"Metal Gear Solid (USA).png",
|
|
"Sonic _ Knuckles Collection (USA).png",
|
|
]
|
|
|
|
NAOMI_LISTING = [
|
|
"Marvel Vs. Capcom 2_ New Age of Heroes (Export, Korea, Rev A).png",
|
|
"mvsc2.png",
|
|
]
|
|
|
|
|
|
@pytest.fixture
|
|
def handler() -> LibretroHandler:
|
|
return LibretroHandler()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pure utilities
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_strip_paren_tags_removes_single_tag():
|
|
assert _strip_paren_tags("Foo (USA)") == "Foo"
|
|
|
|
|
|
def test_strip_paren_tags_removes_multiple_tags():
|
|
assert _strip_paren_tags("Foo (USA) (Rev 1)") == "Foo"
|
|
|
|
|
|
def test_strip_paren_tags_preserves_when_no_tags():
|
|
assert _strip_paren_tags("Foo") == "Foo"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Platform resolution
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_get_platform_supported_platform(handler: LibretroHandler):
|
|
# PSX is explicitly mapped to "Sony - PlayStation"
|
|
assert handler.get_platform("psx")["libretro_slug"] == "Sony - PlayStation"
|
|
|
|
|
|
def test_get_platform_unsupported_platform(handler: LibretroHandler):
|
|
assert handler.get_platform("not-a-real-platform")["libretro_slug"] is None
|
|
|
|
|
|
def test_get_platform_rpg_maker(handler: LibretroHandler):
|
|
assert handler.get_platform("rpg-maker")["libretro_slug"] == "RPG Maker"
|
|
|
|
|
|
def test_platform_list_uses_ups_keys():
|
|
"""Every entry in LIBRETRO_PLATFORM_LIST should be a UniversalPlatformSlug."""
|
|
from utils.platform_slugs import UniversalPlatformSlug
|
|
|
|
for key in LIBRETRO_PLATFORM_LIST.keys():
|
|
assert isinstance(key, UniversalPlatformSlug)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Matching logic
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_match_art_name_exact_case_insensitive(handler: LibretroHandler):
|
|
# The match should prefer the exact case-insensitive filename (region tag
|
|
# included), so a PAL ROM lands on the (Europe) artwork.
|
|
result = handler._match_art_name(
|
|
"Castlevania - Symphony of the Night (Europe)", PSX_LISTING
|
|
)
|
|
assert result == "Castlevania - Symphony of the Night (Europe).png"
|
|
|
|
|
|
def test_match_art_name_different_case(handler: LibretroHandler):
|
|
result = handler._match_art_name(
|
|
"CASTLEVANIA - SYMPHONY OF THE NIGHT (USA)", PSX_LISTING
|
|
)
|
|
assert result == "Castlevania - Symphony of the Night (USA).png"
|
|
|
|
|
|
def test_match_art_name_ampersand_normalized(handler: LibretroHandler):
|
|
# Libretro filenames replace `&` with `_`; ROM filename uses `&`.
|
|
result = handler._match_art_name("Sonic & Knuckles Collection (USA)", PSX_LISTING)
|
|
assert result == "Sonic _ Knuckles Collection (USA).png"
|
|
|
|
|
|
def test_match_art_name_fuzzy_fallback(handler: LibretroHandler):
|
|
# No exact match, since the ROM has an extra `(Rev 1)` tag that libretro doesn't
|
|
# index. Fuzzy fallback strips tags from both sides; the Europe variant
|
|
# is the first tag-stripped candidate and wins.
|
|
result = handler._match_art_name(
|
|
"Castlevania - Symphony of the Night (Europe) (Rev 1)", PSX_LISTING
|
|
)
|
|
assert result is not None
|
|
assert result.startswith("Castlevania - Symphony of the Night")
|
|
|
|
|
|
def test_match_art_name_no_match(handler: LibretroHandler):
|
|
result = handler._match_art_name("Completely Made Up Game Title XYZ", PSX_LISTING)
|
|
assert result is None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# get_rom (scan path)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_unsupported_platform_returns_empty(handler: LibretroHandler):
|
|
result = await handler.get_rom("whatever.iso", "not-a-real-platform")
|
|
assert result == {"libretro_id": None}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_matched_returns_cover_url(handler: LibretroHandler):
|
|
# Isolate from SCAN_MEDIA defaults so this test only exercises box art.
|
|
with (
|
|
patch.object(
|
|
handler.service,
|
|
"fetch_listing",
|
|
AsyncMock(return_value=PSX_LISTING),
|
|
) as mock_fetch,
|
|
patch(
|
|
"handler.metadata.libretro_handler.get_preferred_media_types",
|
|
return_value=[],
|
|
),
|
|
):
|
|
result = await handler.get_rom(
|
|
"Castlevania - Symphony of the Night (Europe).iso", "psx"
|
|
)
|
|
|
|
mock_fetch.assert_awaited_once()
|
|
# libretro_id is the SHA1 hex of the matched libretro filename
|
|
expected_id = libretro_id_for("Castlevania - Symphony of the Night (Europe).png")
|
|
assert result["libretro_id"]
|
|
assert result["libretro_id"] == expected_id
|
|
assert len(result["libretro_id"]) == 40 # SHA1 hex
|
|
assert result.get("url_cover", "").startswith("https://thumbnails.libretro.com/")
|
|
assert "Sony%20-%20PlayStation" in result.get("url_cover", "")
|
|
assert "Named_Boxarts" in result.get("url_cover", "")
|
|
assert "Europe" in result.get("url_cover", "")
|
|
# Scan path intentionally does not populate `name` so it doesn't
|
|
# overwrite a real IGDB name.
|
|
assert "name" not in result
|
|
# No extra art types requested, so url_screenshots is absent.
|
|
assert "url_screenshots" not in result
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_fetches_extra_art_when_preferred(handler: LibretroHandler):
|
|
"""SCREENSHOT/TITLE_SCREEN/LOGO in SCAN_MEDIA trigger the corresponding
|
|
Named_Snaps/Named_Titles/Named_Logos fetches; matches land in
|
|
url_screenshots so the scan's artwork merge can pick them up."""
|
|
with (
|
|
patch.object(
|
|
handler.service,
|
|
"fetch_listing",
|
|
AsyncMock(return_value=PSX_LISTING),
|
|
) as mock_fetch,
|
|
patch(
|
|
"handler.metadata.libretro_handler.get_preferred_media_types",
|
|
return_value=[
|
|
MetadataMediaType.SCREENSHOT,
|
|
MetadataMediaType.TITLE_SCREEN,
|
|
MetadataMediaType.LOGO,
|
|
],
|
|
),
|
|
):
|
|
result = await handler.get_rom(
|
|
"Castlevania - Symphony of the Night (Europe).iso", "psx"
|
|
)
|
|
|
|
# Box art + three extras = four listings fetched in parallel.
|
|
assert mock_fetch.await_count == 4
|
|
screenshots = result.get("url_screenshots", [])
|
|
assert len(screenshots) == 3
|
|
assert any("Named_Snaps" in s for s in screenshots)
|
|
assert any("Named_Titles" in s for s in screenshots)
|
|
assert any("Named_Logos" in s for s in screenshots)
|
|
# url_cover still comes from Named_Boxarts.
|
|
assert "Named_Boxarts" in result.get("url_cover", "")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_skips_extra_art_when_not_preferred(handler: LibretroHandler):
|
|
"""Only Named_Boxarts is fetched when no extra media types are in SCAN_MEDIA."""
|
|
with (
|
|
patch.object(
|
|
handler.service,
|
|
"fetch_listing",
|
|
AsyncMock(return_value=PSX_LISTING),
|
|
) as mock_fetch,
|
|
patch(
|
|
"handler.metadata.libretro_handler.get_preferred_media_types",
|
|
return_value=[MetadataMediaType.BOX2D, MetadataMediaType.MANUAL],
|
|
),
|
|
):
|
|
result = await handler.get_rom(
|
|
"Castlevania - Symphony of the Night (Europe).iso", "psx"
|
|
)
|
|
|
|
mock_fetch.assert_awaited_once()
|
|
assert "url_screenshots" not in result
|
|
|
|
|
|
def test_libretro_id_for_is_deterministic():
|
|
f = "Castlevania - Symphony of the Night (Europe).png"
|
|
assert libretro_id_for(f) == libretro_id_for(f)
|
|
# Sanity-check the algorithm so the ID is stable across releases.
|
|
assert libretro_id_for(f) == hashlib.sha1(f.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def test_libretro_id_for_distinguishes_regions():
|
|
assert libretro_id_for(
|
|
"Castlevania - Symphony of the Night (USA).png"
|
|
) != libretro_id_for("Castlevania - Symphony of the Night (Europe).png")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_matches_a_mame_shortname_by_its_full_title(
|
|
handler: LibretroHandler,
|
|
):
|
|
entry = {
|
|
"description": "Marvel Vs. Capcom 2: New Age of Heroes (Export, Korea, Rev A)"
|
|
}
|
|
with (
|
|
patch.object(
|
|
handler.service, "fetch_listing", AsyncMock(return_value=NAOMI_LISTING)
|
|
),
|
|
patch(
|
|
"handler.metadata.libretro_handler.get_preferred_media_types",
|
|
return_value=[],
|
|
),
|
|
patch(
|
|
"handler.metadata.base_handler.async_cache.hget",
|
|
AsyncMock(return_value=json.dumps(entry)),
|
|
) as mock_hget,
|
|
):
|
|
result = await handler.get_rom("mvsc2.zip", "naomi")
|
|
|
|
mock_hget.assert_awaited_once_with(MAME_XML_KEY, "mvsc2")
|
|
assert result["libretro_id"] == libretro_id_for(NAOMI_LISTING[0])
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_skips_the_mame_lookup_off_arcade(handler: LibretroHandler):
|
|
with (
|
|
patch.object(
|
|
handler.service, "fetch_listing", AsyncMock(return_value=PSX_LISTING)
|
|
),
|
|
patch(
|
|
"handler.metadata.libretro_handler.get_preferred_media_types",
|
|
return_value=[],
|
|
),
|
|
patch(
|
|
"handler.metadata.base_handler.async_cache.hget", AsyncMock()
|
|
) as mock_hget,
|
|
):
|
|
await handler.get_rom("Final Fantasy VII (USA).bin", "psx")
|
|
|
|
mock_hget.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_no_match_returns_empty(handler: LibretroHandler):
|
|
with patch.object(
|
|
handler.service,
|
|
"fetch_listing",
|
|
AsyncMock(return_value=PSX_LISTING),
|
|
):
|
|
result = await handler.get_rom("Totally Unknown Title.iso", "psx")
|
|
|
|
assert result == {"libretro_id": None}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_empty_listing_returns_empty(handler: LibretroHandler):
|
|
with patch.object(
|
|
handler.service,
|
|
"fetch_listing",
|
|
AsyncMock(return_value=[]),
|
|
):
|
|
result = await handler.get_rom("Whatever.iso", "psx")
|
|
|
|
assert result == {"libretro_id": None}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# LibretroThumbnailsService helpers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_build_art_url_encodes_spaces_and_special_chars():
|
|
url = LibretroThumbnailsService.build_art_url(
|
|
"Sony - PlayStation",
|
|
LibretroArtType.BOX_ART,
|
|
"Castlevania - Symphony of the Night (Europe).png",
|
|
)
|
|
assert url.startswith("https://thumbnails.libretro.com/")
|
|
assert "Sony%20-%20PlayStation" in url
|
|
assert "Named_Boxarts" in url
|
|
# Filename-level encoding is strict (space → %20, paren encoded).
|
|
assert "Castlevania%20-%20Symphony%20of%20the%20Night" in url
|
|
|
|
|
|
def test_art_type_values():
|
|
assert LibretroArtType.BOX_ART.value == "Named_Boxarts"
|
|
assert LibretroArtType.TITLE_SCREEN.value == "Named_Titles"
|
|
assert LibretroArtType.LOGO.value == "Named_Logos"
|
|
assert LibretroArtType.SCREENSHOT.value == "Named_Snaps"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Handler basics
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_is_enabled_always_true():
|
|
# No API key required; this is a public server.
|
|
assert LibretroHandler.is_enabled() is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_an_empty_extra_listing_adds_no_screenshot(handler: LibretroHandler):
|
|
async def listing(_system: str, art_type: LibretroArtType) -> list[str]:
|
|
return PSX_LISTING if art_type == LibretroArtType.BOX_ART else []
|
|
|
|
with (
|
|
patch.object(handler.service, "fetch_listing", side_effect=listing),
|
|
patch(
|
|
"handler.metadata.libretro_handler.get_preferred_media_types",
|
|
return_value=[MetadataMediaType.SCREENSHOT],
|
|
),
|
|
):
|
|
result = await handler.get_rom(
|
|
"Castlevania - Symphony of the Night (Europe).iso", "psx"
|
|
)
|
|
|
|
assert "url_screenshots" not in result
|
|
assert "Named_Boxarts" in result.get("url_cover", "")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("head", "healthy"),
|
|
[
|
|
(AsyncMock(return_value=True), True),
|
|
(AsyncMock(return_value=False), False),
|
|
(AsyncMock(side_effect=RuntimeError("no session")), False),
|
|
],
|
|
ids=["reachable", "unreachable", "error"],
|
|
)
|
|
async def test_heartbeat_follows_the_server(
|
|
handler: LibretroHandler, head: AsyncMock, healthy: bool
|
|
):
|
|
with patch.object(handler.service, "head", head):
|
|
assert await handler.heartbeat() is healthy
|
|
|
|
|
|
def test_no_listing_has_no_fuzzy_match(handler: LibretroHandler):
|
|
assert handler._find_fuzzy_match("Castlevania", []) is None
|