feat(api): finish Group A stubbed endpoints
Implements previously-stubbed /api/v1 endpoints (hexagonal: ports -> repos
-> services -> routers wired in deps):
- playlists: GET /{id}/cover (serves stored cover, 404 when absent)
- settings: GET/PATCH /settings + GET/PUT /settings/scrobbling — lazy
per-user row, write-only Fernet-encrypted scrobble session key; adds
user_settings table + migration (chains off dc126696f5a6)
- storage: GET /duplicates, /broken, /missing-metadata + admin POST
/cleanup (arq cleanup_storage worker; reconciles local refs only,
guarded against a storage-outage mass delete)
- admin: GET /services, /sources, /settings + POST /reindex; PATCH
/settings and /sources/{source} return 501 (config is env-managed)
Adds NotSupportedError (-> HTTP 501). Integration tests for each surface.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
"""Integration test for the playlist cover endpoint.
|
||||
|
||||
Master already covers playlist reorder in ``test_playlists_api.py``; this file
|
||||
only exercises ``GET /playlists/{id}/cover`` (served when set, 404 otherwise).
|
||||
Requires a reachable Postgres; skips otherwise.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
from collections.abc import AsyncIterator
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from app.core.config import get_settings
|
||||
from app.infrastructure.db import Base, dispose_engine, get_engine, session_scope
|
||||
from app.infrastructure.db.repositories import (
|
||||
SqlAlchemyPlaylistRepository,
|
||||
SqlAlchemyRefreshTokenRepository,
|
||||
SqlAlchemyUserRepository,
|
||||
)
|
||||
from app.infrastructure.storage.provider import get_file_storage
|
||||
from asgi_lifespan import LifespanManager
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
# A minimal valid 1x1 PNG.
|
||||
_PNG_BYTES = bytes.fromhex(
|
||||
"89504e470d0a1a0a0000000d4948445200000001000000010802000000907753"
|
||||
"de0000000c4944415408d763f8cfc0f01f0005000155a2b4f60000000049454e44ae426082"
|
||||
)
|
||||
|
||||
_db_reachable_cache: bool | None = None
|
||||
|
||||
|
||||
async def _db_reachable() -> bool:
|
||||
global _db_reachable_cache
|
||||
if _db_reachable_cache is not None:
|
||||
return _db_reachable_cache
|
||||
from sqlalchemy import text
|
||||
|
||||
try:
|
||||
async with asyncio.timeout(3):
|
||||
async with get_engine().connect() as conn:
|
||||
await conn.execute(text("SELECT 1"))
|
||||
_db_reachable_cache = True
|
||||
except Exception:
|
||||
_db_reachable_cache = False
|
||||
return _db_reachable_cache
|
||||
|
||||
|
||||
async def _seed_playlist(*, owner_id: uuid.UUID, cover: Path | None) -> uuid.UUID:
|
||||
"""Create a playlist owned by ``owner_id``; if ``cover`` is given, store it
|
||||
and point the playlist's ``cover_path`` at it."""
|
||||
from app.infrastructure.db.models.playlist import PlaylistModel
|
||||
|
||||
async with session_scope() as session:
|
||||
playlist = await SqlAlchemyPlaylistRepository(session).add(
|
||||
name="Mix", description=None, owner_id=owner_id
|
||||
)
|
||||
if cover is not None:
|
||||
key = f"covers/playlists/{playlist.id}.png"
|
||||
await get_file_storage().save_file(key, cover)
|
||||
row = await session.get(PlaylistModel, playlist.id)
|
||||
assert row is not None
|
||||
row.cover_path = key
|
||||
return playlist.id
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def ctx(tmp_path: Path) -> AsyncIterator[tuple[AsyncClient, uuid.UUID, Path]]:
|
||||
if not await _db_reachable():
|
||||
pytest.skip("Postgres not reachable — integration test skipped.")
|
||||
|
||||
os.environ["MEDIA_PATH"] = str(tmp_path)
|
||||
get_settings.cache_clear()
|
||||
|
||||
import app.infrastructure.storage.provider as _storage_provider
|
||||
|
||||
_storage_provider._storage = None
|
||||
|
||||
try:
|
||||
async with get_engine().begin() as conn:
|
||||
await conn.run_sync(Base.metadata.drop_all)
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
from app.application.user_service import UserService
|
||||
from app.core.security import Argon2PasswordHasher
|
||||
|
||||
async with session_scope() as session:
|
||||
user = await UserService(
|
||||
users=SqlAlchemyUserRepository(session),
|
||||
refresh_tokens=SqlAlchemyRefreshTokenRepository(session),
|
||||
hasher=Argon2PasswordHasher(),
|
||||
).create_user(username="pluser", password="testpass1", is_superuser=False)
|
||||
user_id = user.id
|
||||
|
||||
# A real source file for save_file (avoids the Windows NamedTemporaryFile
|
||||
# re-open quirk).
|
||||
src = tmp_path / "src_cover.png"
|
||||
src.write_bytes(_PNG_BYTES)
|
||||
|
||||
from app.main import create_app
|
||||
|
||||
app = create_app()
|
||||
async with LifespanManager(app):
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client, user_id, src
|
||||
|
||||
async with get_engine().begin() as conn:
|
||||
await conn.run_sync(Base.metadata.drop_all)
|
||||
await dispose_engine()
|
||||
finally:
|
||||
_storage_provider._storage = None
|
||||
os.environ.pop("MEDIA_PATH", None)
|
||||
get_settings.cache_clear()
|
||||
|
||||
|
||||
async def _token(api: AsyncClient) -> str:
|
||||
resp = await api.post(
|
||||
"/api/v1/auth/login", json={"username": "pluser", "password": "testpass1"}
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
return str(resp.json()["access_token"])
|
||||
|
||||
|
||||
async def test_playlist_cover_served(ctx: tuple[AsyncClient, uuid.UUID, Path]) -> None:
|
||||
api, user_id, src = ctx
|
||||
token = await _token(api)
|
||||
playlist_id = await _seed_playlist(owner_id=user_id, cover=src)
|
||||
|
||||
resp = await api.get(f"/api/v1/playlists/{playlist_id}/cover?token={token}")
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.headers["content-type"] == "image/png"
|
||||
assert resp.content == _PNG_BYTES
|
||||
|
||||
|
||||
async def test_playlist_without_cover_is_404(ctx: tuple[AsyncClient, uuid.UUID, Path]) -> None:
|
||||
api, user_id, _ = ctx
|
||||
token = await _token(api)
|
||||
playlist_id = await _seed_playlist(owner_id=user_id, cover=None)
|
||||
|
||||
resp = await api.get(f"/api/v1/playlists/{playlist_id}/cover?token={token}")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
async def test_playlist_cover_requires_auth(ctx: tuple[AsyncClient, uuid.UUID, Path]) -> None:
|
||||
api, user_id, src = ctx
|
||||
playlist_id = await _seed_playlist(owner_id=user_id, cover=src)
|
||||
resp = await api.get(f"/api/v1/playlists/{playlist_id}/cover")
|
||||
assert resp.status_code == 401
|
||||
Reference in New Issue
Block a user