mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* 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>
1032 lines
40 KiB
Python
1032 lines
40 KiB
Python
import json
|
|
import re
|
|
from collections.abc import AsyncIterator
|
|
from unittest.mock import AsyncMock, patch
|
|
from urllib.parse import parse_qsl, urlparse
|
|
|
|
import httpx2
|
|
import pytest
|
|
from tests.handler.metadata.conftest import schema_stamp_get
|
|
|
|
from handler.metadata import base_handler
|
|
from handler.metadata.base_handler import (
|
|
LEADING_ARTICLE_PATTERN,
|
|
MAME_XML_KEY,
|
|
MULTIPLE_SPACE_PATTERN,
|
|
NON_WORD_SPACE_PATTERN,
|
|
PS1_SERIAL_INDEX_KEY,
|
|
PS2_OPL_KEY,
|
|
PS2_OPL_REGEX,
|
|
PS2_SERIAL_INDEX_KEY,
|
|
PSP_SERIAL_INDEX_KEY,
|
|
SONY_SERIAL_REGEX,
|
|
SWITCH_PRODUCT_ID_REGEX,
|
|
SWITCH_TITLEDB_REGEX,
|
|
BaseRom,
|
|
IndexedFormatPlatforms,
|
|
MetadataHandler,
|
|
_normalize_search_term,
|
|
provider_tag_regex,
|
|
restore_sensitive_query_params,
|
|
strip_sensitive_query_params,
|
|
tag_id_from_filename,
|
|
)
|
|
from handler.redis_handler import async_cache
|
|
from models.platform import Platform
|
|
from models.rom import Rom
|
|
from tasks.scheduled.update_switch_titledb import (
|
|
SWITCH_PRODUCT_ID_KEY,
|
|
SWITCH_TITLEDB_INDEX_KEY,
|
|
SWITCH_TITLEDB_STORE,
|
|
)
|
|
from utils.context import ctx_httpx_client
|
|
from utils.platform_slugs import UniversalPlatformSlug
|
|
|
|
|
|
class ExampleMetadataHandler(MetadataHandler):
|
|
@classmethod
|
|
def is_enabled(cls) -> bool:
|
|
return True
|
|
|
|
|
|
class TestNormalizeSearchTerm:
|
|
"""Test the _normalize_search_term function."""
|
|
|
|
def test_basic_normalization(self):
|
|
"""Test basic string normalization."""
|
|
result = _normalize_search_term("Test Game")
|
|
assert result == "test game"
|
|
|
|
def test_underscore_replacement(self):
|
|
"""Test underscore replacement with spaces."""
|
|
result = _normalize_search_term("Test_Game_Name")
|
|
assert result == "test game name"
|
|
|
|
def test_remove_leading_articles(self):
|
|
"""Test removal of leading articles."""
|
|
assert _normalize_search_term("The Legend of Zelda") == "legend of zelda"
|
|
assert _normalize_search_term("A New Hope") == "new hope"
|
|
assert _normalize_search_term("An Adventure") == "adventure"
|
|
|
|
def test_remove_trailing_articles(self):
|
|
"""Test removal of trailing articles."""
|
|
assert _normalize_search_term("Game, The") == "game"
|
|
assert _normalize_search_term("Hope, A") == "hope"
|
|
|
|
def test_remove_punctuation(self):
|
|
"""Test punctuation removal."""
|
|
result = _normalize_search_term("Mario's Adventure: The Game!")
|
|
assert result == "mario s adventure the game"
|
|
|
|
def test_normalize_spaces(self):
|
|
"""Test space normalization."""
|
|
result = _normalize_search_term("Game with multiple spaces")
|
|
assert result == "game with multiple spaces"
|
|
|
|
def test_unicode_normalization(self):
|
|
"""Test Unicode character normalization."""
|
|
result = _normalize_search_term("Pokémon")
|
|
assert result == "pokemon"
|
|
|
|
def test_preserve_articles_flag(self):
|
|
"""Test keeping articles when remove_articles=False."""
|
|
result = _normalize_search_term("The Legend of Zelda", remove_articles=False)
|
|
assert result == "the legend of zelda"
|
|
|
|
def test_preserve_punctuation_flag(self):
|
|
"""Test keeping punctuation when remove_punctuation=False."""
|
|
result = _normalize_search_term("Mario's Adventure!", remove_punctuation=False)
|
|
assert result == "mario's adventure!"
|
|
|
|
def test_empty_string(self):
|
|
"""Test empty string input."""
|
|
result = _normalize_search_term("")
|
|
assert result == ""
|
|
|
|
def test_whitespace_only(self):
|
|
"""Test whitespace-only input."""
|
|
result = _normalize_search_term(" \t\n ")
|
|
assert result == ""
|
|
|
|
def test_caching_behavior(self):
|
|
"""Test that results are cached."""
|
|
_normalize_search_term.cache_clear()
|
|
|
|
result1 = _normalize_search_term("Test Game")
|
|
cache_info1 = _normalize_search_term.cache_info()
|
|
|
|
result2 = _normalize_search_term("Test Game")
|
|
cache_info2 = _normalize_search_term.cache_info()
|
|
|
|
assert result1 == result2
|
|
assert cache_info2.hits == cache_info1.hits + 1
|
|
|
|
|
|
class TestMetadataHandlerMethods:
|
|
"""Test MetadataHandler instance methods."""
|
|
|
|
@pytest.fixture
|
|
def handler(self):
|
|
return ExampleMetadataHandler()
|
|
|
|
def test_normalize_cover_url_with_url(self, handler: MetadataHandler):
|
|
"""Test URL normalization with valid URL."""
|
|
url = "//images.example.com/cover.jpg"
|
|
result = handler.normalize_cover_url(url)
|
|
assert result == "https://images.example.com/cover.jpg"
|
|
|
|
def test_normalize_cover_url_with_https(self, handler: MetadataHandler):
|
|
"""Test URL normalization with existing https."""
|
|
url = "https://images.example.com/cover.jpg"
|
|
result = handler.normalize_cover_url(url)
|
|
assert result == "https://images.example.com/cover.jpg"
|
|
|
|
def test_normalize_cover_url_empty(self, handler: MetadataHandler):
|
|
"""Test URL normalization with empty string."""
|
|
result = handler.normalize_cover_url("")
|
|
assert result == ""
|
|
|
|
def test_normalize_search_term_delegates(self, handler: MetadataHandler):
|
|
"""Test that normalize_search_term delegates to the cached function."""
|
|
with patch("handler.metadata.base_handler._normalize_search_term") as mock_func:
|
|
mock_func.return_value = "normalized"
|
|
|
|
result = handler.normalize_search_term("Test Game", True, False)
|
|
|
|
mock_func.assert_called_once_with("Test Game", True, False)
|
|
assert result == "normalized"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ps2_opl_format_found(self, handler: MetadataHandler):
|
|
"""Test PS2 OPL format when serial is found."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = json.dumps({"Name": "Test Game Name"})
|
|
|
|
match = re.match(PS2_OPL_REGEX, "SLUS_123.45.iso")
|
|
assert match is not None
|
|
result = await handler._ps2_opl_format(match, "original_name")
|
|
|
|
mock_hget.assert_called_once_with(PS2_OPL_KEY, "SLUS_123.45")
|
|
assert result == "Test Game Name"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ps2_opl_format_not_found(self, handler: MetadataHandler):
|
|
"""Test PS2 OPL format when serial is not found."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = None
|
|
|
|
match = re.match(PS2_OPL_REGEX, "SLUS_123.45.iso")
|
|
assert match is not None
|
|
result = await handler._ps2_opl_format(match, "original_name")
|
|
|
|
assert result == "original_name"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sony_serial_format_found(self, handler: MetadataHandler):
|
|
"""Test Sony serial format when found."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = json.dumps({"title": "Found Game Title"})
|
|
|
|
result = await handler._sony_serial_format("test_key", "SLUS-12345")
|
|
|
|
mock_hget.assert_called_once_with("test_key", "SLUS-12345")
|
|
assert result == "Found Game Title"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sony_serial_format_not_found(self, handler: MetadataHandler):
|
|
"""Test Sony serial format when not found."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = None
|
|
|
|
result = await handler._sony_serial_format("test_key", "SLUS-12345")
|
|
|
|
assert result is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_sony_serial_format_normalizes_casing(self, handler: MetadataHandler):
|
|
"""Test Sony serial format uppercases the serial before lookup."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = json.dumps({"title": "Found Game Title"})
|
|
|
|
result = await handler._sony_serial_format("test_key", "slus-12345")
|
|
|
|
mock_hget.assert_called_once_with("test_key", "SLUS-12345")
|
|
assert result == "Found Game Title"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ps1_serial_format(self, handler: MetadataHandler):
|
|
"""Test PS1 serial format."""
|
|
with patch.object(
|
|
handler, "_sony_serial_format", new_callable=AsyncMock
|
|
) as mock_sony:
|
|
mock_sony.return_value = "PS1 Game Title"
|
|
|
|
match = re.match(SONY_SERIAL_REGEX, "SLUS-12345")
|
|
assert match is not None
|
|
result = await handler._ps1_serial_format(match, "original")
|
|
|
|
mock_sony.assert_called_once_with(PS1_SERIAL_INDEX_KEY, "SLUS-12345")
|
|
assert result == "PS1 Game Title"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ps1_serial_format_fallback(self, handler: MetadataHandler):
|
|
"""Test PS1 serial format fallback to original."""
|
|
with patch.object(
|
|
handler, "_sony_serial_format", new_callable=AsyncMock
|
|
) as mock_sony:
|
|
mock_sony.return_value = None
|
|
|
|
match = re.match(SONY_SERIAL_REGEX, "SLUS-12345")
|
|
assert match is not None
|
|
result = await handler._ps1_serial_format(match, "original")
|
|
|
|
assert result == "original"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ps2_serial_format(self, handler: MetadataHandler):
|
|
"""Test PS2 serial format."""
|
|
with patch.object(
|
|
handler, "_sony_serial_format", new_callable=AsyncMock
|
|
) as mock_sony:
|
|
mock_sony.return_value = "PS2 Game Title"
|
|
|
|
match = re.match(SONY_SERIAL_REGEX, "SLUS-12345")
|
|
if match:
|
|
result = await handler._ps2_serial_format(match, "original")
|
|
|
|
mock_sony.assert_called_once_with(PS2_SERIAL_INDEX_KEY, "SLUS-12345")
|
|
assert result == "PS2 Game Title"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_psp_serial_format(self, handler: MetadataHandler):
|
|
"""Test PSP serial format."""
|
|
with patch.object(
|
|
handler, "_sony_serial_format", new_callable=AsyncMock
|
|
) as mock_sony:
|
|
mock_sony.return_value = "PSP Game Title"
|
|
|
|
match = re.match(SONY_SERIAL_REGEX, "ULUS-12345")
|
|
if match:
|
|
result = await handler._psp_serial_format(match, "original")
|
|
|
|
mock_sony.assert_called_once_with(PSP_SERIAL_INDEX_KEY, "ULUS-12345")
|
|
assert result == "PSP Game Title"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_switch_titledb_format_cache_exists(self, handler: MetadataHandler):
|
|
"""Test Switch TitleDB format when cache exists."""
|
|
with (
|
|
patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists,
|
|
patch.object(async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE)),
|
|
patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget,
|
|
):
|
|
mock_exists.return_value = True
|
|
mock_hget.return_value = json.dumps(
|
|
{"name": "Switch Game", "publisher": "Nintendo"}
|
|
)
|
|
|
|
match = re.match(SWITCH_TITLEDB_REGEX, "70123456789012")
|
|
assert match is not None
|
|
index_name, index_entry = await handler._switch_titledb_format(
|
|
match, "original"
|
|
)
|
|
|
|
mock_hget.assert_called_once()
|
|
assert index_name == "Switch Game"
|
|
assert index_entry is not None
|
|
assert index_entry["publisher"] == "Nintendo"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_switch_titledb_format_not_found(self, handler: MetadataHandler):
|
|
"""Test Switch TitleDB format when title ID not found."""
|
|
with (
|
|
patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists,
|
|
patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget,
|
|
):
|
|
mock_exists.return_value = True
|
|
mock_hget.return_value = None
|
|
|
|
match = re.match(SWITCH_TITLEDB_REGEX, "70123456789012")
|
|
assert match is not None
|
|
result = await handler._switch_titledb_format(match, "original")
|
|
|
|
assert result == ("original", None)
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
"product_id",
|
|
[
|
|
# A base game is looked up as-is.
|
|
"0100ABCD12340000",
|
|
# An update carries bitmask 0x800.
|
|
"0100ABCD12340800",
|
|
# DLC carries an addon index in the low 12 bits.
|
|
"0100ABCD12341001",
|
|
],
|
|
)
|
|
async def test_switch_productid_format_found(
|
|
self, handler: MetadataHandler, product_id: str
|
|
):
|
|
"""Only the base application has a titledb entry, so updates and DLC
|
|
are resolved to it before the lookup."""
|
|
with (
|
|
patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists,
|
|
patch.object(async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE)),
|
|
patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget,
|
|
):
|
|
mock_exists.return_value = True
|
|
mock_hget.side_effect = [
|
|
json.dumps("70010000000025"),
|
|
json.dumps({"name": "Product Game"}),
|
|
]
|
|
|
|
rom = Rom(fs_name="Game.nsp", title_id=product_id)
|
|
result = await handler._switch_productid_format(rom, "Game.nsp", "original")
|
|
|
|
# The product id index holds the title id of its titleID entry.
|
|
assert [call.args for call in mock_hget.await_args_list] == [
|
|
(SWITCH_PRODUCT_ID_KEY, "0100ABCD12340000"),
|
|
(SWITCH_TITLEDB_INDEX_KEY, "70010000000025"),
|
|
]
|
|
assert result[0] == "Product Game"
|
|
|
|
@pytest.mark.parametrize(
|
|
("title_id", "fs_name", "expected"),
|
|
[
|
|
# The extracted id wins over whatever the filename says.
|
|
("0100ABCD12340000", "Game [0100999988880000].nsp", "0100ABCD12340000"),
|
|
# sigil reports lowercase; the titledb index is keyed uppercase.
|
|
("0100abcd12340000", "Game.nsp", "0100ABCD12340000"),
|
|
# With nothing extracted, the filename is still scraped.
|
|
(None, "Game [0100ABCD12340000].nsp", "0100ABCD12340000"),
|
|
# A non-Switch id is not a product id.
|
|
("SLUS-20152", "Game.nsp", None),
|
|
(None, "Game.nsp", None),
|
|
],
|
|
)
|
|
@pytest.mark.asyncio
|
|
async def test_switch_productid_format_prefers_the_extracted_id(
|
|
self,
|
|
handler: MetadataHandler,
|
|
title_id: str | None,
|
|
fs_name: str,
|
|
expected: str | None,
|
|
):
|
|
rom = Rom(fs_name=fs_name, title_id=title_id)
|
|
|
|
with (
|
|
patch.object(async_cache, "exists", new_callable=AsyncMock) as mock_exists,
|
|
patch.object(async_cache, "get", schema_stamp_get(SWITCH_TITLEDB_STORE)),
|
|
patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget,
|
|
):
|
|
mock_exists.return_value = True
|
|
mock_hget.return_value = None
|
|
|
|
await handler._switch_productid_format(rom, fs_name, "original")
|
|
|
|
if expected is None:
|
|
mock_hget.assert_not_called()
|
|
else:
|
|
mock_hget.assert_called_once_with(SWITCH_PRODUCT_ID_KEY, expected)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mame_format_found(self, handler: MetadataHandler):
|
|
"""Test MAME format when entry is found."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = json.dumps(
|
|
{"description": "Test MAME Game (Version 1.0)"}
|
|
)
|
|
|
|
# Mock the fs_rom_handler import from handler.filesystem
|
|
with patch("handler.filesystem.fs_rom_handler") as mock_fs_handler:
|
|
mock_fs_handler.get_file_name_with_no_tags.return_value = (
|
|
"Test MAME Game"
|
|
)
|
|
|
|
result = await handler._mame_format("test_rom")
|
|
|
|
mock_hget.assert_called_once_with(MAME_XML_KEY, "test_rom")
|
|
mock_fs_handler.get_file_name_with_no_tags.assert_called_once_with(
|
|
"Test MAME Game (Version 1.0)"
|
|
)
|
|
assert result == "Test MAME Game"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mame_format_not_found(self, handler: MetadataHandler):
|
|
"""Test MAME format when entry is not found."""
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
mock_hget.return_value = None
|
|
|
|
result = await handler._mame_format("test_rom")
|
|
|
|
assert result == "test_rom"
|
|
|
|
def test_mask_sensitive_values_authorization_bearer(self, handler: MetadataHandler):
|
|
"""Test masking Bearer token in Authorization header."""
|
|
values = {"Authorization": "Bearer abc123def456ghi789"}
|
|
result = handler._mask_sensitive_values(values)
|
|
assert result["Authorization"] == "Bearer ab***89"
|
|
|
|
def test_mask_sensitive_values_client_keys(self, handler: MetadataHandler):
|
|
"""Test masking client keys and secrets."""
|
|
values = {
|
|
"Client-ID": "abcdef123456",
|
|
"Client-Secret": "secret123456789",
|
|
"client_id": "client123456",
|
|
"client_secret": "clientsecret123",
|
|
"api_key": "apikey123456789",
|
|
}
|
|
result = handler._mask_sensitive_values(values)
|
|
|
|
assert result["Client-ID"] == "ab***56"
|
|
assert result["Client-Secret"] == "se***89"
|
|
assert result["client_id"] == "cl***56"
|
|
assert result["client_secret"] == "cl***23"
|
|
assert result["api_key"] == "ap***89"
|
|
|
|
def test_mask_sensitive_values_retroachievements_keys(
|
|
self, handler: MetadataHandler
|
|
):
|
|
"""Test masking RetroAchievements specific keys."""
|
|
values = {
|
|
"ssid": "sessionid123",
|
|
"sspassword": "sessionpass123",
|
|
"devid": "developer123",
|
|
"devpassword": "devpass123",
|
|
"y": "rapikey123",
|
|
}
|
|
result = handler._mask_sensitive_values(values)
|
|
|
|
assert result["ssid"] == "se***23"
|
|
assert result["sspassword"] == "se***23"
|
|
assert result["devid"] == "de***23"
|
|
assert result["devpassword"] == "de***23"
|
|
assert result["y"] == "ra***23"
|
|
|
|
def test_mask_sensitive_values_preserves_other_keys(self, handler: MetadataHandler):
|
|
"""Test that non-sensitive keys are preserved."""
|
|
values = {
|
|
"regular_key": "regular_value",
|
|
"another_key": "another_value",
|
|
"api_key": "sensitive123",
|
|
}
|
|
result = handler._mask_sensitive_values(values)
|
|
|
|
assert result["regular_key"] == "regular_value"
|
|
assert result["another_key"] == "another_value"
|
|
assert result["api_key"] == "se***23"
|
|
|
|
def test_mask_sensitive_values_short_values(self, handler: MetadataHandler):
|
|
"""Test masking of short values."""
|
|
values = {"api_key": "ab"}
|
|
result = handler._mask_sensitive_values(values)
|
|
assert result["api_key"] == "ab***ab" # Shows first 2 and last 2
|
|
|
|
|
|
class TestResolveIndexedTitle:
|
|
PLATFORMS = IndexedFormatPlatforms(ps1=1, ps2=2, psp=3, switch=4, scummvm=7)
|
|
|
|
@pytest.fixture
|
|
def handler(self) -> MetadataHandler:
|
|
return ExampleMetadataHandler()
|
|
|
|
async def _resolve(
|
|
self,
|
|
handler: MetadataHandler,
|
|
fs_name: str,
|
|
platform_id: int,
|
|
platforms: IndexedFormatPlatforms = PLATFORMS,
|
|
slug: str | None = None,
|
|
) -> tuple[str, BaseRom]:
|
|
fallback_rom = BaseRom()
|
|
platform = Platform(slug=slug, fs_slug=slug) if slug else None
|
|
term = await handler._resolve_indexed_title(
|
|
Rom(fs_name=fs_name, platform=platform),
|
|
fs_name,
|
|
"original",
|
|
platform_id,
|
|
platforms,
|
|
fallback_rom,
|
|
)
|
|
return term, fallback_rom
|
|
|
|
@pytest.mark.parametrize(
|
|
("fs_name", "platform_id", "method"),
|
|
[
|
|
("SLUS_200.62.Grand Theft Auto.iso", 2, "_ps2_opl_format"),
|
|
("Crash [SCUS-94900].bin", 1, "_ps1_serial_format"),
|
|
("Ridge Racer [SLUS-01234].iso", 2, "_ps2_serial_format"),
|
|
("Lumines [ULUS-10046].iso", 3, "_psp_serial_format"),
|
|
("monkey1.scummvm", 7, "_scummvm_format"),
|
|
],
|
|
)
|
|
@pytest.mark.asyncio
|
|
async def test_named_index_sets_term_and_fallback_name(
|
|
self, handler: MetadataHandler, fs_name: str, platform_id: int, method: str
|
|
):
|
|
with patch.object(handler, method, AsyncMock(return_value="Indexed Title")):
|
|
term, fallback_rom = await self._resolve(handler, fs_name, platform_id)
|
|
|
|
assert term == "Indexed Title"
|
|
assert fallback_rom == BaseRom(name="Indexed Title")
|
|
|
|
@pytest.mark.parametrize("slug", ["arcade", "fbneo", "naomi", "neogeomvs"])
|
|
@pytest.mark.asyncio
|
|
async def test_a_mame_shortname_platform_resolves_the_set_title(
|
|
self, handler: MetadataHandler, slug: str
|
|
):
|
|
with patch.object(handler, "_mame_format", AsyncMock(return_value="Pac-Man")):
|
|
term, fallback_rom = await self._resolve(
|
|
handler, "pacman.zip", 99, slug=slug
|
|
)
|
|
|
|
assert term == "Pac-Man"
|
|
assert fallback_rom == BaseRom(name="Pac-Man")
|
|
|
|
@pytest.mark.parametrize(
|
|
"slug", ["daphne", "singe", "type-x", "lindbergh", "teknoparrot"]
|
|
)
|
|
@pytest.mark.asyncio
|
|
async def test_an_arcade_platform_with_its_own_set_names_is_left_alone(
|
|
self, handler: MetadataHandler, slug: str
|
|
):
|
|
with patch.object(handler, "_mame_format", new_callable=AsyncMock) as fmt:
|
|
term, _ = await self._resolve(handler, "ace.zip", 99, slug=slug)
|
|
|
|
fmt.assert_not_called()
|
|
assert term == "original"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_switch_entry_fills_the_fallback(self, handler: MetadataHandler):
|
|
entry = {
|
|
"name": "Celeste",
|
|
"description": "Climb",
|
|
"iconUrl": "https://example.com/icon.png",
|
|
"screenshots": None,
|
|
}
|
|
with (
|
|
patch.object(
|
|
handler,
|
|
"_switch_titledb_format",
|
|
AsyncMock(return_value=("Celeste", entry)),
|
|
),
|
|
patch.object(
|
|
handler,
|
|
"_switch_productid_format",
|
|
AsyncMock(return_value=("Celeste", None)),
|
|
),
|
|
):
|
|
term, fallback_rom = await self._resolve(
|
|
handler, "Celeste [70010000000025].nsp", 4
|
|
)
|
|
|
|
assert term == "Celeste"
|
|
assert fallback_rom == BaseRom(
|
|
name="Celeste",
|
|
summary="Climb",
|
|
url_cover="https://example.com/icon.png",
|
|
url_screenshots=[],
|
|
)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_other_platform_is_left_alone(self, handler: MetadataHandler):
|
|
with patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget:
|
|
term, fallback_rom = await self._resolve(handler, "SLUS-12345.bin", 99)
|
|
|
|
mock_hget.assert_not_called()
|
|
assert term == "original"
|
|
assert fallback_rom == BaseRom()
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_provider_without_scummvm_skips_it(self, handler: MetadataHandler):
|
|
platforms = IndexedFormatPlatforms(ps1=1, ps2=2, psp=3, switch=4)
|
|
with patch.object(handler, "_scummvm_format", new_callable=AsyncMock) as fmt:
|
|
term, _ = await self._resolve(handler, "monkey1", 7, platforms)
|
|
|
|
fmt.assert_not_called()
|
|
assert term == "original"
|
|
|
|
|
|
class TestProviderTags:
|
|
TAG = provider_tag_regex("igdb")
|
|
|
|
@pytest.mark.parametrize(
|
|
("fs_name", "expected"),
|
|
[
|
|
("Zelda (igdb-1025).sfc", 1025),
|
|
("Zelda (IGDB-1025).sfc", 1025),
|
|
("Zelda (moby-1025).sfc", None),
|
|
("Zelda (igdb-).sfc", None),
|
|
("Zelda.sfc", None),
|
|
# Past 4300 digits int() raises instead of parsing.
|
|
("Zelda (igdb-" + "1" * 5000 + ").sfc", None),
|
|
],
|
|
ids=["tagged", "any_case", "other_provider", "no_id", "untagged", "too_long"],
|
|
)
|
|
def test_reads_the_id_from_the_tag(self, fs_name: str, expected: int | None):
|
|
assert tag_id_from_filename(self.TAG, fs_name) == expected
|
|
|
|
|
|
class _HeartbeatHandler(MetadataHandler):
|
|
enabled = True
|
|
|
|
@classmethod
|
|
def is_enabled(cls) -> bool:
|
|
return cls.enabled
|
|
|
|
|
|
class TestHeartbeat:
|
|
@pytest.mark.parametrize("answer", [True, False])
|
|
@pytest.mark.asyncio
|
|
async def test_reports_what_the_probe_finds(self, answer: bool):
|
|
probe = AsyncMock(return_value=answer)
|
|
|
|
assert await _HeartbeatHandler()._heartbeat("Test API", probe) is answer
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_failing_probe_is_down(self):
|
|
probe = AsyncMock(side_effect=RuntimeError("down"))
|
|
|
|
assert await _HeartbeatHandler()._heartbeat("Test API", probe) is False
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_disabled_provider_is_not_probed(
|
|
self, monkeypatch: pytest.MonkeyPatch
|
|
):
|
|
monkeypatch.setattr(_HeartbeatHandler, "enabled", False)
|
|
probe = AsyncMock(return_value=True)
|
|
|
|
assert await _HeartbeatHandler()._heartbeat("Test API", probe) is False
|
|
probe.assert_not_awaited()
|
|
|
|
|
|
class TestStripSensitiveQueryParams:
|
|
"""Test the strip_sensitive_query_params function."""
|
|
|
|
def test_removes_known_sensitive_keys(self):
|
|
"""ssid and sspassword should be stripped from the query string."""
|
|
url = "https://api.example.com/media?ssid=user&sspassword=secret&crc=abc"
|
|
result = strip_sensitive_query_params(url)
|
|
assert "ssid=" not in result
|
|
assert "sspassword=" not in result
|
|
assert "crc=abc" in result
|
|
|
|
def test_preserves_non_sensitive_params(self):
|
|
"""Non-sensitive params should keep their values and ordering."""
|
|
url = "https://api.example.com/media?systemeid=1&ssid=user&romnom=Game.zip"
|
|
result = strip_sensitive_query_params(url)
|
|
# parse rather than rely on a literal; urlencode may reorder identically-named keys
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
assert ("systemeid", "1") in parsed
|
|
assert ("romnom", "Game.zip") in parsed
|
|
assert all(k != "ssid" for k, _ in parsed)
|
|
|
|
def test_case_insensitive_key_matching(self):
|
|
"""Keys should match regardless of case (SSID, SsId, etc.)."""
|
|
url = "https://api.example.com/media?SSID=user&SSPassword=secret&crc=abc"
|
|
result = strip_sensitive_query_params(url)
|
|
assert "SSID=" not in result
|
|
assert "SSPassword=" not in result
|
|
assert "crc=abc" in result
|
|
|
|
def test_url_with_no_query(self):
|
|
"""URLs without a query string should pass through unchanged in shape."""
|
|
url = "https://api.example.com/media"
|
|
result = strip_sensitive_query_params(url)
|
|
assert result == "https://api.example.com/media"
|
|
|
|
def test_url_with_no_sensitive_params(self):
|
|
"""URLs whose params are all non-sensitive should be preserved."""
|
|
url = "https://api.example.com/media?systemeid=1&romnom=Game.zip"
|
|
result = strip_sensitive_query_params(url)
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
assert ("systemeid", "1") in parsed
|
|
assert ("romnom", "Game.zip") in parsed
|
|
|
|
def test_preserves_other_url_components(self):
|
|
"""Scheme, host, path, and fragment should be preserved."""
|
|
url = "https://api.example.com:8080/path/to/media?ssid=u&keep=1#frag"
|
|
result = strip_sensitive_query_params(url)
|
|
parsed = urlparse(result)
|
|
assert parsed.scheme == "https"
|
|
assert parsed.netloc == "api.example.com:8080"
|
|
assert parsed.path == "/path/to/media"
|
|
assert parsed.fragment == "frag"
|
|
assert "ssid" not in parsed.query
|
|
|
|
def test_custom_sensitive_keys_override(self):
|
|
"""A caller-supplied sensitive_keys set should override the default."""
|
|
url = "https://api.example.com/m?ssid=user&token=tk&keep=1"
|
|
result = strip_sensitive_query_params(url, sensitive_keys={"token"})
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
# ssid is not in the custom set so it stays; token is stripped
|
|
assert ("ssid", "user") in parsed
|
|
assert ("keep", "1") in parsed
|
|
assert all(k != "token" for k, _ in parsed)
|
|
|
|
def test_blank_values_preserved(self):
|
|
"""Blank values for non-sensitive keys should not be dropped."""
|
|
url = "https://api.example.com/m?empty=&keep=1&ssid=user"
|
|
result = strip_sensitive_query_params(url)
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
assert ("empty", "") in parsed
|
|
assert ("keep", "1") in parsed
|
|
|
|
|
|
class TestRestoreSensitiveQueryParams:
|
|
"""Test the restore_sensitive_query_params function."""
|
|
|
|
def test_appends_to_url_with_no_query(self):
|
|
"""Restoring onto a URL with no query should produce a valid query."""
|
|
url = "https://api.example.com/media"
|
|
result = restore_sensitive_query_params(
|
|
url, {"ssid": "user", "sspassword": "secret"}
|
|
)
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
assert ("ssid", "user") in parsed
|
|
assert ("sspassword", "secret") in parsed
|
|
|
|
def test_preserves_existing_non_conflicting_params(self):
|
|
"""Other params present on the URL must be kept alongside restored ones."""
|
|
url = "https://api.example.com/m?systemeid=1&romnom=Game.zip"
|
|
result = restore_sensitive_query_params(url, {"ssid": "user"})
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
assert ("systemeid", "1") in parsed
|
|
assert ("romnom", "Game.zip") in parsed
|
|
assert ("ssid", "user") in parsed
|
|
|
|
def test_overwrites_existing_same_key_no_duplicates(self):
|
|
"""If the URL already has the key, it should be replaced, not duplicated."""
|
|
url = "https://api.example.com/m?ssid=old&keep=1"
|
|
result = restore_sensitive_query_params(url, {"ssid": "new"})
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
ssid_values = [v for k, v in parsed if k == "ssid"]
|
|
assert ssid_values == ["new"]
|
|
assert ("keep", "1") in parsed
|
|
|
|
def test_overwrite_is_case_insensitive(self):
|
|
"""Existing keys differing only in case should still be replaced."""
|
|
url = "https://api.example.com/m?SSID=old&keep=1"
|
|
result = restore_sensitive_query_params(url, {"ssid": "new"})
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
# No leftover SSID=old entry under any casing
|
|
ssid_values = [v for k, v in parsed if k.lower() == "ssid"]
|
|
assert ssid_values == ["new"]
|
|
|
|
def test_encodes_special_characters_in_values(self):
|
|
"""Values with reserved URL characters must be percent-encoded."""
|
|
url = "https://api.example.com/m"
|
|
result = restore_sensitive_query_params(url, {"sspassword": "p@ss w&rd=!"})
|
|
# The raw value must not appear unencoded in the query
|
|
assert "p@ss w&rd=!" not in result
|
|
# But round-tripping through parse_qsl recovers the original value
|
|
parsed = parse_qsl(urlparse(result).query, keep_blank_values=True)
|
|
assert ("sspassword", "p@ss w&rd=!") in parsed
|
|
|
|
def test_preserves_other_url_components(self):
|
|
"""Scheme, host, path, and fragment should be preserved."""
|
|
url = "https://api.example.com:8080/path?keep=1#frag"
|
|
result = restore_sensitive_query_params(url, {"ssid": "u"})
|
|
parsed = urlparse(result)
|
|
assert parsed.scheme == "https"
|
|
assert parsed.netloc == "api.example.com:8080"
|
|
assert parsed.path == "/path"
|
|
assert parsed.fragment == "frag"
|
|
|
|
def test_strip_then_restore_roundtrip(self):
|
|
"""strip → restore should recover an equivalent URL for the credential keys."""
|
|
original = "https://api.example.com/m?ssid=user&sspassword=secret&crc=abc"
|
|
stripped = strip_sensitive_query_params(original)
|
|
restored = restore_sensitive_query_params(
|
|
stripped, {"ssid": "user", "sspassword": "secret"}
|
|
)
|
|
parsed = parse_qsl(urlparse(restored).query, keep_blank_values=True)
|
|
assert ("ssid", "user") in parsed
|
|
assert ("sspassword", "secret") in parsed
|
|
assert ("crc", "abc") in parsed
|
|
|
|
|
|
class TestRegexPatterns:
|
|
"""Test regex patterns used in the metadata handler."""
|
|
|
|
def test_switch_titledb_regex(self):
|
|
"""Test Switch TitleDB regex pattern."""
|
|
# Valid title IDs (70 followed by exactly 12 digits)
|
|
assert SWITCH_TITLEDB_REGEX.match("70123456789012")
|
|
assert SWITCH_TITLEDB_REGEX.match("70999999999999")
|
|
|
|
# Test finding title IDs within filenames (as used in real code)
|
|
assert SWITCH_TITLEDB_REGEX.search("Game [70123456789012].nsp")
|
|
assert SWITCH_TITLEDB_REGEX.search("70999999999999_update.nsp")
|
|
|
|
# Invalid title IDs that should not match
|
|
assert not SWITCH_TITLEDB_REGEX.match("60123456789012") # Wrong prefix
|
|
assert not SWITCH_TITLEDB_REGEX.match("7012345678901") # Too short
|
|
assert not SWITCH_TITLEDB_REGEX.search(
|
|
"Game [60123456789012].nsp"
|
|
) # Wrong prefix in filename
|
|
assert not SWITCH_TITLEDB_REGEX.search(
|
|
"Game [7012345678901].nsp"
|
|
) # Too short in filename
|
|
|
|
def test_switch_product_id_regex(self):
|
|
"""Test Switch Product ID regex pattern."""
|
|
# Valid product IDs (0100 followed by exactly 12 hex chars)
|
|
assert SWITCH_PRODUCT_ID_REGEX.match("0100ABC123456789")
|
|
assert SWITCH_PRODUCT_ID_REGEX.match("0100123456789ABC")
|
|
|
|
# Invalid product IDs
|
|
assert not SWITCH_PRODUCT_ID_REGEX.match("0200ABC123456789") # Wrong prefix
|
|
assert not SWITCH_PRODUCT_ID_REGEX.match("0100ABC12345678") # Too short
|
|
|
|
def test_ps2_opl_regex(self):
|
|
"""Test PS2 OPL regex pattern."""
|
|
# Valid OPL codes
|
|
match = PS2_OPL_REGEX.match("SLUS_123.45.iso")
|
|
assert match and match.group(1) == "SLUS_123.45"
|
|
|
|
match = PS2_OPL_REGEX.match("SCES_987.65.bin")
|
|
assert match and match.group(1) == "SCES_987.65"
|
|
|
|
# Invalid codes
|
|
assert not PS2_OPL_REGEX.match("SLUS123.45.iso") # Missing underscore
|
|
assert not PS2_OPL_REGEX.match("SLU_123.45.iso") # Wrong length
|
|
|
|
def test_sony_serial_regex(self):
|
|
"""Test Sony serial regex pattern."""
|
|
# Valid serials
|
|
match = SONY_SERIAL_REGEX.match("SLUS-12345")
|
|
assert match and match.group(1) == "SLUS-12345"
|
|
|
|
match = SONY_SERIAL_REGEX.match("Game Title [ULUS-98765]")
|
|
assert match and match.group(1) == "ULUS-98765"
|
|
|
|
# Invalid serials
|
|
assert not SONY_SERIAL_REGEX.match("SLU-12345") # Wrong length
|
|
assert not SONY_SERIAL_REGEX.match("SLUS_12345") # Wrong separator
|
|
|
|
def test_article_patterns(self):
|
|
"""Test article removal patterns."""
|
|
# Leading articles (should match at start of string - pattern expects lowercase)
|
|
assert LEADING_ARTICLE_PATTERN.match("the game")
|
|
assert LEADING_ARTICLE_PATTERN.match("a game")
|
|
assert LEADING_ARTICLE_PATTERN.match("an adventure")
|
|
assert LEADING_ARTICLE_PATTERN.match("The Game")
|
|
# Should not match when not at start
|
|
assert not LEADING_ARTICLE_PATTERN.match("game the")
|
|
|
|
def test_space_patterns(self):
|
|
"""Test space normalization patterns."""
|
|
# Non-word space pattern (should find punctuation)
|
|
assert NON_WORD_SPACE_PATTERN.search("Game's Adventure!")
|
|
assert NON_WORD_SPACE_PATTERN.search("Game: The Return")
|
|
|
|
# Multiple space pattern (matches any whitespace - used to normalize spaces)
|
|
assert MULTIPLE_SPACE_PATTERN.search("Game with spaces") # Multiple spaces
|
|
assert MULTIPLE_SPACE_PATTERN.search(
|
|
"Game with spaces"
|
|
) # Single spaces also match
|
|
assert MULTIPLE_SPACE_PATTERN.search("Game\twith\nspaces") # Tabs and newlines
|
|
assert not MULTIPLE_SPACE_PATTERN.search("Gamewithoutspaces") # No spaces
|
|
|
|
|
|
class TestUniversalPlatformSlug:
|
|
"""Test UniversalPlatformSlug enum."""
|
|
|
|
def test_enum_values_are_strings(self):
|
|
"""Test that all enum values are strings."""
|
|
for slug in UniversalPlatformSlug:
|
|
assert isinstance(slug.value, str)
|
|
assert slug.value # Not empty
|
|
|
|
def test_specific_platform_slugs(self):
|
|
"""Test specific platform slug values."""
|
|
assert UniversalPlatformSlug.N64.value == "n64"
|
|
assert UniversalPlatformSlug.PSX.value == "psx"
|
|
assert UniversalPlatformSlug.PS2.value == "ps2"
|
|
assert UniversalPlatformSlug.SWITCH.value == "switch"
|
|
assert UniversalPlatformSlug.ARCADE.value == "arcade"
|
|
|
|
def test_enum_contains_expected_platforms(self):
|
|
"""Test that enum contains major gaming platforms."""
|
|
expected_platforms = [
|
|
"n64",
|
|
"psx",
|
|
"ps2",
|
|
"ps3",
|
|
"ps4",
|
|
"ps5",
|
|
"switch",
|
|
"wii",
|
|
"wiiu",
|
|
"xbox",
|
|
"xbox360",
|
|
"xboxone",
|
|
"nes",
|
|
"snes",
|
|
"gb",
|
|
"gba",
|
|
"nds",
|
|
"3ds",
|
|
"genesis",
|
|
"saturn",
|
|
"dc",
|
|
"arcade",
|
|
]
|
|
|
|
enum_values = [slug.value for slug in UniversalPlatformSlug]
|
|
for platform in expected_platforms:
|
|
assert platform in enum_values
|
|
|
|
|
|
class TestBaseRomTypedDict:
|
|
"""Test BaseRom TypedDict structure."""
|
|
|
|
def test_baserom_optional_fields(self):
|
|
"""Test that BaseRom allows optional fields."""
|
|
# Empty dict should be valid
|
|
rom: BaseRom = {}
|
|
assert isinstance(rom, dict)
|
|
|
|
# Partial dict should be valid
|
|
rom = {"name": "Test Game"}
|
|
assert rom["name"] == "Test Game"
|
|
|
|
# Full dict should be valid
|
|
rom = {
|
|
"name": "Test Game",
|
|
"summary": "A test game",
|
|
"url_cover": "https://example.com/cover.jpg",
|
|
"url_screenshots": ["https://example.com/shot1.jpg"],
|
|
"url_manual": "https://example.com/manual.pdf",
|
|
}
|
|
assert len(rom) == 5
|
|
|
|
|
|
class TestConstants:
|
|
"""Test module constants."""
|
|
|
|
def test_redis_keys_format(self):
|
|
"""Test that Redis keys follow expected format."""
|
|
expected_prefix = "romm:"
|
|
|
|
redis_keys = [
|
|
MAME_XML_KEY,
|
|
PS2_OPL_KEY,
|
|
PS1_SERIAL_INDEX_KEY,
|
|
PS2_SERIAL_INDEX_KEY,
|
|
PSP_SERIAL_INDEX_KEY,
|
|
]
|
|
|
|
for key in redis_keys:
|
|
assert key.startswith(expected_prefix)
|
|
assert len(key) > len(expected_prefix)
|
|
|
|
def test_key_uniqueness(self):
|
|
"""Test that all Redis keys are unique."""
|
|
keys = [
|
|
MAME_XML_KEY,
|
|
PS2_OPL_KEY,
|
|
PS1_SERIAL_INDEX_KEY,
|
|
PS2_SERIAL_INDEX_KEY,
|
|
PSP_SERIAL_INDEX_KEY,
|
|
]
|
|
|
|
assert len(keys) == len(set(keys))
|
|
|
|
|
|
class _CappedHandler(base_handler.MetadataHandler):
|
|
@classmethod
|
|
def is_enabled(cls) -> bool:
|
|
return True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fetch_capped_abandons_an_oversized_body_mid_stream(monkeypatch):
|
|
"""Providers are third parties: the read stops instead of buffering it all."""
|
|
monkeypatch.setattr(base_handler, "MAX_RESPONSE_BYTES", 1024)
|
|
sent = 0
|
|
|
|
async def endless() -> AsyncIterator[bytes]:
|
|
nonlocal sent
|
|
while True:
|
|
sent += 1
|
|
yield b"A" * 512
|
|
|
|
async def respond(request: httpx2.Request) -> httpx2.Response:
|
|
if "big" in str(request.url):
|
|
return httpx2.Response(200, content=endless())
|
|
return httpx2.Response(200, content=b"small")
|
|
|
|
client = httpx2.AsyncClient(transport=httpx2.MockTransport(respond))
|
|
token = ctx_httpx_client.set(client)
|
|
try:
|
|
handler = _CappedHandler()
|
|
assert await handler._fetch_capped("https://x.test/", headers={}) == b"small"
|
|
assert await handler._fetch_capped("https://x.test/?big=1", headers={}) is None
|
|
finally:
|
|
ctx_httpx_client.reset(token)
|
|
await client.aclose()
|
|
|
|
assert sent == 3, f"stream should stop just past the cap, pulled {sent} chunks"
|