Files
romm/backend/tests/endpoints/test_config.py
Georges-Antoine Assi 05bf29fe09 feat(converto): read per-file title ids with rom-converto during scans (#5031)
* feat(converto): read per-file title ids with rom-converto during scans

The title-id half of #5002: rom-converto's info runs fill rom_files.title_id
and title_version, sigil fills what rom-converto can't read and keeps owning
save targets, and roms in a scan batch share info runs of up to 64 files.
A converto_read_at marker lets quick scans backfill files rom-converto has
not read yet. converto.scan_metadata (config.yml only) turns it off.

The other per-file fields and embedded images stay out until a UI reads them.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the same-content check that keeps unread title ids

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): queue unread files in one pass over the built rows

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): address Greptile review on #5031

- A file refresh now persists converto_read_at when rom-converto's read
  confirms a reused row's stored title id, so the file isn't re-read on
  every refresh.
- RomConvertoService.read_infos splits its paths into info runs of at
  most INFO_BATCH_SIZE, so a rom with many files can't send them all
  through one run.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(converto): apply code-review fixes

- A stored file title id counts as rom-converto's only once rom-converto
  has read the row, so a stale sigil id can't override a fresh extraction.
- Fresh hashes decide whether unread title ids still describe a file,
  ahead of a size and mtime a copy can preserve.
- One rom's failed candidate listing no longer aborts its scan batch.
- The info paths file's cleanup can't raise out of read_infos.
- _rom_file_order sorts by Path like _TitleIdSource.order.
- Restored the in-place reconcile test for _identify_rom.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): apply simplify pass

- sync_rom_files reads 'rom-converto read this pass' off converto_read_at
  instead of an inspected set threaded through ParsedRomFiles, FSRom, the
  scan socket and the refresh.
- One _converto_may_read check serves the scan and the batch candidates.
- converto_candidates reuses _list_rom_dir, validates paths off the event
  loop and is best-effort itself, so the scan socket gathers it plainly.
- get_rom_files builds rom-converto paths from the validated rom dir
  instead of validating each file again.
- _rom_level_identity returns early on sigil's extraction.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(converto): apply review-polish pass

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): drop the shared info batch

Sharing rom-converto info runs across a scan batch saved about 2 ms per
rom (one process start) in exchange for a second directory walk per
rebuilt rom, the RomConvertoInfoBatch bookkeeping and the scan socket
wiring. Each rom now reads its own files; read_infos still caps a run
at INFO_RUN_MAX_FILES.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(converto): name the rom-converto columns inline

Drops ROM_FILE_CONVERTO_COLUMNS and ROM_FILE_CONVERTO_KEPT_COLUMNS, so
_copy_scanned_columns keeps master's frozenset keep_when_unset.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-02 13:49:40 -04:00

333 lines
12 KiB
Python

