Files
romm/backend/tests/endpoints/roms/test_random.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

283 lines
9.2 KiB
Python

"""Tests for `GET /api/roms/random` (issue #4066).
The endpoint replaces the two-call "count the library, then fetch the row at a
random offset" dance the Home widget used to run. Paging to a random offset
costs more the bigger the library gets, so these tests pin both the behaviour
(a rom from the requested scope, every rom reachable) and the mechanism (no
offset walk, no full count).
"""
from collections import Counter
from unittest.mock import patch
import pytest
from fastapi import status
from fastapi.testclient import TestClient
from tests.factories import make_rom
from handler.database import (
db_collection_handler,
db_platform_handler,
db_rom_handler,
roms_handler,
)
from handler.database.base_handler import sync_session
from models.collection import Collection
from models.permission import HiddenEntity, PermEntity
from models.platform import Platform
from models.rom import Rom
from models.user import User
@pytest.fixture
def other_platform() -> Platform:
return db_platform_handler.add_platform(
Platform(
name="other_platform",
slug="other_platform_slug",
fs_slug="other_platform_slug",
)
)
def test_get_random_rom_returns_a_rom(
client: TestClient, access_token: str, rom: Rom
) -> None:
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body is not None
assert body["id"] == rom.id
# The widget renders cover, platform and release year straight off the pick.
assert body["platform_slug"] == rom.platform_slug
def test_get_random_rom_requires_auth(client: TestClient) -> None:
response = client.get("/api/roms/random")
assert response.status_code == status.HTTP_401_UNAUTHORIZED
def test_get_random_rom_without_roms_returns_null(
client: TestClient, access_token: str, platform: Platform
) -> None:
"""An empty library is not an error: the widget shows its own empty copy."""
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json() is None
def test_get_random_rom_reaches_every_rom(
client: TestClient, access_token: str, rom: Rom, platform: Platform
) -> None:
"""Sampling must cover the whole set, not park on one end of it."""
ids = {rom.id} | {make_rom(platform, f"rom_{i}").id for i in range(4)}
seen: Counter[int] = Counter()
for _ in range(120):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
seen[response.json()["id"]] += 1
assert set(seen) == ids
def test_get_random_rom_scoped_to_platform(
client: TestClient,
access_token: str,
rom: Rom,
platform: Platform,
other_platform: Platform,
) -> None:
other_ids = {make_rom(other_platform, f"other_{i}").id for i in range(3)}
for _ in range(20):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
params={"platform_ids": [other_platform.id]},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["id"] in other_ids
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
params={"platform_ids": [platform.id]},
)
assert response.json()["id"] == rom.id
def test_get_random_rom_scoped_to_collection(
client: TestClient,
access_token: str,
admin_user: User,
rom: Rom,
platform: Platform,
) -> None:
in_collection = make_rom(platform, "in_collection")
make_rom(platform, "out_of_collection")
collection = db_collection_handler.add_collection(
Collection(name="Picks", description="", user_id=admin_user.id)
)
db_collection_handler.add_roms_to_collection(collection.id, [in_collection.id])
for _ in range(10):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
params={"collection_id": collection.id},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["id"] == in_collection.id
def test_get_random_rom_scoped_to_empty_collection_returns_null(
client: TestClient, access_token: str, admin_user: User, rom: Rom
) -> None:
"""No sampled key can land in an empty scope, so this is the fallback's null."""
collection = db_collection_handler.add_collection(
Collection(name="Empty", description="", user_id=admin_user.id)
)
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
params={"collection_id": collection.id},
)
assert response.status_code == status.HTTP_200_OK
assert response.json() is None
def test_get_random_rom_skips_hidden_roms(
client: TestClient,
viewer_user: User,
viewer_access_token: str,
rom: Rom,
platform: Platform,
) -> None:
"""Admin-hidden roms are out of scope for the pick, like any other list."""
visible = make_rom(platform, "visible_rom")
with sync_session.begin() as session:
session.add(
HiddenEntity(
entity=PermEntity.ROMS, entity_id=rom.id, user_id=viewer_user.id
)
)
for _ in range(30):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {viewer_access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["id"] == visible.id
def test_get_random_rom_rechecks_visibility_after_fetching(
client: TestClient,
viewer_user: User,
viewer_access_token: str,
rom: Rom,
platform: Platform,
) -> None:
"""The pick is re-checked against the row that came back, not the filter.
The id is chosen by a filtered query but fetched by raw id, so a rom that
moved to a hidden platform in between would arrive hidden. Standing in for
that race by handing the endpoint a rom the filter would have excluded.
"""
# A visible rom so the pick resolves an id, otherwise the empty scope
# returns null on its own and the fetch is never reached.
make_rom(platform, "visible_rom")
with sync_session.begin() as session:
session.add(
HiddenEntity(
entity=PermEntity.ROMS, entity_id=rom.id, user_id=viewer_user.id
)
)
with patch.object(db_rom_handler, "get_rom_simple", return_value=rom):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {viewer_access_token}"},
)
assert response.status_code == status.HTTP_200_OK
# Null, not 404: a hidden rom stays indistinguishable from an empty scope.
assert response.json() is None
def test_get_random_rom_does_not_page_or_count(
client: TestClient,
access_token: str,
rom: Rom,
platform: Platform,
executed_statements: list[str],
) -> None:
"""The point of the endpoint: cost that doesn't grow with the library.
Both mechanisms it replaces walk the whole filtered set: an OFFSET steps
over every preceding row, and the total was its own count of the library.
Sampling primary keys does neither, and consecutively-numbered roms always
land it a hit.
"""
for i in range(5):
make_rom(platform, f"rom_{i}")
executed_statements.clear()
with (
patch.object(
db_rom_handler, "get_rom_count", wraps=db_rom_handler.get_rom_count
) as get_rom_count,
patch.object(
db_rom_handler, "get_rom_id_index", wraps=db_rom_handler.get_rom_id_index
) as get_rom_id_index,
):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
get_rom_count.assert_not_called()
get_rom_id_index.assert_not_called()
rom_queries = [sql for sql in executed_statements if " roms" in sql.lower()]
assert rom_queries, "expected the pick to query the roms table"
assert not [sql for sql in rom_queries if "offset" in sql.lower()]
def test_get_random_rom_falls_back_when_sampling_misses(
client: TestClient, access_token: str, rom: Rom, platform: Platform
) -> None:
"""A scope the sampled keys never hit still resolves a pick.
Sampling zero keys stands in for the real cases: a narrow filter, or an id
space left sparse by deletions.
"""
ids = {rom.id} | {make_rom(platform, f"rom_{i}").id for i in range(4)}
seen: set[int] = set()
with patch.object(roms_handler, "RANDOM_ID_SAMPLE_SIZE", 0):
for _ in range(120):
response = client.get(
"/api/roms/random",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
seen.add(response.json()["id"])
# The fallback is a position in the set, so it reaches all of it too.
assert seen == ids