Files
romm/backend/tests/handler/metadata/test_libretro_handler.py
Spinnich 60703be09c chore(platforms): split arcade aliases into per-emulator-family slugs (#5273)
* feat(platforms): split arcade aliases into per-emulator-family slugs

Give MAME, AdvanceMAME, FBNeo, FBA, Daphne, Singe and the arcade boards
that need their own emulator (NAOMI/NAOMI 2/NAOMI GD-ROM, Model 2/3,
Hikaru, Triforce, Lindbergh, Namco System 246/3xx, Gaelco, ...) their own
slugs with verified provider IDs. Providers without a dedicated entry fall
back to their Arcade platform via arcade_fallbacks(). MAME-only boards
(CPS1-3, System 16/32, Model 1, Namco 22) stay aliases of arcade.

Refs #5272

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): code-review pass on arcade slugs

- Retry IGDB on unmatched scans for every platform IGDB resolves, not
  just slugs in IGDB_PLATFORM_LIST.
- Resolve config binding/version values through the alias table, so a
  binding to a retired slug (cps2, model1, ...) still lands on a platform.
- Alias the Batocera `typex` folder to type-x.
- Build provider id->slug reverse maps before merging Arcade fallbacks.
- Share one MAME title lookup between base_handler and libretro.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(platforms): simplify pass on arcade slugs

- Alias the three RomM-keyed IGDB versions inside IGDB_PLATFORM_VERSIONS,
  dropping IGDB_VERSION_SLUGS and _version_slug.
- Derive EmulatorJS arcade entries from ARCADE_SET_PLATFORMS.
- Remove the unused provider id->slug reverse maps, so the Arcade
  fallback merge no longer has an ordering constraint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(platforms): humanizer pass on arcade slug comments

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): settle arcade slug review decisions

- Migration 0154 moves platforms still on a retired MAME-only board slug
  (cps1-3, model1, system16, system32, system-32) to arcade, so no row
  carries a slug the enum no longer has.
- MAME shortname expansion keys off the RomM slug via
  MAME_SHORTNAME_PLATFORMS instead of per-provider arcade ids, so Daphne,
  Singe, Type X and Lindbergh sets are no longer read as MAME sets. Neo Geo
  now expands at ScreenScraper too, as it already did at IGDB and Moby.
- fba offers fbneo before the FinalBurn Alpha CPS cores.
- AdvanceMAME leaves the WebRcade feed; EmulatorJS and WebRcade share
  PLAYABLE_ARCADE_SET_PLATFORMS.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): code-review pass (xhigh) on arcade slugs

Verify arcade-board BIOS files against the known list's arcade entries,
and make migration 0154 match retired slugs case-insensitively.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(platforms): simplify pass on arcade slugs

Apply IGDB family overrides once in get_platform instead of on each
return path.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(platforms): use a slug with no shipped icon

singe now ships an icon, so the no-icon prefetch test needs a slug that never will.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(platforms): add a teknoparrot arcade slug

TeknoParrot runs PC-based arcade boards outside the MAME/FinalBurn family,
so its folder gets its own platform (RetroBat and ES-DE both use
`teknoparrot`). Providers fall back to their Arcade entry, MAME shortname
expansion skips it, and it gets a placeholder icon copied from `arcade`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(platforms): give each arcade-family icon its own marquee title

Redraws the ARCADE marquee on the copied cabinet icons with each
platform's name, in the Bungee typeface with the original inline and
extrusion styling. Sega boards use Sega blue, Namco systems Namco red,
and Type X Taito blue; the rest keep the original amber.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(platforms): code-review pass (xhigh) on arcade slugs

Neo Geo BIOS lives under arcade in the known BIOS list, so map
neogeoaes and neogeomvs there too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(platforms): simplify pass on arcade slug tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-10-28 19:53:06 -04:00

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_handler artwork loop 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