mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 10:01:00 +01:00
* Keep ScreenScraper disc art for every disc of a multi-disc game ScreenScraper tags each disc's support-2D art with a "support" number, but the extractor kept only the first support-2D it met, so discs 2 and up were never downloaded or shown. The first disc still fills physical_url/physical_path, which the cover art, disc-spin animation and exporters read. Every later disc goes to a new ss_metadata.physical_extra_discs list, is downloaded next to it as physical/physical_disc<N>.png, and gets its own entry on the v2 Artwork subtab. Existing ROMs pick up the extra discs on their next metadata refresh. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * Type the extra-disc test metadata so mypy can index it Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * Label the first disc's art on multi-disc games ss_metadata now records which disc physical_url shows, so the Artwork subtab can label it "Physical media (disc N)" alongside the later discs. It stays plain "Physical media" for single-disc games, gamelist art, or when no later disc's art is on disk. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * pr-ready step 2 (code-review): harden disc numbers and rematch cleanup - Read ScreenScraper's disc number with safe_int and clamp it to 1, so a zero, negative or non-string "support" value counts as the first disc. - Remove the physical folder on an ss_id change when only later discs had art, so a rematch doesn't keep the old game's disc images. - Collapse store_metadata_media's two result lists into one target list. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * pr-ready step 3 (simplify): one home for the media a provider dict records - Add FSResourcesHandler.recorded_media, which lists every recorded file including a <type>_extra_discs list, so store_metadata_media and the update_rom cleanup share one rule and neither special-cases physical. - Skip stripping a disc's URL once a better region already supplied it. - Share the ScreenScraper disc tests' patch setup in an _extract helper and spell out each test's discs instead of slicing a fixture. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * Refetch media whose source changed and keep shared art on rematch - A scan now deletes each stored media file whose recorded URL changed, or a later disc's file the new metadata dropped, before storing, so a physical.png saved from another disc's art is fetched again instead of showing under a "(disc 1)" label. - A rematch deletes a later disc's own file instead of the whole physical folder, so gamelist art sharing that folder survives. Addresses the Greptile review on this PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * Keep a shared media file a higher-priority provider still records The stale-media check could delete a shared file such as physical.png because a lower-priority provider's URL for it changed, even though the file held a higher-priority provider's unchanged art. Each provider now leaves alone the paths the providers before it still record. Addresses the second Greptile review on this PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * Decide stale shared media by which provider owns the path The previous rule kept any path a higher-priority provider recorded, so when ScreenScraper newly claimed a physical.png that still held older gamelist art, neither provider refetched it. A shared path's file now belongs to the first provider, in priority order, that records it, and the file is refetched when that owner or its URL differs between the previous and current metadata. Every provider is compared in one pass, including ones outside this scan's sources. Addresses the third Greptile review on this PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 * Name the fields of recorded media instead of using bare tuples RecordedMedia was a four-item tuple alias that callers unpacked by position, with a comment spelling out what each slot held. It is now a NamedTuple with explicit fields and a path property, and the per-path ownership claim in remove_stale_media gets the same treatment. Addresses review feedback on this PR. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018qtuXherdgoU89KtrSeU22 --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2415 lines
90 KiB
Python
2415 lines
90 KiB
Python
"""Tests for the ScreenScraper metadata handler."""
|
|
|
|
import json
|
|
from typing import Any, cast
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
from urllib.parse import parse_qs, urlparse
|
|
|
|
import pytest
|
|
from fastapi import HTTPException, status
|
|
from tests.handler.metadata.conftest import schema_stamp_get
|
|
|
|
from adapters.services.screenscraper import (
|
|
ScreenScraperCredentialsError,
|
|
ScreenScraperRateLimitError,
|
|
SSAccountLimits,
|
|
SSCredentialSet,
|
|
)
|
|
from adapters.services.screenscraper_types import SSGame, SSGameRom
|
|
from config.config_manager import Config, MetadataMediaType
|
|
from handler.metadata import ss_handler
|
|
from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY
|
|
from handler.metadata.ss_handler import (
|
|
PS1_SS_ID,
|
|
SWITCH_SS_ID,
|
|
ScreenScraperExhaustedError,
|
|
SSHandler,
|
|
SSMetadataMedia,
|
|
SSRom,
|
|
_get_rom_type,
|
|
_is_daily_quota_error,
|
|
_is_notgame,
|
|
add_ss_auth_to_url,
|
|
build_ss_game,
|
|
extract_languages_from_ss_dump,
|
|
extract_media_from_ss_game,
|
|
extract_metadata_from_ss_rom,
|
|
extract_regions_from_ss_dump,
|
|
extract_tags_from_ss_dump,
|
|
find_ss_dump,
|
|
get_preferred_languages,
|
|
get_preferred_regions,
|
|
get_rate_limited_rom_names,
|
|
get_taxonomy_languages,
|
|
note_rate_limited_rom,
|
|
reset_rate_limited_roms,
|
|
)
|
|
from handler.redis_handler import async_cache
|
|
from models.rom import LookupHashes, Rom
|
|
from tasks.scheduled.update_switch_titledb import SWITCH_TITLEDB_STORE
|
|
|
|
|
|
def _make_config(
|
|
region_priority: list[str] | None = None,
|
|
scan_media: list[str] | None = None,
|
|
region_mode: str = "prefer_rom_tags",
|
|
language_priority: list[str] | None = None,
|
|
) -> Config:
|
|
"""Build a minimal Config object for testing."""
|
|
return Config(
|
|
SCAN_REGION_MODE=region_mode,
|
|
EXCLUDED_PLATFORMS=[],
|
|
EXCLUDED_SINGLE_EXT=[],
|
|
EXCLUDED_SINGLE_FILES=[],
|
|
EXCLUDED_MULTI_FILES=[],
|
|
EXCLUDED_MULTI_PARTS_EXT=[],
|
|
EXCLUDED_MULTI_PARTS_FILES=[],
|
|
PLATFORMS_BINDING={},
|
|
PLATFORMS_VERSIONS={},
|
|
STRUCTURE_TEMPLATES={
|
|
"default": "{platform}/roms/{game}",
|
|
"firmware": "{platform}/bios",
|
|
},
|
|
SCAN_REGION_PRIORITY=region_priority or [],
|
|
SCAN_LANGUAGE_PRIORITY=(
|
|
language_priority if language_priority is not None else ["en"]
|
|
),
|
|
SCAN_MEDIA=(
|
|
scan_media if scan_media is not None else ["box2d", "box3d", "screenshot"]
|
|
),
|
|
GAMELIST_MEDIA_THUMBNAIL=MetadataMediaType.BOX2D,
|
|
GAMELIST_MEDIA_IMAGE=MetadataMediaType.SCREENSHOT,
|
|
)
|
|
|
|
|
|
class TestGetPreferredRegions:
|
|
def test_includes_cus_by_default(self):
|
|
"""cus (custom) region should be included even without user config."""
|
|
config = _make_config(region_priority=[])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions()
|
|
|
|
assert "cus" in regions
|
|
|
|
def test_user_cus_priority_respected(self):
|
|
"""When user places cus early in priority, it should appear before defaults."""
|
|
config = _make_config(region_priority=["cus", "eu"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions()
|
|
|
|
assert regions.index("cus") < regions.index("us")
|
|
|
|
def test_always_ends_with_unk(self):
|
|
"""unk (unknown/no-region) should always be the last fallback."""
|
|
config = _make_config(region_priority=[])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions()
|
|
|
|
assert regions[-1] == "unk"
|
|
|
|
def test_no_duplicates(self):
|
|
"""Region list should not contain duplicate entries."""
|
|
config = _make_config(region_priority=["us", "wor", "eu"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions()
|
|
|
|
assert len(regions) == len(set(regions))
|
|
|
|
def test_multi_region_rom_respects_user_priority(self):
|
|
"""For a multi-region ROM, the user's priority order wins among the
|
|
regions the file is tagged as."""
|
|
rom = MagicMock()
|
|
rom.regions = ["Japan", "USA"]
|
|
config = _make_config(region_priority=["us", "eu"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions(rom)
|
|
|
|
assert regions.index("us") < regions.index("jp")
|
|
|
|
def test_multi_region_rom_untagged_priority_does_not_win(self):
|
|
"""A region in SCAN_REGION_PRIORITY that the file is NOT tagged as
|
|
should not outrank a region the file IS tagged as."""
|
|
rom = MagicMock()
|
|
rom.regions = ["Japan", "USA"]
|
|
config = _make_config(region_priority=["eu", "us"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions(rom)
|
|
|
|
assert regions.index("us") < regions.index("eu")
|
|
assert regions.index("jp") < regions.index("eu")
|
|
|
|
def test_multi_region_rom_unprioritized_tags_preserve_order(self):
|
|
"""Filename regions not in the priority list keep their filename order
|
|
and follow the prioritized ones."""
|
|
rom = MagicMock()
|
|
rom.regions = ["Japan", "Brazil"]
|
|
config = _make_config(region_priority=["us"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions(rom)
|
|
|
|
assert regions.index("jp") < regions.index("br")
|
|
|
|
def test_prefer_config_mode_config_region_outranks_rom_tags(self):
|
|
"""With region_mode=prefer_config, a configured region wins even when
|
|
the file is not tagged with it."""
|
|
rom = MagicMock()
|
|
rom.regions = ["Europe"]
|
|
config = _make_config(region_priority=["fr", "eu"], region_mode="prefer_config")
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions(rom)
|
|
|
|
assert regions.index("fr") < regions.index("eu")
|
|
|
|
def test_prefer_config_mode_rom_tags_follow_config(self):
|
|
"""With region_mode=prefer_config, the rom's own tags still follow the
|
|
configured regions as fallback."""
|
|
rom = MagicMock()
|
|
rom.regions = ["Japan"]
|
|
config = _make_config(region_priority=["fr"], region_mode="prefer_config")
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions(rom)
|
|
|
|
assert regions.index("fr") < regions.index("jp")
|
|
assert regions.index("jp") < regions.index("us")
|
|
|
|
def test_default_mode_rom_tags_still_win(self):
|
|
"""Default prefer_rom_tags mode keeps the current behavior."""
|
|
rom = MagicMock()
|
|
rom.regions = ["Europe"]
|
|
config = _make_config(region_priority=["fr", "eu"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
regions = get_preferred_regions(rom)
|
|
|
|
assert regions.index("eu") < regions.index("fr")
|
|
|
|
|
|
class TestGetPreferredLanguages:
|
|
def test_returns_configured_order(self):
|
|
config = _make_config(language_priority=["de", "es"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
assert get_preferred_languages() == ["de", "es"]
|
|
|
|
def test_does_not_append_french(self):
|
|
"""A configured language list is honored as-is, so descriptions are not
|
|
silently served in a language the user did not ask for."""
|
|
config = _make_config(language_priority=["de"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
assert get_preferred_languages() == ["de"]
|
|
|
|
def test_empty_falls_back_to_english(self):
|
|
config = _make_config(language_priority=[])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
assert get_preferred_languages() == ["en"]
|
|
|
|
def test_drops_duplicates(self):
|
|
config = _make_config(language_priority=["de", "en", "de"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
assert get_preferred_languages() == ["de", "en"]
|
|
|
|
def test_taxonomy_languages_append_fallbacks(self):
|
|
config = _make_config(language_priority=["de"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
assert get_taxonomy_languages() == ["de", "en", "fr"]
|
|
|
|
def test_taxonomy_languages_keep_user_order(self):
|
|
config = _make_config(language_priority=["fr", "de"])
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
assert get_taxonomy_languages() == ["fr", "de", "en"]
|
|
|
|
|
|
class TestExtractMediaFromSsGame:
|
|
"""Tests for extract_media_from_ss_game."""
|
|
|
|
def _make_rom(self, regions: list[str] | None = None) -> MagicMock:
|
|
rom = MagicMock()
|
|
rom.platform_id = 1
|
|
rom.id = 100
|
|
rom.regions = regions
|
|
return rom
|
|
|
|
def _make_game_with_cus_only(self) -> SSGame:
|
|
"""A game that only has box-2D available in the cus (custom) region."""
|
|
return cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "cus",
|
|
"url": "https://screenscraper.example.com/box-2D(cus)",
|
|
"crc": "aabbccdd",
|
|
"md5": "deadbeef",
|
|
"sha1": "cafebabe",
|
|
"size": "12345",
|
|
"format": "png",
|
|
}
|
|
]
|
|
},
|
|
)
|
|
|
|
def test_box2d_cus_region_fetched_without_user_config(self):
|
|
"""box-2D with region='cus' must be fetched even when user has no explicit cus config."""
|
|
config = _make_config(region_priority=[])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_cus_only()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/box2d",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_url"] is not None
|
|
assert "box-2D(cus)" in result["box2d_url"]
|
|
|
|
def test_preferred_region_wins_over_cus(self):
|
|
"""A preferred region match should take priority over cus fallback."""
|
|
config = _make_config(region_priority=["us"])
|
|
rom = self._make_rom()
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "cus",
|
|
"url": "https://screenscraper.example.com/box-2D(cus)",
|
|
"crc": "aabbccdd",
|
|
"md5": "deadbeef",
|
|
"sha1": "cafebabe",
|
|
"size": "12345",
|
|
"format": "png",
|
|
},
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": "https://screenscraper.example.com/box-2D(us)",
|
|
"crc": "11223344",
|
|
"md5": "feedface",
|
|
"sha1": "baadf00d",
|
|
"size": "67890",
|
|
"format": "png",
|
|
},
|
|
]
|
|
},
|
|
)
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/box2d",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_url"] is not None
|
|
assert "box-2D(us)" in result["box2d_url"]
|
|
|
|
def _make_game_with_box_faces(self) -> SSGame:
|
|
"""A game exposing all three box faces: front, back and spine."""
|
|
return cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": "https://screenscraper.example.com/box-2D",
|
|
"crc": "aabbccdd",
|
|
"md5": "deadbeef",
|
|
"sha1": "cafebabe",
|
|
"size": "12345",
|
|
"format": "png",
|
|
},
|
|
{
|
|
"type": "box-2D-back",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": "https://screenscraper.example.com/box-2D-back",
|
|
"crc": "11223344",
|
|
"md5": "feedface",
|
|
"sha1": "baadf00d",
|
|
"size": "23456",
|
|
"format": "png",
|
|
},
|
|
{
|
|
"type": "box-2D-side",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": "https://screenscraper.example.com/box-2D-side",
|
|
"crc": "55667788",
|
|
"md5": "0ddba11",
|
|
"sha1": "f00dcafe",
|
|
"size": "34567",
|
|
"format": "png",
|
|
},
|
|
]
|
|
},
|
|
)
|
|
|
|
def test_box2d_path_set_when_in_config(self):
|
|
"""When 'box2d' is in SCAN_MEDIA the box front is persisted locally, so it
|
|
stays reachable when another provider wins the cover."""
|
|
config = _make_config(scan_media=["box2d"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_box_faces()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
side_effect=lambda pid, rid, mt: f"roms/{pid}/{rid}/{mt.value}",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_url"] is not None
|
|
assert "box-2D" in result["box2d_url"]
|
|
assert result["box2d_path"] == "roms/1/100/box2d/box2d.png"
|
|
|
|
def test_box2d_path_not_set_when_absent_from_config(self):
|
|
"""Without 'box2d' in SCAN_MEDIA the front URL is kept but not stored."""
|
|
config = _make_config(scan_media=["box2d_back"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_box_faces()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
side_effect=lambda pid, rid, mt: f"roms/{pid}/{rid}/{mt.value}",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_url"] is not None
|
|
assert result["box2d_path"] is None
|
|
|
|
def test_box2d_side_path_set_when_in_config(self):
|
|
"""When 'box2d_side' is in SCAN_MEDIA the spine is persisted locally."""
|
|
config = _make_config(scan_media=["box2d", "box2d_back", "box2d_side"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_box_faces()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
side_effect=lambda pid, rid, mt: f"roms/{pid}/{rid}/{mt.value}",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_side_url"] is not None
|
|
assert "box-2D-side" in result["box2d_side_url"]
|
|
assert result["box2d_side_path"] == "roms/1/100/box2d_side/box2d_side.png"
|
|
|
|
def test_box2d_side_path_not_set_when_absent_from_config(self):
|
|
"""Without 'box2d_side' in SCAN_MEDIA the spine URL is kept but not stored."""
|
|
config = _make_config(scan_media=["box2d", "box2d_back"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_box_faces()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
side_effect=lambda pid, rid, mt: f"roms/{pid}/{rid}/{mt.value}",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_side_url"] is not None
|
|
assert result["box2d_side_path"] is None
|
|
|
|
def _make_game_with_both_miximage_versions(self) -> SSGame:
|
|
"""A game that has both mixrbv1 and mixrbv2 (v1 listed first, matching SS API order)."""
|
|
return cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "mixrbv1",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": "https://screenscraper.example.com/mixrbv1",
|
|
"crc": "aabbccdd",
|
|
"md5": "deadbeef",
|
|
"sha1": "cafebabe",
|
|
"size": "12345",
|
|
"format": "png",
|
|
},
|
|
{
|
|
"type": "mixrbv2",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": "https://screenscraper.example.com/mixrbv2",
|
|
"crc": "11223344",
|
|
"md5": "feedface",
|
|
"sha1": "baadf00d",
|
|
"size": "67890",
|
|
"format": "png",
|
|
},
|
|
]
|
|
},
|
|
)
|
|
|
|
def test_miximage_maps_to_mixrbv1(self):
|
|
"""When 'miximage' is in SCAN_MEDIA, only mixrbv1 is downloaded."""
|
|
config = _make_config(scan_media=["miximage"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_both_miximage_versions()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/miximage",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["miximage_url"] is not None
|
|
assert "mixrbv1" in result["miximage_url"]
|
|
assert result["miximage_path"] is not None
|
|
assert result["miximage_v2_url"] is not None
|
|
assert "mixrbv2" in result["miximage_v2_url"]
|
|
assert result["miximage_v2_path"] is None
|
|
|
|
def test_miximage_v2_maps_to_mixrbv2(self):
|
|
"""When 'miximage_v2' is in SCAN_MEDIA, only mixrbv2 is downloaded."""
|
|
config = _make_config(scan_media=["miximage_v2"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_both_miximage_versions()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/miximage_v2",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["miximage_v2_url"] is not None
|
|
assert "mixrbv2" in result["miximage_v2_url"]
|
|
assert result["miximage_v2_path"] is not None
|
|
assert result["miximage_url"] is not None
|
|
assert "mixrbv1" in result["miximage_url"]
|
|
assert result["miximage_path"] is None
|
|
|
|
def test_miximage_v2_not_downloaded_when_only_miximage_in_config(self):
|
|
"""When only 'miximage' is in SCAN_MEDIA, miximage_v2_path is not set."""
|
|
config = _make_config(scan_media=["miximage"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_both_miximage_versions()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/miximage",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["miximage_v2_path"] is None
|
|
|
|
def test_miximage_v1_not_downloaded_when_only_miximage_v2_in_config(self):
|
|
"""When only 'miximage_v2' is in SCAN_MEDIA, miximage_path is not set."""
|
|
config = _make_config(scan_media=["miximage_v2"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_both_miximage_versions()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/miximage_v2",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["miximage_path"] is None
|
|
|
|
def test_both_miximage_versions_downloaded_when_both_in_config(self):
|
|
"""When both 'miximage' and 'miximage_v2' are in SCAN_MEDIA, both are downloaded."""
|
|
config = _make_config(scan_media=["miximage", "miximage_v2"])
|
|
rom = self._make_rom()
|
|
game = self._make_game_with_both_miximage_versions()
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
side_effect=lambda pid, rid, mt: f"roms/{pid}/{rid}/{mt.value}",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["miximage_url"] is not None
|
|
assert "mixrbv1" in result["miximage_url"]
|
|
assert result["miximage_path"] is not None
|
|
assert result["miximage_v2_url"] is not None
|
|
assert "mixrbv2" in result["miximage_v2_url"]
|
|
assert result["miximage_v2_path"] is not None
|
|
|
|
@staticmethod
|
|
def _disc(region: str, support: str | None = None) -> dict[str, str]:
|
|
"""A support-2D media item, tagged with ``support`` when one is given."""
|
|
suffix = f"[{support}]" if support else ""
|
|
media = {
|
|
"type": "support-2D",
|
|
"parent": "jeu",
|
|
"region": region,
|
|
"url": f"https://screenscraper.example.com/support-2D({region}){suffix}",
|
|
"crc": "aabbccdd",
|
|
"md5": "deadbeef",
|
|
"sha1": "cafebabe",
|
|
"format": "png",
|
|
}
|
|
if support is not None:
|
|
media["support"] = support
|
|
return media
|
|
|
|
def _extract(self, medias: list[dict[str, str]], config: Config) -> SSMetadataMedia:
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
side_effect=lambda pid, rid, mt: f"roms/{pid}/{rid}/{mt.value}",
|
|
),
|
|
):
|
|
return extract_media_from_ss_game(
|
|
self._make_rom(), cast(SSGame, {"medias": medias})
|
|
)
|
|
|
|
def _three_disc_medias(self) -> list[dict[str, str]]:
|
|
"""Disc art spread across regions, with untagged and tagged disc 1 art."""
|
|
return [
|
|
self._disc("jp"),
|
|
self._disc("jp", "1"),
|
|
self._disc("jp", "2"),
|
|
self._disc("us", "2"),
|
|
self._disc("eu", "3"),
|
|
]
|
|
|
|
def test_every_disc_of_a_multi_disc_game_is_kept(self):
|
|
result = self._extract(
|
|
self._three_disc_medias(),
|
|
_make_config(region_priority=["us"], scan_media=["physical"]),
|
|
)
|
|
|
|
# Untagged art stands for the first disc.
|
|
assert (
|
|
result["physical_url"] == "https://screenscraper.example.com/support-2D(jp)"
|
|
)
|
|
assert result["physical_path"] == "roms/1/100/physical/physical.png"
|
|
assert result["physical_disc"] == 1
|
|
assert result["physical_extra_discs"] == [
|
|
{
|
|
"disc": 2,
|
|
"url": "https://screenscraper.example.com/support-2D(us)[2]",
|
|
"path": "roms/1/100/physical/physical_disc2.png",
|
|
},
|
|
{
|
|
"disc": 3,
|
|
"url": "https://screenscraper.example.com/support-2D(eu)[3]",
|
|
"path": "roms/1/100/physical/physical_disc3.png",
|
|
},
|
|
]
|
|
|
|
def test_extra_discs_not_stored_when_physical_absent_from_config(self):
|
|
result = self._extract(
|
|
self._three_disc_medias(), _make_config(scan_media=["box2d"])
|
|
)
|
|
|
|
assert result["physical_path"] is None
|
|
assert [d["disc"] for d in result["physical_extra_discs"]] == [2, 3]
|
|
assert all(d["path"] is None for d in result["physical_extra_discs"])
|
|
|
|
def test_single_disc_game_has_no_extra_discs(self):
|
|
result = self._extract(
|
|
[self._disc("jp"), self._disc("jp", "1")],
|
|
_make_config(scan_media=["physical"]),
|
|
)
|
|
|
|
assert (
|
|
result["physical_url"] == "https://screenscraper.example.com/support-2D(jp)"
|
|
)
|
|
assert result["physical_disc"] == 1
|
|
assert result["physical_extra_discs"] == []
|
|
|
|
def test_first_disc_with_art_leads_when_disc_one_has_none(self):
|
|
result = self._extract(
|
|
[self._disc("us", "2"), self._disc("eu", "3")],
|
|
_make_config(scan_media=["physical"]),
|
|
)
|
|
|
|
assert result["physical_disc"] == 2
|
|
assert result["physical_url"] == (
|
|
"https://screenscraper.example.com/support-2D(us)[2]"
|
|
)
|
|
assert [d["disc"] for d in result["physical_extra_discs"]] == [3]
|
|
|
|
@pytest.mark.parametrize("support", ["0", "-1", "two", ""])
|
|
def test_unreadable_disc_number_counts_as_the_first(self, support: str):
|
|
result = self._extract(
|
|
[self._disc("jp", support), self._disc("us", "2")],
|
|
_make_config(scan_media=["physical"]),
|
|
)
|
|
|
|
assert result["physical_disc"] == 1
|
|
assert [d["disc"] for d in result["physical_extra_discs"]] == [2]
|
|
|
|
|
|
class TestExtractMetadataFromSsRom:
|
|
def _make_rom(self, regions: list[str] | None = None) -> MagicMock:
|
|
rom = MagicMock()
|
|
rom.platform_id = 1
|
|
rom.id = 100
|
|
rom.regions = regions
|
|
return rom
|
|
|
|
def test_release_date_prefers_tagged_region(self):
|
|
config = _make_config(region_priority=[])
|
|
rom = self._make_rom(regions=["Japan", "USA"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"dates": [
|
|
{"region": "us", "text": "1990-02-12"},
|
|
{"region": "jp", "text": "1988-10-23"},
|
|
{"region": "eu", "text": "1991-08-29"},
|
|
],
|
|
"medias": [],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
metadata = extract_metadata_from_ss_rom(rom, game)
|
|
|
|
assert metadata["first_release_date"] == 593568000
|
|
|
|
def test_release_date_follows_the_configured_region_under_prefer_config(self):
|
|
"""The same ordering that picks the artwork and the title picks the
|
|
date, so a game resolved as French is not dated by its US release."""
|
|
config = _make_config(region_priority=["fr"], region_mode="prefer_config")
|
|
rom = self._make_rom(regions=["USA"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"dates": [
|
|
{"region": "us", "text": "1990-02-12"},
|
|
{"region": "fr", "text": "1991-08-29"},
|
|
],
|
|
"medias": [],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
metadata = extract_metadata_from_ss_rom(rom, game)
|
|
|
|
assert metadata["first_release_date"] == 683424000
|
|
|
|
def test_release_date_keeps_the_rom_s_region_under_prefer_rom_tags(self):
|
|
config = _make_config(region_priority=["fr"])
|
|
rom = self._make_rom(regions=["USA"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"dates": [
|
|
{"region": "us", "text": "1990-02-12"},
|
|
{"region": "fr", "text": "1991-08-29"},
|
|
],
|
|
"medias": [],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
metadata = extract_metadata_from_ss_rom(rom, game)
|
|
|
|
assert metadata["first_release_date"] == 634780800
|
|
|
|
def test_franchises_fall_back_to_french(self):
|
|
"""ScreenScraper's taxonomy is often French-only, so those fields still
|
|
fall back even when the user asked for another language."""
|
|
config = _make_config(language_priority=["de"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"familles": [{"noms": [{"langue": "fr", "text": "Mario"}]}],
|
|
"modes": [{"noms": [{"langue": "fr", "text": "Solo"}]}],
|
|
"medias": [],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
metadata = extract_metadata_from_ss_rom(self._make_rom(), game)
|
|
|
|
assert metadata["franchises"] == ["Mario"]
|
|
assert metadata["game_modes"] == ["Solo"]
|
|
|
|
def test_taxonomy_prefers_configured_language(self):
|
|
config = _make_config(language_priority=["de"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"familles": [
|
|
{
|
|
"noms": [
|
|
{"langue": "fr", "text": "Mario"},
|
|
{"langue": "de", "text": "Mario DE"},
|
|
]
|
|
}
|
|
],
|
|
"medias": [],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
metadata = extract_metadata_from_ss_rom(self._make_rom(), game)
|
|
|
|
assert metadata["franchises"] == ["Mario DE"]
|
|
|
|
|
|
class TestBuildSSGame:
|
|
def _make_rom(self, regions: list[str] | None = None) -> MagicMock:
|
|
rom = MagicMock()
|
|
rom.platform_id = 1
|
|
rom.id = 100
|
|
rom.regions = regions
|
|
return rom
|
|
|
|
def _make_media(self, media_type: str) -> dict[str, Any]:
|
|
return {
|
|
"type": media_type,
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": f"https://screenscraper.example.com/{media_type}(us)",
|
|
"crc": "aabbccdd",
|
|
"md5": "deadbeef",
|
|
"sha1": "cafebabe",
|
|
"size": "12345",
|
|
"format": "png",
|
|
}
|
|
|
|
def test_title_screen_and_fanart_not_duplicated_into_screenshots(self):
|
|
"""Media stored in dedicated folders must not also land in
|
|
url_screenshots (issue #3911)."""
|
|
config = _make_config(
|
|
region_priority=["us"],
|
|
scan_media=["screenshot", "title_screen", "fanart"],
|
|
)
|
|
rom = self._make_rom()
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"id": "42",
|
|
"medias": [
|
|
self._make_media("ss"),
|
|
self._make_media("sstitle"),
|
|
self._make_media("fanart"),
|
|
],
|
|
},
|
|
)
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/media",
|
|
),
|
|
):
|
|
result = build_ss_game(rom, game)
|
|
|
|
assert result["url_screenshots"] == ["https://screenscraper.example.com/ss(us)"]
|
|
# Dedicated media folders are still populated.
|
|
assert result["ss_metadata"]["title_screen_path"]
|
|
assert result["ss_metadata"]["fanart_path"]
|
|
|
|
def test_summary_does_not_fall_back_to_unrequested_language(self):
|
|
"""An untranslated synopsis is left empty rather than served in French."""
|
|
config = _make_config(language_priority=["de"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"id": "42",
|
|
"medias": [],
|
|
"synopsis": [{"langue": "fr", "text": "Un jeu."}],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
result = build_ss_game(self._make_rom(), game)
|
|
|
|
# Empty values are stripped from the returned dict.
|
|
assert "summary" not in result
|
|
|
|
def test_prefer_config_picks_the_title_from_the_configured_region(self):
|
|
"""The mode used to reach the artwork only, so a European rom came back
|
|
with French box art under an English title."""
|
|
config = _make_config(region_priority=["fr", "eu"], region_mode="prefer_config")
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"id": "42",
|
|
"medias": [],
|
|
"noms": [
|
|
{"region": "eu", "text": "007 - Everything or Nothing"},
|
|
{"region": "fr", "text": "007 : Quitte ou Double"},
|
|
],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
result = build_ss_game(self._make_rom(regions=["Europe"]), game)
|
|
|
|
assert result["name"] == "007: Quitte ou Double"
|
|
|
|
def test_prefer_rom_tags_keeps_the_title_of_the_rom_s_own_region(self):
|
|
config = _make_config(region_priority=["fr", "eu"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"id": "42",
|
|
"medias": [],
|
|
"noms": [
|
|
{"region": "eu", "text": "007 - Everything or Nothing"},
|
|
{"region": "fr", "text": "007 : Quitte ou Double"},
|
|
],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
result = build_ss_game(self._make_rom(regions=["Europe"]), game)
|
|
|
|
assert result["name"] == "007 - Everything or Nothing"
|
|
|
|
def test_summary_uses_configured_language(self):
|
|
config = _make_config(language_priority=["de", "en"])
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"id": "42",
|
|
"medias": [],
|
|
"synopsis": [
|
|
{"langue": "en", "text": "A game."},
|
|
{"langue": "de", "text": "Ein Spiel."},
|
|
],
|
|
},
|
|
)
|
|
|
|
with patch("handler.metadata.ss_handler.cm.get_config", return_value=config):
|
|
result = build_ss_game(self._make_rom(), game)
|
|
|
|
assert result["summary"] == "Ein Spiel."
|
|
|
|
|
|
class TestIsNotgame:
|
|
def _game(self, notgame: str = "false", names: list[str] | None = None) -> SSGame:
|
|
return cast(
|
|
SSGame,
|
|
{
|
|
"notgame": notgame,
|
|
"noms": [
|
|
{"region": "ss", "text": n} for n in (names or ["Clean Game"])
|
|
],
|
|
},
|
|
)
|
|
|
|
def test_notgame_field_true(self):
|
|
assert _is_notgame(self._game(notgame="true")) is True
|
|
|
|
def test_notgame_field_false_clean_name(self):
|
|
assert _is_notgame(self._game(notgame="false")) is False
|
|
|
|
def test_zzz_notgame_lowercase_name(self):
|
|
assert _is_notgame(self._game(names=["ZZZ(notgame)"])) is True
|
|
|
|
def test_zzz_notgame_long_form(self):
|
|
assert (
|
|
_is_notgame(self._game(names=["ZZZ(NOTGAME):Fichier Annexes - Non Jeux"]))
|
|
is True
|
|
)
|
|
|
|
def test_zzz_prefix_only_no_match(self):
|
|
assert _is_notgame(self._game(names=["ZZZ Game Title"])) is False
|
|
|
|
def test_missing_notgame_field_clean_name(self):
|
|
game = cast(SSGame, {"noms": [{"region": "ss", "text": "Normal Game"}]})
|
|
assert _is_notgame(game) is False
|
|
|
|
|
|
class TestExtractMediaSensitiveKeyStripping:
|
|
def test_media_url_credentials_stripped(self):
|
|
config = _make_config()
|
|
rom = MagicMock()
|
|
rom.platform_id = 1
|
|
rom.id = 100
|
|
full_url = "https://screenscraper.fr/img.png?ssid=user&sspassword=pass&devid=dev&devpassword=devpass&other=keep"
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": full_url,
|
|
"crc": "",
|
|
"md5": "",
|
|
"sha1": "",
|
|
"size": "0",
|
|
"format": "png",
|
|
}
|
|
]
|
|
},
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/box2d",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
# ssid/sspassword must be stripped before storage so user creds don't
|
|
# end up in the DB. Dev creds and other params must be preserved so
|
|
# subsequent media fetches still resolve.
|
|
stored_url = result["box2d_url"]
|
|
assert stored_url is not None
|
|
query = parse_qs(urlparse(stored_url).query)
|
|
assert "ssid" not in query
|
|
assert "sspassword" not in query
|
|
assert query.get("devid") == ["dev"]
|
|
assert query.get("devpassword") == ["devpass"]
|
|
assert query.get("other") == ["keep"]
|
|
|
|
def test_clean_url_unchanged(self):
|
|
config = _make_config()
|
|
rom = MagicMock()
|
|
rom.platform_id = 1
|
|
rom.id = 100
|
|
clean_url = "https://screenscraper.fr/img.png?format=png"
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": clean_url,
|
|
"crc": "",
|
|
"md5": "",
|
|
"sha1": "",
|
|
"size": "0",
|
|
"format": "png",
|
|
}
|
|
]
|
|
},
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/box2d",
|
|
),
|
|
):
|
|
result = extract_media_from_ss_game(rom, game)
|
|
|
|
assert result["box2d_url"] == clean_url
|
|
|
|
|
|
class TestAddSsAuthToUrl:
|
|
"""Tests for add_ss_auth_to_url — re-attaches user creds at download time."""
|
|
|
|
def test_appends_credentials_when_configured(self):
|
|
"""With both user and password set, creds are appended to the URL."""
|
|
url = "https://screenscraper.fr/img.png?systemeid=1&romnom=Game.zip"
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
):
|
|
result = add_ss_auth_to_url(url)
|
|
|
|
query = parse_qs(urlparse(result).query)
|
|
assert query.get("ssid") == ["user1"]
|
|
assert query.get("sspassword") == ["pw1"]
|
|
# Other params are preserved
|
|
assert query.get("systemeid") == ["1"]
|
|
assert query.get("romnom") == ["Game.zip"]
|
|
|
|
def test_no_op_when_user_missing(self):
|
|
"""If SCREENSCRAPER_USER is unset, the URL is returned unchanged."""
|
|
url = "https://screenscraper.fr/img.png?systemeid=1"
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", ""),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
):
|
|
result = add_ss_auth_to_url(url)
|
|
|
|
assert result == url
|
|
|
|
def test_no_op_when_password_missing(self):
|
|
"""If SCREENSCRAPER_PASSWORD is unset, the URL is returned unchanged."""
|
|
url = "https://screenscraper.fr/img.png?systemeid=1"
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", ""),
|
|
):
|
|
result = add_ss_auth_to_url(url)
|
|
|
|
assert result == url
|
|
|
|
def test_does_not_duplicate_existing_credentials(self):
|
|
"""Pre-existing ssid/sspassword on the URL are replaced, not duplicated."""
|
|
url = "https://screenscraper.fr/img.png?ssid=old&sspassword=oldpw&keep=1"
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "new"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "newpw"),
|
|
):
|
|
result = add_ss_auth_to_url(url)
|
|
|
|
query = parse_qs(urlparse(result).query)
|
|
# Exactly one occurrence of each, with the new values
|
|
assert query.get("ssid") == ["new"]
|
|
assert query.get("sspassword") == ["newpw"]
|
|
assert query.get("keep") == ["1"]
|
|
|
|
def test_handles_stripped_url_from_extract_media(self):
|
|
"""A URL that's already had ssid/sspassword stripped (the storage form)
|
|
gets credentials re-attached cleanly, with dev creds and other params
|
|
left intact."""
|
|
# Shape mirrors what extract_media_from_ss_game persists
|
|
stripped_url = (
|
|
"https://screenscraper.fr/img.png?devid=dev&devpassword=devpw&other=keep"
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
):
|
|
result = add_ss_auth_to_url(stripped_url)
|
|
|
|
query = parse_qs(urlparse(result).query)
|
|
assert query.get("ssid") == ["user1"]
|
|
assert query.get("sspassword") == ["pw1"]
|
|
assert query.get("devid") == ["dev"]
|
|
assert query.get("devpassword") == ["devpw"]
|
|
assert query.get("other") == ["keep"]
|
|
|
|
def test_rejects_lookalike_and_attacker_hosts(self):
|
|
"""Credentials must only be injected when the hostname is exactly
|
|
screenscraper.fr or a subdomain. A substring match would leak creds
|
|
to attacker-controlled domains."""
|
|
hostile_urls = [
|
|
# Suffix attack: hostname ends with attacker-controlled domain
|
|
"https://screenscraper.fr.evil.example/img.png",
|
|
# Substring in path/query of unrelated host
|
|
"https://evil.example/?u=screenscraper.fr",
|
|
"https://evil.example/screenscraper.fr/img.png",
|
|
# Credentials in userinfo pointing at attacker host
|
|
"https://screenscraper.fr@evil.example/img.png",
|
|
# Prefix attack
|
|
"https://notscreenscraper.fr/img.png",
|
|
]
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
):
|
|
for url in hostile_urls:
|
|
result = add_ss_auth_to_url(url)
|
|
assert result == url, f"Credentials leaked to {url!r}"
|
|
assert "ssid" not in parse_qs(urlparse(result).query)
|
|
assert "sspassword" not in parse_qs(urlparse(result).query)
|
|
|
|
def test_accepts_screenscraper_subdomains(self):
|
|
"""Subdomains of screenscraper.fr (e.g. api.screenscraper.fr) are
|
|
treated as the same trust boundary and receive credentials."""
|
|
urls = [
|
|
"https://screenscraper.fr/img.png",
|
|
"https://api.screenscraper.fr/api2/foo",
|
|
"https://www.screenscraper.fr/img.png",
|
|
"https://SCREENSCRAPER.FR/img.png", # case-insensitive host
|
|
]
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
):
|
|
for url in urls:
|
|
result = add_ss_auth_to_url(url)
|
|
query = parse_qs(urlparse(result).query)
|
|
assert query.get("ssid") == ["user1"], f"Creds missing on {url!r}"
|
|
assert query.get("sspassword") == ["pw1"], f"Creds missing on {url!r}"
|
|
|
|
def test_strip_then_reauth_roundtrip(self):
|
|
"""End-to-end: storing media strips user creds; download-time auth
|
|
restores them without leaking creds into intermediate state."""
|
|
config = _make_config()
|
|
rom = MagicMock()
|
|
rom.platform_id = 1
|
|
rom.id = 100
|
|
original_url = (
|
|
"https://screenscraper.fr/img.png"
|
|
"?ssid=scanner-user&sspassword=scanner-pw&systemeid=1"
|
|
)
|
|
game = cast(
|
|
SSGame,
|
|
{
|
|
"medias": [
|
|
{
|
|
"type": "box-2D",
|
|
"parent": "jeu",
|
|
"region": "us",
|
|
"url": original_url,
|
|
"crc": "",
|
|
"md5": "",
|
|
"sha1": "",
|
|
"size": "0",
|
|
"format": "png",
|
|
}
|
|
]
|
|
},
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch(
|
|
"handler.metadata.ss_handler.fs_resource_handler.get_media_resources_path",
|
|
return_value="roms/1/100/box2d",
|
|
),
|
|
):
|
|
extracted = extract_media_from_ss_game(rom, game)
|
|
|
|
stored_url = extracted["box2d_url"]
|
|
assert stored_url is not None
|
|
|
|
# Stored URL must not carry user creds
|
|
stored_query = parse_qs(urlparse(stored_url).query)
|
|
assert "ssid" not in stored_query
|
|
assert "sspassword" not in stored_query
|
|
|
|
# At download time, add_ss_auth_to_url re-attaches the *current* creds
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "download-user"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "download-pw"),
|
|
):
|
|
download_url = add_ss_auth_to_url(stored_url)
|
|
|
|
download_query = parse_qs(urlparse(download_url).query)
|
|
assert download_query.get("ssid") == ["download-user"]
|
|
assert download_query.get("sspassword") == ["download-pw"]
|
|
assert download_query.get("systemeid") == ["1"]
|
|
|
|
|
|
class TestGetPlatform:
|
|
"""Tests for SSHandler.get_platform — the slug → ScreenScraper system map."""
|
|
|
|
def test_unmapped_platform_returns_none_ss_id(self):
|
|
"""A slug with no ScreenScraper mapping yields ss_id=None (lookup skipped)."""
|
|
handler = SSHandler()
|
|
platform = handler.get_platform("not-a-real-platform")
|
|
|
|
assert platform["ss_id"] is None
|
|
assert platform["slug"] == "not-a-real-platform"
|
|
|
|
def test_rpg_maker_maps_to_the_easyrpg_system(self):
|
|
"""ScreenScraper files RPG Maker games under its EasyRPG system."""
|
|
handler = SSHandler()
|
|
platform = handler.get_platform("rpg-maker")
|
|
|
|
assert platform["ss_id"] == 231
|
|
assert platform["name"] == "EasyRPG"
|
|
|
|
def test_win9x_maps_to_the_generic_windows_system(self):
|
|
handler = SSHandler()
|
|
platform = handler.get_platform("win9x")
|
|
|
|
assert platform["ss_id"] == handler.get_platform("win")["ss_id"] == 138
|
|
assert platform["name"] == "PC Win9X"
|
|
|
|
|
|
class TestGetRomType:
|
|
def _file(self, ext: str, top_level: bool = True) -> MagicMock:
|
|
f = MagicMock()
|
|
f.file_extension = ext
|
|
f.is_top_level = top_level
|
|
return f
|
|
|
|
def test_iso_extension(self):
|
|
assert _get_rom_type(self._file("iso")) == "iso"
|
|
|
|
def test_chd_extension(self):
|
|
assert _get_rom_type(self._file("chd")) == "iso"
|
|
|
|
def test_rom_extension(self):
|
|
assert _get_rom_type(self._file("nes")) == "rom"
|
|
|
|
def test_folder_based_rom(self):
|
|
assert _get_rom_type(self._file("bin", top_level=False)) == "dossier"
|
|
|
|
|
|
class TestLookupRom:
|
|
def _make_mock_file(self) -> MagicMock:
|
|
f = MagicMock()
|
|
f.file_size_bytes = 1024
|
|
f.is_top_level = True
|
|
f.file_extension = "bin"
|
|
f.md5_hash = "abc123"
|
|
f.sha1_hash = "def456"
|
|
f.crc_hash = "12345678"
|
|
f.file_name = "bios.bin"
|
|
return f
|
|
|
|
def _make_unhashed_file(
|
|
self, file_name: str = "Adventure Island II (USA).nes"
|
|
) -> MagicMock:
|
|
"""A top-level file with no hashes, as produced for NON_HASHABLE_PLATFORMS
|
|
or when SKIP_HASH_CALCULATION is enabled."""
|
|
f = MagicMock()
|
|
f.file_size_bytes = 131072
|
|
f.is_top_level = True
|
|
f.file_extension = "nes"
|
|
f.md5_hash = ""
|
|
f.sha1_hash = ""
|
|
f.crc_hash = ""
|
|
f.file_name = file_name
|
|
f.archive_members = None
|
|
return f
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_hash_still_attempts_jeuinfos_by_filename(self):
|
|
"""A file with no hashes must still reach jeuInfos using the filename
|
|
(romnom) + platform (systemeid), instead of bailing out and degrading to
|
|
the weaker jeuRecherche name search."""
|
|
handler = SSHandler()
|
|
mock_file = self._make_unhashed_file("Adventure Island II (USA).nes")
|
|
captured = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
result, is_not_game = await handler.lookup_rom(
|
|
MagicMock(platform_slug="nes"), 3, [mock_file]
|
|
)
|
|
|
|
assert captured, "get_game_info should be called even without hashes"
|
|
assert captured.get("rom_name") == "Adventure Island II (USA).nes"
|
|
assert captured.get("system_id") == 3
|
|
assert not captured.get("md5")
|
|
assert not captured.get("sha1")
|
|
assert not captured.get("crc")
|
|
assert result["ss_id"] is None
|
|
assert is_not_game is False
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_hash_match_builds_game(self):
|
|
"""When jeuInfos matches an un-hashed file by filename, the game is built
|
|
and returned (the romnom matcher bridges number-style differences such as
|
|
'Adventure Island II' -> 'Adventure Island 2')."""
|
|
config = _make_config(region_priority=["us"])
|
|
game = {
|
|
"id": "1234",
|
|
"noms": [{"region": "us", "text": "Adventure Island 2"}],
|
|
"medias": [],
|
|
"synopsis": [],
|
|
"dates": [],
|
|
"genres": [],
|
|
"familles": [],
|
|
"modes": [],
|
|
"joueurs": {},
|
|
"note": {},
|
|
}
|
|
handler = SSHandler()
|
|
mock_file = self._make_unhashed_file("Adventure Island II (USA).nes")
|
|
rom = MagicMock(platform_slug="nes", platform_id=1, id=100, regions=["USA"])
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch.object(handler.ss_service, "get_game_info", return_value=game),
|
|
):
|
|
result, is_not_game = await handler.lookup_rom(rom, 3, [mock_file])
|
|
|
|
assert result["ss_id"] == 1234
|
|
assert result["name"] == "Adventure Island 2"
|
|
assert is_not_game is False
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_filename_match_reports_no_regions(self):
|
|
"""A bare romnom match identifies a title, so it says nothing about the
|
|
dump on disk and must not tag it."""
|
|
config = _make_config(region_priority=["us"])
|
|
game = {
|
|
"id": "1234",
|
|
"noms": [{"region": "us", "text": "Adventure Island 2"}],
|
|
"medias": [],
|
|
"synopsis": [],
|
|
"dates": [],
|
|
"genres": [],
|
|
"familles": [],
|
|
"modes": [],
|
|
"joueurs": {},
|
|
"note": {},
|
|
"roms": [
|
|
{
|
|
"id": 7,
|
|
"rommd5": "B330314E19126D87D156D0618C4657B0",
|
|
"regions": {"regions_shortname": ["jp"]},
|
|
}
|
|
],
|
|
}
|
|
handler = SSHandler()
|
|
mock_file = self._make_unhashed_file("Adventure Island II.nes")
|
|
rom = MagicMock(platform_slug="nes", platform_id=1, id=100, regions=[])
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch.object(handler.ss_service, "get_game_info", return_value=game),
|
|
):
|
|
result, _ = await handler.lookup_rom(rom, 3, [mock_file])
|
|
|
|
assert result["ss_id"] == 1234
|
|
assert "regions" not in result
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_a_hash_match_reports_the_dumps_tags(self):
|
|
"""A hash picks one entry out of `jeu.roms`, and that entry is the file."""
|
|
config = _make_config(region_priority=["us"])
|
|
game = {
|
|
"id": "1234",
|
|
"noms": [{"region": "us", "text": "Adventure Island 2"}],
|
|
"medias": [],
|
|
"synopsis": [],
|
|
"dates": [],
|
|
"genres": [],
|
|
"familles": [],
|
|
"modes": [],
|
|
"joueurs": {},
|
|
"note": {},
|
|
"roms": [
|
|
{
|
|
"id": 7,
|
|
"rommd5": "999999",
|
|
"regions": {"regions_shortname": ["us"]},
|
|
},
|
|
{
|
|
"id": 8,
|
|
"rommd5": "ABC123",
|
|
"regions": {"regions_shortname": ["jp"]},
|
|
"langues": {"langues_shortname": ["ja"]},
|
|
},
|
|
],
|
|
}
|
|
handler = SSHandler()
|
|
mock_file = self._make_mock_file()
|
|
rom = MagicMock(platform_slug="nes", platform_id=1, id=100, regions=[])
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.cm.get_config", return_value=config),
|
|
patch.object(handler.ss_service, "get_game_info", return_value=game),
|
|
):
|
|
result, _ = await handler.lookup_rom(rom, 3, [mock_file])
|
|
|
|
assert result["regions"] == ["Japan"]
|
|
assert result["languages"] == ["Japanese"]
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_hash_no_filename_skips_lookup(self):
|
|
"""With neither a hash nor a filename there is nothing to match on, so the
|
|
lookup is skipped without spending an API call."""
|
|
handler = SSHandler()
|
|
mock_file = self._make_unhashed_file(file_name="")
|
|
called = False
|
|
|
|
async def capture(**kwargs):
|
|
nonlocal called
|
|
called = True
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
result, is_not_game = await handler.lookup_rom(
|
|
MagicMock(platform_slug="nes"), 3, [mock_file]
|
|
)
|
|
|
|
assert called is False
|
|
assert result["ss_id"] is None
|
|
assert is_not_game is False
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_returns_notgame_flag_on_notgame_field(self):
|
|
notgame_response = {
|
|
"id": "999",
|
|
"notgame": "true",
|
|
"noms": [{"region": "wor", "text": "SomeBios"}],
|
|
}
|
|
handler = SSHandler()
|
|
with patch.object(
|
|
handler.ss_service, "get_game_info", return_value=notgame_response
|
|
):
|
|
result, is_not_game = await handler.lookup_rom(
|
|
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
|
|
)
|
|
assert result["ss_id"] is None
|
|
assert is_not_game is True
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_romnom_uses_archive_member_name_for_single_file_archive(self):
|
|
handler = SSHandler()
|
|
mock_file = self._make_mock_file()
|
|
mock_file.file_name = "Mario.zip"
|
|
mock_file.archive_members = [
|
|
{
|
|
"name": "mario.n64",
|
|
"size": 1024,
|
|
"crc_hash": "",
|
|
"md5_hash": "",
|
|
"sha1_hash": "",
|
|
}
|
|
]
|
|
captured = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
await handler.lookup_rom(MagicMock(platform_slug="n64"), 14, [mock_file])
|
|
assert captured.get("rom_name") == "mario.n64"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_romnom_uses_archive_filename_for_multi_file_archive(self):
|
|
handler = SSHandler()
|
|
mock_file = self._make_mock_file()
|
|
mock_file.file_name = "Mario.zip"
|
|
mock_file.archive_members = [
|
|
{
|
|
"name": "mario.bin",
|
|
"size": 1024,
|
|
"crc_hash": "",
|
|
"md5_hash": "",
|
|
"sha1_hash": "",
|
|
},
|
|
{
|
|
"name": "mario.cue",
|
|
"size": 64,
|
|
"crc_hash": "",
|
|
"md5_hash": "",
|
|
"sha1_hash": "",
|
|
},
|
|
]
|
|
captured = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
await handler.lookup_rom(MagicMock(platform_slug="psx"), 57, [mock_file])
|
|
assert captured.get("rom_name") == "Mario.zip"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_multi_file_archive_keeps_sending_the_composite_hashes(self):
|
|
"""Unlike Hasheous and Playmatch, ScreenScraper stays on the archive's
|
|
own digests: jeuInfos falls back to romnom, so an arcade set still
|
|
resolves by name, and moving to the member hash would shift match
|
|
results across every library."""
|
|
handler = SSHandler()
|
|
mock_file = self._make_mock_file()
|
|
mock_file.file_name = "Mario.zip"
|
|
mock_file.archive_members = [
|
|
{
|
|
"name": "mario.bin",
|
|
"size": 1024,
|
|
"crc_hash": "membercrc",
|
|
"md5_hash": "membermd5",
|
|
"sha1_hash": "membersha1",
|
|
},
|
|
{
|
|
"name": "mario.cue",
|
|
"size": 64,
|
|
"crc_hash": "cuecrc",
|
|
"md5_hash": "cuemd5",
|
|
"sha1_hash": "cuesha1",
|
|
},
|
|
]
|
|
captured = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
await handler.lookup_rom(MagicMock(platform_slug="psx"), 57, [mock_file])
|
|
|
|
assert captured.get("md5") == "abc123"
|
|
assert captured.get("sha1") == "def456"
|
|
assert captured.get("crc") == "12345678"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_romnom_uses_archive_filename_when_no_archive_members(self):
|
|
handler = SSHandler()
|
|
mock_file = self._make_mock_file()
|
|
mock_file.file_name = "mario.n64"
|
|
mock_file.archive_members = None
|
|
captured = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
await handler.lookup_rom(MagicMock(platform_slug="n64"), 14, [mock_file])
|
|
assert captured.get("rom_name") == "mario.n64"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_romnom_uses_archive_filename_when_archive_members_empty(self):
|
|
handler = SSHandler()
|
|
mock_file = self._make_mock_file()
|
|
mock_file.file_name = "Mario.zip"
|
|
mock_file.archive_members = []
|
|
captured = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return None
|
|
|
|
with patch.object(handler.ss_service, "get_game_info", side_effect=capture):
|
|
await handler.lookup_rom(MagicMock(platform_slug="n64"), 14, [mock_file])
|
|
assert captured.get("rom_name") == "Mario.zip"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_returns_notgame_flag_on_zzz_prefix(self):
|
|
notgame_response = {
|
|
"id": "0",
|
|
"notgame": "false",
|
|
"noms": [{"region": "wor", "text": "ZZZ(NOTGAME)SomeBios"}],
|
|
}
|
|
handler = SSHandler()
|
|
with patch.object(
|
|
handler.ss_service, "get_game_info", return_value=notgame_response
|
|
):
|
|
result, is_not_game = await handler.lookup_rom(
|
|
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
|
|
)
|
|
assert result["ss_id"] is None
|
|
assert is_not_game is True
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_reports_a_short_circuit_on_daily_quota_exhausted(self):
|
|
"""A breaker answered, so the caller has to hear that ScreenScraper did
|
|
not: an empty match would read as a miss it never made."""
|
|
handler = SSHandler()
|
|
mock_get_info = AsyncMock(
|
|
side_effect=HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="quota"
|
|
)
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(handler.ss_service, "get_game_info", mock_get_info),
|
|
):
|
|
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
|
|
await handler.lookup_rom(
|
|
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
|
|
)
|
|
mock_get_info.assert_awaited_once()
|
|
assert exc_info.value.fallback["ss_id"] is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_reraises_non_quota_http_error(self):
|
|
"""A non-429 error is a real failure and must propagate."""
|
|
handler = SSHandler()
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
AsyncMock(
|
|
side_effect=HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="down"
|
|
)
|
|
),
|
|
),
|
|
):
|
|
with pytest.raises(HTTPException):
|
|
await handler.lookup_rom(
|
|
MagicMock(platform_slug="snes"), 3, [self._make_mock_file()]
|
|
)
|
|
|
|
|
|
class TestScreenScraperQuotaFallback:
|
|
"""The scan-facing lookups report a short circuit when the daily quota is
|
|
exhausted (HTTP 429), so a scan degrades to the other providers without
|
|
reading the silence as a miss. Non-429 errors are real failures and must
|
|
propagate."""
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _credentials(self):
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
):
|
|
yield
|
|
|
|
@staticmethod
|
|
def _exhausted() -> AsyncMock:
|
|
return AsyncMock(
|
|
side_effect=HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS, detail="quota"
|
|
)
|
|
)
|
|
|
|
@staticmethod
|
|
def _unavailable() -> AsyncMock:
|
|
return AsyncMock(
|
|
side_effect=HTTPException(
|
|
status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="down"
|
|
)
|
|
)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_by_id_reports_a_short_circuit_on_daily_quota(self):
|
|
handler = SSHandler()
|
|
mock_get_info = self._exhausted()
|
|
with patch.object(handler.ss_service, "get_game_info", mock_get_info):
|
|
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
|
|
await handler.get_rom_by_id(MagicMock(), 1234)
|
|
mock_get_info.assert_awaited_once()
|
|
assert exc_info.value.fallback["ss_id"] is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_by_id_reraises_non_quota_error(self):
|
|
handler = SSHandler()
|
|
with patch.object(handler.ss_service, "get_game_info", self._unavailable()):
|
|
with pytest.raises(HTTPException):
|
|
await handler.get_rom_by_id(MagicMock(), 1234)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_carries_its_name_only_fallback_on_daily_quota(self):
|
|
"""The filename lookup derives a name locally, so the short circuit hands
|
|
it back rather than dropping it."""
|
|
handler = SSHandler()
|
|
rom = MagicMock(platform_slug="genesis", platform_id=1, id=1, regions=[])
|
|
mock_search = self._exhausted()
|
|
with patch.object(handler.ss_service, "search_games", mock_search):
|
|
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
|
|
await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
|
|
mock_search.assert_awaited()
|
|
assert exc_info.value.fallback["ss_id"] is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_matching_by_name_returns_empty_on_daily_quota(self):
|
|
"""A manual search wants whatever the other providers found, so an
|
|
exhausted ScreenScraper contributes nothing rather than reporting."""
|
|
handler = SSHandler()
|
|
mock_search = self._exhausted()
|
|
with patch.object(handler.ss_service, "search_games", mock_search):
|
|
result = await handler.get_matched_roms_by_name(MagicMock(), "Sonic", 3)
|
|
mock_search.assert_awaited_once()
|
|
assert result == []
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_matching_by_name_reraises_non_quota_error(self):
|
|
handler = SSHandler()
|
|
with patch.object(handler.ss_service, "search_games", self._unavailable()):
|
|
with pytest.raises(HTTPException):
|
|
await handler.get_matched_roms_by_name(MagicMock(), "Sonic", 3)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_matching_by_id_returns_no_match_on_daily_quota(self):
|
|
"""A manual match wants the providers that can still answer, so this one
|
|
contributes nothing rather than reporting a short circuit."""
|
|
handler = SSHandler()
|
|
with patch.object(handler.ss_service, "get_game_info", self._exhausted()):
|
|
assert await handler.get_matched_rom_by_id(MagicMock(), 1234) is None
|
|
|
|
|
|
class TestScreenScraperCredentialFallback:
|
|
"""Rejected credentials are a configuration problem, not a scan failure: the
|
|
service reports them once and the scan carries on with the other providers,
|
|
hearing that ScreenScraper never answered rather than that it missed."""
|
|
|
|
def _make_file(self) -> MagicMock:
|
|
mock_file = MagicMock()
|
|
mock_file.file_size_bytes = 131072
|
|
mock_file.is_top_level = True
|
|
mock_file.file_extension = "md"
|
|
mock_file.md5_hash = "abc123"
|
|
mock_file.sha1_hash = "def456"
|
|
mock_file.crc_hash = "78901234"
|
|
mock_file.file_name = "Sonic (USA).md"
|
|
mock_file.archive_members = None
|
|
return mock_file
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lookup_rom_reports_a_short_circuit_on_rejected_credentials(self):
|
|
handler = SSHandler()
|
|
rom = MagicMock(
|
|
platform_slug="genesis", platform_id=1, id=1, fs_name="Sonic (USA).md"
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
AsyncMock(
|
|
side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER)
|
|
),
|
|
),
|
|
):
|
|
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
|
|
await handler.lookup_rom(rom, 1, [self._make_file()])
|
|
|
|
assert exc_info.value.fallback["ss_id"] is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_reports_a_short_circuit_on_rejected_credentials(self):
|
|
handler = SSHandler()
|
|
rom = MagicMock(platform_slug="genesis", platform_id=1, id=1, regions=[])
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"search_games",
|
|
AsyncMock(
|
|
side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER)
|
|
),
|
|
),
|
|
):
|
|
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
|
|
await handler.get_rom(rom, "Sonic.bin", platform_ss_id=3)
|
|
|
|
assert exc_info.value.fallback["ss_id"] is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_by_id_reports_a_short_circuit_on_rejected_credentials(self):
|
|
handler = SSHandler()
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
AsyncMock(
|
|
side_effect=ScreenScraperCredentialsError(SSCredentialSet.USER)
|
|
),
|
|
),
|
|
):
|
|
with pytest.raises(ScreenScraperExhaustedError) as exc_info:
|
|
await handler.get_rom_by_id(MagicMock(), 1234)
|
|
|
|
assert exc_info.value.fallback["ss_id"] is None
|
|
|
|
|
|
class TestScreenScraperRateLimitPropagation:
|
|
"""A per-minute refusal that survives the retry must reach the scan, which
|
|
records the ROM as skipped once and stops asking ScreenScraper about it.
|
|
Swallowing it here would send the caller on to the next lookup, spending
|
|
another retried request against a budget that is already gone."""
|
|
|
|
def _make_file(self) -> MagicMock:
|
|
mock_file = MagicMock()
|
|
mock_file.file_size_bytes = 131072
|
|
mock_file.is_top_level = True
|
|
mock_file.file_extension = "md"
|
|
mock_file.md5_hash = "abc123"
|
|
mock_file.sha1_hash = "def456"
|
|
mock_file.crc_hash = "78901234"
|
|
mock_file.file_name = "Sonic (USA).md"
|
|
mock_file.archive_members = None
|
|
return mock_file
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lookup_rom_propagates(self):
|
|
handler = SSHandler()
|
|
rom = MagicMock(
|
|
platform_slug="genesis", platform_id=1, id=1, fs_name="Sonic (USA).md"
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
AsyncMock(side_effect=ScreenScraperRateLimitError()),
|
|
),
|
|
pytest.raises(ScreenScraperRateLimitError),
|
|
):
|
|
await handler.lookup_rom(rom, 1, [self._make_file()])
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_propagates(self):
|
|
handler = SSHandler()
|
|
rom = MagicMock(
|
|
platform_slug="genesis",
|
|
platform_id=1,
|
|
id=1,
|
|
regions=[],
|
|
fs_name="Sonic (USA).md",
|
|
)
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"search_games",
|
|
AsyncMock(side_effect=ScreenScraperRateLimitError()),
|
|
),
|
|
pytest.raises(ScreenScraperRateLimitError),
|
|
):
|
|
await handler.get_rom(rom, "Sonic (USA).md", platform_ss_id=1)
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_rom_by_id_propagates(self):
|
|
handler = SSHandler()
|
|
rom = MagicMock(platform_slug="genesis", fs_name="Sonic (USA).md")
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
AsyncMock(side_effect=ScreenScraperRateLimitError()),
|
|
),
|
|
pytest.raises(ScreenScraperRateLimitError),
|
|
):
|
|
await handler.get_rom_by_id(rom, 1234)
|
|
|
|
def test_rate_limit_is_not_treated_as_daily_quota_exhaustion(self):
|
|
"""Both are 429s, but only the daily one trips the breaker that skips
|
|
ScreenScraper for the rest of the scan."""
|
|
assert _is_daily_quota_error(ScreenScraperRateLimitError()) is False
|
|
assert (
|
|
_is_daily_quota_error(
|
|
HTTPException(
|
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
|
detail="ScreenScraper daily scrape quota exhausted.",
|
|
)
|
|
)
|
|
is True
|
|
)
|
|
|
|
|
|
class TestRateLimitedRomBookkeeping:
|
|
"""The scan reports the ROMs it had to skip, so each is recorded once."""
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_skips(self):
|
|
reset_rate_limited_roms()
|
|
yield
|
|
reset_rate_limited_roms()
|
|
|
|
def test_records_each_rom_once(self):
|
|
note_rate_limited_rom("Sonic (USA).md")
|
|
note_rate_limited_rom("Sonic (USA).md")
|
|
note_rate_limited_rom("Streets of Rage (USA).md")
|
|
|
|
assert get_rate_limited_rom_names() == [
|
|
"Sonic (USA).md",
|
|
"Streets of Rage (USA).md",
|
|
]
|
|
|
|
def test_reset_clears_the_record(self):
|
|
note_rate_limited_rom("Sonic (USA).md")
|
|
reset_rate_limited_roms()
|
|
|
|
assert get_rate_limited_rom_names() == []
|
|
|
|
|
|
class TestScanReporting:
|
|
"""A scan has to say what ScreenScraper allowed it to do: how much of the
|
|
daily quota is left, and which ROMs it had to skip when refused."""
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_state(self):
|
|
ss_handler._scan_state.reset()
|
|
yield
|
|
ss_handler._scan_state.reset()
|
|
|
|
@pytest.fixture
|
|
def mock_log(self, mocker):
|
|
return mocker.patch.object(ss_handler, "log")
|
|
|
|
async def test_begin_scan_drops_the_previous_scan_state(self, mocker):
|
|
mocker.patch.object(
|
|
ss_handler, "prime_account_limits", new=AsyncMock(return_value=None)
|
|
)
|
|
reset_scan_state = mocker.patch.object(ss_handler, "reset_scan_state")
|
|
note_rate_limited_rom("Sonic (USA).md")
|
|
|
|
await ss_handler.begin_scan()
|
|
|
|
reset_scan_state.assert_called_once()
|
|
assert get_rate_limited_rom_names() == []
|
|
|
|
async def test_begin_scan_primes_the_account_limits(self, mocker):
|
|
"""Reading the limits up front means the first ROMs are already paced
|
|
correctly, instead of running at the default until the first response."""
|
|
prime = mocker.patch.object(
|
|
ss_handler, "prime_account_limits", new=AsyncMock(return_value=None)
|
|
)
|
|
mocker.patch.object(ss_handler, "reset_scan_state")
|
|
|
|
await ss_handler.begin_scan()
|
|
|
|
prime.assert_awaited_once()
|
|
|
|
def test_does_not_repeat_an_unchanged_quota_line(self, mocker, mock_log):
|
|
mocker.patch.object(
|
|
ss_handler,
|
|
"get_account_limits",
|
|
return_value=SSAccountLimits(
|
|
max_requests_per_day=20000, requests_today=1500
|
|
),
|
|
)
|
|
|
|
ss_handler.log_quota()
|
|
ss_handler.log_quota()
|
|
|
|
assert mock_log.info.call_count == 1
|
|
|
|
def test_reports_the_quota_again_once_it_changes(self, mocker, mock_log):
|
|
mocker.patch.object(
|
|
ss_handler,
|
|
"get_account_limits",
|
|
side_effect=[
|
|
SSAccountLimits(max_requests_per_day=20000, requests_today=1500),
|
|
SSAccountLimits(max_requests_per_day=20000, requests_today=1900),
|
|
],
|
|
)
|
|
|
|
ss_handler.log_quota()
|
|
ss_handler.log_quota()
|
|
|
|
assert mock_log.info.call_count == 2
|
|
|
|
def test_stays_quiet_without_account_limits(self, mocker, mock_log):
|
|
mocker.patch.object(ss_handler, "get_account_limits", return_value=None)
|
|
|
|
ss_handler.log_quota()
|
|
|
|
mock_log.info.assert_not_called()
|
|
|
|
def test_summary_reports_remaining_quota_and_skipped_roms(self, mocker, mock_log):
|
|
mocker.patch.object(
|
|
ss_handler,
|
|
"get_account_limits",
|
|
return_value=SSAccountLimits(
|
|
max_requests_per_day=20000,
|
|
requests_today=1500,
|
|
max_ko_requests_per_day=2000,
|
|
ko_requests_today=300,
|
|
),
|
|
)
|
|
note_rate_limited_rom("Sonic (USA).md")
|
|
note_rate_limited_rom("Streets of Rage (USA).md")
|
|
|
|
ss_handler.log_scan_summary()
|
|
|
|
info = " ".join(str(call) for call in mock_log.info.call_args_list)
|
|
warnings = " ".join(str(call) for call in mock_log.warning.call_args_list)
|
|
assert "18500" in info
|
|
assert "1700" in info
|
|
assert "Sonic (USA).md" in warnings
|
|
assert "Streets of Rage (USA).md" in warnings
|
|
|
|
def test_summary_skips_the_rom_list_when_nothing_was_skipped(
|
|
self, mocker, mock_log
|
|
):
|
|
mocker.patch.object(
|
|
ss_handler,
|
|
"get_account_limits",
|
|
return_value=SSAccountLimits(
|
|
max_requests_per_day=20000, requests_today=1500
|
|
),
|
|
)
|
|
|
|
ss_handler.log_scan_summary()
|
|
|
|
mock_log.warning.assert_not_called()
|
|
|
|
|
|
class TestSearchTermEncoding:
|
|
"""Regression tests for issue #3467: the SS name-search term must be
|
|
URL-encoded exactly once.
|
|
|
|
The handler must pass the *raw* (un-percent-encoded) term to the service
|
|
layer, which percent-encodes it a single time when building the request URL
|
|
via ``with_query(...)``. Pre-encoding the term in the handler caused a
|
|
second round of encoding (``%2B`` -> ``%252B``), so ScreenScraper searched
|
|
for literal gibberish and returned no match for any title containing a
|
|
character that has to be URL-encoded (``+``, ``&``, an apostrophe, ...).
|
|
"""
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize(
|
|
("search_term", "literal", "double_encoded"),
|
|
[
|
|
("super mario 3d world + bowsers fury", "+", "%2B"),
|
|
("sonic & knuckles", "&", "%26"),
|
|
("marvel's spider-man", "'", "%27"),
|
|
],
|
|
)
|
|
async def test_search_rom_passes_unencoded_term_to_service(
|
|
self, search_term, literal, double_encoded
|
|
):
|
|
"""``_search_rom`` hands the service a term that is not pre-encoded."""
|
|
handler = SSHandler()
|
|
captured: dict[str, Any] = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return []
|
|
|
|
with patch.object(handler.ss_service, "search_games", side_effect=capture):
|
|
await handler._search_rom(search_term, 225)
|
|
|
|
term = captured["term"]
|
|
assert literal in term
|
|
assert double_encoded not in term
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_search_rom_still_transliterates_unicode(self):
|
|
"""Unidecode is still applied so accented titles match ScreenScraper."""
|
|
handler = SSHandler()
|
|
captured: dict[str, Any] = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return []
|
|
|
|
with patch.object(handler.ss_service, "search_games", side_effect=capture):
|
|
await handler._search_rom("Pokémon Snap", 14)
|
|
|
|
assert captured["term"] == "Pokemon Snap"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_matched_roms_by_name_passes_unencoded_term(self):
|
|
"""``get_matched_roms_by_name`` also avoids pre-encoding the term."""
|
|
handler = SSHandler()
|
|
captured: dict[str, Any] = {}
|
|
|
|
async def capture(**kwargs):
|
|
captured.update(kwargs)
|
|
return []
|
|
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_USER", "user1"),
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_PASSWORD", "pw1"),
|
|
patch.object(handler.ss_service, "search_games", side_effect=capture),
|
|
):
|
|
await handler.get_matched_roms_by_name(MagicMock(), "sonic & knuckles", 1)
|
|
|
|
term = captured["term"]
|
|
assert "&" in term
|
|
assert "%26" not in term
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_search_rom_url_single_encodes_plus(self):
|
|
"""End-to-end through the real service: a ``+`` is encoded exactly once
|
|
in the request URL (``%2B``), never doubly (``%252B``)."""
|
|
handler = SSHandler()
|
|
captured: dict[str, Any] = {}
|
|
|
|
async def capture_request(url, *args, **kwargs):
|
|
captured["url"] = url
|
|
return {"response": {"jeux": []}}
|
|
|
|
with patch.object(handler.ss_service, "_request", side_effect=capture_request):
|
|
await handler._search_rom("super mario 3d world + bowsers fury", 225)
|
|
|
|
url = captured["url"]
|
|
assert "%2B" in url
|
|
assert "%252B" not in url
|
|
|
|
|
|
class TestSonySerialFilenames:
|
|
"""Tests for Sony serial resolution in get_rom."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_serial_at_filename_start_resolves_title(self):
|
|
"""A serial in the first two characters of the filename must still hit
|
|
the serial index. Regression: re.IGNORECASE was passed as the ``pos``
|
|
argument of ``Pattern.search()``, skipping the first two characters,
|
|
so files named by their serial (e.g. ``SCUS-94163.bin``) were never
|
|
resolved."""
|
|
handler = SSHandler()
|
|
|
|
with (
|
|
patch(
|
|
"handler.metadata.ss_handler.SSHandler.is_enabled",
|
|
return_value=True,
|
|
),
|
|
patch.object(async_cache, "hget", new_callable=AsyncMock) as mock_hget,
|
|
patch.object(
|
|
SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None
|
|
),
|
|
):
|
|
mock_hget.return_value = json.dumps({"title": "Gran Turismo"})
|
|
result = await handler.get_rom(MagicMock(), "SCUS-94163.bin", PS1_SS_ID)
|
|
|
|
mock_hget.assert_awaited_once_with(PS1_SERIAL_INDEX_KEY, "SCUS-94163")
|
|
assert result.get("name") == "Gran Turismo"
|
|
assert result["ss_id"] is None
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_switch_titledb_fallback_does_not_set_icon_as_manual(self):
|
|
"""The Switch TitleDB index has no manual, so the fallback must not
|
|
reuse the icon URL as ``url_manual``. Doing so made RomM try to fetch
|
|
an icon as a game manual on every scan of such a ROM."""
|
|
handler = SSHandler()
|
|
|
|
with (
|
|
patch(
|
|
"handler.metadata.ss_handler.SSHandler.is_enabled",
|
|
return_value=True,
|
|
),
|
|
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,
|
|
patch.object(
|
|
SSHandler, "_search_rom", new_callable=AsyncMock, return_value=None
|
|
),
|
|
):
|
|
mock_exists.return_value = True
|
|
mock_hget.return_value = json.dumps(
|
|
{
|
|
"name": "Switch Game",
|
|
"description": "A game",
|
|
"iconUrl": "https://example.net/icon.png",
|
|
}
|
|
)
|
|
result = await handler.get_rom(
|
|
Rom(fs_name="70123456789012.nsp"), "70123456789012.nsp", SWITCH_SS_ID
|
|
)
|
|
|
|
assert result.get("name") == "Switch Game"
|
|
assert result.get("url_cover") == "https://example.net/icon.png"
|
|
assert not result.get("url_manual")
|
|
|
|
|
|
class TestDevCredentials:
|
|
"""Tests for ``SSHandler.has_dev_credentials``."""
|
|
|
|
@pytest.mark.parametrize(
|
|
("dev_id", "dev_password", "expected"),
|
|
[
|
|
("dev", "devpass", True),
|
|
(None, "devpass", False),
|
|
("dev", None, False),
|
|
(None, None, False),
|
|
("", "", False),
|
|
],
|
|
)
|
|
def test_reports_whether_both_credentials_are_present(
|
|
self, dev_id: str | None, dev_password: str | None, expected: bool
|
|
):
|
|
with (
|
|
patch("handler.metadata.ss_handler.SCREENSCRAPER_DEV_ID", dev_id),
|
|
patch(
|
|
"handler.metadata.ss_handler.SCREENSCRAPER_DEV_PASSWORD", dev_password
|
|
),
|
|
):
|
|
assert SSHandler.has_dev_credentials() is expected
|
|
|
|
|
|
class TestExtractFromSSDump:
|
|
"""`jeu.roms` lists every dump of a game; only ours describes the file."""
|
|
|
|
# Shaped after a real jeuInfos payload, trimmed to the keys read here.
|
|
ROMS = [
|
|
{
|
|
"id": "4219",
|
|
"romfilename": "Super Mario Bros.",
|
|
"rommd5": "B330314E19126D87D156D0618C4657B0",
|
|
"romsha1": "8EE8032491DEE422534B82F107DE0E9F5F9D44F9",
|
|
"romcrc": "A5C2849E",
|
|
"trad": 0,
|
|
"regions": {"regions_shortname": ["wor"], "regions_en": ["World"]},
|
|
},
|
|
{
|
|
"id": "154585",
|
|
"romfilename": "Super Mario Bros. (W) [T Fre].nes",
|
|
"rommd5": "811B027EAF99C2DEF7B933C5208636DE",
|
|
"romsha1": "",
|
|
"romcrc": "",
|
|
"trad": 1,
|
|
"regions": {"regions_shortname": ["us", "jp", "ss"]},
|
|
"langues": {"langues_shortname": ["fr"], "langues_en": ["French"]},
|
|
},
|
|
]
|
|
|
|
def _game(self) -> SSGame:
|
|
# `romid` names a dump that is not ours, which is why hashes decide.
|
|
return cast(SSGame, {"id": "1245", "romid": "999999", "roms": self.ROMS})
|
|
|
|
def test_the_dump_is_found_by_md5_whatever_romid_says(self):
|
|
dump = find_ss_dump(
|
|
self._game(),
|
|
LookupHashes(crc=None, md5="811b027eaf99c2def7b933c5208636de", sha1=None),
|
|
)
|
|
|
|
assert dump is not None
|
|
assert dump["id"] == "154585"
|
|
|
|
def test_the_dump_is_found_by_sha1(self):
|
|
dump = find_ss_dump(
|
|
self._game(),
|
|
LookupHashes(
|
|
crc=None, md5=None, sha1="8ee8032491dee422534b82f107de0e9f5f9d44f9"
|
|
),
|
|
)
|
|
|
|
assert dump is not None
|
|
assert dump["id"] == "4219"
|
|
|
|
def test_a_hash_no_dump_carries_matches_nothing(self):
|
|
assert (
|
|
find_ss_dump(self._game(), LookupHashes(crc=None, md5="0" * 32, sha1=None))
|
|
is None
|
|
)
|
|
|
|
def test_no_hashes_match_nothing(self):
|
|
assert (
|
|
find_ss_dump(self._game(), LookupHashes(crc=None, md5=None, sha1=None))
|
|
is None
|
|
)
|
|
|
|
def test_regions_come_from_the_dump(self):
|
|
dump = cast(SSGameRom, self.ROMS[1])
|
|
|
|
# "ss" is a ScreenScraper bucket rather than a place.
|
|
assert extract_regions_from_ss_dump(dump) == ["USA", "Japan"]
|
|
|
|
def test_languages_come_from_the_dump(self):
|
|
assert extract_languages_from_ss_dump(cast(SSGameRom, self.ROMS[1])) == [
|
|
"French"
|
|
]
|
|
|
|
def test_a_translated_dump_is_tagged(self):
|
|
"""ScreenScraper sends the flag as a string, not an int."""
|
|
assert extract_tags_from_ss_dump(SSGameRom(trad="1")) == ["Translation"]
|
|
assert extract_tags_from_ss_dump(SSGameRom(trad=1)) == ["Translation"]
|
|
|
|
@pytest.mark.parametrize("trad", ["0", 0, ""])
|
|
def test_an_untranslated_dump_is_not_tagged(self, trad: int | str):
|
|
assert extract_tags_from_ss_dump(SSGameRom(trad=trad)) == []
|
|
|
|
@pytest.mark.parametrize(
|
|
("dump", "tag"),
|
|
[
|
|
(SSGameRom(hack="1"), "Hack"),
|
|
(SSGameRom(beta="1"), "Beta"),
|
|
(SSGameRom(demo="1"), "Demo"),
|
|
],
|
|
)
|
|
def test_the_other_flags_spell_their_tag_the_way_a_filename_does(
|
|
self, dump: SSGameRom, tag: str
|
|
):
|
|
assert extract_tags_from_ss_dump(dump) == [tag]
|
|
|
|
def test_a_dump_raising_several_flags_carries_each_tag(self):
|
|
dump = SSGameRom(trad="1", hack="1", beta="1")
|
|
|
|
assert extract_tags_from_ss_dump(dump) == ["Translation", "Hack", "Beta"]
|
|
|
|
def test_unl_is_not_a_tag(self):
|
|
"""No filename tag answers to it, so reading it would split the facet."""
|
|
assert extract_tags_from_ss_dump(SSGameRom(unl="1")) == []
|
|
|
|
async def test_a_hash_match_carries_the_dump_tags(self):
|
|
"""The primary path: lookup_rom answers a hash, so its dump is ours."""
|
|
handler = SSHandler()
|
|
rom_file = MagicMock(
|
|
file_size_bytes=40976,
|
|
is_top_level=True,
|
|
file_extension="nes",
|
|
file_name="Super Mario Bros. (W) [T Fre].nes",
|
|
archive_members=None,
|
|
md5_hash="811b027eaf99c2def7b933c5208636de",
|
|
sha1_hash="",
|
|
crc_hash="",
|
|
)
|
|
rom = MagicMock(platform_slug="nes", platform_id=1, id=100, regions=[])
|
|
|
|
with (
|
|
patch.object(handler, "is_enabled", return_value=True),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
new=AsyncMock(return_value=self._game()),
|
|
),
|
|
patch(
|
|
"handler.metadata.ss_handler.build_ss_game",
|
|
side_effect=lambda *_: SSRom(ss_id=1245),
|
|
),
|
|
):
|
|
result, _ = await handler.lookup_rom(rom, 3, [rom_file])
|
|
|
|
assert result.get("tags") == ["Translation"]
|
|
assert result.get("languages") == ["French"]
|
|
|
|
def test_a_dump_without_tags_reports_nothing(self):
|
|
dump = cast(SSGameRom, {"id": 1})
|
|
|
|
assert extract_regions_from_ss_dump(dump) == []
|
|
assert extract_languages_from_ss_dump(dump) == []
|
|
assert extract_tags_from_ss_dump(dump) == []
|
|
|
|
async def test_a_refetch_by_id_keeps_our_dump_when_given_the_files(self):
|
|
"""An UPDATE scan refetches by id, so the dump has to survive that path."""
|
|
handler = SSHandler()
|
|
rom = MagicMock(platform_slug="nes")
|
|
rom_file = MagicMock(
|
|
file_size_bytes=40976,
|
|
is_top_level=True,
|
|
file_extension="nes",
|
|
md5_hash="811b027eaf99c2def7b933c5208636de",
|
|
sha1_hash=None,
|
|
crc_hash=None,
|
|
)
|
|
|
|
with (
|
|
patch.object(handler, "is_enabled", return_value=True),
|
|
patch.object(
|
|
handler.ss_service,
|
|
"get_game_info",
|
|
new=AsyncMock(return_value=self._game()),
|
|
),
|
|
patch(
|
|
"handler.metadata.ss_handler.build_ss_game",
|
|
side_effect=lambda *_: SSRom(ss_id=1245),
|
|
),
|
|
):
|
|
with_files = await handler.get_rom_by_id(rom, 1245, [rom_file])
|
|
without_files = await handler.get_rom_by_id(rom, 1245)
|
|
|
|
assert with_files.get("tags") == ["Translation"]
|
|
assert with_files.get("languages") == ["French"]
|
|
|
|
# A caller that only picked an id, like a manual match, says nothing
|
|
# about which dump is on disk.
|
|
assert "tags" not in without_files
|
|
|
|
def test_a_game_with_no_dumps_matches_nothing(self):
|
|
game = cast(SSGame, {"id": 1})
|
|
|
|
assert (
|
|
find_ss_dump(game, LookupHashes(crc=None, md5="a" * 32, sha1=None)) is None
|
|
)
|