mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 02:22:44 +01:00
fix(backend): satisfy mypy and bandit on the new tests and tools
Four findings trunk reports on files this branch adds, none of which CI tolerates. `_make_game` claimed `dict`, so passing it to `extract_metadata_from_igdb_rom` (which takes `Game`) was an arg-type error. It builds a real `Game` now. `Game` is `total=False` over a base that requires `id`, so the three keys the factory set to `None` are simply absent instead: every reader goes through `.get()`, which cannot tell the two apart. `alternative_names` and `game_localizations` need their element type spelled out, because mypy will not push a union context into a dict literal. `series_keys` takes a `Rom` and the diversity tests pass a stand-in, for the reason the module docstring gives. Cast at the one call that reaches a `Rom`-typed signature rather than grow the fake a database row's worth of attributes. `backfill_igdb_tags` reads fields named by a loop variable, which a TypedDict answers as `object`. It reads through a plain-mapping view instead. Bandit read `token == "--report"` as a hardcoded password on the strength of the variable's name. Renamed, rather than suppressed.
This commit is contained in:
@@ -1,11 +1,18 @@
|
||||
"""Tests for the IGDB metadata handler."""
|
||||
|
||||
import json
|
||||
from typing import Any, cast
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from adapters.services.igdb_types import GameType
|
||||
from adapters.services.igdb_types import (
|
||||
AlternativeName,
|
||||
ExpandableField,
|
||||
Game,
|
||||
GameLocalization,
|
||||
GameType,
|
||||
)
|
||||
from handler.metadata.base_handler import PS1_SERIAL_INDEX_KEY
|
||||
from handler.metadata.igdb_handler import (
|
||||
FAMICOM_IGDB_ID,
|
||||
@@ -14,6 +21,7 @@ from handler.metadata.igdb_handler import (
|
||||
SNES_IGDB_ID,
|
||||
SUPER_FAMICOM_IGDB_ID,
|
||||
IGDBHandler,
|
||||
IGDBMetadata,
|
||||
_build_platforms_where,
|
||||
_platform_igdb_ids_with_twin,
|
||||
extract_metadata_from_igdb_rom,
|
||||
@@ -29,12 +37,20 @@ def _make_game(
|
||||
name: str,
|
||||
alternative_names: list[str] | None = None,
|
||||
game_localizations: list[str] | None = None,
|
||||
) -> dict:
|
||||
"""Build a minimal IGDB Game dict for testing.
|
||||
) -> Game:
|
||||
"""Build a minimal IGDB Game for testing.
|
||||
|
||||
``alternative_names`` and ``game_localizations`` accept plain title strings
|
||||
and are wrapped into the ``{"name": ...}`` shape IGDB returns.
|
||||
"""
|
||||
alt_names: list[ExpandableField[AlternativeName]] = [
|
||||
AlternativeName(id=i, name=n)
|
||||
for i, n in enumerate(alternative_names or [], start=1)
|
||||
]
|
||||
localizations: list[ExpandableField[GameLocalization]] = [
|
||||
GameLocalization(id=i, name=n)
|
||||
for i, n in enumerate(game_localizations or [], start=1)
|
||||
]
|
||||
return {
|
||||
"id": game_id,
|
||||
"name": name,
|
||||
@@ -42,14 +58,11 @@ def _make_game(
|
||||
"summary": "",
|
||||
"total_rating": 0.0,
|
||||
"aggregated_rating": 0.0,
|
||||
"first_release_date": None,
|
||||
"artworks": [],
|
||||
"cover": None,
|
||||
"screenshots": [],
|
||||
"platforms": [{"id": GENESIS_IGDB_ID, "name": "Sega Mega Drive/Genesis"}],
|
||||
"alternative_names": [{"name": n} for n in (alternative_names or [])],
|
||||
"alternative_names": alt_names,
|
||||
"genres": [],
|
||||
"franchise": None,
|
||||
"franchises": [],
|
||||
"collections": [],
|
||||
"game_modes": [],
|
||||
@@ -64,7 +77,7 @@ def _make_game(
|
||||
"videos": [],
|
||||
"age_ratings": [],
|
||||
"multiplayer_modes": [],
|
||||
"game_localizations": [{"name": n} for n in (game_localizations or [])],
|
||||
"game_localizations": localizations,
|
||||
}
|
||||
|
||||
|
||||
@@ -882,10 +895,10 @@ class TestSearchRomPrefixSupersetVariant:
|
||||
search_mock.assert_not_awaited()
|
||||
|
||||
|
||||
def _extract_metadata(**overrides) -> dict:
|
||||
def _extract_metadata(**overrides: Any) -> IGDBMetadata:
|
||||
"""Run the extractor over a minimal game with the given fields overridden."""
|
||||
game = _make_game(1, "Test Game")
|
||||
game.update(overrides)
|
||||
game.update(cast("Game", overrides))
|
||||
return extract_metadata_from_igdb_rom(IGDBHandler(), game, GENESIS_IGDB_ID)
|
||||
|
||||
|
||||
|
||||
@@ -5,11 +5,13 @@ lightweight stand-ins rather than database rows.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import cast
|
||||
|
||||
from handler.recommendation.diversity import (
|
||||
cap_by_series,
|
||||
series_keys,
|
||||
)
|
||||
from models.rom import Rom
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -110,7 +112,7 @@ def test_unresolvable_items_are_dropped():
|
||||
def test_series_keys_returns_every_franchise_and_collection():
|
||||
entry = rom(1, collection="Madden NFL", franchises=["Madden", "NFL"])
|
||||
|
||||
assert series_keys(entry) == {"Madden", "NFL", "Madden NFL"}
|
||||
assert series_keys(cast("Rom", entry)) == {"Madden", "NFL", "Madden NFL"}
|
||||
|
||||
|
||||
def test_a_series_listed_under_several_names_shares_one_allowance():
|
||||
|
||||
@@ -23,7 +23,7 @@ import argparse
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
from typing import Any
|
||||
from typing import Any, cast
|
||||
|
||||
# Allow running as `python3 tools/backfill_igdb_tags.py` from backend/.
|
||||
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
|
||||
@@ -111,15 +111,17 @@ async def fetch_tags(igdb_ids: list[int]) -> dict[int, dict[str, Any]]:
|
||||
game_id = game.get("id")
|
||||
if game_id is None:
|
||||
continue
|
||||
# Keyed by the loop variables below, which a TypedDict cannot answer.
|
||||
fields = cast("dict[str, Any]", game)
|
||||
values: dict[str, Any] = {
|
||||
key: [
|
||||
entry.get("name", "")
|
||||
for entry in (game.get(key) or [])
|
||||
for entry in (fields.get(key) or [])
|
||||
if isinstance(entry, dict) and entry.get("name")
|
||||
]
|
||||
for key in TAG_KEYS
|
||||
}
|
||||
values.update({key: game.get(key, 0) for key in SCALAR_KEYS})
|
||||
values.update({key: fields.get(key, 0) for key in SCALAR_KEYS})
|
||||
involved = game.get("involved_companies") or []
|
||||
for key, role in ROLE_KEYS.items():
|
||||
values[key] = [
|
||||
|
||||
@@ -526,16 +526,16 @@ def main() -> int:
|
||||
# rather than echoed: the point of the line is the sampling flags.
|
||||
flags: list[str] = []
|
||||
skip_next = False
|
||||
for token in sys.argv[1:]:
|
||||
for arg in sys.argv[1:]:
|
||||
if skip_next:
|
||||
skip_next = False
|
||||
continue
|
||||
if token == "--report":
|
||||
if arg == "--report":
|
||||
skip_next = True
|
||||
continue
|
||||
if token.startswith("--report="):
|
||||
if arg.startswith("--report="):
|
||||
continue
|
||||
flags.append(token)
|
||||
flags.append(arg)
|
||||
|
||||
write_report(
|
||||
args.report,
|
||||
|
||||
Reference in New Issue
Block a user