sonda/internal/api/http/contract_test.go
tgiachi aafb2dd906 feat(discovery): similar artists from Last.fm
- feat: GET /api/v1/artists/{id}/similar lists the artists Last.fm finds similar
  to one in the library, best first, each with the provider's own score and
  rank and a flag saying whether it is in the library. It answers 200 when the
  provider is off or failing, with provider_status, stale and retrieved_at
- feat: a thin Last.fm client on top of the outbound client. It always sends
  autocorrect=0 so a misspelled local name cannot turn into another artist,
  prefers the MusicBrainz id when known, always sets a limit, and reads the
  error field even when the status is 200. Errors never carry the URL or the
  provider's own message, because the key travels in the query string
- feat: results are stored in artist_similar with a freshness ledger in
  provider_fetches: 7 days for an answer, 1 day for "unknown artist". Old data
  is served when the provider fails, and concurrent requests for the same
  artist share one call that does not depend on the first caller staying
- feat: artists named by a provider but without files become artists without
  tracks. GET /artists/{id} can show them (track_count 0), the lists of the
  library never include them, and a later scan adopts them by name. A provider
  id is never written onto an existing artist; names match only when at least
  one side has no id, and different ids always mean different artists
- feat: POST /providers/{name}/test (admin) checks a stored key with one cheap
  request, whether the provider is on or off, and reports ok, no_api_key,
  key_refused, rate_limited, unreachable or error
- test: the whole request is checked from the receiving end, with a user, a
  listen, a title and a library path in the database: only the artist and the
  key leave, with a User-Agent that names the project
- docs: README and OpenAPI updated; the contract test calls the new operations
2026-11-11 16:42:52 +01:00

512 lines
26 KiB
Go

package httpapi
import (
"bytes"
"context"
"encoding/json"
"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/library"
"codeberg.org/squidd/sonda/internal/providers"
"codeberg.org/squidd/sonda/internal/providers/lastfm"
"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() error { return a.m.Start(context.Background()) }
func (a scanAdapter) StartLibrary(id int64) error { return a.m.StartLibrary(context.Background(), id) }
func (a scanAdapter) Status() library.Status { return a.m.Status() }
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{}
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 := providers.NewService(storage.NewProviderRepo(db))
prov.SetChecker(providers.LastFM, func(context.Context, string) error { return nil })
d.Providers = prov
d.Discovery = discovery.NewService(storage.NewDiscoveryRepo(db), lf, 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)
})
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)
}
}
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{"username": "alice", "password": "correct horse"}
c.expect(c.call("POST", "/auth/register", "", map[string]string{"username": "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{"username": "eve", "password": "correct horse"}), 403, "register closed", "registration_closed")
c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "alice", "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{"username": "bob", "password": "bobs long pass"}), 201, "create user")
c.expect(c.call("POST", "/users", token, map[string]any{"username": "BOB", "password": "bobs long pass"}), 409, "create duplicate", "username_taken")
c.expect(c.call("POST", "/users", token, map[string]any{"username": "x", "password": "bobs long pass"}), 400, "create invalid", "invalid_input")
bobToken := c.expect(c.call("POST", "/auth/login", "", map[string]string{"username": "bob", "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", 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("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) != 2 || listed[0].(map[string]any)["enabled"] != false || listed[1].(map[string]any)["enabled"] != false {
t.Fatalf("providers = %v, want two, both off", listed)
}
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")
c.expect(c.call("POST", "/providers/musicbrainz/test", token, nil), 400, "test a provider that has no test", "invalid_input")
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")
// ---- 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")
// ---- 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)}
}