from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
import pytest
from fastapi import status
from config.config_manager import (
DEFAULT_EXCLUDED_EXTENSIONS,
DEFAULT_EXCLUDED_FILES,
DEFAULT_EXCLUDED_MULTI_FILE_DIRS,
DEFAULT_EXCLUDED_PLATFORM_DIRS,
ConvertoConfig,
ExclusionType,
)
from config.config_manager import config_manager as cm
def test_config(client):
response = client.get("/api/config")
assert response.status_code == status.HTTP_200_OK
config = response.json()
assert config.get("EXCLUDED_PLATFORMS") == sorted(DEFAULT_EXCLUDED_PLATFORM_DIRS)
assert config.get("EXCLUDED_SINGLE_EXT") == sorted(
e.lower() for e in DEFAULT_EXCLUDED_EXTENSIONS
)
assert config.get("EXCLUDED_SINGLE_FILES") == sorted(DEFAULT_EXCLUDED_FILES)
assert config.get("EXCLUDED_MULTI_FILES") == sorted(
DEFAULT_EXCLUDED_MULTI_FILE_DIRS
)
assert config.get("EXCLUDED_MULTI_PARTS_EXT") == sorted(
e.lower() for e in DEFAULT_EXCLUDED_EXTENSIONS
)
assert config.get("EXCLUDED_MULTI_PARTS_FILES") == sorted(DEFAULT_EXCLUDED_FILES)
assert config.get("DEFAULT_EXCLUDED_MULTI_FILE_DIRS") == list(
DEFAULT_EXCLUDED_MULTI_FILE_DIRS
)
assert config.get("PLATFORMS_BINDING") == {}
assert config.get("EJS_DEFAULT_CORES") == {}
assert not config.get("SKIP_HASH_CALCULATION")
assert config.get("GAMELIST_MEDIA_THUMBNAIL") == "box2d"
assert config.get("GAMELIST_MEDIA_IMAGE") == "screenshot"
assert config.get("GAMELIST_AUTO_EXPORT_ON_SCAN") is False
assert config.get("PEGASUS_AUTO_EXPORT_ON_SCAN") is False
def test_config_parse_error_gated_by_auth(client, access_token: str):
# The raw parser error can leak the config file path, so it is only
# returned to authenticated users.
cfg = cm.get_config()
cfg.CONFIG_FILE_PARSE_ERROR = 'in "/data/config.yml", line 2'
with patch.object(cm, "get_config", return_value=cfg):
anon = client.get("/api/config")
assert anon.status_code == status.HTTP_200_OK
assert anon.json().get("CONFIG_FILE_PARSE_ERROR") is None
auth = client.get(
"/api/config",
headers={"Authorization": f"Bearer {access_token}"},
)
assert auth.status_code == status.HTTP_200_OK
assert (
auth.json().get("CONFIG_FILE_PARSE_ERROR")
== 'in "/data/config.yml", line 2'
)
def test_add_platform_binding_payload_shape(client, access_token: str):
with patch.object(cm, "add_platform_binding") as add_platform_binding:
response = client.post(
"/api/config/system/platforms",
headers={"Authorization": f"Bearer {access_token}"},
json={"fs_slug": "n64", "slug": "nintendo-64"},
)
assert response.status_code == status.HTTP_200_OK
add_platform_binding.assert_called_once_with("n64", "nintendo-64")
def test_add_platform_version_payload_shape(client, access_token: str):
with patch.object(cm, "add_platform_version") as add_platform_version:
response = client.post(
"/api/config/system/versions",
headers={"Authorization": f"Bearer {access_token}"},
json={"fs_slug": "n64", "slug": "1.0"},
)
assert response.status_code == status.HTTP_200_OK
add_platform_version.assert_called_once_with("n64", "1.0")
def test_mapping_a_folder_with_a_case_variant_sibling_is_rejected(
client, access_token: str
):
"""One config key covers both, so the write would remap the sibling too."""
with (
patch(
"endpoints.configs.fs_platform_handler.find_ambiguous_folders",
AsyncMock(return_value=["PSX", "psx"]),
),
patch.object(cm, "add_platform_binding") as add_platform_binding,
):
response = client.post(
"/api/config/system/platforms",
headers={"Authorization": f"Bearer {access_token}"},
json={"fs_slug": "PSX", "slug": "ps2"},
)
assert response.status_code == status.HTTP_409_CONFLICT
assert "differ only by case" in response.json()["detail"]
add_platform_binding.assert_not_called()
def test_mapping_a_folder_whose_name_is_unique_is_allowed(client, access_token: str):
with (
patch(
"endpoints.configs.fs_platform_handler.find_ambiguous_folders",
AsyncMock(return_value=[]),
),
patch.object(cm, "add_platform_binding") as add_platform_binding,
):
response = client.post(
"/api/config/system/platforms",
headers={"Authorization": f"Bearer {access_token}"},
json={"fs_slug": "Nintendo 64", "slug": "n64"},
)
assert response.status_code == status.HTTP_200_OK
add_platform_binding.assert_called_once_with("Nintendo 64", "n64")
def test_add_exclusion_payload_shape(client, access_token: str):
with patch.object(cm, "add_exclusion") as add_exclusion:
response = client.post(
"/api/config/exclude",
headers={"Authorization": f"Bearer {access_token}"},
json={
"exclusion_type": "EXCLUDED_SINGLE_FILES",
"exclusion_value": "README.txt",
},
)
assert response.status_code == status.HTTP_200_OK
add_exclusion.assert_called_once_with(
ExclusionType.EXCLUDED_SINGLE_FILES, "README.txt"
)
def test_add_exclusion_rejects_unknown_type(client, access_token: str):
"""An unknown type used to reach `Config.__getattribute__` and 500."""
with patch.object(cm, "add_exclusion") as add_exclusion:
response = client.post(
"/api/config/exclude",
headers={"Authorization": f"Bearer {access_token}"},
json={"exclusion_type": "platforms", "exclusion_value": "README.txt"},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
add_exclusion.assert_not_called()
def test_delete_exclusion_rejects_unknown_type(client, access_token: str):
with patch.object(cm, "remove_exclusion") as remove_exclusion:
response = client.delete(
"/api/config/exclude/platforms/README.txt",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
remove_exclusion.assert_not_called()
def _scan_payload(**overrides):
payload = {
"metadata_priority": ["igdb", "moby"],
"artwork_priority": ["sgdb", "igdb"],
"cover_priority": ["igdb", "ss"],
"screenshot_priority": None,
"manual_priority": None,
"region_priority": ["us", "eu"],
"language_priority": ["en", "fr"],
"media": ["box2d", "screenshot"],
"gamelist_export": True,
"gamelist_thumbnail": "box2d",
"gamelist_image": "screenshot",
"pegasus_export": False,
}
payload.update(overrides)
return payload
def test_update_scan_settings_payload_shape(client, access_token: str):
with patch.object(cm, "update_scan_settings") as update_scan_settings:
response = client.put(
"/api/config/scan",
headers={"Authorization": f"Bearer {access_token}"},
json=_scan_payload(),
)
assert response.status_code == status.HTTP_200_OK
update_scan_settings.assert_called_once_with(
metadata_priority=["igdb", "moby"],
artwork_priority=["sgdb", "igdb"],
artwork_overrides={
"cover": ["igdb", "ss"],
"screenshot": None,
"manual": None,
},
region_priority=["us", "eu"],
language_priority=["en", "fr"],
media=["box2d", "screenshot"],
gamelist_export=True,
gamelist_thumbnail="box2d",
gamelist_image="screenshot",
pegasus_export=False,
)
def test_update_scan_settings_requires_auth(client):
response = client.put("/api/config/scan", json=_scan_payload())
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_update_scan_settings_rejects_unknown_source(client, access_token: str):
with patch.object(cm, "update_scan_settings") as update_scan_settings:
response = client.put(
"/api/config/scan",
headers={"Authorization": f"Bearer {access_token}"},
json=_scan_payload(metadata_priority=["igdb", "not-a-source"]),
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
update_scan_settings.assert_not_called()
def test_update_scan_settings_rejects_invalid_gamelist_thumbnail(
client, access_token: str
):
# `screenshot` is a valid media type but not a valid gamelist thumbnail.
with patch.object(cm, "update_scan_settings") as update_scan_settings:
response = client.put(
"/api/config/scan",
headers={"Authorization": f"Bearer {access_token}"},
json=_scan_payload(gamelist_thumbnail="screenshot"),
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
update_scan_settings.assert_not_called()
def test_update_scan_settings_normalizes_codes(client, access_token: str):
with patch.object(cm, "update_scan_settings") as update_scan_settings:
response = client.put(
"/api/config/scan",
headers={"Authorization": f"Bearer {access_token}"},
json=_scan_payload(
region_priority=["US", " eu ", "us", ""],
language_priority=["EN", "en"],
),
)
assert response.status_code == status.HTTP_200_OK
_, kwargs = update_scan_settings.call_args
assert kwargs["region_priority"] == ["us", "eu"]
assert kwargs["language_priority"] == ["en"]
def _converto_payload(**overrides):
payload = {
"download_conversion_enabled": True,
"cache_max_size_gb": 20,
"platform_formats": {"psp": "cso"},
}
payload.update(overrides)
return payload
def test_update_converto_settings_normalizes_formats_and_keeps_the_ttl(
client, access_token: str
):
current = SimpleNamespace(
CONVERTO=ConvertoConfig(cache_ttl_hours=72, scan_metadata=False)
)
with (
patch.object(cm, "get_config", return_value=current),
patch.object(cm, "update_converto_settings") as update_converto_settings,
):
response = client.put(
"/api/config/converto_settings",
headers={"Authorization": f"Bearer {access_token}"},
json=_converto_payload(platform_formats={" PSP ": "CSO"}),
)
assert response.status_code == status.HTTP_200_OK
update_converto_settings.assert_called_once_with(
ConvertoConfig(
download_conversion_enabled=True,
scan_metadata=False,
cache_ttl_hours=72,
cache_max_size_gb=20,
platform_formats={"psp": "cso"},
)
)
def test_update_converto_settings_requires_auth(client):
response = client.put("/api/config/converto_settings", json=_converto_payload())
assert response.status_code == status.HTTP_401_UNAUTHORIZED
@pytest.mark.parametrize(
"overrides",
[
{"platform_formats": {"psp": "rvz"}},
{"platform_formats": {"psvita": "iso"}},
{"platform_formats": {"xbox": "xiso"}},
{"cache_max_size_gb": -1},
],
)
def test_update_converto_settings_rejects_invalid_values(
client, access_token: str, overrides
):
with patch.object(cm, "update_converto_settings") as update_converto_settings:
response = client.put(
"/api/config/converto_settings",
headers={"Authorization": f"Bearer {access_token}"},
json=_converto_payload(**overrides),
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
update_converto_settings.assert_not_called()