Files
romm/backend/tests/handler/test_scan_complete_rescan_ids.py
Georges-Antoine Assi b35eb4d07c fix(scan): clean up unreferenced rescan media, split scan_rom and move its parts into handler/scan (#5408)
* fix(scan): delete screenshots and media a rescan leaves unreferenced

A complete rescan keeps the stored artwork, so two kinds of file stayed on
disk with nothing pointing at them:

- screenshots indexed past a shorter new list, since files are named by
  position and only the indexes in range were rewritten
- media of a type removed from the preferences, since providers record no
  path for it and stale media was compared over the preferred types only

get_rom_screenshots now deletes the indexes past the new list, and
remove_stale_media compares every media type.

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

* refactor(scan): split scan_rom's merge into named steps

scan_rom held seeding the row, following Demozoo links, splicing scene
summaries, resetting rematched sources, the scene lock, rehash cleanup,
priority merges for fields, tags and artwork, and the SteamGridDB pass in one
body. Each step is now its own helper, the SteamGridDB lookup a _RomLookups
method, and the providers' answers a dict keyed by source instead of fourteen
locals. The Pouet and CSDb link follows share one helper. Behaviour is
unchanged.

McCabe complexity of scan_rom goes from 68 to 13, and the function from 664
to 215 lines.

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

* fix(scan): trim remove_stale_media's docstring per Greptile review

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

* refactor(scan): move the scan vocabulary, lookups and merge into handler/scan

scan_handler.py held the scan types and metadata sources, the per-source
lookups, the merge of their answers and the orchestration in one 2,000-line
module. It now builds on a handler/scan package:

- sources.py: ScanType, MetadataSource, the tag constants, RESCAN_RULES,
  should_consult, stored_match_id and the priority ordering
- lookups.py: RomLookups, the LaunchBox and Steam resolvers and
  get_main_platform_igdb_id
- merge.py: the pure steps that merge the sources' answers into a rom's
  columns

scan_handler.py keeps scan_platform, scan_rom, the asset scans and the media
downloads. Importers point at the module that now defines each name, and the
helpers that crossed a module boundary lost their leading underscore.
clear_rehash_misses takes the attempted sources instead of the lookups, so
merge does not depend on lookups. Behaviour is unchanged.

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

* fix(ci): import ScanType from handler.scan.sources in the e2e seed script

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

* fix(scan): harden leftover screenshot cleanup (pr-ready: code-review)

List the screenshots folder once, use isdecimal() for the index test, and
log rather than raise when a leftover can't be removed. Point three
comments at handler/scan instead of scan_handler.

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

* refactor(scan): tidy the merge helpers and patch paths (pr-ready: simplify)

- fetch_sgdb_rom refetches by stored_id and builds the SGDB name list
  itself, so the name sources stay private to lookups.
- follow_demozoo_link checks the source is enabled; scan_rom loops over
  Pouët and CSDb.
- order_merge_sources holds the one ordering pass, and
  build_metadata_handlers adds the empty SGDB entry.
- Leftover screenshots go through the quiet-delete helper, renamed
  _discard_file.
- Tests patch rom lookups through handler.scan.lookups.

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

* fix(scan): never leave a recorded media or screenshot path without its file

- remove_stale_media only deletes a file whose owner or source changed
  when that new owner stores the type again in this pass. A file nothing
  records is still deleted.
- Screenshots past a shorter list are pruned by remove_screenshots_past
  once the new paths are saved, in both download_rom_resources and
  update_rom, so a failed cover or manual leaves them in place.
- The release-notes schema diff watches scan_handler.py beside
  scan/sources.py, for ranges that span the move.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:23:13 -04:00

277 lines
9.1 KiB
Python

"""What a scan does to a ROM's external IDs.
A complete rescan clears every ID it could rematch; a provider that failed
answered nothing, so the ID it could not check has to survive.
"""
from typing import Any
from unittest.mock import AsyncMock, patch
import pytest
from fastapi import HTTPException
from tests.handler.scan_stubs import add_n64_platform, add_rom, run_scan
from handler.database import db_rom_handler
from handler.metadata.hasheous_handler import HasheousRom
from handler.metadata.igdb_handler import IGDBRom
from handler.metadata.pouet_handler import PouetRom
from handler.metadata.sgdb_handler import SGDBRom
from handler.metadata.ss_handler import ScreenScraperExhaustedError, SSRom
from handler.scan.sources import MetadataSource, ScanType
from models.rom import Rom
FS_NAME = "Some Homebrew Thing (Aftermarket).z64"
STALE_IGDB_ID = 1289
STALE_MOBY_ID = 42
STALE_SGDB_ID = 777
STALE_POUET_ID = 106640
STALE_SS_ID = 314
STALE_HASHEOUS_ID = 2718
MISS = IGDBRom(igdb_id=None)
SGDB_MISS = SGDBRom(sgdb_id=None)
POUET_MISS = PouetRom(pouet_id=None)
MATCH = IGDBRom(igdb_id=9999, name="A Real Game")
UNREACHABLE = HTTPException(status_code=503, detail="provider is down")
SS_MISS = SSRom(ss_id=None)
SS_SHORT_CIRCUITED = ScreenScraperExhaustedError(SS_MISS)
HASHEOUS_MISS = HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None)
def _lookup(result: Any) -> AsyncMock:
"""A provider lookup that answers with `result`, or fails when it is one."""
if isinstance(result, Exception):
return AsyncMock(side_effect=result)
return AsyncMock(return_value=result)
async def _rescan(
sources: list[str],
*,
scan_type: ScanType = ScanType.COMPLETE,
igdb_result: IGDBRom | Exception = MISS,
sgdb_result: SGDBRom | Exception = SGDB_MISS,
pouet_result: PouetRom | Exception = POUET_MISS,
platform_igdb_id: int | None = 4,
ss_lookup_result: tuple[SSRom, bool] | Exception = (SS_MISS, False),
ss_get_rom_result: SSRom | Exception = SS_MISS,
platform_hasheous_id: int | None = None,
hasheous_lookup_result: tuple[HasheousRom, bool] = (HASHEOUS_MISS, True),
**rom_fields: Any,
) -> Rom:
"""Rescan a ROM carrying hand-set IDs, and persist the result."""
platform = add_n64_platform(
igdb_id=platform_igdb_id, ss_id=14, hasheous_id=platform_hasheous_id
)
rom = add_rom(
platform,
FS_NAME,
"Some Homebrew Thing",
name="Wrong Match",
igdb_id=STALE_IGDB_ID,
igdb_metadata={"total_rating": "9"},
moby_id=STALE_MOBY_ID,
sgdb_id=STALE_SGDB_ID,
pouet_id=STALE_POUET_ID,
ss_id=STALE_SS_ID,
hasheous_id=STALE_HASHEOUS_ID,
**rom_fields,
)
igdb_mock = _lookup(igdb_result)
pouet_mock = _lookup(pouet_result)
with (
patch("handler.scan.lookups.meta_igdb_handler.get_rom", new=igdb_mock),
patch("handler.scan.lookups.meta_igdb_handler.get_rom_by_id", new=igdb_mock),
patch(
"handler.scan.lookups.meta_sgdb_handler.get_details_by_names",
new=_lookup(sgdb_result),
),
patch("handler.scan.lookups.meta_pouet_handler.get_rom", new=pouet_mock),
patch("handler.scan.lookups.meta_pouet_handler.get_rom_by_id", new=pouet_mock),
patch(
"handler.scan.lookups.meta_ss_handler.lookup_rom",
new=_lookup(ss_lookup_result),
),
patch(
"handler.scan.lookups.meta_ss_handler.get_rom",
new=_lookup(ss_get_rom_result),
),
patch(
"handler.scan.lookups.meta_hasheous_handler.is_enabled", return_value=True
),
patch(
"handler.scan.lookups.meta_hasheous_handler.lookup_rom",
new=_lookup(hasheous_lookup_result),
),
patch(
"handler.scan.lookups.meta_hasheous_handler.get_igdb_game",
new=_lookup(HASHEOUS_MISS),
),
):
scanned = await run_scan(
platform, rom, scan_type=scan_type, metadata_sources=sources
)
return db_rom_handler.add_rom(scanned) # noqa: TID251
async def test_a_searched_source_that_misses_drops_its_stale_id():
saved = await _rescan([MetadataSource.IGDB])
assert saved.igdb_id is None
assert saved.igdb_metadata == {}
async def test_a_searched_source_that_matches_stores_the_new_id():
saved = await _rescan([MetadataSource.IGDB], igdb_result=MATCH)
assert saved.igdb_id == 9999
async def test_a_source_the_platform_cannot_use_keeps_its_id():
"""No `platform.igdb_id` means IGDB never ran, so it rules nothing out."""
saved = await _rescan([MetadataSource.IGDB], platform_igdb_id=None)
assert saved.igdb_id == STALE_IGDB_ID
async def test_a_source_that_fails_keeps_its_id():
saved = await _rescan(
[MetadataSource.IGDB], igdb_result=RuntimeError("IGDB is down")
)
assert saved.igdb_id == STALE_IGDB_ID
async def test_a_source_that_could_not_be_reached_keeps_its_id():
"""Pouët reports an outage as an empty match, so the handler has to raise."""
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.POUET], pouet_result=UNREACHABLE
)
assert saved.pouet_id == STALE_POUET_ID
async def test_a_screenscraper_breaker_keeps_its_id():
"""A breaker answers every remaining ROM, so it rules nothing out."""
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.SS],
ss_lookup_result=SS_SHORT_CIRCUITED,
ss_get_rom_result=SS_SHORT_CIRCUITED,
)
assert saved.ss_id == STALE_SS_ID
async def test_a_screenscraper_breaker_that_recovers_mid_rom_keeps_its_id():
"""The breaker can clear between this rom's two lookups, but the hash lookup
it short-circuited still ruled nothing out."""
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.SS],
ss_lookup_result=SS_SHORT_CIRCUITED,
ss_get_rom_result=SS_MISS,
)
assert saved.ss_id == STALE_SS_ID
async def test_a_hasheous_lookup_that_never_answered_keeps_its_id():
"""Hasheous swallows its own failures, so the conclusive flag is all a rescan
has to tell an outage from a miss it confirmed."""
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.HASHEOUS],
platform_hasheous_id=64,
hasheous_lookup_result=(HASHEOUS_MISS, False),
)
assert saved.hasheous_id == STALE_HASHEOUS_ID
async def test_a_hasheous_miss_it_confirmed_still_drops_its_id():
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.HASHEOUS],
platform_hasheous_id=64,
)
assert saved.hasheous_id is None
async def test_a_selected_screenscraper_that_misses_still_drops_its_id():
saved = await _rescan([MetadataSource.IGDB, MetadataSource.SS])
assert saved.ss_id is None
async def test_a_deselected_source_still_drops_its_id():
saved = await _rescan([MetadataSource.IGDB])
assert saved.moby_id is None
async def test_steamgriddb_drops_its_stale_id_after_a_miss():
"""SteamGridDB resolves after the reset, so it clears its own ID."""
saved = await _rescan([MetadataSource.IGDB, MetadataSource.SGDB], igdb_result=MATCH)
assert saved.sgdb_id is None
async def test_steamgriddb_keeps_its_stale_id_when_it_could_not_be_reached():
saved = await _rescan(
[MetadataSource.IGDB, MetadataSource.SGDB],
igdb_result=MATCH,
sgdb_result=UNREACHABLE,
)
assert saved.sgdb_id == STALE_SGDB_ID
@pytest.mark.parametrize(
"scan_type", [ScanType.QUICK, ScanType.UPDATE, ScanType.UNMATCHED]
)
async def test_only_a_complete_rescan_drops_ids(scan_type: ScanType):
"""Every other scan type carries the existing IDs forward untouched."""
saved = await _rescan([MetadataSource.IGDB], scan_type=scan_type)
assert saved.igdb_id == STALE_IGDB_ID
async def test_a_complete_rescan_keeps_artwork_no_source_replaces():
"""The files stay on disk, so their paths must too: a provider that is down
must not leave the ROM without a cover, manual or screenshots."""
saved = await _rescan(
[MetadataSource.IGDB],
igdb_result=UNREACHABLE,
url_cover="https://example.com/cover.png",
path_cover_s="roms/1/1/cover/small.png",
path_cover_l="roms/1/1/cover/big.png",
path_manual="roms/1/1/manual/1.pdf",
path_screenshots=["roms/1/1/screenshots/0.jpg"],
)
assert saved.url_cover == ""
assert saved.path_cover_s == "roms/1/1/cover/small.png"
assert saved.path_cover_l == "roms/1/1/cover/big.png"
assert saved.path_manual == "roms/1/1/manual/1.pdf"
assert saved.path_screenshots == ["roms/1/1/screenshots/0.jpg"]
@pytest.mark.parametrize(
("path_cover_s", "url_cover"),
[("roms/1/1/cover/small.png", ""), ("", "file:///cart.p8.png")],
)
async def test_a_complete_rescan_falls_back_to_the_cartridge_only_without_a_cover(
path_cover_s: str, url_cover: str
):
with patch(
"handler.scan_handler.fs_rom_handler.get_pico8_cover_url",
return_value="file:///cart.p8.png",
):
saved = await _rescan(
[MetadataSource.IGDB],
igdb_result=UNREACHABLE,
path_cover_s=path_cover_s,
)
assert saved.url_cover == url_cover