Files
romm/backend/tests/handler/metadata/test_libretro_handler.py
Georges-Antoine Assi ec1684d2af perf(metadata): serve the metadata dumps and fixtures from SQLite files (#5844)
* perf(metadata): serve the metadata dumps and fixtures from SQLite files

The LaunchBox and Switch TitleDB stores sat in valkey, which keeps every
byte resident: about 300MB on an instance with both imported, against
roughly 1MB for an empty server. Every read is an exact-key lookup and
nothing writes between imports, so they now live in read-only SQLite
files under RESOURCES_BASE_PATH/metadata, where the OS page cache holds
only the pages lookups touch.

A build writes a temporary file and renames it over the previous one,
so readers see the old store or the new one and never a partial import.
That replaces the initial-import flag and the schema stamp: the store
revision is part of the file name. A failed import keeps serving the
previous file.

The startup fixture indexes (MAME, ScummVM, Sony serials, known BIOS)
no longer get copied into valkey on every boot. They build on first use
into a file under the cache path, named after a hash of the JSON.

Startup deletes the old valkey keys and any file of an older revision,
and queues a rebuild when a store had data, so an upgrade refills
LaunchBox and TitleDB on its own. nginx returns 404 for the metadata
folder, since /assets/romm/resources is otherwise served without auth.

Measured against the real dumps: LaunchBox builds in 22s into 263MB on
disk, TitleDB in 1.2s into 54MB, the fixtures in 0.2s into 8MB. A hit
costs 10-23us including decompression, a miss about 7us.

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

* pr-ready: code-review

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

* pr-ready: simplify

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

* pr-ready: review-polish

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

* pr-ready: prose

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

* pr-ready: prose (code-review fixes)

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

* Keep the previous metadata store when a dump comes out empty

A LaunchBox or TitleDB build that writes no rows to its main table now
fails with EmptyDumpError instead of swapping an empty store over a
populated one.

Each store keeps one connection per process behind a lock instead of one
per thread. A build closes it once it swaps the file in, and any other
process closes its own on its next lookup, so a replaced file's disk
space is released instead of held by idle threads.

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

* Address Greptile review: trim DumpStore comments

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

* Restore valkey's own snapshot policy by default

The hourly default (48259b3a9, #3980) kept valkey from rewriting the
hundreds of MB of LaunchBox and TitleDB data it held. With those moved to
SQLite files, a snapshot holds only sessions, queues and query caches, so
an unset REDIS_SAVE_POLICY now leaves valkey's stock policy in place and
loses less on a crash. An empty value still disables snapshots.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:49:15 -05:00

383 lines
13 KiB
Python

"""Tests for the libretro thumbnails metadata handler."""
import hashlib
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.fixture_store import MAME_TABLE
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.fixture_get", return_value=entry
) as mock_get,
):
result = await handler.get_rom("mvsc2.zip", "naomi")
mock_get.assert_called_once_with(MAME_TABLE, "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.fixture_get") as mock_get,
):
await handler.get_rom("Final Fantasy VII (USA).bin", "psx")
mock_get.assert_not_called()
@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