Files
romm/backend/tests/endpoints/test_collection.py
Georges-Antoine Assi 2d7b9e3c34 test(api): check that routes document the error statuses they raise (#5686)
* test(api): check that routes document the error statuses they raise

protected_route now documents the scope guard's 401 and 403 on every
route that declares scopes, appending to a route's own description when
it has one.

tools/route_errors.py follows each route's calls through imports,
handler instances, custom exception classes and HTTPException subclasses
to the statuses it can raise. test_raised_statuses_are_documented fails
on a status the route's responses= leaves out, against a baseline of
existing gaps that can only shrink.

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

* docs(api): document error responses for roms routes

Describe every 4xx and 5xx the rom routes and their helpers raise in each
decorator's responses=, so the OpenAPI schema lists them. A hidden rom,
platform or file is described like a missing one.

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

* docs(api): document error responses for saves routes

Describe every 4xx/5xx the saves, states, screenshots, snapshots,
play-sessions and sync routes raise in their responses=, and rewrite the
states identifiers docstring that carried Args/Returns blocks.

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

* docs(api): document error responses for devices routes

Describe the 4xx/5xx statuses that the device, device auth, install,
client token, notification, notification channel, sync channel and
heartbeat routes raise, and fill the empty install route entries.
Rewrite the setup and heartbeat docstrings that published Args and
Returns blocks.

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

* docs(api): document error responses for streaming routes

Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim.

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

* docs(api): document error responses for admin routes

Describe the 4xx and 5xx statuses the config, permissions, user, auth,
tasks, logs, activity and export routes raise, and rewrite their
Args/Returns docstrings as plain operation descriptions.

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

* docs(api): document error responses for library routes

Describe the 400/403/404/409/500 statuses the collection, feed, firmware,
platform, music, playlist and search routes raise, and replace route
docstrings that carried Args/Returns blocks with plain sentences.

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

* fix(api): answer like a missing resource for hidden play sessions and private collections

DELETE /play-sessions/{id} deleted the caller's session even on a rom
hidden from them, so 204 versus 404 showed the session existed. The
handler now takes the caller's rom visibility.

Another user's private collection, smart collection or playlist
answered 403, which showed it existed. It now answers 404 on every
route; a public one the caller does not own still answers 403 on write.

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

* docs(api): describe private collections and playlists as missing

Matches #5686, where another user's private collection or playlist
answers 404 and a play session on a hidden rom answers like a missing
one. The read routes drop their 403, and the write 403 now covers only
a public resource another user owns.

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

* docs(collections): use #5693's docstrings on the routes this PR touches

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

* docs(api): address Greptile review on route error docs

Fold the nine multi-paragraph route docstrings into one line, and keep
the device-scope 403 descriptions in utils/auth.py next to
resolve_device, which raises them, instead of in both saves.py and
states.py.

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

* test(api): follow route dependencies in the status analyzer

Addresses Greptile's review: route_errors now follows the callable in
Depends(...) and Security(...), whether it is a parameter default or
inside an Annotated alias, and the module docstring is one line.

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

* docs(api): tighten wording of route error descriptions

Give clipped responses descriptions and helper docstrings their missing
subjects and verbs, use 'the caller lacks' and 'is not allowed to'
consistently, and replace 'picked' with 'chosen'.

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

* test(api): drop the route error baseline

Every status left in the baseline was one a client cannot get:

- The export routes' empty platform list check is dead, since FastAPI
  answers a missing required list query with 422. Removed.
- get_save_layouts went through _restore_error, whose 500 fallback it
  cannot reach. It raises its 400 and 503 directly now.
- The notification test and confirm routes only catch ChannelError,
  since the cooldown and email errors come from other actions.
- The analyzer now skips asyncio.gather(..., return_exceptions=True),
  which covers search_rom.
- A '# route-errors: ignore' marker, with its reason, skips code whose
  errors never reach the client: the metadata heartbeat probe, the
  force-release teardowns, and the legacy save adoption.

The check now fails on any undocumented status.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:00:18 -05:00

1392 lines
49 KiB
Python

import json
from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, patch
import pytest
from fastapi import status
from tests.utils.test_images import jxl_image_bytes
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
from handler.auth.base_handler import oauth_handler
from handler.database import db_collection_handler
from handler.filesystem.resources_handler import FSResourcesHandler
from models.collection import COLLECTION_NAME_MAX_LENGTH, Collection, SmartCollection
from models.rom import Rom
from models.user import User
# Minimal valid PNG (1x1 transparent pixel)
_PNG_BYTES = (
b"\x89PNG\r\n\x1a\n"
b"\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01"
b"\x08\x06\x00\x00\x00\x1f\x15\xc4\x89"
b"\x00\x00\x00\rIDATx\x9cc\xfc\xff\xff?\x00\x05\xfe\x02\xfe\xa75\x81\x84"
b"\x00\x00\x00\x00IEND\xaeB`\x82"
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def collection(admin_user: User) -> Collection:
return db_collection_handler.add_collection(
Collection(
name="Test Collection",
description="A test collection",
is_public=False,
is_favorite=False,
user_id=admin_user.id,
)
)
@pytest.fixture
def favorite_collection(admin_user: User) -> Collection:
return db_collection_handler.add_collection(
Collection(
name="Favorites",
description="",
is_public=False,
is_favorite=True,
user_id=admin_user.id,
)
)
@pytest.fixture
def other_user_token(editor_user: User) -> str:
"""Access token for a second user, used to test ownership checks."""
return oauth_handler.create_access_token(
data={
"sub": editor_user.username,
"iss": "romm:oauth",
"scopes": " ".join(editor_user.oauth_scopes),
},
expires_delta=timedelta(seconds=OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS),
)
@pytest.fixture
def other_user_collection(editor_user: User) -> Collection:
"""A collection owned by the editor user, not the admin user."""
return db_collection_handler.add_collection(
Collection(
name="Editor Collection",
description="",
is_public=False,
is_favorite=False,
user_id=editor_user.id,
)
)
# ---------------------------------------------------------------------------
# Collection CRUD
# ---------------------------------------------------------------------------
class TestCreateCollection:
def test_creates_collection(self, client, access_token: str):
response = client.post(
"/api/collections",
data={"name": "My Games", "description": "Classic games"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["name"] == "My Games"
assert data["description"] == "Classic games"
assert data["is_favorite"] is False
assert data["is_public"] is False
assert data["rom_ids"] == []
def test_creates_favorite_collection(self, client, access_token: str):
response = client.post(
"/api/collections",
data={"name": "Favorites"},
params={"is_favorite": True},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["is_favorite"] is True
def test_duplicate_name_returns_conflict(
self, client, access_token: str, collection: Collection
):
response = client.post(
"/api/collections",
data={"name": collection.name},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_409_CONFLICT
def test_name_over_column_length_is_rejected(self, client, access_token: str):
response = client.post(
"/api/collections",
data={"name": "a" * (COLLECTION_NAME_MAX_LENGTH + 1)},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
def test_requires_auth(self, client):
response = client.post("/api/collections", data={"name": "No Auth"})
assert response.status_code in (
status.HTTP_401_UNAUTHORIZED,
status.HTTP_403_FORBIDDEN,
)
class TestRenameCollection:
def test_taken_name_returns_conflict(
self,
client,
access_token: str,
collection: Collection,
favorite_collection: Collection,
):
response = client.put(
f"/api/collections/{collection.id}",
data={"rom_ids": "[]", "name": favorite_collection.name},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_409_CONFLICT
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None and refreshed.name == "Test Collection"
def test_own_name_in_another_case_is_allowed(
self, client, access_token: str, collection: Collection
):
response = client.put(
f"/api/collections/{collection.id}",
data={"rom_ids": "[]", "name": "TEST COLLECTION"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["name"] == "TEST COLLECTION"
@pytest.mark.parametrize("rom_ids", ["5", "null", '{"1": 1}', '["1"]', "[1"])
def test_rom_ids_must_be_a_list_of_ids(
self, client, access_token: str, collection: Collection, rom_ids: str
):
response = client.put(
f"/api/collections/{collection.id}",
data={"rom_ids": rom_ids},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT
def test_taken_smart_collection_name_returns_conflict(
self, client, access_token: str, admin_user: User
):
first, second = (
db_collection_handler.add_smart_collection(
SmartCollection(
name=name, description="", user_id=admin_user.id, filter_criteria={}
)
)
for name in ("First", "Second")
)
response = client.put(
f"/api/collections/smart/{second.id}",
data={"name": first.name},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_409_CONFLICT
class TestGetCollections:
def test_returns_own_collections(
self, client, access_token: str, collection: Collection
):
response = client.get(
"/api/collections",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert len(data) == 1
assert data[0]["id"] == collection.id
assert data[0]["name"] == collection.name
def test_returns_public_collections_from_other_users(
self,
client,
access_token: str,
admin_user: User,
editor_user: User,
):
public_col = db_collection_handler.add_collection(
Collection(
name="Public Editor Collection",
description="",
is_public=True,
is_favorite=False,
user_id=editor_user.id,
)
)
db_collection_handler.add_collection(
Collection(
name="Private Editor Collection",
description="",
is_public=False,
is_favorite=False,
user_id=editor_user.id,
)
)
response = client.get(
"/api/collections",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
ids = [c["id"] for c in response.json()]
assert public_col.id in ids
def test_empty_when_no_collections(self, client, access_token: str):
response = client.get(
"/api/collections",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json() == []
class TestDeleteCollection:
def test_deletes_own_collection(
self, client, access_token: str, collection: Collection
):
response = client.delete(
f"/api/collections/{collection.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert db_collection_handler.get_collection(collection.id) is None
def test_another_users_private_collection_answers_like_a_missing_one(
self,
client,
access_token: str,
other_user_collection: Collection,
):
response = client.delete(
f"/api/collections/{other_user_collection.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_cannot_delete_another_users_public_collection(
self,
client,
access_token: str,
other_user_collection: Collection,
):
db_collection_handler.update_collection(
other_user_collection.id, {"is_public": True}
)
response = client.delete(
f"/api/collections/{other_user_collection.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_403_FORBIDDEN
def test_returns_404_for_missing_collection(self, client, access_token: str):
response = client.delete(
"/api/collections/999999",
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
# ---------------------------------------------------------------------------
# POST /collections/{id}/roms (atomic add)
# ---------------------------------------------------------------------------
class TestAddRomsToCollection:
def test_adds_roms_to_empty_collection(
self, client, access_token: str, collection: Collection, rom: Rom
):
response = client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert rom.id in data["rom_ids"]
assert data["rom_count"] == 1
def test_adds_multiple_roms(
self,
client,
access_token: str,
collection: Collection,
rom: Rom,
second_rom: Rom,
):
response = client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id, second_rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert set(data["rom_ids"]) == {rom.id, second_rom.id}
assert data["rom_count"] == 2
def test_is_idempotent_no_duplicates(
self, client, access_token: str, collection: Collection, rom: Rom
):
"""Adding a ROM that is already in the collection should not duplicate it."""
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
response = client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert data["rom_ids"].count(rom.id) == 1
assert data["rom_count"] == 1
def test_preserves_existing_roms_when_adding_new(
self,
client,
access_token: str,
collection: Collection,
rom: Rom,
second_rom: Rom,
):
"""Adding a new ROM must not remove previously added ROMs."""
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
response = client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [second_rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert set(data["rom_ids"]) == {rom.id, second_rom.id}
def test_silently_ignores_nonexistent_rom_ids(
self, client, access_token: str, collection: Collection
):
"""Invalid ROM IDs should be filtered out without raising an error."""
response = client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [999999]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["rom_count"] == 0
def test_returns_404_for_missing_collection(
self, client, access_token: str, rom: Rom
):
response = client.post(
"/api/collections/999999/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_returns_404_for_other_users_private_collection(
self,
client,
access_token: str,
other_user_collection: Collection,
rom: Rom,
):
response = client.post(
f"/api/collections/{other_user_collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_requires_auth(self, client, collection: Collection, rom: Rom):
response = client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
)
assert response.status_code in (
status.HTTP_401_UNAUTHORIZED,
status.HTTP_403_FORBIDDEN,
)
def test_bumps_updated_at(
self, client, access_token: str, collection: Collection, rom: Rom
):
# Record time before call (truncated to seconds to match MariaDB precision)
before_call = datetime.now(timezone.utc).replace(microsecond=0, tzinfo=None)
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None
assert refreshed.updated_at.replace(tzinfo=None) >= before_call
# ---------------------------------------------------------------------------
# DELETE /collections/{id}/roms (atomic remove)
# ---------------------------------------------------------------------------
class TestRemoveRomsFromCollection:
def _seed(self, client, access_token, collection_id, rom_ids):
"""Helper: add ROMs to a collection before testing removal."""
client.post(
f"/api/collections/{collection_id}/roms",
json={"rom_ids": rom_ids},
headers={"Authorization": f"Bearer {access_token}"},
)
def test_removes_rom_from_collection(
self, client, access_token: str, collection: Collection, rom: Rom
):
self._seed(client, access_token, collection.id, [rom.id])
response = client.request(
"DELETE",
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert rom.id not in data["rom_ids"]
assert data["rom_count"] == 0
def test_removes_only_specified_roms(
self,
client,
access_token: str,
collection: Collection,
rom: Rom,
second_rom: Rom,
):
self._seed(client, access_token, collection.id, [rom.id, second_rom.id])
response = client.request(
"DELETE",
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
data = response.json()
assert rom.id not in data["rom_ids"]
assert second_rom.id in data["rom_ids"]
assert data["rom_count"] == 1
def test_removing_absent_rom_is_a_noop(
self, client, access_token: str, collection: Collection, rom: Rom
):
"""Removing a ROM that isn't in the collection should not raise an error."""
response = client.request(
"DELETE",
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["rom_count"] == 0
def test_returns_404_for_missing_collection(
self, client, access_token: str, rom: Rom
):
response = client.request(
"DELETE",
"/api/collections/999999/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_returns_404_for_other_users_private_collection(
self,
client,
access_token: str,
other_user_collection: Collection,
rom: Rom,
):
response = client.request(
"DELETE",
f"/api/collections/{other_user_collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_requires_auth(self, client, collection: Collection, rom: Rom):
response = client.request(
"DELETE",
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
)
assert response.status_code in (
status.HTTP_401_UNAUTHORIZED,
status.HTTP_403_FORBIDDEN,
)
def test_bumps_updated_at(
self, client, access_token: str, collection: Collection, rom: Rom
):
self._seed(client, access_token, collection.id, [rom.id])
# Record time before the remove call (truncated to seconds for MariaDB precision)
before_remove = datetime.now(timezone.utc).replace(microsecond=0, tzinfo=None)
client.request(
"DELETE",
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None
assert refreshed.updated_at.replace(tzinfo=None) >= before_remove
# ---------------------------------------------------------------------------
# Race condition regression: concurrent adds must not lose data
# ---------------------------------------------------------------------------
class TestAtomicBehavior:
def test_sequential_adds_accumulate(
self,
client,
access_token: str,
collection: Collection,
rom: Rom,
second_rom: Rom,
):
"""
Simulates the corrected behavior: two separate add calls, each with a
single ROM, should result in both ROMs being present, even if they
arrive close together. This would previously fail under the full-replace
approach when requests arrived out of order.
"""
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [second_rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None
assert set(refreshed.rom_ids) == {rom.id, second_rom.id}
def test_interleaved_add_remove_stays_consistent(
self,
client,
access_token: str,
collection: Collection,
rom: Rom,
second_rom: Rom,
):
"""
Add both ROMs, remove one, add it back. The final state should
reflect only the last operation per ROM.
"""
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id, second_rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
client.request(
"DELETE",
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
client.post(
f"/api/collections/{collection.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None
assert set(refreshed.rom_ids) == {rom.id, second_rom.id}
# ---------------------------------------------------------------------------
# Artwork upload validation
# ---------------------------------------------------------------------------
class TestArtworkUpload:
def test_add_collection_rejects_non_image_artwork(self, client, access_token: str):
response = client.post(
"/api/collections",
data={"name": "Bad Cover Collection"},
files={"artwork": ("cover.png", b"<script>alert(1)</script>", "image/png")},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "PNG, JPEG, WebP, GIF, or JPEG XL" in response.json()["detail"]
@patch.object(
FSResourcesHandler,
"store_artwork",
new_callable=AsyncMock,
return_value=("path/to/big.png", "path/to/small.png"),
)
def test_add_collection_artwork_uses_detected_extension(
self,
store_artwork_mock: AsyncMock,
client,
access_token: str,
):
response = client.post(
"/api/collections",
data={"name": "Good Cover Collection"},
files={"artwork": ("payload.html", _PNG_BYTES, "image/png")},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert store_artwork_mock.called
_, _, file_ext = store_artwork_mock.call_args.args
assert file_ext == "png"
@patch.object(
FSResourcesHandler,
"store_artwork",
new_callable=AsyncMock,
return_value=("path/to/big.png", "path/to/small.png"),
)
def test_add_collection_accepts_jpeg_xl_artwork_as_png(
self,
store_artwork_mock: AsyncMock,
client,
access_token: str,
):
response = client.post(
"/api/collections",
data={"name": "JPEG XL Cover Collection"},
files={"artwork": ("cover.jxl", jxl_image_bytes(), "image/jxl")},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
call_args = store_artwork_mock.call_args
assert call_args is not None
_, _, file_ext = call_args.args
assert file_ext == "png"
def test_update_collection_rejects_non_image_artwork(
self, client, access_token: str, collection: Collection
):
response = client.put(
f"/api/collections/{collection.id}",
data={"rom_ids": "[]"},
files={"artwork": ("cover.png", b"<script>alert(1)</script>", "image/png")},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
assert "PNG, JPEG, WebP, GIF, or JPEG XL" in response.json()["detail"]
@patch.object(
FSResourcesHandler,
"store_artwork",
new_callable=AsyncMock,
return_value=("path/to/big.png", "path/to/small.png"),
)
def test_update_collection_artwork_uses_detected_extension(
self,
store_artwork_mock: AsyncMock,
client,
access_token: str,
collection: Collection,
):
response = client.put(
f"/api/collections/{collection.id}",
data={"rom_ids": "[]"},
files={"artwork": ("payload.html", _PNG_BYTES, "image/png")},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert store_artwork_mock.called
_, _, file_ext = store_artwork_mock.call_args.args
assert file_ext == "png"
class TestLocalFileCoverUrl:
@pytest.mark.parametrize(
"url_cover", ["file://n64/cover.png", "launchbox-file://Images/a.png"]
)
@patch.object(FSResourcesHandler, "get_cover", new_callable=AsyncMock)
def test_add_collection_rejects_local_file_url(
self,
get_cover_mock: AsyncMock,
client,
access_token: str,
admin_user: User,
url_cover: str,
):
response = client.post(
"/api/collections",
data={"name": "Local Cover Collection", "url_cover": url_cover},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
get_cover_mock.assert_not_awaited()
assert (
db_collection_handler.get_collection_by_name(
"Local Cover Collection", admin_user.id
)
is None
)
@pytest.mark.parametrize(
"url_cover", ["file://n64/cover.png", "LAUNCHBOX-FILE://Images/a.png"]
)
@patch.object(FSResourcesHandler, "get_cover", new_callable=AsyncMock)
def test_update_collection_rejects_local_file_url(
self,
get_cover_mock: AsyncMock,
client,
access_token: str,
collection: Collection,
url_cover: str,
):
response = client.put(
f"/api/collections/{collection.id}",
data={"rom_ids": "[]", "url_cover": url_cover},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
get_cover_mock.assert_not_awaited()
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None
assert refreshed.url_cover == collection.url_cover
@patch.object(
FSResourcesHandler,
"get_cover",
new_callable=AsyncMock,
return_value=("small.png", "big.png"),
)
def test_add_collection_accepts_remote_url(
self, get_cover_mock: AsyncMock, client, access_token: str
):
response = client.post(
"/api/collections",
data={
"name": "Remote Cover Collection",
"url_cover": "https://example.com/cover.png",
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
get_cover_mock.assert_awaited_once()
class TestSmartCollectionEndpoints:
"""Smart collections cache their membership on the row, so the create and
update endpoints have to recompute it (the gallery no longer does)."""
def test_create_populates_membership_from_criteria(
self, client, access_token: str, rom: Rom, second_rom: Rom
):
response = client.post(
"/api/collections/smart",
data={
"name": "Everything on the test platform",
"description": "",
"filter_criteria": json.dumps({"platform_ids": [rom.platform_id]}),
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body["rom_count"] == 2
assert set(body["rom_ids"]) == {rom.id, second_rom.id}
def test_update_recomputes_membership(
self, client, access_token: str, admin_user: User, rom: Rom
):
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="Nothing yet",
description="",
user_id=admin_user.id,
filter_criteria={"platform_ids": [rom.platform_id + 999]},
)
)
response = client.put(
f"/api/collections/smart/{smart_collection.id}",
data={"filter_criteria": json.dumps({"platform_ids": [rom.platform_id]})},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["rom_ids"] == [rom.id]
@pytest.mark.parametrize("criteria", ["[]", "1", '"x"', "null"])
def test_non_object_criteria_are_rejected(
self, client, access_token: str, admin_user: User, criteria: str
):
created = client.post(
"/api/collections/smart",
data={"name": "Broken", "is_public": "true", "filter_criteria": criteria},
headers={"Authorization": f"Bearer {access_token}"},
)
assert created.status_code == status.HTTP_400_BAD_REQUEST
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="Valid",
description="",
user_id=admin_user.id,
filter_criteria={},
is_public=True,
)
)
updated = client.put(
f"/api/collections/smart/{smart_collection.id}",
data={"filter_criteria": criteria},
headers={"Authorization": f"Bearer {access_token}"},
)
assert updated.status_code == status.HTTP_400_BAD_REQUEST
listed = client.get(
"/api/collections/smart",
headers={"Authorization": f"Bearer {access_token}"},
)
assert listed.status_code == status.HTTP_200_OK
assert [c["name"] for c in listed.json()] == ["Valid"]
def test_reading_a_smart_collection_does_not_touch_it(
self, client, access_token: str, admin_user: User, rom: Rom
):
# Writing membership back while serving a page bumps `updated_at`, which
# is the `?ts=` cover cache-buster, so every visit re-downloaded
# thumbnails and every `updated_after` sync client saw a change.
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="All roms",
description="",
user_id=admin_user.id,
filter_criteria={"platform_ids": [rom.platform_id]},
)
)
db_collection_handler.refresh_smart_collection(smart_collection.id)
before = db_collection_handler.get_smart_collection(smart_collection.id)
assert before is not None
response = client.get(
"/api/roms",
params={"smart_collection_id": smart_collection.id},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert [item["id"] for item in response.json()["items"]] == [rom.id]
after = db_collection_handler.get_smart_collection(smart_collection.id)
assert after is not None
assert after.updated_at == before.updated_at
assert list(after.rom_ids) == list(before.rom_ids)
assert after.path_covers_small == before.path_covers_small
def test_adding_a_rom_to_a_collection_refreshes_scoped_membership(
self, client, access_token: str, admin_user: User, rom: Rom
):
shelf = db_collection_handler.add_collection(
Collection(name="Shelf", description="", user_id=admin_user.id)
)
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="On the shelf",
description="",
user_id=admin_user.id,
filter_criteria={"collection_id": shelf.id},
)
)
db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.post(
f"/api/collections/{shelf.id}/roms",
json={"rom_ids": [rom.id]},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
refreshed = db_collection_handler.get_smart_collection(smart_collection.id)
assert refreshed is not None
assert refreshed.rom_ids == [rom.id]
def test_setting_a_rom_status_refreshes_membership(
self, client, access_token: str, admin_user: User, rom: Rom
):
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="Finished games",
description="",
user_id=admin_user.id,
filter_criteria={"statuses": ["finished"]},
)
)
db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.put(
f"/api/roms/{rom.id}/props",
json={"status": "finished"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
refreshed = db_collection_handler.get_smart_collection(smart_collection.id)
assert refreshed is not None
assert refreshed.rom_ids == [rom.id]
@pytest.mark.parametrize("field", ("now_playing", "backlogged", "hidden"))
def test_setting_a_rom_flag_refreshes_membership(
self, client, access_token: str, admin_user: User, rom: Rom, field: str
):
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name=f"Flagged {field}",
description="",
user_id=admin_user.id,
filter_criteria={"statuses": [field]},
)
)
db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.put(
f"/api/roms/{rom.id}/props",
json={field: True},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
refreshed = db_collection_handler.get_smart_collection(smart_collection.id)
assert refreshed is not None
assert refreshed.rom_ids == [rom.id]
class TestCollectionVisibility:
"""Sharing is a flag of its own: it must not rewrite what a collection holds."""
def test_sharing_keeps_the_collection_games(
self, client, access_token: str, collection: Collection, rom: Rom
):
db_collection_handler.update_collection(
collection.id, {"description": "kept"}, [rom.id]
)
response = client.put(
f"/api/collections/{collection.id}/visibility",
json={"is_public": True},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert body["is_public"] is True
assert body["rom_ids"] == [rom.id]
assert body["description"] == "kept"
def test_only_the_owner_can_share(
self, client, other_user_token: str, collection: Collection
):
response = client.put(
f"/api/collections/{collection.id}/visibility",
json={"is_public": True},
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
refreshed = db_collection_handler.get_collection(collection.id)
assert refreshed is not None and refreshed.is_public is False
def test_sharing_a_smart_collection_keeps_its_filters(
self, client, access_token: str, admin_user: User, rom: Rom
):
criteria = {"platform_ids": [rom.platform_id]}
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="All roms",
description="",
user_id=admin_user.id,
filter_criteria=criteria,
)
)
response = client.put(
f"/api/collections/smart/{smart_collection.id}/visibility",
json={"is_public": True},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["is_public"] is True
refreshed = db_collection_handler.get_smart_collection(smart_collection.id)
assert refreshed is not None
assert refreshed.is_public is True
assert refreshed.filter_criteria == criteria
def _scope_to(
collection: Collection, owner: User, is_public: bool = False
) -> SmartCollection:
return db_collection_handler.add_smart_collection(
SmartCollection(
name="Scoped",
description="",
user_id=owner.id,
is_public=is_public,
filter_criteria={"collection_id": collection.id},
)
)
def _cached_rom_ids(smart_collection_id: int) -> list[int]:
smart_collection = db_collection_handler.get_smart_collection(smart_collection_id)
assert smart_collection is not None
return smart_collection.rom_ids
class TestRomFiltersRespectCollectionPrivacy:
"""The ROM endpoints take a collection id as a filter, so they must refuse
the same private collections the collection endpoints do."""
@pytest.fixture
def private_collection(self, admin_user: User, rom: Rom) -> Collection:
collection = db_collection_handler.add_collection(
Collection(name="Secret", description="", user_id=admin_user.id)
)
db_collection_handler.add_roms_to_collection(collection.id, [rom.id])
return collection
def test_listing_another_users_private_collection_is_empty(
self, client, other_user_token: str, private_collection: Collection
):
response = client.get(
f"/api/roms?collection_id={private_collection.id}",
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["items"] == []
def test_random_pick_from_another_users_private_collection_is_null(
self, client, other_user_token: str, private_collection: Collection
):
response = client.get(
f"/api/roms/random?collection_id={private_collection.id}",
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json() is None
def test_downloading_another_users_private_collection_is_refused(
self, client, other_user_token: str, private_collection: Collection
):
response = client.get(
f"/api/roms/download?collection_id={private_collection.id}",
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_another_users_public_collection_is_listed(
self,
client,
other_user_token: str,
private_collection: Collection,
rom: Rom,
):
db_collection_handler.update_collection(
private_collection.id, {"is_public": True}
)
response = client.get(
f"/api/roms?collection_id={private_collection.id}",
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert [item["id"] for item in response.json()["items"]] == [rom.id]
def test_another_users_private_smart_collection_is_empty(
self, client, other_user_token: str, admin_user: User, rom: Rom
):
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="Mine",
description="",
user_id=admin_user.id,
filter_criteria={"platform_ids": [rom.platform_id]},
)
)
response = client.get(
f"/api/roms?smart_collection_id={smart_collection.id}",
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.json()["items"] == []
def test_smart_collection_cannot_be_scoped_to_another_users_private_collection(
self, client, other_user_token: str, private_collection: Collection
):
response = client.post(
"/api/collections/smart?is_public=true",
data={
"name": "Pivot",
"filter_criteria": json.dumps({"collection_id": private_collection.id}),
},
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_stored_scope_to_another_users_private_collection_matches_nothing(
self,
client,
access_token: str,
editor_user: User,
private_collection: Collection,
):
smart_collection = _scope_to(private_collection, editor_user, is_public=True)
refreshed = db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.get(
f"/api/roms?smart_collection_id={smart_collection.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert refreshed is not None
assert refreshed.rom_ids == []
assert response.json()["items"] == []
def test_owner_can_scope_a_smart_collection_to_their_private_collection(
self,
client,
access_token: str,
private_collection: Collection,
rom: Rom,
):
response = client.post(
"/api/collections/smart",
data={
"name": "Within secret",
"filter_criteria": json.dumps({"collection_id": private_collection.id}),
},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert response.json()["rom_ids"] == [rom.id]
def test_owners_public_smart_scope_to_their_private_collection_is_shared(
self,
client,
other_user_token: str,
admin_user: User,
private_collection: Collection,
rom: Rom,
):
smart_collection = _scope_to(private_collection, admin_user, is_public=True)
response = client.get(
f"/api/roms?smart_collection_id={smart_collection.id}",
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert [item["id"] for item in response.json()["items"]] == [rom.id]
def test_unsharing_a_collection_empties_other_owners_smart_scopes(
self,
client,
access_token: str,
editor_user: User,
private_collection: Collection,
):
db_collection_handler.update_collection(
private_collection.id, {"is_public": True}
)
# Unparseable criteria elsewhere must not block this refresh.
db_collection_handler.add_smart_collection(
SmartCollection(
name="Broken",
description="",
user_id=editor_user.id,
filter_criteria=[1],
)
)
smart_collection = _scope_to(private_collection, editor_user, is_public=True)
shared = db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.put(
f"/api/collections/{private_collection.id}/visibility",
json={"is_public": False},
headers={"Authorization": f"Bearer {access_token}"},
)
assert shared is not None and shared.rom_ids != []
assert response.status_code == status.HTTP_200_OK
assert _cached_rom_ids(smart_collection.id) == []
def test_sharing_through_the_edit_form_fills_other_owners_smart_scopes(
self,
client,
access_token: str,
editor_user: User,
private_collection: Collection,
rom: Rom,
):
smart_collection = _scope_to(private_collection, editor_user)
response = client.put(
f"/api/collections/{private_collection.id}",
params={"is_public": True},
data={"rom_ids": json.dumps([rom.id])},
headers={"Authorization": f"Bearer {access_token}"},
)
assert response.status_code == status.HTTP_200_OK
assert _cached_rom_ids(smart_collection.id) == [rom.id]
def test_replacing_a_collections_roms_refreshes_its_smart_scopes(
self,
client,
access_token: str,
admin_user: User,
private_collection: Collection,
rom: Rom,
):
smart_collection = _scope_to(private_collection, admin_user)
before = db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.put(
f"/api/collections/{private_collection.id}",
data={"rom_ids": "[]"},
headers={"Authorization": f"Bearer {access_token}"},
)
assert before is not None and before.rom_ids == [rom.id]
assert response.status_code == status.HTTP_200_OK
assert _cached_rom_ids(smart_collection.id) == []
def test_deleting_a_collection_empties_its_smart_scopes(
self,
client,
access_token: str,
admin_user: User,
private_collection: Collection,
):
smart_collection = _scope_to(private_collection, admin_user)
before = db_collection_handler.refresh_smart_collection(smart_collection.id)
response = client.delete(
f"/api/collections/{private_collection.id}",
headers={"Authorization": f"Bearer {access_token}"},
)
assert before is not None and before.rom_ids != []
assert response.status_code == status.HTTP_200_OK
assert _cached_rom_ids(smart_collection.id) == []
def test_a_smart_collection_that_lost_its_scope_can_still_be_renamed(
self,
client,
access_token: str,
other_user_token: str,
editor_user: User,
private_collection: Collection,
):
db_collection_handler.update_collection(
private_collection.id, {"is_public": True}
)
criteria = {"collection_id": private_collection.id}
smart_collection = _scope_to(private_collection, editor_user)
unshared = client.put(
f"/api/collections/{private_collection.id}/visibility",
json={"is_public": False},
headers={"Authorization": f"Bearer {access_token}"},
)
response = client.put(
f"/api/collections/smart/{smart_collection.id}",
data={"name": "Renamed", "filter_criteria": json.dumps(criteria)},
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert unshared.status_code == status.HTTP_200_OK
assert response.status_code == status.HTTP_200_OK
assert response.json()["name"] == "Renamed"
assert response.json()["rom_ids"] == []
def test_smart_collection_cannot_be_rescoped_to_another_users_private_collection(
self,
client,
other_user_token: str,
editor_user: User,
private_collection: Collection,
):
smart_collection = db_collection_handler.add_smart_collection(
SmartCollection(
name="Mine",
description="",
user_id=editor_user.id,
filter_criteria={"matched": True},
)
)
response = client.put(
f"/api/collections/smart/{smart_collection.id}",
data={
"filter_criteria": json.dumps({"collection_id": private_collection.id})
},
headers={"Authorization": f"Bearer {other_user_token}"},
)
assert response.status_code == status.HTTP_404_NOT_FOUND