Files
mcma-backend/tests/test_admin_api.py
T
Цвылев Александр Вадимович 048854f92a feat(api): offline-first sync layer
Implements the stubbed /sync endpoints:
- GET /sync/changes — delta pull (likes, plays, changed playlists with
  their track ids, changed catalogue tracks) over the half-open window
  (since, cursor]; the cursor is the DB clock, so it's immune to app/DB
  skew.
- POST /sync/push — idempotent append of client like/play events
  (ON CONFLICT DO NOTHING by client-supplied id); events for tracks the
  server doesn't have are skipped (graceful degradation).

Adds a server-ingestion column `synced_at` to the likes + play_history
event logs (migration) as the delta ordering key, so an event pushed
with an older event time still surfaces for other devices. Repos gain
list_since/add_event (likes, history), list_changed_since (playlists,
tracks) and playlist.track_ids; wired via SyncService in deps.

Also fixes test isolation exposed by the registry-backed /admin/sources
endpoint: test_sources_api clears the process-cached source registry,
and test_admin_api no longer hardcodes the environment name.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-28 15:04:13 +03:00

145 lines
5.2 KiB
Python

"""Integration tests for the admin instance-management endpoints.
Covers ``/admin/services`` (dependency health), ``/admin/sources``,
``/admin/reindex`` (enqueue), and ``/admin/settings`` (effective config) plus
their admin gating. Requires a reachable Postgres; skips otherwise.
"""
import asyncio
import os
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 (
SqlAlchemyRefreshTokenRepository,
SqlAlchemyUserRepository,
)
from asgi_lifespan import LifespanManager
from httpx import ASGITransport, AsyncClient
pytestmark = pytest.mark.asyncio
_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
@pytest.fixture
async def api(tmp_path: Path) -> AsyncIterator[AsyncClient]:
if not await _db_reachable():
pytest.skip("Postgres not reachable — integration test skipped.")
os.environ["MEDIA_PATH"] = str(tmp_path)
get_settings.cache_clear()
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:
svc = UserService(
users=SqlAlchemyUserRepository(session),
refresh_tokens=SqlAlchemyRefreshTokenRepository(session),
hasher=Argon2PasswordHasher(),
)
await svc.create_user(username="user", password="testpass1", is_superuser=False)
await svc.create_user(username="admin", password="testpass1", is_superuser=True)
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
async with get_engine().begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await dispose_engine()
finally:
os.environ.pop("MEDIA_PATH", None)
get_settings.cache_clear()
async def _auth(api: AsyncClient, username: str) -> dict[str, str]:
resp = await api.post(
"/api/v1/auth/login", json={"username": username, "password": "testpass1"}
)
assert resp.status_code == 200, resp.text
return {"Authorization": f"Bearer {resp.json()['access_token']}"}
async def test_services_reports_dependency_health(api: AsyncClient) -> None:
headers = await _auth(api, "admin")
resp = await api.get("/api/v1/admin/services", headers=headers)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["database"] == "ok"
assert body["redis"] in ("ok", "down") # redis is up in CI/dev, but don't hard-require it
assert body["ml"] == "skipped" # no ML_SERVICE_URL configured
async def test_services_requires_admin(api: AsyncClient) -> None:
headers = await _auth(api, "user")
resp = await api.get("/api/v1/admin/services", headers=headers)
assert resp.status_code == 403
async def test_sources_list_is_admin_only(api: AsyncClient) -> None:
user = await _auth(api, "user")
assert (await api.get("/api/v1/admin/sources", headers=user)).status_code == 403
admin = await _auth(api, "admin")
resp = await api.get("/api/v1/admin/sources", headers=admin)
assert resp.status_code == 200, resp.text
assert isinstance(resp.json(), list)
async def test_reindex_without_indexable_source_is_503(api: AsyncClient) -> None:
# No LOCAL_MEDIA_IMPORT_PATH configured → nothing to index.
headers = await _auth(api, "admin")
resp = await api.post("/api/v1/admin/reindex", headers=headers)
assert resp.status_code == 503, resp.text
async def test_settings_exposes_effective_config_without_secrets(api: AsyncClient) -> None:
headers = await _auth(api, "admin")
resp = await api.get("/api/v1/admin/settings", headers=headers)
assert resp.status_code == 200, resp.text
body = resp.json()
# environment reflects however the process booted (test on host, dev in the
# container) — assert it's a valid value, not a specific one.
assert body["environment"] in ("dev", "test", "prod")
assert body["storage_backend"] == "local"
assert body["allow_registration"] is True
# No secret material should ever appear in the payload.
assert "jwt_secret" not in body
assert "subsonic_secret_key" not in body
async def test_settings_requires_admin(api: AsyncClient) -> None:
headers = await _auth(api, "user")
resp = await api.get("/api/v1/admin/settings", headers=headers)
assert resp.status_code == 403