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

312 lines
8.8 KiB
Python

from io import BytesIO
from unittest import mock
from fastapi import status
from tests.factories import make_screenshot
from handler.database import db_screenshot_handler
from handler.database.base_handler import sync_session
from models.assets import Screenshot
from models.permission import HiddenEntity, PermEntity
from models.platform import Platform
from models.rom import Rom
from models.user import User
def _auth(token: str) -> dict[str, str]:
return {"Authorization": f"Bearer {token}"}
def _hide(entity: PermEntity, entity_id: int, user_id: int) -> None:
with sync_session.begin() as s:
s.add(HiddenEntity(entity=entity, entity_id=entity_id, user_id=user_id))
# ---------- POST /api/screenshots ----------
@mock.patch(
"endpoints.screenshots.fs_asset_handler.write_file", new_callable=mock.AsyncMock
)
@mock.patch("endpoints.screenshots.scan_screenshot", new_callable=mock.AsyncMock)
def test_upload_gallery_screenshot_sets_flags(
mock_scan,
_mock_write,
client,
access_token: str,
rom: Rom,
platform: Platform,
admin_user: User,
):
mock_scan.return_value = Screenshot(
file_name="shot1.png",
file_name_no_tags="shot1",
file_name_no_ext="shot1",
file_extension="png",
file_path=f"{platform.slug}/screenshots",
file_size_bytes=100,
)
response = client.post(
f"/api/screenshots?rom_id={rom.id}",
files={"screenshotFile": ("shot1.png", BytesIO(b"img"), "image/png")},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["is_gallery"] is True
assert data["is_public"] is False
@mock.patch(
"endpoints.screenshots.fs_asset_handler.write_file", new_callable=mock.AsyncMock
)
@mock.patch("endpoints.screenshots.scan_screenshot", new_callable=mock.AsyncMock)
def test_upload_rejects_invalid_extension(
_mock_scan,
_mock_write,
client,
access_token: str,
rom: Rom,
):
response = client.post(
f"/api/screenshots?rom_id={rom.id}",
files={"screenshotFile": ("notes.txt", BytesIO(b"nope"), "text/plain")},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "Unsupported image file type" in response.json()["detail"]
# ---------- PUT /api/screenshots/{id} (visibility) ----------
def test_update_visibility_owner(client, access_token: str, screenshot: Screenshot):
response = client.put(
f"/api/screenshots/{screenshot.id}",
json={"is_public": True},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["is_public"] is True
refreshed = db_screenshot_handler.get_screenshot_by_id(screenshot.id)
assert refreshed is not None and refreshed.is_public is True
def test_update_visibility_other_user_returns_404(
client,
access_token: str,
rom: Rom,
editor_user: User,
):
others = make_screenshot(rom, editor_user, "other.png", file_size_bytes=10)
response = client.put(
f"/api/screenshots/{others.id}",
json={"is_public": True},
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
# ---------- DELETE /api/screenshots/{id} ----------
@mock.patch(
"endpoints.screenshots.fs_asset_handler.remove_file", new_callable=mock.AsyncMock
)
def test_delete_screenshot_owner(
_mock_remove,
client,
access_token: str,
screenshot: Screenshot,
):
response = client.delete(
f"/api/screenshots/{screenshot.id}",
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_200_OK
assert db_screenshot_handler.get_screenshot_by_id(screenshot.id) is None
@mock.patch(
"endpoints.screenshots.fs_asset_handler.remove_file", new_callable=mock.AsyncMock
)
def test_delete_screenshot_other_user_returns_404(
_mock_remove,
client,
access_token: str,
rom: Rom,
editor_user: User,
):
others = make_screenshot(rom, editor_user, "other.png", file_size_bytes=10)
response = client.delete(
f"/api/screenshots/{others.id}",
headers=_auth(access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert db_screenshot_handler.get_screenshot_by_id(others.id) is not None
# ---------- Gallery visibility query ----------
def _add_screenshot(rom, user, name, *, is_gallery, is_public):
return make_screenshot(
rom,
user,
f"{name}.png",
file_size_bytes=10,
is_gallery=is_gallery,
is_public=is_public,
)
def test_gallery_query_excludes_thumbnails_and_others_private(
rom: Rom,
admin_user: User,
editor_user: User,
):
# Own save/state thumbnail, not a gallery upload.
_add_screenshot(rom, admin_user, "thumb", is_gallery=False, is_public=False)
# Own private gallery screenshot, visible to self.
mine = _add_screenshot(rom, admin_user, "mine", is_gallery=True, is_public=False)
# Another user's public gallery screenshot, visible (community).
others_public = _add_screenshot(
rom, editor_user, "pub", is_gallery=True, is_public=True
)
# Another user's private gallery screenshot, hidden.
_add_screenshot(rom, editor_user, "priv", is_gallery=True, is_public=False)
visible = {
s.id
for s in db_screenshot_handler.get_rom_gallery_screenshots(
rom_id=rom.id, user_id=admin_user.id
)
}
assert mine.id in visible
assert others_public.id in visible
assert len(visible) == 2
# ---------- GET /api/screenshots/{id}/content ----------
@mock.patch("endpoints.screenshots.fs_asset_handler.validate_path")
def test_owner_downloads_own_screenshot(
mock_validate_path,
client,
access_token: str,
admin_user: User,
rom: Rom,
tmp_path,
):
screenshot = _add_screenshot(
rom, admin_user, "shot", is_gallery=True, is_public=False
)
test_file = tmp_path / "shot.png"
test_file.write_bytes(b"SHOT_DATA")
mock_validate_path.return_value = test_file
response = client.get(
f"/api/screenshots/{screenshot.id}/content", headers=_auth(access_token)
)
assert response.status_code == status.HTTP_200_OK
assert response.content == b"SHOT_DATA"
def test_other_user_cannot_download_private_screenshot(
client,
viewer_access_token: str,
admin_user: User,
rom: Rom,
):
screenshot = _add_screenshot(
rom, admin_user, "shot", is_gallery=True, is_public=False
)
response = client.get(
f"/api/screenshots/{screenshot.id}/content",
headers=_auth(viewer_access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
@mock.patch("endpoints.screenshots.fs_asset_handler.validate_path")
def test_other_user_downloads_public_screenshot(
mock_validate_path,
client,
viewer_access_token: str,
admin_user: User,
rom: Rom,
tmp_path,
):
screenshot = _add_screenshot(
rom, admin_user, "shot", is_gallery=True, is_public=True
)
test_file = tmp_path / "shot.png"
test_file.write_bytes(b"SHARED_SHOT")
mock_validate_path.return_value = test_file
response = client.get(
f"/api/screenshots/{screenshot.id}/content",
headers=_auth(viewer_access_token),
)
assert response.status_code == status.HTTP_200_OK
assert response.content == b"SHARED_SHOT"
def test_hidden_rom_masks_public_screenshot_download(
client,
viewer_access_token: str,
viewer_user: User,
admin_user: User,
rom: Rom,
):
# A public screenshot on a ROM hidden from the caller must stay 404-masked;
# sharing cannot override the hidden-resource boundary.
screenshot = _add_screenshot(
rom, admin_user, "shot", is_gallery=True, is_public=True
)
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
response = client.get(
f"/api/screenshots/{screenshot.id}/content",
headers=_auth(viewer_access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_hidden_platform_masks_public_screenshot_download(
client,
viewer_access_token: str,
viewer_user: User,
admin_user: User,
rom: Rom,
platform: Platform,
):
# Hiding the parent platform cascades to its screenshots as well.
screenshot = _add_screenshot(
rom, admin_user, "shot", is_gallery=True, is_public=True
)
_hide(PermEntity.PLATFORMS, platform.id, viewer_user.id)
response = client.get(
f"/api/screenshots/{screenshot.id}/content",
headers=_auth(viewer_access_token),
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_download_screenshot_not_found(client, access_token: str):
response = client.get("/api/screenshots/99999/content", headers=_auth(access_token))
assert response.status_code == status.HTTP_404_NOT_FOUND