Files
romm/backend/tests/handler/test_rom_files.py
Sam Dornan 79fbce6beb test(backend): build test rows through shared factories and enforce them with ruff (#4972)
* test(backend): build test ROMs through one make_rom factory

Tests created Rom rows by hand in dozens of places, each spelling out the
same slug and filename fields and deriving the slug inline. Production never
computes a slug from a name, so this was test-only filler duplicated across
files.

tests/factories.py adds make_rom(platform, name, *, fs_stem, fs_extension,
**overrides), which fills the slug and filename columns and persists through
db_rom_handler.add_rom. The shared conftest fixtures, scan_stubs.add_rom and
the local helpers and inline constructors across 35 test files now use it.
Each test keeps its filename shape (underscored stems in the FULLTEXT search
tests, spaced "Name (USA)" stems in the sibling tests), and fixtures shared
across files keep their exact slugs.

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

* test(backend): keep extensionless filenames intact in scan_stubs.add_rom

rpartition(".") on a name with no dot returned an empty stem and the whole
name as the extension, so make_rom stored ".README" for "README".
os.path.splitext leaves such names whole.

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

* test(backend): build test saves, states and screenshots through factories

Tests built Save, State and Screenshot rows by hand across about 20 files,
each spelling out file_name_no_tags, file_name_no_ext and file_extension
although BaseAsset already derives them from file_name.

tests/factories.py adds make_save, make_state and make_screenshot. Each sets
the rom and user ids, the file name, and a default file_path under the rom's
platform, applies overrides last, and persists through the matching db
handler. The conftest asset fixtures and the persisted constructors and local
helpers now use them. Rows a test observes keep their file_path, emulator,
slot, size and hash, and a filename part stays an override wherever it
differs from what the model derives.

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

* test(backend): ban direct add_* persistence in tests via ruff TID251

The factories only stay the one home for test rows if nothing routes
around them. Ruff's banned-api rule now flags db_rom_handler.add_rom,
db_save_handler.add_save, db_state_handler.add_state and
db_screenshot_handler.add_screenshot anywhere under tests/ except
tests/factories.py. Production code is unaffected.

The remaining add_rom calls move onto make_rom: the unique-path, soundtrack
and id-index tests in test_roms_handler.py, the scan tests in
test_fastapi.py, physical and missing rows in the feed, download and model
tests, and the name=None exporter rows. Scan tests keep a filename-derived
placeholder as the name, which scan_rom treats the same as no name. Three
calls keep a noqa: the tests of how add_rom merges a partial scanned row,
and the rescan test that persists scan_rom's output as a scan does.

The backend skill and the architecture doc now point at tests/factories.py.

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

* test(backend): move the firmware and client-token factories into tests/factories.py

The add_firmware and add_device_token conftest fixtures returned a builder,
unlike the importable make_* functions. They become make_firmware and
make_device_token alongside them, with the same defaults, and their callers
import them rather than requesting a fixture. make_device_token now draws the
raw credential from auth_handler.generate_client_token, so it carries the
real rmm_ prefix instead of restating it, and the hand-built client tokens in
the auth tests use it too.

The ruff TID251 ban now also covers db_firmware_handler.add_firmware and
db_client_token_handler.add_token under tests/.

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

* docs: point at every test factory, not just the ROM and asset ones

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 14:01:56 -05:00

314 lines
10 KiB
Python

import hashlib
import os
from pathlib import Path
from unittest.mock import AsyncMock, patch
import pytest
from tests.factories import make_rom
from handler.database import db_rom_handler
from handler.filesystem import fs_rom_handler
from handler.filesystem.roms_handler import ParsedRomFiles, category_for_path_parts
from handler.rom_files import refresh_rom_files
from models.platform import Platform
from models.rom import (
Rom,
RomFile,
RomFileCategory,
RomIdentity,
SaveTargetLayout,
)
from models.user import User
FOLDER = "Multi"
@pytest.fixture
def library(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
lib = tmp_path / "library"
lib.mkdir()
monkeypatch.setattr(fs_rom_handler, "base_path", lib.resolve())
return lib
def _write(lib: Path, rel: str, data: bytes) -> os.stat_result:
path = lib / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path.stat()
def _folder_rom(
platform: Platform, admin_user: User, lib: Path, files: dict[str, bytes]
) -> Rom:
"""A folder ROM whose rows describe the files on disk, with stored hashes."""
rom = make_rom(
platform,
FOLDER,
fs_extension="",
fs_path=f"{platform.fs_slug}/roms",
fs_size_bytes=sum(len(data) for data in files.values()),
crc_hash="stored-crc",
md5_hash="stored-md5",
sha1_hash="stored-sha1",
)
db_rom_handler.add_rom_user(rom_id=rom.id, user_id=admin_user.id)
for rel, data in files.items():
st = _write(lib, f"{rom.fs_path}/{FOLDER}/{rel}", data)
db_rom_handler.add_rom_file(
RomFile(
rom_id=rom.id,
file_name=Path(rel).name,
file_path=str(Path(rom.fs_path, FOLDER, rel).parent),
category=category_for_path_parts(
[part.lower() for part in Path(rel).parent.parts]
),
file_size_bytes=st.st_size,
last_modified=st.st_mtime,
crc_hash="row-crc",
md5_hash="row-md5",
sha1_hash="row-sha1",
)
)
return _reload(rom.id)
def _reload(rom_id: int) -> Rom:
rom = db_rom_handler.get_rom(rom_id)
assert rom is not None
return rom
def _files_by_name(rom_id: int) -> dict[str, RomFile]:
return {f.file_name: f for f in _reload(rom_id).files}
async def test_registers_new_nested_file(platform, admin_user, library):
rom = _folder_rom(
platform, admin_user, library, {"game.bin": b"game", "readme.txt": b"readme"}
)
_write(library, f"{rom.fs_path}/{FOLDER}/patches/v2/fix.ips", b"patch bytes")
result = await refresh_rom_files(rom)
assert (result.new_files, result.updated_files, result.removed_files) == (1, 0, 0)
new = _files_by_name(rom.id)["fix.ips"]
assert new.category == RomFileCategory.PATCH
assert (
new.md5_hash == hashlib.md5(b"patch bytes", usedforsecurity=False).hexdigest()
)
after = _reload(rom.id)
assert after.fs_size_bytes == len(b"game") + len(b"readme") + len(b"patch bytes")
assert after.md5_hash == "stored-md5"
async def test_top_level_addition_updates_rom_hashes_and_size(
platform, admin_user, library
):
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
_write(library, f"{rom.fs_path}/{FOLDER}/extra.bin", b"extra")
result = await refresh_rom_files(rom)
assert result.new_files == 1
either_order = {
hashlib.md5(a + b, usedforsecurity=False).hexdigest()
for a, b in ((b"game", b"extra"), (b"extra", b"game"))
}
after = _reload(rom.id)
assert after.md5_hash in either_order
assert after.fs_size_bytes == len(b"game") + len(b"extra")
assert (
_files_by_name(rom.id)["game.bin"].md5_hash
== hashlib.md5(b"game", usedforsecurity=False).hexdigest()
)
async def test_unchanged_rom_writes_nothing(platform, admin_user, library, mocker):
rom = _folder_rom(
platform, admin_user, library, {"game.bin": b"game", "hack/x.bin": b"hack"}
)
sync = mocker.spy(db_rom_handler, "sync_rom_files")
update = mocker.spy(db_rom_handler, "update_rom")
result = await refresh_rom_files(rom)
assert not result.changed
sync.assert_not_called()
update.assert_not_called()
async def test_removes_rows_for_vanished_files(platform, admin_user, library):
rom = _folder_rom(
platform, admin_user, library, {"game.bin": b"game", "hack/old.bin": b"old"}
)
(library / rom.fs_path / FOLDER / "hack/old.bin").unlink()
result = await refresh_rom_files(rom)
assert result.removed_files == 1
assert set(_files_by_name(rom.id)) == {"game.bin"}
# A nested file leaves the top level, and so the rom hash, alone.
assert _reload(rom.id).md5_hash == "stored-md5"
async def test_clears_missing_flag(platform, admin_user, library):
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
db_rom_handler.update_rom(rom.id, {"missing_from_fs": True})
rom = _reload(rom.id)
result = await refresh_rom_files(rom)
assert not result.changed
assert _reload(rom.id).missing_from_fs is False
async def test_empty_folder_keeps_recorded_rows(platform, admin_user, library):
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
(library / rom.fs_path / FOLDER / "game.bin").unlink()
result = await refresh_rom_files(rom)
assert not result.changed
assert set(_files_by_name(rom.id)) == {"game.bin"}
async def test_edited_file_is_rehashed_in_place(platform, admin_user, library):
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"stale"})
row_id = rom.files[0].id
_write(library, f"{rom.fs_path}/{FOLDER}/game.bin", b"game")
result = await refresh_rom_files(rom)
assert result.updated_files == 1
after = _reload(rom.id)
assert after.files[0].id == row_id
assert (
after.files[0].md5_hash
== hashlib.md5(b"game", usedforsecurity=False).hexdigest()
)
assert after.md5_hash == hashlib.md5(b"game", usedforsecurity=False).hexdigest()
async def test_loads_files_when_relationship_is_unloaded(platform, admin_user, library):
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
lean = db_rom_handler.get_roms_by_fs_name(
platform_id=platform.id, fs_names={FOLDER}
)[rom.full_path]
_write(library, f"{rom.fs_path}/{FOLDER}/cheats/codes.cht", b"cheats")
result = await refresh_rom_files(lean)
assert result.new_files == 1
assert _files_by_name(rom.id)["codes.cht"].category == RomFileCategory.CHEAT
async def test_disabled_hashing_keeps_stored_rom_hashes(
platform, admin_user, library, mocker
):
from config.config_manager import config_manager as cm
config = cm.get_config()
mocker.patch.object(config, "SKIP_HASH_CALCULATION", True)
mocker.patch.object(cm, "get_config", return_value=config)
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
_write(library, f"{rom.fs_path}/{FOLDER}/extra.bin", b"extra")
result = await refresh_rom_files(rom)
assert result.new_files == 1
after = _reload(rom.id)
assert (after.crc_hash, after.md5_hash, after.sha1_hash) == (
"stored-crc",
"stored-md5",
"stored-sha1",
)
assert _files_by_name(rom.id)["extra.bin"].md5_hash == ""
async def test_disabled_title_id_extraction_is_passed_through(
platform, admin_user, library, mocker
):
from config.config_manager import config_manager as cm
config = cm.get_config()
mocker.patch.object(config, "SKIP_TITLE_ID_EXTRACTION", True)
mocker.patch.object(cm, "get_config", return_value=config)
get_rom_files = mocker.spy(fs_rom_handler, "get_rom_files")
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
await refresh_rom_files(rom)
assert get_rom_files.call_args.kwargs["extract_title_ids"] is False
def _unchanged_parse(rom: Rom, identity: RomIdentity) -> ParsedRomFiles:
"""A listing that found every file untouched, carrying the given identity."""
return ParsedRomFiles(
rom_files=list(rom.files),
crc_hash=rom.crc_hash or "",
md5_hash=rom.md5_hash or "",
sha1_hash=rom.sha1_hash or "",
ra_hash="",
top_level_changed=False,
identity=identity,
)
async def test_a_newly_read_identity_is_persisted(platform, admin_user, library):
"""The refresh pays for the parse, so the id it reads has to land somewhere."""
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
identity = RomIdentity(
title_id="0100ABCD12340000",
save_target="0100ABCD12340000",
save_target_layout=SaveTargetLayout.FOLDER_EXACT,
)
with patch.object(
fs_rom_handler,
"get_rom_files",
AsyncMock(return_value=_unchanged_parse(rom, identity)),
):
result = await refresh_rom_files(rom)
assert result.changed
refreshed = _reload(rom.id)
assert refreshed.title_id == "0100ABCD12340000"
assert refreshed.save_target == "0100ABCD12340000"
assert refreshed.save_target_layout == SaveTargetLayout.FOLDER_EXACT
async def test_a_stored_identity_survives_a_parse_that_read_none(
platform, admin_user, library
):
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
db_rom_handler.update_rom(rom.id, {"title_id": "ULUS-10041"})
rom = _reload(rom.id)
with patch.object(
fs_rom_handler,
"get_rom_files",
AsyncMock(return_value=_unchanged_parse(rom, RomIdentity())),
):
await refresh_rom_files(rom)
assert _reload(rom.id).title_id == "ULUS-10041"
async def test_a_category_settled_on_a_reused_row_is_persisted(
platform, admin_user, library
):
"""Extraction settles a Switch file's category on the row it reused."""
rom = _folder_rom(platform, admin_user, library, {"game.bin": b"game"})
async def settle_category(*_args, **_kwargs) -> ParsedRomFiles:
parsed = _unchanged_parse(rom, RomIdentity())
parsed.rom_files[0].category = RomFileCategory.DLC
return parsed
with patch.object(fs_rom_handler, "get_rom_files", settle_category):
result = await refresh_rom_files(rom)
assert result.updated_files == 1
assert _files_by_name(rom.id)["game.bin"].category == RomFileCategory.DLC