Files
Scrobbler/tests/test_openapi.py
T
mattandClaude Sonnet 5 0acce9b948
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 13s
CI / federation-interop (push) Successful in 1m0s
CI / test (push) Successful in 2m53s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s
API and web UI for posts, previews and post settings (phase 3, step 8)
/api/v1/federation gains:
  - GET /posts, DELETE /posts/{id}: manage your own posts from the UI.
  - GET /preview/weekly: what the weekly summary would say right now, for
    the week still in progress - never posted or stored. Backed by a new
    weekly.preview() and schedule.current_week_start().
  - GET /profiles/{username}/posts/{post_uuid} (public, unauthenticated):
    backs the UI's post page, which can't itself speak ActivityPub.

Settings gain timezone/post_weekly_summary/post_milestones, already
present in sharing.EDITABLE since phase 3 step 2 but never added to
SharingSettingsSchema, so the API was silently dropping them from
responses. timezone validates against the same is_valid_timezone() the
service layer uses, with a dedicated marshmallow validator.

Fixed a real gap found while wiring the post page: ids.post_page_url()
took a username but never put it in the URL, so post.html would have
had no way to know whose post to look up. It's now ?u=<username>&id=<uuid>.

Sharing page gets a "What to post" section (weekly summary and
milestones toggles, a timezone field with a browser-supplied IANA
datalist where Intl.supportedValuesOf exists, and a live preview).
New posts.html lists a user's posts with delete (mirroring followers.js's
confirm-before-destructive-action pattern); new post.html is the public
landing page for a post's `url`, reached by browsers redirected from the
raw ActivityPub endpoint.

Verified by hand against a local dev server and a real browser: sign in,
enable sharing, preview and publish, list and delete a post, and follow
the ActivityPub redirect through to the public post page and its 404
after deletion - fixed one bug found this way (the preview box was
collapsing the summary's line breaks).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
2026-09-26 16:24:35 +01:00

108 lines
3.4 KiB
Python

import json
import re
from pathlib import Path
import pytest
from openapi_spec_validator import validate
from scrobbler.lastfm.registry import METHODS
COMMITTED_SPEC = Path(__file__).resolve().parents[1] / "docs" / "openapi.json"
DOCUMENTED_PREFIXES = (
"/api/v1/",
"/2.0/",
"/api/auth/",
"/healthz",
"/.well-known/",
"/nodeinfo/",
"/users/",
"/inbox",
"/actor",
)
HTTP_VERBS = {"get", "put", "post", "delete", "patch", "head", "options"}
@pytest.fixture(scope="module")
def spec(app):
return app.test_client().get("/api/openapi.json").get_json()
def openapi_path(rule: str) -> str:
return re.sub(r"<(?:[^:<>]+:)?([^<>]+)>", r"{\1}", rule)
def test_spec_is_valid_openapi(spec):
validate(spec)
@pytest.fixture(scope="module")
def fed_spec(fed_app):
return fed_app.test_client().get("/api/openapi.json").get_json()
def test_every_api_route_is_documented(app, spec, fed_app, fed_spec):
_check_documented(app, spec)
_check_documented(fed_app, fed_spec) # with federation's routes too
def test_federation_off_documents_no_federation_paths(spec):
assert not [p for p in spec["paths"] if p.startswith(("/api/v1/federation", "/users/"))]
def _check_documented(app, spec):
for rule in app.url_map.iter_rules():
if not rule.rule.startswith(DOCUMENTED_PREFIXES):
continue
path = openapi_path(rule.rule)
assert path in spec["paths"], f"{rule.rule} is missing from the OpenAPI document"
documented = {m.upper() for m in spec["paths"][path] if m in HTTP_VERBS}
assert rule.methods - {"HEAD", "OPTIONS"} <= documented, rule.rule
def test_every_lastfm_method_is_documented(spec):
get = spec["paths"]["/2.0/"]["get"]
[method_param] = [p for p in get["parameters"] if p["name"] == "method"]
assert set(method_param["schema"]["enum"]) == {m.name for m in METHODS.values()}
for method in METHODS.values():
assert f"### `{method.name}`" in get["description"]
request_schemas = spec["paths"]["/2.0/"]["post"]["requestBody"]["content"][
"application/x-www-form-urlencoded"
]["schema"]["oneOf"]
assert len(request_schemas) == len(METHODS)
def test_ui_routes_declare_bearer_auth(fed_spec):
spec = fed_spec # includes the federation API
public = {
("/api/v1/auth/login", "post"),
("/api/v1/auth/register", "post"),
("/api/v1/federation/profiles/{username}", "get"),
("/api/v1/federation/profiles/{username}/posts/{post_uuid}", "get"),
}
for path, operations in spec["paths"].items():
if not path.startswith("/api/v1/"):
continue
for verb, operation in operations.items():
if verb not in HTTP_VERBS:
continue
if (path, verb) in public:
assert "security" not in operation
else:
assert operation.get("security") == [{"bearerAuth": []}], f"{verb} {path}"
assert "401" in operation["responses"], f"{verb} {path}"
def test_docs_pages_are_served(client):
assert client.get("/api/docs").status_code == 200
assert client.get("/api/redoc").status_code == 200
def test_committed_spec_is_up_to_date():
from scrobbler.openapi.export import build_spec
committed = json.loads(COMMITTED_SPEC.read_text())
assert committed == build_spec(), (
"docs/openapi.json is stale. Regenerate it with: "
"uv run python -m scrobbler.openapi.export docs/openapi.json"
)