Registration, login and the admin's create-user call take `email` instead of `username`, and the user object returns `email`. The address is checked for its shape (a plain address, no display name, at most 254 bytes), trimmed, lowercased and unique. Sonda sends no mail and does not verify it. - Migration 0018 renames the users column (and the PostgreSQL index); values are kept, so an account made before keeps its plain name and still logs in with it (login does not check the shape). - Error code username_taken becomes email_taken; the JWT claim is now `email`, so access tokens issued before the upgrade are refused once and clients refresh. - OpenAPI spec, README, the web login form (type email), strings (en, it) and the generated API types follow. Closes #65
800 lines
45 KiB
Go
800 lines
45 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/images"
|
|
"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}
|
|
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 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) != 6 || 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 six, 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")
|
|
|
|
// ---- 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")
|
|
|
|
// ---- 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)
|
|
}
|
|
}
|
|
|
|
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)}
|
|
}
|