sonda/internal/api/http/lidarr_test.go
tgiachi 23ae396430 feat(naming): names for playlists, with the Claude API as an option
- A pipeline over the facts about a list of songs (up to 5 genres, up to 8 artist names, how many songs, a few words about the rules of a smart playlist, the language). A local namer builds a name from the genres and the artists on this server and is always there; Claude is asked first only when an admin turned the new anthropic provider on with an API key. A failure or a refusal gives the local name. What Claude answers is kept under a hash of the facts, so the same question is not asked or paid twice.
- The anthropic provider: a write-only key (kept as typed, it is case-sensitive), a test that reads one model and sends no text, and a plain statement of what is sent. It uses the official Go SDK with nothing taken from the environment of the server (no key, profile, base URL or extra headers), no redirects, no system headers, and an answer that is cleaned and bounded.
- POST /playlists/{id}/suggest-name, POST /mixes/{id}/suggest-name and POST /smart-playlists/{id}/suggest-name answer with a name, a description and where it came from.
2026-11-13 10:33:48 +01:00

281 lines
12 KiB
Go

package httpapi
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"testing"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/discovery"
"codeberg.org/squidd/sonda/internal/providers/lidarr"
)
const lidarrAPIKey = "fedcba9876543210fedcba9876543210"
type fakeLidarr struct {
options lidarr.Options
err error
asked int
}
func (f *fakeLidarr) Options(context.Context) (lidarr.Options, error) {
f.asked++
return f.options, f.err
}
func newLidarrAPI(t *testing.T) (http.Handler, *fakeLidarr, string, string) {
t.Helper()
fake := &fakeLidarr{options: lidarr.Options{
QualityProfiles: []lidarr.Profile{{ID: 1, Name: "Any"}, {ID: 2, Name: "Lossless"}},
MetadataProfiles: []lidarr.Profile{{ID: 1, Name: "Standard"}},
RootFolders: []lidarr.RootFolder{{Path: "/music", Accessible: true}},
}}
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.Lidarr = fake })
admin := registerAndLogin(t, h)
_, bob := addUser(t, h, admin, "bob", false)
return h, fake, admin, bob
}
func TestLidarrIsListedAfterTheOthersWithItsAddressAndOptions(t *testing.T) {
h, _, admin, _ := newLidarrAPI(t)
list := do(t, h, "GET", "/api/v1/providers", admin, nil).Body["providers"].([]any)
if len(list) != 7 {
t.Fatalf("providers = %v", list)
}
for _, it := range list[:5] {
p := it.(map[string]any)
if p["needs_url"] != false || p["url"] != "" || p["lidarr"] != nil {
t.Errorf("%v has an address or Lidarr options: %v", p["name"], p)
}
}
l := list[5].(map[string]any)
sameKeys(t, "lidarr", l, "name", "enabled", "needs_api_key", "needs_url", "has_api_key", "contact", "url", "lidarr", "sends", "notes", "updated_at")
opts, _ := l["lidarr"].(map[string]any)
sameKeys(t, "lidarr options", opts, "quality_profile_id", "metadata_profile_id", "root_folder_path", "monitor", "search_missing")
if l["name"] != "lidarr" || l["enabled"] != false || l["needs_api_key"] != true || l["needs_url"] != true ||
opts["monitor"] != "all" || opts["search_missing"] != true || opts["quality_profile_id"] != float64(0) {
t.Errorf("lidarr = %v", l)
}
}
func TestSettingLidarrUp(t *testing.T) {
h, _, admin, _ := newLidarrAPI(t)
put := func(body map[string]any) resp { return do(t, h, "PUT", "/api/v1/providers/lidarr", admin, body) }
if r := put(map[string]any{"enabled": true}); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Fatalf("enabled with nothing: %d %v", r.Code, r.Body)
}
r := put(map[string]any{"api_key": lidarrAPIKey, "url": "http://orion:8686/"})
if r.Code != http.StatusOK || r.Body["url"] != "http://orion:8686" || r.Body["has_api_key"] != true || r.Body["enabled"] != false {
t.Fatalf("key and address: %d %v", r.Code, r.Body)
}
if raw, _ := json.Marshal(r.Body); strings.Contains(string(raw), lidarrAPIKey) {
t.Fatal("the response carries the API key")
}
// What is not said in the options is the default; what is said replaces all of them.
r = put(map[string]any{"lidarr": map[string]any{"quality_profile_id": 2, "metadata_profile_id": 1, "root_folder_path": "/music"}})
opts, _ := r.Body["lidarr"].(map[string]any)
if r.Code != http.StatusOK || opts["quality_profile_id"] != float64(2) || opts["root_folder_path"] != "/music" ||
opts["monitor"] != "all" || opts["search_missing"] != true {
t.Fatalf("options: %d %v", r.Code, r.Body)
}
r = put(map[string]any{"lidarr": map[string]any{"quality_profile_id": 2, "metadata_profile_id": 1, "root_folder_path": "/music", "monitor": "latest", "search_missing": false}})
opts, _ = r.Body["lidarr"].(map[string]any)
if opts["monitor"] != "latest" || opts["search_missing"] != false {
t.Fatalf("options: %v", r.Body)
}
if r := put(map[string]any{"enabled": true}); r.Code != http.StatusOK || r.Body["enabled"] != true {
t.Fatalf("enable: %d %v", r.Code, r.Body)
}
for name, body := range map[string]map[string]any{
"an address that is not http": {"url": "ftp://orion"},
"an address with a secret": {"url": "http://orion/?apikey=x"},
"a short key": {"api_key": "abc"},
"a monitor that is not one": {"lidarr": map[string]any{"monitor": "everything"}},
} {
if r := put(body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("%s: %d %v", name, r.Code, r.Body)
}
}
// Clearing the address turns it off.
if r := put(map[string]any{"url": ""}); r.Code != http.StatusOK || r.Body["enabled"] != false || r.Body["url"] != "" {
t.Errorf("clear the address: %d %v", r.Code, r.Body)
}
// Other providers have neither.
if r := do(t, h, "PUT", "/api/v1/providers/musicbrainz", admin, map[string]any{"url": "http://orion"}); r.Code != http.StatusBadRequest {
t.Errorf("an address for MusicBrainz: %d %v", r.Code, r.Body)
}
}
func TestOnlyAnAdminReadsWhatLidarrOffers(t *testing.T) {
h, fake, admin, bob := newLidarrAPI(t)
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", bob, nil); r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
t.Errorf("as a user: %d %v", r.Code, r.Body)
}
if fake.asked != 0 {
t.Error("Lidarr was asked on behalf of someone who is not an admin")
}
r := do(t, h, "GET", "/api/v1/providers/lidarr/options", admin, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
sameKeys(t, "options", r.Body, "quality_profiles", "metadata_profiles", "root_folders")
q := r.Body["quality_profiles"].([]any)
if len(q) != 2 || q[1].(map[string]any)["id"] != float64(2) || q[1].(map[string]any)["name"] != "Lossless" {
t.Errorf("quality profiles = %v", q)
}
sameKeys(t, "profile", q[0].(map[string]any), "id", "name")
f := r.Body["root_folders"].([]any)[0].(map[string]any)
sameKeys(t, "root folder", f, "path", "accessible")
if f["path"] != "/music" || f["accessible"] != true {
t.Errorf("root folder = %v", f)
}
}
func TestWhatGoesWrongAskingLidarrIsSaidPlainly(t *testing.T) {
h, fake, admin, _ := newLidarrAPI(t)
for _, c := range []struct {
err error
status int
code string
}{
{lidarr.ErrNotConfigured, http.StatusConflict, "lidarr_not_configured"},
{lidarr.ErrKeyRefused, http.StatusBadGateway, "lidarr_key_refused"},
{lidarr.ErrUnreachable, http.StatusBadGateway, "lidarr_unavailable"},
{lidarr.ErrBadResponse, http.StatusBadGateway, "lidarr_unavailable"},
{context.DeadlineExceeded, http.StatusBadGateway, "lidarr_unavailable"},
} {
fake.err = c.err
if r := do(t, h, "GET", "/api/v1/providers/lidarr/options", admin, nil); r.Code != c.status || errCode(r) != c.code {
t.Errorf("%v: %d %v, want %d %s", c.err, r.Code, r.Body, c.status, c.code)
}
}
}
// ---- sending an artist ----
type fakeSender struct {
outcome lidarr.Outcome
err error
sent []int64
presence lidarr.Presence
perr error
}
func (f *fakeSender) Send(_ context.Context, id int64) (lidarr.Outcome, error) {
if f.err != nil {
return "", f.err
}
f.sent = append(f.sent, id)
return f.outcome, nil
}
func (f *fakeSender) Presence(context.Context, int64) (lidarr.Presence, error) {
return f.presence, f.perr
}
func newSenderAPI(t *testing.T) (http.Handler, *fakeSender, string, string) {
t.Helper()
fake := &fakeSender{outcome: lidarr.Added}
h, _ := newTestEnvDB(t, func(d *Deps, _ *bun.DB) { d.LidarrArtists = fake })
admin := registerAndLogin(t, h)
_, bob := addUser(t, h, admin, "bob", false)
return h, fake, admin, bob
}
func TestOnlyAnAdminSendsAnArtistToLidarr(t *testing.T) {
h, fake, admin, bob := newSenderAPI(t)
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", bob, nil); r.Code != http.StatusForbidden || errCode(r) != "admin_required" {
t.Errorf("as a user: %d %v", r.Code, r.Body)
}
if len(fake.sent) != 0 {
t.Fatal("an artist was sent on behalf of someone who is not an admin")
}
r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
if r.Code != http.StatusOK || r.Body["status"] != "added" || len(fake.sent) != 1 || fake.sent[0] != 7 {
t.Fatalf("%d %v sent %v", r.Code, r.Body, fake.sent)
}
sameKeys(t, "sent", r.Body, "status")
fake.outcome = lidarr.AlreadyAdded
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != http.StatusOK || r.Body["status"] != "already_added" {
t.Errorf("again: %d %v", r.Code, r.Body)
}
if r := do(t, h, "POST", "/api/v1/artists/abc/lidarr", admin, nil); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("a bad id: %d %v", r.Code, r.Body)
}
}
func TestWhatStopsAnArtistFromBeingSentIsSaid(t *testing.T) {
h, fake, admin, _ := newSenderAPI(t)
for _, c := range []struct {
err error
status int
code string
}{
{discovery.ErrNotFound, http.StatusNotFound, "artist_not_found"},
{lidarr.ErrNoID, http.StatusUnprocessableEntity, "no_musicbrainz_id"},
{lidarr.ErrDisabled, http.StatusConflict, "lidarr_disabled"},
{lidarr.ErrNotSetUp, http.StatusConflict, "lidarr_not_configured"},
{lidarr.ErrNotConfigured, http.StatusConflict, "lidarr_not_configured"},
{lidarr.ErrNotFound, http.StatusUnprocessableEntity, "lidarr_unknown_artist"},
{lidarr.ErrKeyRefused, http.StatusBadGateway, "lidarr_key_refused"},
{lidarr.ErrUnreachable, http.StatusBadGateway, "lidarr_unavailable"},
{lidarr.ErrBadResponse, http.StatusBadGateway, "lidarr_unavailable"},
{context.DeadlineExceeded, http.StatusBadGateway, "lidarr_unavailable"},
} {
fake.err = c.err
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != c.status || errCode(r) != c.code {
t.Errorf("%v: %d %v, want %d %s", c.err, r.Code, r.Body, c.status, c.code)
}
}
// A refusal carries Lidarr's reason, which the admin needs; a timeout says the artist may be there.
fake.err = fmt.Errorf("%w: Root folder does not exist", lidarr.ErrRejected)
r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
msg, _ := r.Body["error"].(map[string]any)["message"].(string)
if r.Code != http.StatusUnprocessableEntity || errCode(r) != "lidarr_rejected" || !strings.Contains(msg, "Root folder does not exist") {
t.Errorf("rejected: %d %v", r.Code, r.Body)
}
for _, cause := range []error{lidarr.ErrUnreachable, lidarr.ErrBadResponse, context.DeadlineExceeded} {
fake.err = cause
r = do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil)
msg, _ = r.Body["error"].(map[string]any)["message"].(string)
if !strings.Contains(msg, "may have been added") {
t.Errorf("%v: %q, want it to say the artist may have been added", cause, msg)
}
}
fake.err = context.Canceled
if r := do(t, h, "POST", "/api/v1/artists/7/lidarr", admin, nil); r.Code != 499 {
t.Errorf("a request that left: %d", r.Code)
}
}
func TestAnyUserSeesWhetherLidarrHasAnArtist(t *testing.T) {
h, fake, _, bob := newSenderAPI(t)
if r := do(t, h, "GET", "/api/v1/artists/7/lidarr", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a token: %d", r.Code)
}
fake.presence = lidarr.Presence{Status: "ok", InLidarr: true, Monitored: true}
r := do(t, h, "GET", "/api/v1/artists/7/lidarr", bob, nil)
sameKeys(t, "presence", r.Body, "provider_status", "in_lidarr", "monitored")
if r.Code != http.StatusOK || r.Body["provider_status"] != "ok" || r.Body["in_lidarr"] != true || r.Body["monitored"] != true {
t.Errorf("%d %v", r.Code, r.Body)
}
fake.presence = lidarr.Presence{Status: "disabled"}
if r := do(t, h, "GET", "/api/v1/artists/7/lidarr", bob, nil); r.Body["provider_status"] != "disabled" || r.Body["in_lidarr"] != false {
t.Errorf("off: %v", r.Body)
}
fake.perr = discovery.ErrNotFound
if r := do(t, h, "GET", "/api/v1/artists/7/lidarr", bob, nil); r.Code != http.StatusNotFound || errCode(r) != "artist_not_found" {
t.Errorf("unknown: %d %v", r.Code, r.Body)
}
}