- Every question asked of Claude is recorded: when, the kind of list, the model, the tokens read and written (also for an answer that was no name but was billed) and how it ended: a name made, a name taken from the kept ones, or a failure and why. Nothing of the facts that were sent is recorded. Records older than a year are removed (migration 0022). - GET /providers/anthropic/usage (admin) gives the totals of the last days (1 to 365, 30 by default), a row for each day with calls and an estimate of the cost in dollars, worked out from the tokens and the price of the model. It says it is an estimate and flags calls to a model whose price is not known. - A Costs section in the admin area shows the last 7, 30 or 90 days.
1119 lines
66 KiB
Go
1119 lines
66 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"image"
|
|
"image/color"
|
|
"image/png"
|
|
"io"
|
|
"mime"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/getkin/kin-openapi/openapi3filter"
|
|
"github.com/getkin/kin-openapi/routers"
|
|
"github.com/getkin/kin-openapi/routers/legacy"
|
|
"github.com/uptrace/bun"
|
|
"go.uber.org/zap"
|
|
|
|
"codeberg.org/squidd/sonda/internal/catalog"
|
|
"codeberg.org/squidd/sonda/internal/discovery"
|
|
"codeberg.org/squidd/sonda/internal/duplicates"
|
|
"codeberg.org/squidd/sonda/internal/images"
|
|
"codeberg.org/squidd/sonda/internal/jobs"
|
|
"codeberg.org/squidd/sonda/internal/library"
|
|
"codeberg.org/squidd/sonda/internal/providers"
|
|
"codeberg.org/squidd/sonda/internal/providers/lastfm"
|
|
"codeberg.org/squidd/sonda/internal/providers/lidarr"
|
|
"codeberg.org/squidd/sonda/internal/storage"
|
|
"codeberg.org/squidd/sonda/internal/streaming"
|
|
)
|
|
|
|
// Contract tests: real requests against the real services, with every request
|
|
// that succeeds and every response checked against openapi.yaml (status,
|
|
// headers, parameters, JSON bodies). A field that is added, renamed or dropped
|
|
// in the code without the spec fails here, and so does an error code that
|
|
// changes, because every error case also asserts its `code`.
|
|
|
|
// contractReader gives the fixture files their tags without real audio. While a
|
|
// gate is held it blocks, so a test can look at a scan that is still running.
|
|
type contractReader struct {
|
|
mu sync.Mutex
|
|
gate chan struct{}
|
|
}
|
|
|
|
// hold makes the next reads wait until the returned channel is closed.
|
|
func (r *contractReader) hold() chan struct{} {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.gate = make(chan struct{})
|
|
return r.gate
|
|
}
|
|
|
|
func (r *contractReader) Read(path string) (library.Metadata, error) {
|
|
r.mu.Lock()
|
|
gate := r.gate
|
|
r.mu.Unlock()
|
|
if gate != nil {
|
|
<-gate
|
|
}
|
|
|
|
m := library.Metadata{
|
|
Tags: library.Tags{Artists: []string{"Artist X"}, Album: "Album Y", AlbumArtist: "Artist X", DiscNo: 1},
|
|
Properties: library.Properties{DurationMs: 180000, SampleRate: 44100},
|
|
}
|
|
switch filepath.Base(path) {
|
|
case "a.mp3":
|
|
m.Title, m.TrackNo, m.Format = "Song A", 1, "mpeg"
|
|
case "b.flac":
|
|
m.Title, m.TrackNo, m.Format = "Song B", 2, "flac"
|
|
case "c.mp3": // a track that belongs to no album
|
|
m.Title, m.Format = "Loose Song", "mpeg"
|
|
m.Album, m.AlbumArtist, m.DiscNo = "", "", 0
|
|
default:
|
|
return library.Metadata{}, library.ErrUnreadable
|
|
}
|
|
return m, nil
|
|
}
|
|
|
|
// scanAdapter lets the API start scans on a real manager.
|
|
type scanAdapter struct{ m *library.Manager }
|
|
|
|
func (a scanAdapter) Start(full bool) error {
|
|
return a.m.Start(context.Background(), scanOptions(full)...)
|
|
}
|
|
|
|
func (a scanAdapter) StartLibrary(id int64, full bool) error {
|
|
return a.m.StartLibrary(context.Background(), id, scanOptions(full)...)
|
|
}
|
|
|
|
func (a scanAdapter) Status() library.Status { return a.m.Status() }
|
|
|
|
func scanOptions(full bool) []library.ScanOption {
|
|
if full {
|
|
return []library.ScanOption{library.FullRescan}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// fakeLidarrRemote is a Lidarr that accepts every artist and has them all.
|
|
type fakeLidarrRemote struct{}
|
|
|
|
func (fakeLidarrRemote) Add(context.Context, lidarr.AddRequest) error { return nil }
|
|
func (fakeLidarrRemote) Artist(context.Context, string) (*lidarr.Artist, error) {
|
|
return &lidarr.Artist{ID: 7, Name: "Someone", Monitored: true}, nil
|
|
}
|
|
|
|
type contract struct {
|
|
lastfm *fakeLastfm
|
|
t *testing.T
|
|
h http.Handler
|
|
db *bun.DB
|
|
reader *contractReader
|
|
router routers.Router
|
|
seen map[string]bool // "METHOD /path" of every operation exercised
|
|
music string
|
|
}
|
|
|
|
func newContract(t *testing.T) *contract {
|
|
t.Helper()
|
|
reader := &contractReader{}
|
|
tagsLF := &fakeTags{tags: []discovery.Tag{{Name: "rock", Weight: 100}}}
|
|
tagsMB := &fakeTags{tags: []discovery.Tag{{Name: "grunge", Weight: 12, Genre: true}}}
|
|
lf := &fakeLastfm{result: []lastfm.Similar{{Name: "Contract Neighbour", MBID: "99999999-0000-0000-0000-000000000009", Match: 1}}}
|
|
h, db := newTestEnvDB(t, func(d *Deps, db *bun.DB) {
|
|
prov := newProviders(db)
|
|
prov.SetChecker(providers.LastFM, func(context.Context, string) error { return nil })
|
|
d.Providers = prov
|
|
prov.SetChecker(providers.MusicBrainz, func(context.Context, string) error { return nil })
|
|
d.Discovery = discovery.NewService(storage.NewDiscoveryRepo(db), lf, prov, zap.NewNop())
|
|
d.Tags = discovery.NewTagService(storage.NewDiscoveryRepo(db),
|
|
map[string]discovery.TagSource{providers.LastFM: tagsLF, providers.MusicBrainz: tagsMB}, prov, zap.NewNop())
|
|
repo := storage.NewLibraryRepo(db)
|
|
mgr := library.NewManager(library.NewScanner(repo, reader, library.NewHub(), 2), repo)
|
|
libs := library.NewLibraries(repo)
|
|
libs.SetBusy(func() bool { return mgr.Status().Running })
|
|
d.Scan = scanAdapter{mgr}
|
|
dupSvc := duplicates.NewService(storage.NewDuplicatesRepo(db), duplicates.Options{
|
|
AllowDelete: true, ScanRunning: func() bool { return mgr.Status().Running }, Logger: zap.NewNop(),
|
|
})
|
|
d.Duplicates = dupSvc
|
|
d.DuplicatesJob = jobs.Runner{Ctx: context.Background(), Job: duplicates.NewHashJob(dupSvc)}
|
|
d.Libraries = libs
|
|
d.Catalog = catalog.NewService(storage.NewCatalogRepo(db))
|
|
d.Streams = streaming.NewService(repo)
|
|
imageRepo := storage.NewImageRepo(db)
|
|
pictures := images.NewService(filepath.Join(t.TempDir(), "data"), imageRepo, imageRepo)
|
|
pictures.SetArtistSource(&fakeArtistPictures{found: images.Found{Data: testJPEG(t, 800, 600, color.White),
|
|
Credit: images.Credit{Author: "Someone", License: "CC BY 4.0", LicenseURL: "https://creativecommons.org/licenses/by/4.0", PageURL: "https://commons.wikimedia.org/wiki/File:X.jpg"}}})
|
|
d.Images, d.ArtistImages = pictures, pictures
|
|
d.LidarrArtists = lidarr.NewService(storage.NewDiscoveryRepo(db), prov, fakeLidarrRemote{})
|
|
})
|
|
|
|
router, err := legacy.NewRouter(loadSpec(t))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
music := t.TempDir()
|
|
for _, f := range []string{"a.mp3", "b.flac", "c.mp3"} {
|
|
if err := os.WriteFile(filepath.Join(music, f), bytes.Repeat([]byte{0xAB}, 400), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
// A picture in the folder of the music, for the cover of its album.
|
|
var pic bytes.Buffer
|
|
if err := png.Encode(&pic, image.NewRGBA(image.Rect(0, 0, 40, 30))); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := os.WriteFile(filepath.Join(music, "cover.png"), pic.Bytes(), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return &contract{lastfm: lf, t: t, h: h, db: db, reader: reader, router: router, seen: map[string]bool{}, music: music}
|
|
}
|
|
|
|
// call sends a request to /api/v1<path>, checks it and its answer against the
|
|
// spec, and returns the answer. headers are extra request headers, in pairs.
|
|
func (c *contract) call(method, path, token string, body any, headers ...string) *httptest.ResponseRecorder {
|
|
c.t.Helper()
|
|
var payload []byte
|
|
if body != nil {
|
|
var err error
|
|
if payload, err = json.Marshal(body); err != nil {
|
|
c.t.Fatal(err)
|
|
}
|
|
}
|
|
req := httptest.NewRequest(method, "/api/v1"+path, bytes.NewReader(payload))
|
|
if body != nil {
|
|
req.Header.Set("Content-Type", "application/json")
|
|
}
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
for i := 0; i+1 < len(headers); i += 2 {
|
|
req.Header.Set(headers[i], headers[i+1])
|
|
}
|
|
rec := httptest.NewRecorder()
|
|
c.h.ServeHTTP(rec, req)
|
|
c.validate(req, payload, rec)
|
|
return rec
|
|
}
|
|
|
|
func (c *contract) validate(req *http.Request, payload []byte, rec *httptest.ResponseRecorder) {
|
|
c.t.Helper()
|
|
route, params, err := c.router.FindRoute(req)
|
|
if err != nil {
|
|
c.t.Errorf("%s %s is not in the spec: %v", req.Method, req.URL.Path, err)
|
|
return
|
|
}
|
|
c.seen[req.Method+" "+route.Path] = true
|
|
opts := &openapi3filter.Options{AuthenticationFunc: openapi3filter.NoopAuthenticationFunc}
|
|
where := req.Method + " " + req.URL.RequestURI()
|
|
|
|
// A request the server accepted must also be valid for the spec: that keeps
|
|
// the request schemas, parameters and headers honest.
|
|
if rec.Code < 400 {
|
|
clone := req.Clone(context.Background())
|
|
clone.Body = io.NopCloser(bytes.NewReader(payload))
|
|
in := &openapi3filter.RequestValidationInput{Request: clone, PathParams: params, Route: route, Options: opts}
|
|
if err := openapi3filter.ValidateRequest(context.Background(), in); err != nil {
|
|
c.t.Errorf("%s was accepted but does not match the spec: %v", where, err)
|
|
}
|
|
}
|
|
|
|
responses := route.Operation.Responses
|
|
documented := responses.Status(rec.Code)
|
|
if documented == nil && responses.Default() == nil {
|
|
c.t.Errorf("%s -> %d: this status is not documented in the spec", where, rec.Code)
|
|
return
|
|
}
|
|
|
|
// The library skips HEAD and redirects, and cannot read audio or YAML.
|
|
// Those are checked by hand: the status above, and the content type here.
|
|
skipBody := req.Method == http.MethodHead || route.Path == "/openapi.yaml" ||
|
|
(rec.Code >= 300 && rec.Code < 400) || (route.Path == "/tracks/{id}/stream" && rec.Code/100 == 2)
|
|
if skipBody && documented != nil && documented.Value != nil && rec.Code/100 == 2 && req.Method != http.MethodHead && route.Path == "/tracks/{id}/stream" {
|
|
mediaType, _, err := mime.ParseMediaType(rec.Header().Get("Content-Type"))
|
|
if err != nil || documented.Value.Content.Get(mediaType) == nil {
|
|
c.t.Errorf("%s -> %d: Content-Type %q is not one the spec lists", where, rec.Code, rec.Header().Get("Content-Type"))
|
|
}
|
|
}
|
|
|
|
in := &openapi3filter.RequestValidationInput{Request: req, PathParams: params, Route: route, Options: opts}
|
|
out := &openapi3filter.ResponseValidationInput{
|
|
RequestValidationInput: in,
|
|
Status: rec.Code,
|
|
Header: rec.Header(),
|
|
Options: &openapi3filter.Options{IncludeResponseStatus: true, ExcludeResponseBody: skipBody},
|
|
}
|
|
out.SetBodyBytes(rec.Body.Bytes())
|
|
if err := openapi3filter.ValidateResponse(context.Background(), out); err != nil {
|
|
c.t.Errorf("%s -> %d does not match the spec: %v\nbody: %.300s", where, rec.Code, err, rec.Body.String())
|
|
}
|
|
}
|
|
|
|
// expect checks the status and decodes a JSON body. For an error status the
|
|
// error code must be given and is compared too.
|
|
func (c *contract) expect(rec *httptest.ResponseRecorder, want int, what string, code ...string) map[string]any {
|
|
c.t.Helper()
|
|
if rec.Code != want {
|
|
c.t.Fatalf("%s: status %d, want %d: %s", what, rec.Code, want, rec.Body.String())
|
|
}
|
|
out := map[string]any{}
|
|
_ = json.Unmarshal(rec.Body.Bytes(), &out)
|
|
|
|
if want >= 400 {
|
|
if len(code) == 0 {
|
|
c.t.Fatalf("%s: an error case must say which error code it expects", what)
|
|
}
|
|
got, _ := out["error"].(map[string]any)["code"].(string)
|
|
if got != code[0] {
|
|
c.t.Fatalf("%s: error code %q, want %q", what, got, code[0])
|
|
}
|
|
}
|
|
return out
|
|
}
|
|
|
|
func mustInt(t *testing.T, s string) int64 {
|
|
t.Helper()
|
|
n, err := strconv.ParseInt(s, 10, 64)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return n
|
|
}
|
|
|
|
func idOf(m map[string]any) string { return strconv.FormatInt(int64(m["id"].(float64)), 10) }
|
|
|
|
// scanDone waits for the running scan to finish.
|
|
func (c *contract) scanDone(token string) {
|
|
c.t.Helper()
|
|
deadline := time.Now().Add(10 * time.Second)
|
|
for time.Now().Before(deadline) {
|
|
st := c.expect(c.call("GET", "/library/scan", token, nil), 200, "scan status")
|
|
if st["running"] == false {
|
|
return
|
|
}
|
|
time.Sleep(20 * time.Millisecond)
|
|
}
|
|
c.t.Fatal("the scan did not finish in time")
|
|
}
|
|
|
|
func TestResponsesMatchTheSpec(t *testing.T) {
|
|
c := newContract(t)
|
|
|
|
// ---- system ----
|
|
c.expect(c.call("GET", "/health", "", nil), 200, "health")
|
|
c.expect(c.call("GET", "/openapi.yaml", "", nil), 200, "openapi.yaml")
|
|
|
|
// ---- auth ----
|
|
creds := map[string]string{"email": "alice@example.org", "password": "correct horse"}
|
|
c.expect(c.call("POST", "/auth/register", "", map[string]string{"email": "x", "password": "short"}), 400, "register invalid", "invalid_input")
|
|
c.expect(c.call("POST", "/auth/register", "", creds), 201, "register")
|
|
c.expect(c.call("POST", "/auth/register", "", map[string]string{"email": "eve@example.org", "password": "correct horse"}), 403, "register closed", "registration_closed")
|
|
|
|
c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "alice@example.org", "password": "wrong password"}), 401, "login wrong", "invalid_credentials")
|
|
c.expect(c.call("POST", "/auth/login", "", "not an object"), 400, "login with a bad body", "invalid_input")
|
|
session := c.expect(c.call("POST", "/auth/login", "", creds), 200, "login")
|
|
token := session["access_token"].(string)
|
|
refresh := session["refresh_token"].(string)
|
|
|
|
c.expect(c.call("GET", "/auth/me", "", nil), 401, "me without token", "unauthorized")
|
|
c.expect(c.call("GET", "/auth/me", token, nil), 200, "me")
|
|
|
|
renewed := c.expect(c.call("POST", "/auth/refresh", "", map[string]string{"refresh_token": refresh}), 200, "refresh")
|
|
c.expect(c.call("POST", "/auth/refresh", "", map[string]string{"refresh_token": refresh}), 401, "refresh replay", "invalid_refresh_token")
|
|
c.expect(c.call("POST", "/auth/refresh", "", "not an object"), 400, "refresh bad body", "invalid_input")
|
|
c.expect(c.call("POST", "/auth/logout", "", map[string]string{"refresh_token": renewed["refresh_token"].(string)}), 204, "logout")
|
|
c.expect(c.call("POST", "/auth/logout", "", "not an object"), 400, "logout bad body", "invalid_input")
|
|
|
|
c.expect(c.call("POST", "/auth/password", token, map[string]string{"current_password": "nope nope nope", "new_password": "brand new pass"}), 403, "password wrong current", "invalid_credentials")
|
|
c.expect(c.call("POST", "/auth/password", token, map[string]string{"current_password": "correct horse", "new_password": "x"}), 400, "password weak", "invalid_input")
|
|
c.expect(c.call("POST", "/auth/password", "", map[string]string{}), 401, "password without token", "unauthorized")
|
|
c.expect(c.call("POST", "/auth/password", token, map[string]string{"current_password": "correct horse", "new_password": "brand new pass"}), 204, "password changed")
|
|
creds["password"] = "brand new pass"
|
|
token = c.expect(c.call("POST", "/auth/login", "", creds), 200, "login again")["access_token"].(string)
|
|
|
|
// ---- users ----
|
|
bob := c.expect(c.call("POST", "/users", token, map[string]any{"email": "bob@example.org", "password": "bobs long pass"}), 201, "create user")
|
|
c.expect(c.call("POST", "/users", token, map[string]any{"email": "BOB@example.org", "password": "bobs long pass"}), 409, "create duplicate", "email_taken")
|
|
c.expect(c.call("POST", "/users", token, map[string]any{"email": "x", "password": "bobs long pass"}), 400, "create invalid", "invalid_input")
|
|
bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "bob@example.org", "password": "bobs long pass"}), 200, "bob logs in")["access_token"].(string)
|
|
c.expect(c.call("GET", "/users", bobToken, nil), 403, "users as non-admin", "admin_required")
|
|
c.expect(c.call("GET", "/providers", bobToken, nil), 403, "providers as non-admin", "admin_required")
|
|
c.expect(c.call("GET", "/users", token, nil), 200, "list users")
|
|
bobID := idOf(bob)
|
|
c.expect(c.call("PATCH", "/users/"+bobID, token, map[string]bool{"is_admin": true}), 200, "promote")
|
|
c.expect(c.call("PATCH", "/users/"+bobID, token, map[string]bool{"is_admin": false}), 200, "demote")
|
|
c.expect(c.call("PATCH", "/users/999", token, map[string]bool{"is_admin": true}), 404, "patch unknown user", "user_not_found")
|
|
aliceID := idOf(c.expect(c.call("GET", "/auth/me", token, nil), 200, "me again"))
|
|
c.expect(c.call("PATCH", "/users/"+aliceID, token, map[string]bool{"is_admin": false}), 409, "demote the last admin", "last_admin")
|
|
c.expect(c.call("PUT", "/users/"+bobID+"/password", token, map[string]string{"password": "reset password"}), 204, "reset password")
|
|
c.expect(c.call("PUT", "/users/999/password", token, map[string]string{"password": "reset password"}), 404, "reset unknown", "user_not_found")
|
|
c.expect(c.call("DELETE", "/users/"+bobID, token, nil), 204, "delete user")
|
|
c.expect(c.call("DELETE", "/users/"+bobID, token, nil), 404, "delete twice", "user_not_found")
|
|
c.expect(c.call("DELETE", "/users/"+aliceID, token, nil), 409, "delete the last admin", "last_admin")
|
|
// A deleted admin's token stops working on admin routes at once.
|
|
c.expect(c.call("GET", "/users", bobToken, nil), 401, "a deleted account's token on an admin route", "unauthorized")
|
|
|
|
// ---- libraries and scan ----
|
|
c.expect(c.call("POST", "/library/scan", token, nil), 409, "scan with no library", "no_libraries")
|
|
lib := c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "Music", "path": c.music}), 201, "create library")
|
|
libID := idOf(lib)
|
|
c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "music", "path": t.TempDir()}), 409, "duplicate library name", "library_exists")
|
|
c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "Bad", "path": "relative/path"}), 400, "invalid library", "invalid_input")
|
|
c.expect(c.call("GET", "/libraries", token, nil), 200, "list libraries")
|
|
c.expect(c.call("PATCH", "/libraries/"+libID, token, map[string]string{"name": "My music"}), 200, "rename library")
|
|
c.expect(c.call("PATCH", "/libraries/999", token, map[string]string{"name": "x"}), 404, "patch unknown library", "library_not_found")
|
|
c.expect(c.call("PATCH", "/libraries/"+libID, token, map[string]string{"foo": "bar"}), 400, "patch with nothing to change", "invalid_input")
|
|
|
|
// A second library to collide with, and to delete at the end.
|
|
extra := c.expect(c.call("POST", "/libraries", token, map[string]string{"name": "Extra", "path": t.TempDir()}), 201, "second library")
|
|
extraID := idOf(extra)
|
|
c.expect(c.call("PATCH", "/libraries/"+extraID, token, map[string]string{"name": "my MUSIC"}), 409, "rename onto another name", "library_exists")
|
|
|
|
c.expect(c.call("POST", "/libraries/999/scan", token, nil), 404, "scan unknown library", "library_not_found")
|
|
|
|
// A scan that is still running: everything that must wait says so.
|
|
gate := c.reader.hold()
|
|
c.expect(c.call("POST", "/libraries/"+libID+"/scan", token, nil), 202, "scan one library")
|
|
if st := c.expect(c.call("GET", "/library/scan", token, nil), 200, "status while scanning"); st["running"] != true {
|
|
t.Fatalf("status = %v, want running", st)
|
|
}
|
|
c.expect(c.call("POST", "/library/scan", token, nil), 409, "scan all while scanning", "scan_running")
|
|
c.expect(c.call("POST", "/libraries/"+libID+"/scan", token, nil), 409, "scan one while scanning", "scan_running")
|
|
c.expect(c.call("PATCH", "/libraries/"+libID, token, map[string]string{"path": t.TempDir()}), 409, "move a library while scanning", "scan_running")
|
|
c.expect(c.call("DELETE", "/libraries/"+libID, token, nil), 409, "delete a library while scanning", "scan_running")
|
|
close(gate)
|
|
c.scanDone(token)
|
|
|
|
c.expect(c.call("POST", "/library/scan?full=maybe", token, nil), 400, "scan with a bad parameter", "invalid_input")
|
|
c.expect(c.call("POST", "/library/scan", token, nil), 202, "scan everything")
|
|
c.scanDone(token)
|
|
status := c.expect(c.call("GET", "/library/scan", token, nil), 200, "scan status")
|
|
last, _ := status["last"].(map[string]any)
|
|
if last["libraries"] != float64(2) || last["found"] != float64(3) || last["added"] != float64(0) || last["unchanged"] != float64(3) {
|
|
t.Fatalf("second scan = %v, want 3 files in 2 libraries, all unchanged", last)
|
|
}
|
|
|
|
c.expect(c.call("POST", "/library/scan?full=true", token, nil), 202, "scan everything again, in full")
|
|
c.scanDone(token)
|
|
if full := c.expect(c.call("GET", "/library/scan", token, nil), 200, "status after a full scan")["last"].(map[string]any); full["updated"] != float64(3) || full["unchanged"] != float64(0) {
|
|
t.Fatalf("full scan = %v, want the 3 files read again", full)
|
|
}
|
|
|
|
c.expect(c.call("DELETE", "/libraries/"+extraID, token, nil), 204, "delete library")
|
|
c.expect(c.call("DELETE", "/libraries/"+extraID, token, nil), 404, "delete library twice", "library_not_found")
|
|
|
|
// An album without an album artist, with a track whose file is gone from disk.
|
|
orphan := c.addOrphan(libID)
|
|
|
|
// ---- catalog ----
|
|
artists := c.expect(c.call("GET", "/artists?q=artist&limit=10&library_id="+libID, token, nil), 200, "artists")
|
|
artistID := idOf(artists["items"].([]any)[0].(map[string]any))
|
|
if page := c.expect(c.call("GET", "/artists?limit=0", token, nil), 200, "artists with limit 0"); page["limit"] != float64(50) {
|
|
t.Fatalf("limit=0 gave limit %v, want the default 50", page["limit"])
|
|
}
|
|
c.expect(c.call("GET", "/artists?limit=abc", token, nil), 400, "artists bad limit", "invalid_input")
|
|
c.expect(c.call("GET", "/artists/"+artistID, token, nil), 200, "artist")
|
|
c.expect(c.call("GET", "/artists/999", token, nil), 404, "artist unknown", "artist_not_found")
|
|
|
|
albums := c.expect(c.call("GET", "/albums?artist_id="+artistID, token, nil), 200, "albums")
|
|
albumID := idOf(albums["items"].([]any)[0].(map[string]any))
|
|
c.expect(c.call("GET", "/albums?offset=-1", token, nil), 400, "albums bad offset", "invalid_input")
|
|
c.expect(c.call("GET", "/albums/"+albumID, token, nil), 200, "album")
|
|
c.expect(c.call("GET", "/albums/999", token, nil), 404, "album unknown", "album_not_found")
|
|
orphanAlbum := c.expect(c.call("GET", "/albums/"+orphan.album, token, nil), 200, "an album without an album artist")
|
|
if v, present := orphanAlbum["artist"]; !present || v != nil {
|
|
t.Fatalf("album.artist = %#v, want an explicit null", v)
|
|
}
|
|
|
|
tracks := c.expect(c.call("GET", "/tracks?album_id="+albumID+"&artist_id="+artistID, token, nil), 200, "tracks")
|
|
items := tracks["items"].([]any)
|
|
if len(items) != 2 || tracks["total"] != float64(2) {
|
|
t.Fatalf("tracks = %v, want the two files of the album", tracks)
|
|
}
|
|
trackID := idOf(items[0].(map[string]any))
|
|
c.expect(c.call("GET", "/tracks?limit=-1", token, nil), 400, "tracks bad limit", "invalid_input")
|
|
c.expect(c.call("GET", "/tracks/"+trackID, token, nil), 200, "track")
|
|
c.expect(c.call("GET", "/tracks/999", token, nil), 404, "track unknown", "track_not_found")
|
|
loose := c.expect(c.call("GET", "/tracks?q=loose", token, nil), 200, "a track without an album")["items"].([]any)[0].(map[string]any)
|
|
if v, present := loose["album"]; !present || v != nil {
|
|
t.Fatalf("track.album = %#v, want an explicit null", v)
|
|
}
|
|
|
|
// ---- providers ----
|
|
listed := c.expect(c.call("GET", "/providers", token, nil), 200, "list providers")["providers"].([]any)
|
|
if len(listed) != 7 || listed[0].(map[string]any)["enabled"] != false || listed[1].(map[string]any)["enabled"] != false || listed[2].(map[string]any)["enabled"] != false || listed[3].(map[string]any)["enabled"] != false || listed[4].(map[string]any)["enabled"] != false || listed[5].(map[string]any)["enabled"] != false {
|
|
t.Fatalf("providers = %v, want seven, all off", listed)
|
|
}
|
|
// ---- lidarr ----
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"enabled": true}), 400, "enable lidarr with nothing", "invalid_input")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"url": "ftp://orion"}), 400, "lidarr with a bad address", "invalid_input")
|
|
c.expect(c.call("PUT", "/providers/musicbrainz", token, map[string]any{"url": "http://orion:8686"}), 400, "an address for a provider that has none", "invalid_input")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"api_key": "0123456789abcdef0123456789abcdef", "url": "http://orion:8686/"}), 200, "set up lidarr")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"lidarr": map[string]any{"quality_profile_id": 2, "metadata_profile_id": 1, "root_folder_path": "/music", "monitor": "latest"}}), 200, "lidarr options")
|
|
c.expect(c.call("GET", "/providers/lidarr/options", token, nil), 200, "what lidarr offers")
|
|
c.expect(c.call("GET", "/providers/lidarr/options", "", nil), 401, "lidarr options without a token", "unauthorized")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"enabled": true}), 200, "enable lidarr")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"enabled": false}), 200, "switch lidarr off again")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"api_key": "", "url": ""}), 200, "take lidarr's key and address away")
|
|
// ---- the other providers ----
|
|
c.expect(c.call("PUT", "/providers/lastfm", token, map[string]any{"enabled": true}), 400, "enable without a key", "invalid_input")
|
|
c.expect(c.call("PUT", "/providers/lastfm", token, map[string]any{"api_key": "short"}), 400, "a bad key", "invalid_input")
|
|
c.expect(c.call("PUT", "/providers/spotify", token, map[string]any{"enabled": true}), 404, "unknown provider", "provider_not_found")
|
|
c.expect(c.call("POST", "/providers/lastfm/test", token, nil), 200, "test without a key")
|
|
if mb := c.expect(c.call("POST", "/providers/musicbrainz/test", token, nil), 200, "test musicbrainz"); mb["ok"] != true {
|
|
t.Fatalf("musicbrainz test = %v", mb)
|
|
}
|
|
c.expect(c.call("POST", "/providers/spotify/test", token, nil), 404, "test an unknown provider", "provider_not_found")
|
|
c.expect(c.call("POST", "/providers/lastfm/test", "", nil), 401, "test without a token", "unauthorized")
|
|
off := c.expect(c.call("GET", "/artists/"+artistID+"/similar", token, nil), 200, "similar artists with the provider off")
|
|
if off["provider_status"] != "disabled" || c.lastfm.count() != 0 {
|
|
t.Fatalf("similar with the provider off = %v, calls %d", off, c.lastfm.count())
|
|
}
|
|
saved := c.expect(c.call("PUT", "/providers/lastfm", token, map[string]any{"api_key": "0123456789abcdef0123456789abcdef"}), 200, "save a key")
|
|
if saved["has_api_key"] != true || saved["updated_at"] == nil {
|
|
t.Fatalf("saved = %v", saved)
|
|
}
|
|
if on := c.expect(c.call("PUT", "/providers/lastfm", token, map[string]any{"enabled": true}), 200, "enable"); on["enabled"] != true {
|
|
t.Fatalf("enabled = %v", on)
|
|
}
|
|
if ok := c.expect(c.call("POST", "/providers/lastfm/test", token, nil), 200, "test with a key"); ok["ok"] != true {
|
|
t.Fatalf("test = %v", ok)
|
|
}
|
|
similar := c.expect(c.call("GET", "/artists/"+artistID+"/similar?limit=5", token, nil), 200, "similar artists")
|
|
if items := similar["items"].([]any); similar["provider_status"] != "ok" || len(items) != 1 {
|
|
t.Fatalf("similar = %v", similar)
|
|
}
|
|
c.expect(c.call("GET", "/artists/999/similar", token, nil), 404, "similar to an unknown artist", "artist_not_found")
|
|
c.expect(c.call("GET", "/artists/"+artistID+"/similar?limit=abc", token, nil), 400, "similar with a bad limit", "invalid_input")
|
|
c.expect(c.call("PUT", "/providers/musicbrainz", token, map[string]any{"enabled": true, "contact": "https://example.org/me"}), 200, "set up musicbrainz")
|
|
tags := c.expect(c.call("GET", "/artists/"+artistID+"/tags", token, nil), 200, "tags")["sources"].([]any)
|
|
if len(tags) != 3 || tags[0].(map[string]any)["provider_status"] != "ok" || tags[1].(map[string]any)["provider_status"] != "no_id" || tags[2].(map[string]any)["provider"] != "files" {
|
|
t.Fatalf("tags = %v, want Last.fm ok, MusicBrainz without an id and the files", tags)
|
|
}
|
|
c.expect(c.call("GET", "/artists/999/tags", token, nil), 404, "tags of an unknown artist", "artist_not_found")
|
|
purged := c.expect(c.call("DELETE", "/providers/lastfm/data", token, nil), 200, "purge a provider's data")
|
|
if purged["tags"] != float64(1) || purged["similar_artists"] != float64(1) {
|
|
t.Fatalf("purge = %v", purged)
|
|
}
|
|
c.expect(c.call("DELETE", "/providers/spotify/data", token, nil), 404, "purge an unknown provider", "provider_not_found")
|
|
c.expect(c.call("GET", "/artists/abc/tags", token, nil), 400, "tags of a bad id", "invalid_input")
|
|
|
|
// ---- playback ----
|
|
stream := "/tracks/" + trackID + "/stream"
|
|
c.expect(c.call("GET", stream, "", nil), 401, "stream without token", "unauthorized")
|
|
if rec := c.call("GET", stream, token, nil); rec.Code != 200 || rec.Body.Len() != 400 {
|
|
t.Fatalf("stream: %d, %d bytes", rec.Code, rec.Body.Len())
|
|
}
|
|
if rec := c.call("GET", stream+"?access_token="+token, "", nil); rec.Code != 200 {
|
|
t.Fatalf("stream with a query token: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", stream, token, nil, "Range", "bytes=0-99"); rec.Code != 206 || rec.Body.Len() != 100 {
|
|
t.Fatalf("stream range: %d, %d bytes", rec.Code, rec.Body.Len())
|
|
}
|
|
if rec := c.call("GET", stream, token, nil, "Range", "bytes=0-1,5-6"); rec.Code != 206 {
|
|
t.Fatalf("stream with two ranges: %d", rec.Code)
|
|
} else if mt, _, _ := mime.ParseMediaType(rec.Header().Get("Content-Type")); mt != "multipart/byteranges" {
|
|
t.Fatalf("two ranges answered with %q", rec.Header().Get("Content-Type"))
|
|
}
|
|
if rec := c.call("GET", stream, token, nil, "Range", "bytes=5000-"); rec.Code != 416 {
|
|
t.Fatalf("stream range past the end: %d", rec.Code)
|
|
}
|
|
future := time.Now().Add(time.Hour).UTC().Format(http.TimeFormat)
|
|
if rec := c.call("GET", stream, token, nil, "If-Modified-Since", future); rec.Code != 304 {
|
|
t.Fatalf("stream conditional: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", stream, token, nil, "If-Unmodified-Since", "Mon, 01 Jan 2001 00:00:00 GMT"); rec.Code != 412 {
|
|
t.Fatalf("stream with a failed precondition: %d", rec.Code)
|
|
}
|
|
if rec := c.call("HEAD", stream, token, nil); rec.Code != 200 || rec.Body.Len() != 0 {
|
|
t.Fatalf("stream HEAD: %d, %d bytes", rec.Code, rec.Body.Len())
|
|
}
|
|
if rec := c.call("HEAD", stream, token, nil, "Range", "bytes=0-9"); rec.Code != 206 {
|
|
t.Fatalf("stream HEAD with a range: %d", rec.Code)
|
|
}
|
|
if rec := c.call("HEAD", stream, token, nil, "If-Modified-Since", future); rec.Code != 304 {
|
|
t.Fatalf("stream HEAD conditional: %d", rec.Code)
|
|
}
|
|
c.expect(c.call("GET", "/tracks/999/stream", token, nil), 404, "stream unknown track", "track_not_found")
|
|
c.expect(c.call("GET", "/tracks/"+orphan.track+"/stream", token, nil), 404, "stream a file that is gone", "file_missing")
|
|
|
|
tid, _ := strconv.Atoi(trackID)
|
|
listen := map[string]any{"track_id": tid, "event_type": "complete", "duration_played_ms": 1000, "idempotency_key": "k1", "occurred_at": "2026-01-02T03:04:05Z"}
|
|
if got := c.expect(c.call("POST", "/listens", token, listen), 201, "listen"); got["counted"] != true {
|
|
t.Fatalf("a complete event must count: %v", got)
|
|
}
|
|
c.expect(c.call("POST", "/listens", token, listen), 200, "listen again")
|
|
short := map[string]any{"track_id": tid, "event_type": "play", "duration_played_ms": 3000, "idempotency_key": "k4"}
|
|
if got := c.expect(c.call("POST", "/listens", token, short), 201, "a short play"); got["counted"] != false {
|
|
t.Fatalf("a 3 s play must not count: %v", got)
|
|
}
|
|
c.expect(c.call("POST", "/listens", token, map[string]any{"track_id": tid, "event_type": "play", "duration_played_ms": 99999999, "idempotency_key": "k5"}), 400, "an implausible duration", "invalid_input")
|
|
history := c.expect(c.call("GET", "/listens", token, nil), 200, "history")
|
|
if history["total"] != float64(2) {
|
|
t.Fatalf("history = %v, want the two stored events", history)
|
|
}
|
|
onlyCounted := c.expect(c.call("GET", "/listens?counted=true&limit=5", token, nil), 200, "counted history")
|
|
if onlyCounted["total"] != float64(1) {
|
|
t.Fatalf("counted history = %v, want one", onlyCounted)
|
|
}
|
|
c.expect(c.call("GET", "/listens", "", nil), 401, "history without token", "unauthorized")
|
|
c.expect(c.call("GET", "/listens?counted=maybe", token, nil), 400, "history bad filter", "invalid_input")
|
|
c.expect(c.call("POST", "/listens", token, map[string]any{"track_id": 999, "event_type": "play", "idempotency_key": "k2"}), 404, "listen unknown track", "track_not_found")
|
|
c.expect(c.call("POST", "/listens", token, map[string]any{"track_id": tid, "event_type": "dance", "idempotency_key": "k3"}), 400, "listen invalid", "invalid_input")
|
|
|
|
// ---- taste ----
|
|
learned := c.expect(c.call("GET", "/me/taste?limit=5", token, nil), 200, "taste")
|
|
if arts := learned["artists"].([]any); len(arts) != 1 || arts[0].(map[string]any)["name"] != "Artist X" || arts[0].(map[string]any)["listens"] != float64(1) {
|
|
t.Fatalf("taste = %v, want Artist X, listened once", learned)
|
|
}
|
|
c.expect(c.call("GET", "/me/taste", "", nil), 401, "taste without a token", "unauthorized")
|
|
c.expect(c.call("GET", "/me/taste?limit=-1", token, nil), 400, "taste with a bad limit", "invalid_input")
|
|
c.expect(c.call("GET", "/me/taste?limit=abc", token, nil), 400, "taste with a limit that is not a number", "invalid_input")
|
|
|
|
// ---- sending an artist to Lidarr ----
|
|
if _, err := c.db.Exec("UPDATE artists SET mbid = NULL WHERE id = ?", artistID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c.expect(c.call("GET", "/artists/"+artistID+"/lidarr", "", nil), 401, "lidarr presence without a token", "unauthorized")
|
|
c.expect(c.call("POST", "/artists/"+artistID+"/lidarr", "", nil), 401, "send an artist without a token", "unauthorized")
|
|
c.expect(c.call("GET", "/artists/abc/lidarr", token, nil), 400, "lidarr presence of a bad id", "invalid_input")
|
|
c.expect(c.call("POST", "/artists/abc/lidarr", token, nil), 400, "send a bad id", "invalid_input")
|
|
c.expect(c.call("GET", "/artists/999999/lidarr", token, nil), 404, "lidarr presence of an unknown artist", "artist_not_found")
|
|
c.expect(c.call("POST", "/artists/999999/lidarr", token, nil), 404, "send an unknown artist", "artist_not_found")
|
|
c.expect(c.call("POST", "/artists/"+artistID+"/lidarr", token, nil), 422, "send an artist with no MusicBrainz id", "no_musicbrainz_id")
|
|
if got := c.expect(c.call("GET", "/artists/"+artistID+"/lidarr", token, nil), 200, "lidarr presence with no id"); got["provider_status"] != "no_id" {
|
|
t.Fatalf("presence = %v", got)
|
|
}
|
|
if _, err := c.db.Exec("UPDATE artists SET mbid = ? WHERE id = ?", "a74b1b7f-71a5-4011-9441-d0b5e4122711", artistID); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if got := c.expect(c.call("GET", "/artists/"+artistID+"/lidarr", token, nil), 200, "lidarr presence with the provider off"); got["provider_status"] != "disabled" || got["in_lidarr"] != false {
|
|
t.Fatalf("presence = %v", got)
|
|
}
|
|
c.expect(c.call("POST", "/artists/"+artistID+"/lidarr", token, nil), 409, "send an artist with lidarr off", "lidarr_disabled")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"api_key": "0123456789abcdef0123456789abcdef", "url": "http://orion:8686", "enabled": false}), 200, "set lidarr up again")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"lidarr": map[string]any{}}), 200, "forget the choices of lidarr")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"enabled": true}), 200, "switch lidarr on")
|
|
c.expect(c.call("POST", "/artists/"+artistID+"/lidarr", token, nil), 409, "send an artist before the profiles are chosen", "lidarr_not_configured")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"lidarr": map[string]any{"quality_profile_id": 1, "metadata_profile_id": 1, "root_folder_path": "/music"}}), 200, "choose the profiles")
|
|
if got := c.expect(c.call("POST", "/artists/"+artistID+"/lidarr", token, nil), 200, "send an artist"); got["status"] != "added" {
|
|
t.Fatalf("sent = %v", got)
|
|
}
|
|
if got := c.expect(c.call("GET", "/artists/"+artistID+"/lidarr", token, nil), 200, "lidarr presence"); got["provider_status"] != "ok" || got["in_lidarr"] != true || got["monitored"] != true {
|
|
t.Fatalf("presence = %v", got)
|
|
}
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"enabled": false}), 200, "switch lidarr off again")
|
|
c.expect(c.call("PUT", "/providers/lidarr", token, map[string]any{"api_key": "", "url": ""}), 200, "take lidarr's key and address away again")
|
|
if _, err := c.db.Exec("UPDATE artists SET mbid = NULL WHERE id = ?", artistID); err != nil { // as it was
|
|
t.Fatal(err)
|
|
}
|
|
|
|
// ---- description ----
|
|
desc := c.expect(c.call("GET", "/artists/"+artistID+"/description", token, nil), 200, "description with the provider off")
|
|
if desc["provider_status"] != "disabled" || desc["description"] != nil {
|
|
t.Fatalf("description = %v", desc)
|
|
}
|
|
c.expect(c.call("PUT", "/providers/wikipedia", token, map[string]any{"enabled": true, "contact": "https://example.org/me"}), 200, "switch Wikipedia on")
|
|
if noID := c.expect(c.call("GET", "/artists/"+artistID+"/description", token, nil), 200, "description of an artist without an id"); noID["provider_status"] != "no_id" {
|
|
t.Fatalf("description = %v, want no_id", noID)
|
|
}
|
|
c.expect(c.call("GET", "/artists/999/description", token, nil), 404, "description of an unknown artist", "artist_not_found")
|
|
c.expect(c.call("GET", "/artists/abc/description", token, nil), 400, "description of a bad id", "invalid_input")
|
|
c.expect(c.call("GET", "/artists/"+artistID+"/description", "", nil), 401, "description without a token", "unauthorized")
|
|
|
|
// ---- the covers job ----
|
|
if idle := c.expect(c.call("GET", "/library/covers", token, nil), 200, "the covers job before it ran"); idle["running"] != false {
|
|
t.Fatalf("covers job = %v", idle)
|
|
}
|
|
c.expect(c.call("POST", "/library/covers?refresh=maybe", token, nil), 400, "a covers job with a bad refresh", "invalid_input")
|
|
c.expect(c.call("POST", "/library/covers", "", nil), 401, "a covers job without a token", "unauthorized")
|
|
c.expect(c.call("POST", "/library/covers?refresh=true", token, nil), 202, "start the covers job")
|
|
for i := 0; ; i++ {
|
|
st := c.expect(c.call("GET", "/library/covers", token, nil), 200, "the covers job running")
|
|
if st["running"] == false {
|
|
if last, _ := st["last"].(map[string]any); last == nil || last["checked"] == nil {
|
|
t.Fatalf("covers job = %v, want a summary", st)
|
|
}
|
|
break
|
|
}
|
|
if i > 400 {
|
|
t.Fatal("the covers job did not finish")
|
|
}
|
|
time.Sleep(25 * time.Millisecond)
|
|
}
|
|
c.expect(c.call("DELETE", "/library/covers", token, nil), 204, "stop the covers job when none runs")
|
|
|
|
// ---- the artist jobs ----
|
|
for _, job := range []struct{ path, what string }{{"/library/artist-images", "artist pictures"}, {"/library/descriptions", "descriptions"}} {
|
|
if idle := c.expect(c.call("GET", job.path, token, nil), 200, "the "+job.what+" job before it ran"); idle["running"] != false {
|
|
t.Fatalf("%s job = %v", job.what, idle)
|
|
}
|
|
c.expect(c.call("POST", job.path+"?refresh=maybe", token, nil), 400, "a "+job.what+" job with a bad refresh", "invalid_input")
|
|
c.expect(c.call("POST", job.path, "", nil), 401, "a "+job.what+" job without a token", "unauthorized")
|
|
c.expect(c.call("POST", job.path, token, nil), 202, "start the "+job.what+" job")
|
|
for i := 0; ; i++ {
|
|
st := c.expect(c.call("GET", job.path, token, nil), 200, "the "+job.what+" job running")
|
|
if st["running"] == false {
|
|
if last, _ := st["last"].(map[string]any); last == nil || last["checked"] == nil {
|
|
t.Fatalf("%s job = %v, want a summary", job.what, st)
|
|
}
|
|
break
|
|
}
|
|
if i > 400 {
|
|
t.Fatalf("the %s job did not finish", job.what)
|
|
}
|
|
time.Sleep(25 * time.Millisecond)
|
|
}
|
|
c.expect(c.call("DELETE", job.path, token, nil), 204, "stop the "+job.what+" job when none runs")
|
|
}
|
|
|
|
// ---- covers ----
|
|
cover := "/albums/" + albumID + "/cover"
|
|
big := c.call("GET", cover, token, nil)
|
|
if big.Code != 200 || big.Header().Get("Content-Type") != "image/jpeg" {
|
|
t.Fatalf("cover: %d %s", big.Code, big.Header().Get("Content-Type"))
|
|
}
|
|
if sm := c.call("GET", cover+"?size=small", token, nil); sm.Code != 200 {
|
|
t.Fatalf("small cover: %d", sm.Code)
|
|
}
|
|
c.expect(c.call("GET", cover+"?size=huge", token, nil), 400, "a cover of a size that does not exist", "invalid_input")
|
|
c.expect(c.call("GET", "/albums/999/cover", token, nil), 404, "the cover of an unknown album", "album_not_found")
|
|
c.expect(c.call("GET", cover, "", nil), 401, "a cover without a token", "unauthorized")
|
|
if rec := c.call("GET", cover+"?access_token="+token, "", nil); rec.Code != 200 {
|
|
t.Fatalf("cover with the token in the query: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", cover, token, nil, "If-None-Match", big.Header().Get("ETag")); rec.Code != 304 {
|
|
t.Fatalf("cover If-None-Match: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", cover, token, nil, "Range", "bytes=0-9"); rec.Code != 206 || rec.Body.Len() != 10 {
|
|
t.Fatalf("cover Range: %d, %d bytes", rec.Code, rec.Body.Len())
|
|
}
|
|
if rec := c.call("HEAD", cover, token, nil); rec.Code != 200 {
|
|
t.Fatalf("cover HEAD: %d", rec.Code)
|
|
}
|
|
|
|
// ---- the picture of an artist ----
|
|
photo := "/artists/" + artistID + "/image"
|
|
if rec := c.call("GET", photo, token, nil); rec.Code != 200 || rec.Header().Get("Content-Type") != "image/jpeg" {
|
|
t.Fatalf("artist image: %d %s", rec.Code, rec.Header().Get("Content-Type"))
|
|
}
|
|
if rec := c.call("GET", photo+"?size=small", token, nil); rec.Code != 200 {
|
|
t.Fatalf("small artist image: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", photo, token, nil, "Range", "bytes=0-9"); rec.Code != 206 {
|
|
t.Fatalf("artist image range: %d", rec.Code)
|
|
}
|
|
if rec := c.call("HEAD", photo, token, nil); rec.Code != 200 {
|
|
t.Fatalf("artist image HEAD: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", photo+"?access_token="+token, "", nil); rec.Code != 200 {
|
|
t.Fatalf("artist image with the token in the query: %d", rec.Code)
|
|
}
|
|
if rec := c.call("GET", photo, token, nil, "If-None-Match", c.call("GET", photo, token, nil).Header().Get("ETag")); rec.Code != 304 {
|
|
t.Fatalf("artist image If-None-Match: %d", rec.Code)
|
|
}
|
|
if cr := c.expect(c.call("GET", photo+"/credit", token, nil), 200, "the credit of the picture"); cr["license"] != "CC BY 4.0" || cr["source"] != "Wikimedia Commons" {
|
|
t.Fatalf("credit = %v", cr)
|
|
}
|
|
c.expect(c.call("GET", photo+"?size=huge", token, nil), 400, "an artist image of a size that does not exist", "invalid_input")
|
|
c.expect(c.call("GET", "/artists/abc/image/credit", token, nil), 400, "the credit of a bad id", "invalid_input")
|
|
c.expect(c.call("GET", photo+"/credit", "", nil), 401, "the credit without a token", "unauthorized")
|
|
|
|
// ---- discover ----
|
|
c.expect(c.call("GET", "/discover", token, nil), 400, "discover with no seed and no permission", "seed_required")
|
|
found := c.expect(c.call("GET", "/discover?seed="+artistID+"&limit=5", token, nil), 200, "discover from a named seed")
|
|
if found["provider_status"] != "ok" || found["from_listening"] != false || len(found["seeds"].([]any)) != 1 {
|
|
t.Fatalf("discover = %v", found)
|
|
}
|
|
for _, it := range found["items"].([]any) {
|
|
if _, present := it.(map[string]any)["components"].(map[string]any)["g"]; !present {
|
|
t.Fatalf("an item has no g, not even null: %v", it)
|
|
}
|
|
}
|
|
c.expect(c.call("GET", "/discover?seed=999", token, nil), 400, "discover from an unknown seed", "invalid_input")
|
|
c.expect(c.call("GET", "/discover?seed="+artistID+"&in_library=maybe", token, nil), 400, "discover with a bad filter", "invalid_input")
|
|
c.expect(c.call("GET", "/discover?seed="+artistID+"&in_library=false", token, nil), 200, "discover outside the library")
|
|
c.expect(c.call("GET", "/discover", "", nil), 401, "discover without a token", "unauthorized")
|
|
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": true}), 200, "allow discover from my listening")
|
|
if fromListening := c.expect(c.call("GET", "/discover", token, nil), 200, "discover from my listening"); fromListening["from_listening"] != true {
|
|
t.Fatalf("discover = %v", fromListening)
|
|
}
|
|
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": false}), 200, "forbid it again")
|
|
|
|
// ---- playlists ----
|
|
c.expect(c.call("GET", "/playlists", "", nil), 401, "playlists without a token", "unauthorized")
|
|
c.expect(c.call("POST", "/playlists", token, map[string]string{"name": " "}), 400, "playlist with a blank name", "invalid_input")
|
|
plID := idOf(c.expect(c.call("POST", "/playlists", token, map[string]string{"name": "Road trip", "description": "for the car"}), 201, "create a playlist"))
|
|
if pls := c.expect(c.call("GET", "/playlists?limit=5", token, nil), 200, "list playlists"); pls["total"] != float64(1) {
|
|
t.Fatalf("playlists = %v", pls)
|
|
}
|
|
c.expect(c.call("GET", "/playlists?limit=-1", token, nil), 400, "playlists with a bad limit", "invalid_input")
|
|
c.expect(c.call("GET", "/playlists/"+plID, token, nil), 200, "get a playlist")
|
|
c.expect(c.call("GET", "/playlists/999", token, nil), 404, "get an unknown playlist", "playlist_not_found")
|
|
c.expect(c.call("PATCH", "/playlists/"+plID, token, map[string]string{"name": "Road trip 2"}), 200, "rename a playlist")
|
|
c.expect(c.call("PATCH", "/playlists/"+plID, token, map[string]string{}), 400, "patch a playlist with nothing", "invalid_input")
|
|
c.expect(c.call("PATCH", "/playlists/999", token, map[string]string{"name": "x"}), 404, "patch an unknown playlist", "playlist_not_found")
|
|
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []string{trackID, trackID}}), 400, "track ids as strings", "invalid_input")
|
|
if pl := c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID), mustInt(t, trackID)}}), 200, "add tracks to a playlist"); pl["track_count"] != float64(2) {
|
|
t.Fatalf("playlist = %v", pl)
|
|
}
|
|
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID)}, "position": 0}), 200, "add a track at the front")
|
|
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID)}, "position": 9}), 400, "add beyond the end", "invalid_position")
|
|
c.expect(c.call("POST", "/playlists/"+plID+"/tracks", token, map[string]any{"track_ids": []int64{999999}}), 422, "add an unknown track", "track_not_found")
|
|
c.expect(c.call("POST", "/playlists/999/tracks", token, map[string]any{"track_ids": []int64{mustInt(t, trackID)}}), 404, "add to an unknown playlist", "playlist_not_found")
|
|
plItems := c.expect(c.call("GET", "/playlists/"+plID+"/tracks?limit=10", token, nil), 200, "the tracks of a playlist")
|
|
if plItems["total"] != float64(3) {
|
|
t.Fatalf("items = %v", plItems)
|
|
}
|
|
firstItem := idOf(plItems["items"].([]any)[0].(map[string]any))
|
|
c.expect(c.call("GET", "/playlists/999/tracks", token, nil), 404, "tracks of an unknown playlist", "playlist_not_found")
|
|
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/"+firstItem, token, map[string]int{"position": 2}), 204, "move an item")
|
|
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/"+firstItem, token, map[string]int{"position": 3}), 400, "move beyond the end", "invalid_position")
|
|
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/"+firstItem, token, map[string]string{}), 400, "move with no position", "invalid_input")
|
|
c.expect(c.call("PATCH", "/playlists/"+plID+"/tracks/999999", token, map[string]int{"position": 0}), 404, "move an unknown item", "item_not_found")
|
|
c.expect(c.call("DELETE", "/playlists/"+plID+"/tracks/"+firstItem, token, nil), 204, "remove an item")
|
|
c.expect(c.call("DELETE", "/playlists/"+plID+"/tracks/"+firstItem, token, nil), 404, "remove it twice", "item_not_found")
|
|
c.expect(c.call("DELETE", "/playlists/"+plID, token, nil), 204, "delete a playlist")
|
|
c.expect(c.call("DELETE", "/playlists/"+plID, token, nil), 404, "delete it twice", "playlist_not_found")
|
|
|
|
// ---- wishlist and dismissed ----
|
|
gammaID := idOf(found["items"].([]any)[0].(map[string]any)["artist"].(map[string]any))
|
|
c.expect(c.call("PUT", "/wishlist/"+gammaID, token, nil), 204, "wish for an artist")
|
|
if wl := c.expect(c.call("GET", "/wishlist?limit=5", token, nil), 200, "wishlist"); wl["total"] != float64(1) {
|
|
t.Fatalf("wishlist = %v", wl)
|
|
}
|
|
c.expect(c.call("PUT", "/wishlist/999", token, nil), 404, "wish for an unknown artist", "artist_not_found")
|
|
c.expect(c.call("PUT", "/wishlist/abc", token, nil), 400, "wish for a bad id", "invalid_input")
|
|
c.expect(c.call("GET", "/wishlist?limit=-1", token, nil), 400, "wishlist with a bad limit", "invalid_input")
|
|
c.expect(c.call("GET", "/wishlist", "", nil), 401, "wishlist without a token", "unauthorized")
|
|
c.expect(c.call("DELETE", "/wishlist/"+gammaID, token, nil), 204, "take it off the wishlist")
|
|
c.expect(c.call("DELETE", "/wishlist/999", token, nil), 404, "take an unknown artist off", "artist_not_found")
|
|
c.expect(c.call("POST", "/discover/"+gammaID+"/dismiss", token, nil), 204, "dismiss an artist")
|
|
if dm := c.expect(c.call("GET", "/discover/dismissed", token, nil), 200, "dismissed"); dm["total"] != float64(1) {
|
|
t.Fatalf("dismissed = %v", dm)
|
|
}
|
|
c.expect(c.call("POST", "/discover/999/dismiss", token, nil), 404, "dismiss an unknown artist", "artist_not_found")
|
|
c.expect(c.call("GET", "/discover/dismissed?offset=-1", token, nil), 400, "dismissed with a bad offset", "invalid_input")
|
|
c.expect(c.call("DELETE", "/discover/"+gammaID+"/dismiss", token, nil), 204, "interested again")
|
|
c.expect(c.call("DELETE", "/discover/999/dismiss", token, nil), 404, "undismiss an unknown artist", "artist_not_found")
|
|
|
|
// ---- my settings ----
|
|
if got := c.expect(c.call("GET", "/me/settings", token, nil), 200, "settings"); got["discover_from_listening"] != false {
|
|
t.Fatalf("settings = %v, want everything off", got)
|
|
}
|
|
if got := c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": true}), 200, "turn a setting on"); got["discover_from_listening"] != true {
|
|
t.Fatalf("settings = %v", got)
|
|
}
|
|
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"discover_from_listening": "yes"}), 400, "a setting that is not a boolean", "invalid_input")
|
|
c.expect(c.call("PATCH", "/me/settings", token, map[string]any{"nope": true}), 400, "a setting that does not exist", "invalid_input")
|
|
c.expect(c.call("GET", "/me/settings", "", nil), 401, "settings without a token", "unauthorized")
|
|
|
|
// ---- duplicate songs ----
|
|
c.duplicates(t, token, libID)
|
|
|
|
// ---- mixes ----
|
|
c.mixes(t, token, libID)
|
|
c.smartPlaylists(t, token)
|
|
c.names(t, token)
|
|
|
|
// ---- every operation in the spec was exercised ----
|
|
var missing []string
|
|
for _, op := range specOperations(loadSpec(t)) {
|
|
if !c.seen[op] {
|
|
missing = append(missing, op)
|
|
}
|
|
}
|
|
if len(missing) > 0 {
|
|
t.Errorf("operations the contract test never called (add a request for each):\n %v", missing)
|
|
}
|
|
}
|
|
|
|
// duplicates exercises the duplicate songs: the same song as a.mp3 is added to the library, as real
|
|
// files, so that what is checked against the spec is what the real services answer.
|
|
func (c *contract) duplicates(t *testing.T, token, libID string) {
|
|
t.Helper()
|
|
repo := storage.NewLibraryRepo(c.db)
|
|
libInt, err := strconv.ParseInt(libID, 10, 64)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// addCopy puts a second file with the tags of Song A in the library, as the scanner would.
|
|
addCopy := func(name string) {
|
|
t.Helper()
|
|
path := filepath.Join(c.music, name)
|
|
if err := os.WriteFile(path, bytes.Repeat([]byte{0xAB}, 400), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
info, err := os.Stat(path)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
f := library.ParsedFile{
|
|
FileInfo: library.FileInfo{RelPath: name, Size: info.Size(), MTimeUnix: info.ModTime().Unix()},
|
|
Metadata: library.Metadata{
|
|
Tags: library.Tags{Title: "Song A", Album: "Compilation", AlbumArtist: "Artist X", Artists: []string{"Artist X"}, TrackNo: 1, DiscNo: 1},
|
|
Properties: library.Properties{Format: "mpeg", DurationMs: 180000, SampleRate: 44100},
|
|
},
|
|
}
|
|
if _, err := repo.SaveFile(context.Background(), libInt, f, 0); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
trackOf := func(name string) int64 {
|
|
t.Helper()
|
|
var id int64
|
|
if err := c.db.QueryRow("SELECT track_id FROM audio_files WHERE rel_path = ?", name).Scan(&id); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return id
|
|
}
|
|
exists := func(name string) bool { _, err := os.Lstat(filepath.Join(c.music, name)); return err == nil }
|
|
body := func(keep int64, remove ...int64) map[string]any {
|
|
return map[string]any{"keep_track_id": keep, "remove_track_ids": remove}
|
|
}
|
|
|
|
none := c.expect(c.call("GET", "/library/duplicates", token, nil), 200, "duplicates when there are none")
|
|
if none["total"] != float64(0) || none["groups"] == nil || none["deletion_allowed"] != true {
|
|
t.Fatalf("duplicates = %v, want no group, an empty list and deleting allowed", none)
|
|
}
|
|
|
|
addCopy("dup.mp3")
|
|
keep, copyID := trackOf("a.mp3"), trackOf("dup.mp3")
|
|
list := c.expect(c.call("GET", "/library/duplicates", token, nil), 200, "duplicates")
|
|
groups, _ := list["groups"].([]any)
|
|
if list["total"] != float64(1) || len(groups) != 1 {
|
|
t.Fatalf("duplicates = %v, want the one group of Song A", list)
|
|
}
|
|
if g := groups[0].(map[string]any); g["title"] != "Song A" || g["suggested_keep_track_id"] != float64(keep) || g["hashed"] != false {
|
|
t.Fatalf("group = %v, want Song A with a.mp3 to keep and nothing read yet", g)
|
|
}
|
|
c.expect(c.call("GET", "/library/duplicates?limit=-1", token, nil), 400, "duplicates with a bad limit", "invalid_input")
|
|
c.expect(c.call("GET", "/library/duplicates", "", nil), 401, "duplicates without a token", "unauthorized")
|
|
|
|
// Not an admin: nothing of this is theirs.
|
|
c.expect(c.call("POST", "/users", token, map[string]any{"email": "carol@example.org", "password": "carols long pass"}), 201, "create a plain user")
|
|
carol := c.expect(c.call("POST", "/auth/login", "", map[string]string{"email": "carol@example.org", "password": "carols long pass"}), 200, "carol logs in")["access_token"].(string)
|
|
c.expect(c.call("GET", "/library/duplicates", carol, nil), 403, "duplicates as a plain user", "admin_required")
|
|
c.expect(c.call("POST", "/library/duplicates/clean", carol, body(keep, copyID)), 403, "cleaning as a plain user", "admin_required")
|
|
|
|
// The check reads the files, and the group is then identical.
|
|
if idle := c.expect(c.call("GET", "/library/duplicates/check", token, nil), 200, "the check before it ran"); idle["running"] != false {
|
|
t.Fatalf("check = %v", idle)
|
|
}
|
|
c.expect(c.call("POST", "/library/duplicates/check?refresh=maybe", token, nil), 400, "a check with a bad refresh", "invalid_input")
|
|
c.expect(c.call("POST", "/library/duplicates/check", "", nil), 401, "a check without a token", "unauthorized")
|
|
c.expect(c.call("POST", "/library/duplicates/check", token, nil), 202, "start the check")
|
|
for i := 0; ; i++ {
|
|
st := c.expect(c.call("GET", "/library/duplicates/check", token, nil), 200, "the check running")
|
|
if st["running"] == false {
|
|
if last, _ := st["last"].(map[string]any); last == nil || last["checked"] != float64(2) || last["hashed"] != float64(2) {
|
|
t.Fatalf("check = %v, want 2 files checked and hashed", st)
|
|
}
|
|
break
|
|
}
|
|
if i > 400 {
|
|
t.Fatal("the check did not finish")
|
|
}
|
|
time.Sleep(25 * time.Millisecond)
|
|
}
|
|
c.expect(c.call("DELETE", "/library/duplicates/check", token, nil), 204, "stop the check when none runs")
|
|
after := c.expect(c.call("GET", "/library/duplicates", token, nil), 200, "duplicates after the check")
|
|
if g := after["groups"].([]any)[0].(map[string]any); g["hashed"] != true || g["identical"] != true {
|
|
t.Fatalf("group = %v, want hashed and identical", g)
|
|
}
|
|
|
|
// Refusals first: nothing is removed by any of them.
|
|
c.expect(c.call("POST", "/library/duplicates/clean", token, body(keep, keep)), 400, "cleaning the copy to keep", "invalid_input")
|
|
c.expect(c.call("POST", "/library/duplicates/clean", token, map[string]any{"keep_track_id": keep}), 400, "cleaning with nothing to remove", "invalid_input")
|
|
c.expect(c.call("POST", "/library/duplicates/clean", token, body(keep, 99999)), 404, "cleaning a track that does not exist", "track_not_found")
|
|
c.expect(c.call("POST", "/library/duplicates/clean", "", body(keep, copyID)), 401, "cleaning without a token", "unauthorized")
|
|
other := trackOf("b.flac")
|
|
c.expect(c.call("POST", "/library/duplicates/clean", token, body(keep, other)), 400, "cleaning something that is not a copy", "invalid_input")
|
|
if !exists("dup.mp3") || !exists("b.flac") {
|
|
t.Fatal("a refused request removed a file")
|
|
}
|
|
|
|
// A copy that changed since the scan is not removed.
|
|
addCopy("dup2.mp3")
|
|
dup2 := trackOf("dup2.mp3")
|
|
if err := os.WriteFile(filepath.Join(c.music, "dup2.mp3"), bytes.Repeat([]byte{0xCD}, 500), 0o644); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
c.expect(c.call("POST", "/library/duplicates/clean", token, body(keep, dup2)), 409, "cleaning a copy that changed", "duplicate_changed")
|
|
if !exists("dup2.mp3") {
|
|
t.Fatal("a copy that changed was removed")
|
|
}
|
|
|
|
// The real thing: the extra copy leaves the disk and the index, the other stays.
|
|
done := c.expect(c.call("POST", "/library/duplicates/clean", token, body(keep, copyID)), 200, "clean the duplicate")
|
|
if done["removed"] != float64(1) || done["freed_bytes"] != float64(400) {
|
|
t.Fatalf("clean = %v, want 1 file and 400 bytes", done)
|
|
}
|
|
if exists("dup.mp3") || !exists("a.mp3") {
|
|
t.Fatalf("after the clean dup.mp3 exists=%v a.mp3 exists=%v", exists("dup.mp3"), exists("a.mp3"))
|
|
}
|
|
}
|
|
|
|
type orphanIDs struct{ album, track string }
|
|
|
|
// addOrphan inserts an album with no album artist and a track in it whose file
|
|
// does not exist, the way rows from an older version or a removed file look.
|
|
func (c *contract) addOrphan(libraryID string) orphanIDs {
|
|
c.t.Helper()
|
|
var album, track int64
|
|
if err := c.db.QueryRow(`INSERT INTO albums (title, title_key) VALUES ('Orphan Album', 'orphan album') RETURNING id`).Scan(&album); err != nil {
|
|
c.t.Fatal(err)
|
|
}
|
|
if err := c.db.QueryRow(`INSERT INTO tracks (title, title_key, album_id) VALUES ('Orphan Song', 'orphan song', ?) RETURNING id`, album).Scan(&track); err != nil {
|
|
c.t.Fatal(err)
|
|
}
|
|
if _, err := c.db.Exec(`INSERT INTO audio_files (track_id, library_id, rel_path, format, size_bytes, mtime_unix)
|
|
VALUES (?, ?, 'no-such-file.mp3', 'mp3', 1, 1)`, track, libraryID); err != nil {
|
|
c.t.Fatal(err)
|
|
}
|
|
return orphanIDs{album: strconv.FormatInt(album, 10), track: strconv.FormatInt(track, 10)}
|
|
}
|
|
|
|
// mixes exercises the mixes. The library gets 40 songs of one genre by 6 artists, enough for a
|
|
// genre mix; they are added last so that nothing that counts songs sees them.
|
|
func (c *contract) mixes(t *testing.T, token, libID string) {
|
|
t.Helper()
|
|
ctx := context.Background()
|
|
repo := storage.NewLibraryRepo(c.db)
|
|
for i := 0; i < 40; i++ {
|
|
artist := "Mix artist " + strconv.Itoa(i%6)
|
|
title := "Mix song " + strconv.Itoa(i)
|
|
f := library.ParsedFile{
|
|
FileInfo: library.FileInfo{RelPath: "mixes/" + title + ".flac", Size: 100, MTimeUnix: 1},
|
|
Metadata: library.Metadata{
|
|
Tags: library.Tags{Title: title, Album: "Mix album", AlbumArtist: artist, Artists: []string{artist}, TrackNo: i + 1, DiscNo: 1, Genres: []string{"synthwave"}},
|
|
Properties: library.Properties{Format: "flac", DurationMs: 60000, SampleRate: 44100},
|
|
},
|
|
}
|
|
if _, err := repo.SaveFile(ctx, mustInt(t, libID), f, 0); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
c.expect(c.call("GET", "/mixes", "", nil), 401, "mixes without a token", "unauthorized")
|
|
list := c.expect(c.call("GET", "/mixes", token, nil), 200, "list mixes")
|
|
var found bool
|
|
for _, x := range list["items"].([]any) {
|
|
if x.(map[string]any)["id"] == "genre:synthwave" {
|
|
found = true
|
|
}
|
|
}
|
|
if !found {
|
|
t.Fatalf("mixes = %v, want a synthwave mix", list)
|
|
}
|
|
mix := c.expect(c.call("GET", "/mixes/genre%3Asynthwave", token, nil), 200, "get a mix")
|
|
if len(mix["tracks"].([]any)) != 40 {
|
|
t.Fatalf("mix = %v", mix)
|
|
}
|
|
c.expect(c.call("GET", "/mixes/genre%3Asynthwave?variant=3", token, nil), 200, "get another variant")
|
|
c.expect(c.call("GET", "/mixes/genre%3Asynthwave?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
|
|
c.expect(c.call("GET", "/mixes/genre%3Apolka", token, nil), 404, "an unknown mix", "mix_not_found")
|
|
c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, map[string]any{"name": "Synth", "variant": 3}), 201, "save a mix as a playlist")
|
|
c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, nil), 201, "save a mix with no body")
|
|
c.expect(c.call("POST", "/mixes/genre%3Apolka/playlist", token, nil), 404, "save an unknown mix", "mix_not_found")
|
|
c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, map[string]any{"variant": -1}), 400, "save with a negative variant", "invalid_input")
|
|
}
|
|
|
|
// smartPlaylists makes, reads, previews, changes, keeps and deletes smart playlists, over the synthwave
|
|
// songs that c.mixes added.
|
|
func (c *contract) smartPlaylists(t *testing.T, token string) {
|
|
t.Helper()
|
|
rules := map[string]any{"genres": []string{"synthwave"}, "formats": []string{"flac"}, "never_played": true}
|
|
c.expect(c.call("GET", "/smart-playlists", "", nil), 401, "smart playlists without a token", "unauthorized")
|
|
sug := c.expect(c.call("GET", "/smart-playlists/suggested", token, nil), 200, "the suggested smart playlists")
|
|
if len(sug["items"].([]any)) < 5 {
|
|
t.Fatalf("suggested = %v", sug)
|
|
}
|
|
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/tracks", token, nil), 200, "the songs of a suggested one")
|
|
c.expect(c.call("GET", "/smart-playlists/suggested/never-played/tracks?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
|
|
c.expect(c.call("GET", "/smart-playlists/suggested/nonsense/tracks", token, nil), 404, "an unknown suggested one", "suggested_not_found")
|
|
c.expect(c.call("POST", "/smart-playlists/suggested/never-played/playlist", token, map[string]any{"name": "Fresh ears", "variant": 1}), 201, "keep a suggested one")
|
|
c.expect(c.call("POST", "/smart-playlists/suggested/never-played/playlist", token, nil), 201, "keep a suggested one with no body")
|
|
c.expect(c.call("POST", "/smart-playlists/suggested/high-quality/playlist", token, nil), 422, "keep a suggested one with no songs", "smart_playlist_empty")
|
|
c.expect(c.call("POST", "/smart-playlists/suggested/nonsense/playlist", token, nil), 404, "keep an unknown suggested one", "suggested_not_found")
|
|
genres := c.expect(c.call("GET", "/genres", token, nil), 200, "the genres of the library")
|
|
if len(genres["items"].([]any)) == 0 {
|
|
t.Fatalf("genres = %v", genres)
|
|
}
|
|
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "", "rules": rules}), 400, "a smart playlist with no name", "invalid_input")
|
|
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "x", "sort": "loudest"}), 400, "an unknown order", "invalid_input")
|
|
made := c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "Fresh synth", "description": "new", "rules": rules, "sort": "title", "limit": 12}), 201, "make a smart playlist")
|
|
id := strconv.Itoa(int(made["id"].(float64)))
|
|
list := c.expect(c.call("GET", "/smart-playlists?limit=5&offset=0", token, nil), 200, "list smart playlists")
|
|
if list["total"] != float64(1) {
|
|
t.Fatalf("smart playlists = %v", list)
|
|
}
|
|
c.expect(c.call("GET", "/smart-playlists/"+id, token, nil), 200, "get a smart playlist")
|
|
c.expect(c.call("GET", "/smart-playlists/999999", token, nil), 404, "an unknown smart playlist", "smart_playlist_not_found")
|
|
c.expect(c.call("GET", "/smart-playlists/0", token, nil), 400, "a bad smart playlist id", "invalid_input")
|
|
got := c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks", token, nil), 200, "the songs of a smart playlist")
|
|
if len(got["tracks"].([]any)) != 12 {
|
|
t.Fatalf("smart playlist songs = %v", got)
|
|
}
|
|
c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks?variant=2", token, nil), 200, "the songs, another variant")
|
|
c.expect(c.call("GET", "/smart-playlists/"+id+"/tracks?variant=-1", token, nil), 400, "a negative variant", "invalid_input")
|
|
c.expect(c.call("GET", "/smart-playlists/999999/tracks", token, nil), 404, "the songs of an unknown smart playlist", "smart_playlist_not_found")
|
|
c.expect(c.call("POST", "/smart-playlists/preview", token, map[string]any{"rules": map[string]any{"min_duration_sec": 30, "liked_artists_only": false}, "sort": "most_played", "limit": 5, "variant": 1}), 200, "preview rules")
|
|
c.expect(c.call("POST", "/smart-playlists/preview", token, map[string]any{"rules": map[string]any{"min_plays": -1}}), 400, "preview bad rules", "invalid_input")
|
|
c.expect(c.call("PATCH", "/smart-playlists/"+id, token, map[string]any{"name": "Fresher", "rules": map[string]any{"added_within_days": 3650}}), 200, "change a smart playlist")
|
|
c.expect(c.call("PATCH", "/smart-playlists/"+id, token, map[string]any{"limit": 0, "name": ""}), 400, "change to a bad name", "invalid_input")
|
|
c.expect(c.call("PATCH", "/smart-playlists/999999", token, map[string]any{"name": "x"}), 404, "change an unknown smart playlist", "smart_playlist_not_found")
|
|
c.expect(c.call("POST", "/smart-playlists/"+id+"/playlist", token, map[string]any{"name": "Kept", "variant": 1}), 201, "keep a smart playlist as a playlist")
|
|
c.expect(c.call("POST", "/smart-playlists/"+id+"/playlist", token, nil), 201, "keep with no body")
|
|
c.expect(c.call("POST", "/smart-playlists/999999/playlist", token, nil), 404, "keep an unknown smart playlist", "smart_playlist_not_found")
|
|
empty := c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "Polka", "rules": map[string]any{"genres": []string{"polka"}}}), 201, "make a smart playlist that gives nothing")
|
|
c.expect(c.call("POST", "/smart-playlists/"+strconv.Itoa(int(empty["id"].(float64)))+"/playlist", token, nil), 422, "keep one that gives no songs", "smart_playlist_empty")
|
|
c.expect(c.call("DELETE", "/smart-playlists/"+id, token, nil), 204, "delete a smart playlist")
|
|
c.expect(c.call("DELETE", "/smart-playlists/"+id, token, nil), 404, "delete it again", "smart_playlist_not_found")
|
|
}
|
|
|
|
// names asks for names with the Claude provider off, so that the local ones answer.
|
|
func (c *contract) names(t *testing.T, token string) {
|
|
t.Helper()
|
|
c.expect(c.call("GET", "/providers/anthropic/usage", "", nil), 401, "the costs without a token", "unauthorized")
|
|
use := c.expect(c.call("GET", "/providers/anthropic/usage?days=7", token, nil), 200, "the costs")
|
|
if use["days"] != float64(7) || use["estimate"] != true || len(use["daily"].([]any)) != 0 {
|
|
t.Fatalf("costs = %v", use)
|
|
}
|
|
c.expect(c.call("GET", "/providers/anthropic/usage?days=366", token, nil), 400, "the costs of too many days", "invalid_input")
|
|
c.expect(c.call("GET", "/naming", "", nil), 401, "naming status without a token", "unauthorized")
|
|
if st := c.expect(c.call("GET", "/naming", token, nil), 200, "naming status"); st["auto"] != false {
|
|
t.Fatalf("naming status = %v, want off", st)
|
|
}
|
|
named := c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, map[string]any{"name": "Synth mix", "auto_name": true, "lang": "it"}), 201, "keep a mix with an automatic name, Claude off")
|
|
if named["name"] != "Synth mix" {
|
|
t.Fatalf("playlist = %v: with Claude off the given name stays", named)
|
|
}
|
|
c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "", "rules": map[string]any{}, "lang": "it"}), 400, "a smart playlist with no name and Claude off", "invalid_input")
|
|
c.expect(c.call("POST", "/mixes/genre%3Asynthwave/suggest-name", "", nil), 401, "a name without a token", "unauthorized")
|
|
mix := c.expect(c.call("POST", "/mixes/genre%3Asynthwave/suggest-name", token, map[string]any{"lang": "it", "variant": 1}), 200, "a name for a mix")
|
|
if mix["source"] != "local" || mix["name"] != "Mix Synthwave" {
|
|
t.Fatalf("mix name = %v", mix)
|
|
}
|
|
c.expect(c.call("POST", "/mixes/genre%3Asynthwave/suggest-name", token, nil), 200, "a name for a mix with no body")
|
|
c.expect(c.call("POST", "/mixes/genre%3Apolka/suggest-name", token, nil), 404, "a name for an unknown mix", "mix_not_found")
|
|
c.expect(c.call("POST", "/mixes/genre%3Asynthwave/suggest-name", token, map[string]any{"variant": -1}), 400, "a bad variant", "invalid_input")
|
|
pl := c.expect(c.call("POST", "/playlists", token, map[string]any{"name": "tmp"}), 201, "make a playlist to name")
|
|
id := strconv.Itoa(int(pl["id"].(float64)))
|
|
c.expect(c.call("POST", "/playlists/"+id+"/suggest-name", token, nil), 200, "a name for an empty playlist")
|
|
c.expect(c.call("POST", "/playlists/999999/suggest-name", token, nil), 404, "a name for an unknown playlist", "playlist_not_found")
|
|
sp := c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "Synth", "rules": map[string]any{"genres": []string{"synthwave"}}, "limit": 10}), 201, "make a smart playlist to name")
|
|
sid := strconv.Itoa(int(sp["id"].(float64)))
|
|
c.expect(c.call("POST", "/smart-playlists/"+sid+"/suggest-name", token, map[string]any{"lang": "en"}), 200, "a name for a smart playlist")
|
|
c.expect(c.call("POST", "/smart-playlists/999999/suggest-name", token, nil), 404, "a name for an unknown smart playlist", "smart_playlist_not_found")
|
|
}
|