mirror of
https://github.com/rommapp/romm.git
synced 2026-11-30 18:42:34 +01:00
Add v2 browser playback for .p8 and .p8.png cartridges, backed by the FAKE-08 WebAssembly runtime, with canvas rendering, audio, fullscreen and keyboard, gamepad, mouse and touch input. Wires up platform detection, play actions, routing, localization, gallery navigation, play-session tracking and lifecycle cleanup. The runtime is fetched in the emulator stage of docker/Dockerfile, pinned by source commit and verified with sha256, so it is provisioned the same way as EmulatorJS, Ruffle and js-dos rather than committed to the repo. DISABLE_PICO8 gates the player, matching the existing DISABLE_EMULATOR_JS, DISABLE_RUFFLE_RS and DISABLE_JSDOS toggles. Based on #4383. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
510 lines
18 KiB
Python
510 lines
18 KiB
Python
import asyncio
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import httpx
|
|
import pytest
|
|
from fastapi import status
|
|
from main import app
|
|
|
|
from endpoints.heartbeat import METADATA_HEARTBEAT_RATE_LIMIT
|
|
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
|
from handler.metadata.launchbox_handler.handler import LaunchboxHandler
|
|
from handler.redis_handler import sync_cache
|
|
from utils import get_version
|
|
|
|
|
|
def test_heartbeat(client):
|
|
response = client.get("/api/heartbeat")
|
|
assert response.status_code == status.HTTP_200_OK
|
|
|
|
heartbeat = response.json()
|
|
|
|
assert "SYSTEM" in heartbeat
|
|
system = heartbeat["SYSTEM"]
|
|
assert system["VERSION"] == get_version()
|
|
assert isinstance(system["SHOW_SETUP_WIZARD"], bool)
|
|
|
|
assert "METADATA_SOURCES" in heartbeat
|
|
metadata = heartbeat["METADATA_SOURCES"]
|
|
assert isinstance(metadata["ANY_SOURCE_ENABLED"], bool)
|
|
assert isinstance(metadata["IGDB_API_ENABLED"], bool)
|
|
assert isinstance(metadata["MOBY_API_ENABLED"], bool)
|
|
assert isinstance(metadata["SS_API_ENABLED"], bool)
|
|
assert isinstance(metadata["SS_DEV_CREDENTIALS_SET"], bool)
|
|
assert isinstance(metadata["STEAMGRIDDB_API_ENABLED"], bool)
|
|
assert isinstance(metadata["RA_API_ENABLED"], bool)
|
|
assert isinstance(metadata["LAUNCHBOX_API_ENABLED"], bool)
|
|
assert isinstance(metadata["PLAYMATCH_API_ENABLED"], bool)
|
|
assert isinstance(metadata["HASHEOUS_API_ENABLED"], bool)
|
|
assert isinstance(metadata["TGDB_API_ENABLED"], bool)
|
|
assert isinstance(metadata["FLASHPOINT_API_ENABLED"], bool)
|
|
|
|
assert "FILESYSTEM" in heartbeat
|
|
filesystem = heartbeat["FILESYSTEM"]
|
|
assert isinstance(filesystem["FS_PLATFORMS"], list)
|
|
|
|
assert "EMULATION" in heartbeat
|
|
emulation = heartbeat["EMULATION"]
|
|
assert isinstance(emulation["DISABLE_EMULATOR_JS"], bool)
|
|
assert isinstance(emulation["DISABLE_RUFFLE_RS"], bool)
|
|
assert isinstance(emulation["DISABLE_JSDOS"], bool)
|
|
assert isinstance(emulation["DISABLE_PICO8"], bool)
|
|
|
|
assert "FRONTEND" in heartbeat
|
|
frontend = heartbeat["FRONTEND"]
|
|
assert isinstance(frontend["DISABLE_USERPASS_LOGIN"], bool)
|
|
|
|
assert "OIDC" in heartbeat
|
|
oidc = heartbeat["OIDC"]
|
|
assert isinstance(oidc["ENABLED"], bool)
|
|
assert isinstance(oidc["PROVIDER"], str)
|
|
assert isinstance(oidc["RP_INITIATED_LOGOUT"], bool)
|
|
|
|
|
|
@pytest.mark.parametrize("authorization_header", ["Bearer ", "Foo", "a b c"])
|
|
def test_heartbeat_with_malformed_authorization_header(
|
|
client, authorization_header: str
|
|
):
|
|
response = client.get(
|
|
"/api/heartbeat", headers={"Authorization": authorization_header}
|
|
)
|
|
assert response.status_code == status.HTTP_200_OK
|
|
|
|
|
|
def test_heartbeat_metadata(client):
|
|
"""LaunchBox is only healthy once its metadata store has been populated."""
|
|
response = client.get("/api/heartbeat/metadata/launchbox")
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.json() is False
|
|
|
|
# That first answer is cached, so drop it before probing for the other state.
|
|
sync_cache.flushall()
|
|
|
|
with patch.object(
|
|
LaunchboxHandler, "is_remote_store_populated", new_callable=AsyncMock
|
|
) as mock_populated:
|
|
mock_populated.return_value = True
|
|
response = client.get("/api/heartbeat/metadata/launchbox")
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.json() is True
|
|
|
|
|
|
def test_heartbeat_metadata_probes_the_provider_once_per_window(client):
|
|
"""A flood of callers must not become a flood of outbound provider probes."""
|
|
with patch.object(
|
|
LaunchboxHandler, "is_remote_store_populated", new_callable=AsyncMock
|
|
) as mock_populated:
|
|
mock_populated.return_value = True
|
|
|
|
for _ in range(METADATA_HEARTBEAT_RATE_LIMIT):
|
|
response = client.get("/api/heartbeat/metadata/launchbox")
|
|
assert response.status_code == status.HTTP_200_OK
|
|
assert response.json() is True
|
|
|
|
assert mock_populated.call_count == 1
|
|
|
|
|
|
async def test_heartbeat_metadata_concurrent_misses_probe_once(client):
|
|
"""Requests racing an in-flight probe must wait for it, not launch their own."""
|
|
|
|
async def slow_probe() -> bool:
|
|
await asyncio.sleep(0.05)
|
|
return True
|
|
|
|
with patch.object(
|
|
LaunchboxHandler,
|
|
"is_remote_store_populated",
|
|
new_callable=AsyncMock,
|
|
side_effect=slow_probe,
|
|
) as mock_populated:
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.ASGITransport(app=app), base_url="http://test"
|
|
) as async_client:
|
|
responses = await asyncio.gather(
|
|
*(
|
|
async_client.get("/api/heartbeat/metadata/launchbox")
|
|
for _ in range(5)
|
|
)
|
|
)
|
|
|
|
assert [r.json() for r in responses] == [True] * 5
|
|
assert mock_populated.call_count == 1
|
|
|
|
|
|
def test_heartbeat_metadata_unknown_source(client):
|
|
response = client.get("/api/heartbeat/metadata/unknown")
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
|
|
def test_heartbeat_metadata_rate_limit(client):
|
|
for _ in range(METADATA_HEARTBEAT_RATE_LIMIT):
|
|
response = client.get("/api/heartbeat/metadata/launchbox")
|
|
assert response.status_code == status.HTTP_200_OK
|
|
|
|
response = client.get("/api/heartbeat/metadata/launchbox")
|
|
assert response.status_code == status.HTTP_429_TOO_MANY_REQUESTS
|
|
|
|
# The window is per source, so another source is untouched by the flood.
|
|
response = client.get("/api/heartbeat/metadata/gamelist")
|
|
assert response.status_code == status.HTTP_200_OK
|
|
|
|
|
|
def test_heartbeat_metadata_unknown_source_is_not_rate_limited(client):
|
|
"""An unparseable source is rejected before the limiter, so it burns no window."""
|
|
for _ in range(METADATA_HEARTBEAT_RATE_LIMIT + 1):
|
|
response = client.get("/api/heartbeat/metadata/unknown")
|
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
|
|
|
|
|
def test_get_setup_library_info_reports_a_ready_library(client, access_token):
|
|
"""Test get_setup_library_info with the platforms folder present"""
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = True
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.get_platforms"
|
|
) as mock_get_platforms:
|
|
mock_get_platforms.return_value = ["n64", "psx"]
|
|
|
|
# Create mock entry objects with .name attribute
|
|
def create_mock_entry(name):
|
|
entry = MagicMock()
|
|
entry.name = name
|
|
return entry
|
|
|
|
async def mock_iterdir_n64():
|
|
yield create_mock_entry("game1.z64")
|
|
yield create_mock_entry("game2.z64")
|
|
|
|
async def mock_iterdir_psx():
|
|
yield create_mock_entry("game1.iso")
|
|
|
|
with patch("endpoints.heartbeat.AnyioPath") as mock_anyio_path:
|
|
# Create side effects for multiple calls to AnyioPath()
|
|
path_instances = []
|
|
|
|
# First call - n64 roms directory
|
|
mock_n64_path = AsyncMock()
|
|
mock_n64_path.exists = AsyncMock(return_value=True)
|
|
mock_n64_path.iterdir = mock_iterdir_n64
|
|
path_instances.append(mock_n64_path)
|
|
|
|
# Second call - psx roms directory
|
|
mock_psx_path = AsyncMock()
|
|
mock_psx_path.exists = AsyncMock(return_value=True)
|
|
mock_psx_path.iterdir = mock_iterdir_psx
|
|
path_instances.append(mock_psx_path)
|
|
|
|
mock_anyio_path.side_effect = path_instances
|
|
|
|
response = client.get(
|
|
"/api/setup/library",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
data = response.json()
|
|
|
|
assert data["library_ready"] is True
|
|
assert len(data["existing_platforms"]) == 2
|
|
assert data["existing_platforms"][0]["fs_slug"] == "n64"
|
|
assert data["existing_platforms"][0]["rom_count"] == 2
|
|
assert data["existing_platforms"][1]["fs_slug"] == "psx"
|
|
assert data["existing_platforms"][1]["rom_count"] == 1
|
|
assert "supported_platforms" in data
|
|
|
|
|
|
def test_get_setup_library_info_counts_one_platform(client, admin_user, access_token):
|
|
"""Test get_setup_library_info reports a single platform's rom count"""
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = True
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.get_platforms"
|
|
) as mock_get_platforms:
|
|
mock_get_platforms.return_value = ["gba"]
|
|
|
|
# Create mock entry objects with .name attribute
|
|
def create_mock_entry(name):
|
|
entry = MagicMock()
|
|
entry.name = name
|
|
return entry
|
|
|
|
async def mock_iterdir_gba():
|
|
yield create_mock_entry("game1.gba")
|
|
yield create_mock_entry("game2.gba")
|
|
yield create_mock_entry("game3.gba")
|
|
|
|
with patch("endpoints.heartbeat.AnyioPath") as mock_anyio_path:
|
|
# Create mock for gba roms directory
|
|
mock_gba_path = AsyncMock()
|
|
mock_gba_path.exists = AsyncMock(return_value=True)
|
|
mock_gba_path.iterdir = mock_iterdir_gba
|
|
|
|
mock_anyio_path.return_value = mock_gba_path
|
|
|
|
response = client.get(
|
|
"/api/setup/library",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
data = response.json()
|
|
|
|
assert data["library_ready"] is True
|
|
assert len(data["existing_platforms"]) == 1
|
|
assert data["existing_platforms"][0]["fs_slug"] == "gba"
|
|
assert data["existing_platforms"][0]["rom_count"] == 3
|
|
|
|
|
|
def test_get_setup_library_info_no_library_yet(client, admin_user, access_token):
|
|
"""Test get_setup_library_info when the platforms folder is absent"""
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = False
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.get_platforms"
|
|
) as mock_get_platforms:
|
|
mock_get_platforms.return_value = []
|
|
|
|
response = client.get(
|
|
"/api/setup/library",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
data = response.json()
|
|
|
|
assert data["library_ready"] is False
|
|
assert data["existing_platforms"] == []
|
|
assert "supported_platforms" in data
|
|
|
|
|
|
def test_get_setup_library_info_handles_errors(client, admin_user, access_token):
|
|
"""Test get_setup_library_info handles filesystem errors gracefully"""
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = True
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.get_platforms"
|
|
) as mock_get_platforms:
|
|
# Simulate error retrieving platforms
|
|
mock_get_platforms.side_effect = Exception("Filesystem error")
|
|
|
|
response = client.get(
|
|
"/api/setup/library",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
data = response.json()
|
|
|
|
# Should return empty platforms list on error
|
|
assert data["existing_platforms"] == []
|
|
|
|
|
|
def test_get_setup_library_info_skips_filesystem_walk_when_roms_exist(
|
|
client, rom, access_token
|
|
):
|
|
"""A library with scanned ROMs never needs the on-disk hint, so skip the walk."""
|
|
with (
|
|
patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect,
|
|
patch(
|
|
"endpoints.heartbeat.fs_platform_handler.get_platforms"
|
|
) as mock_get_platforms,
|
|
):
|
|
mock_detect.return_value = True
|
|
mock_get_platforms.return_value = ["n64"]
|
|
|
|
response = client.get(
|
|
"/api/setup/library",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
data = response.json()
|
|
|
|
assert data["library_ready"] is True
|
|
assert data["existing_platforms"] == []
|
|
assert len(data["supported_platforms"]) > 0
|
|
mock_get_platforms.assert_not_called()
|
|
|
|
|
|
def test_get_setup_library_info_walks_when_platforms_have_no_roms(
|
|
client, platform, access_token
|
|
):
|
|
"""Platform rows without ROMs still need the hint: that is the case it exists for."""
|
|
with (
|
|
patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect,
|
|
patch(
|
|
"endpoints.heartbeat.fs_platform_handler.get_platforms"
|
|
) as mock_get_platforms,
|
|
patch("endpoints.heartbeat.AnyioPath") as mock_anyio_path,
|
|
):
|
|
mock_detect.return_value = True
|
|
mock_get_platforms.return_value = ["n64"]
|
|
|
|
async def mock_iterdir():
|
|
entry = MagicMock()
|
|
entry.name = "game1.z64"
|
|
yield entry
|
|
|
|
mock_path = AsyncMock()
|
|
mock_path.exists = AsyncMock(return_value=True)
|
|
mock_path.iterdir = mock_iterdir
|
|
mock_anyio_path.return_value = mock_path
|
|
|
|
response = client.get(
|
|
"/api/setup/library",
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_200_OK
|
|
data = response.json()
|
|
|
|
assert data["existing_platforms"] == [{"fs_slug": "n64", "rom_count": 1}]
|
|
|
|
|
|
def test_create_setup_platforms_success(client, admin_user, access_token):
|
|
"""Test create_setup_platforms successfully creates platforms"""
|
|
platform_slugs = ["n64", "psx", "gba"]
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = True
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.add_platform"
|
|
) as mock_add_platform:
|
|
mock_add_platform.return_value = None # Successful creation
|
|
|
|
response = client.post(
|
|
"/api/setup/platforms",
|
|
json=platform_slugs,
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
data = response.json()
|
|
|
|
assert data["success"] is True
|
|
assert data["created_count"] == 3
|
|
assert "Successfully created 3 platform folder(s)" in data["message"]
|
|
assert mock_add_platform.call_count == 3
|
|
|
|
|
|
def test_create_setup_platforms_empty_list(client, admin_user, access_token):
|
|
"""Test create_setup_platforms with empty platform list"""
|
|
response = client.post(
|
|
"/api/setup/platforms",
|
|
json=[],
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
data = response.json()
|
|
|
|
assert data["success"] is True
|
|
assert data["created_count"] == 0
|
|
assert data["message"] == "No platforms selected"
|
|
|
|
|
|
def test_create_setup_platforms_creates_the_library_when_absent(
|
|
client, admin_user, access_token
|
|
):
|
|
"""Test create_setup_platforms creates the platforms folder when absent"""
|
|
platform_slugs = ["n64"]
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = None # No structure detected
|
|
|
|
with patch("os.makedirs") as mock_makedirs:
|
|
with patch("endpoints.heartbeat.fs_platform_handler.add_platform"):
|
|
response = client.post(
|
|
"/api/setup/platforms",
|
|
json=platform_slugs,
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
# The test config puts platform folders at the library root.
|
|
mock_makedirs.assert_called_once()
|
|
assert str(mock_makedirs.call_args[0][0]).endswith("library/")
|
|
|
|
|
|
def test_create_setup_platforms_skips_existing_platforms(
|
|
client, admin_user, access_token
|
|
):
|
|
"""Test create_setup_platforms skips platforms that already exist"""
|
|
platform_slugs = ["n64", "psx", "gba"]
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = True
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.add_platform"
|
|
) as mock_add_platform:
|
|
# First platform already exists, second succeeds, third succeeds
|
|
mock_add_platform.side_effect = [
|
|
PlatformAlreadyExistsException("n64"),
|
|
None,
|
|
None,
|
|
]
|
|
|
|
response = client.post(
|
|
"/api/setup/platforms",
|
|
json=platform_slugs,
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_201_CREATED
|
|
data = response.json()
|
|
|
|
assert data["success"] is True
|
|
# Should only count 2 created (psx and gba)
|
|
assert data["created_count"] == 2
|
|
|
|
|
|
def test_create_setup_platforms_handles_permission_errors(
|
|
client, admin_user, access_token
|
|
):
|
|
"""Test create_setup_platforms handles permission errors"""
|
|
platform_slugs = ["n64"]
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.library_structure_exists"
|
|
) as mock_detect:
|
|
mock_detect.return_value = True
|
|
|
|
with patch(
|
|
"endpoints.heartbeat.fs_platform_handler.add_platform"
|
|
) as mock_add_platform:
|
|
mock_add_platform.side_effect = PermissionError("Permission denied")
|
|
|
|
response = client.post(
|
|
"/api/setup/platforms",
|
|
json=platform_slugs,
|
|
headers={"Authorization": f"Bearer {access_token}"},
|
|
)
|
|
|
|
assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR
|
|
assert "Failed to create some platform folders" in response.json()["detail"]
|