package httpapi import ( "context" "net/http" "sort" "testing" "git.kmalloc.org/squid/sonda/internal/catalog" ) // fakeCatalog returns canned data and records the last filter it received. type fakeCatalog struct { last catalog.Filter err error artists []catalog.Artist albums []catalog.Album tracks []catalog.Track } func (f *fakeCatalog) Artists(_ context.Context, fl catalog.Filter) (catalog.Page[catalog.Artist], error) { f.last = fl return catalog.Page[catalog.Artist]{Items: f.artists, Total: 123, Limit: fl.Limit, Offset: fl.Offset}, f.err } func (f *fakeCatalog) Albums(_ context.Context, fl catalog.Filter) (catalog.Page[catalog.Album], error) { f.last = fl return catalog.Page[catalog.Album]{Items: f.albums, Total: 7, Limit: fl.Limit, Offset: fl.Offset}, f.err } func (f *fakeCatalog) Tracks(_ context.Context, fl catalog.Filter) (catalog.Page[catalog.Track], error) { f.last = fl return catalog.Page[catalog.Track]{Items: f.tracks, Total: 9, Limit: fl.Limit, Offset: fl.Offset}, f.err } func (f *fakeCatalog) Artist(_ context.Context, id int64) (catalog.Artist, error) { if f.err != nil { return catalog.Artist{}, f.err } return catalog.Artist{ID: id, Name: "Radiohead", AlbumCount: 2, TrackCount: 20}, nil } func (f *fakeCatalog) Album(_ context.Context, id int64) (catalog.Album, error) { if f.err != nil { return catalog.Album{}, f.err } return catalog.Album{ID: id, Title: "OK Computer", TrackCount: 12, DurationMs: 3200000, Artist: &catalog.ArtistRef{ID: 1, Name: "Radiohead"}}, nil } func (f *fakeCatalog) Track(_ context.Context, id int64) (catalog.Track, error) { if f.err != nil { return catalog.Track{}, f.err } return catalog.Track{ID: id, Title: "Airbag", DurationMs: 284000, TrackNo: 1, DiscNo: 1, Format: "flac", Album: &catalog.AlbumRef{ID: 3, Title: "OK Computer"}, Artists: []catalog.ArtistRef{{ID: 1, Name: "Radiohead"}}}, nil } var catalogRoutes = []string{ "/api/v1/artists", "/api/v1/albums", "/api/v1/tracks", "/api/v1/artists/1", "/api/v1/albums/1", "/api/v1/tracks/1", } func catalogAPI(t *testing.T, fc *fakeCatalog) (http.Handler, string) { t.Helper() h := newTestAPIWith(t, func(d *Deps) { d.Catalog = fc }) return h, registerAndLogin(t, h) } func keys(m map[string]any) []string { var out []string for k := range m { out = append(out, k) } sort.Strings(out) return out } func sameKeys(t *testing.T, what string, got map[string]any, want ...string) { t.Helper() sort.Strings(want) g := keys(got) if len(g) != len(want) { t.Errorf("%s keys = %v, want %v", what, g, want) return } for i := range g { if g[i] != want[i] { t.Errorf("%s keys = %v, want %v", what, g, want) return } } } func TestCatalogRoutesRequireAuth(t *testing.T) { h, _ := catalogAPI(t, &fakeCatalog{}) for _, path := range catalogRoutes { if r := do(t, h, "GET", path, "", nil); r.Code != http.StatusUnauthorized { t.Errorf("GET %s without a token: %d", path, r.Code) } if r := do(t, h, "GET", path+"?access_token=x", "", nil); r.Code != http.StatusUnauthorized { t.Errorf("GET %s: a token in the URL must not work here: %d", path, r.Code) } } } func TestAnySignedInUserCanBrowse(t *testing.T) { fc := &fakeCatalog{} h, admin := catalogAPI(t, fc) _, bob := addUser(t, h, admin, "bob", false) for _, path := range catalogRoutes { if r := do(t, h, "GET", path, bob, nil); r.Code != http.StatusOK { t.Errorf("GET %s as a normal user: %d %v", path, r.Code, r.Body) } } } func TestCatalogListShapeAndPaging(t *testing.T) { fc := &fakeCatalog{ artists: []catalog.Artist{{ID: 1, Name: "Björk", AlbumCount: 3, TrackCount: 30}}, albums: []catalog.Album{{ID: 2, Title: "Post", TrackCount: 11, DurationMs: 2400000, Artist: &catalog.ArtistRef{ID: 1, Name: "Björk"}}}, tracks: []catalog.Track{{ID: 3, Title: "Army of Me", DurationMs: 235000, TrackNo: 1, DiscNo: 1, Format: "flac", Album: &catalog.AlbumRef{ID: 2, Title: "Post"}, Artists: []catalog.ArtistRef{{ID: 1, Name: "Björk"}}}}, } h, tok := catalogAPI(t, fc) r := do(t, h, "GET", "/api/v1/artists?limit=20&offset=40", tok, nil) if r.Code != http.StatusOK || r.Body["total"] != float64(123) || r.Body["limit"] != float64(20) || r.Body["offset"] != float64(40) { t.Fatalf("artists page: %d %v", r.Code, r.Body) } sameKeys(t, "artists response", r.Body, "items", "total", "limit", "offset") a := r.Body["items"].([]any)[0].(map[string]any) sameKeys(t, "artist", a, "id", "name", "album_count", "track_count") if a["name"] != "Björk" || a["album_count"] != float64(3) || a["track_count"] != float64(30) { t.Errorf("artist = %v", a) } r = do(t, h, "GET", "/api/v1/albums", tok, nil) al := r.Body["items"].([]any)[0].(map[string]any) sameKeys(t, "album", al, "id", "title", "artist", "track_count", "duration_ms") sameKeys(t, "album artist", al["artist"].(map[string]any), "id", "name") r = do(t, h, "GET", "/api/v1/tracks", tok, nil) tr := r.Body["items"].([]any)[0].(map[string]any) // No file path, root or library path may ever appear. sameKeys(t, "track", tr, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") sameKeys(t, "track album", tr["album"].(map[string]any), "id", "title") if tr["format"] != "flac" || len(tr["artists"].([]any)) != 1 { t.Errorf("track = %v", tr) } } func TestCatalogEmptyListIsAnArrayNotNull(t *testing.T) { h, tok := catalogAPI(t, &fakeCatalog{}) for _, path := range []string{"/api/v1/artists", "/api/v1/albums", "/api/v1/tracks"} { r := do(t, h, "GET", path, tok, nil) items, ok := r.Body["items"].([]any) if !ok || len(items) != 0 { t.Errorf("%s: items = %#v, want an empty array", path, r.Body["items"]) } } } func TestTrackWithoutAlbumHasNullAlbum(t *testing.T) { fc := &fakeCatalog{tracks: []catalog.Track{{ID: 1, Title: "Loose", Artists: nil}}} h, tok := catalogAPI(t, fc) r := do(t, h, "GET", "/api/v1/tracks", tok, nil) tr := r.Body["items"].([]any)[0].(map[string]any) if v, present := tr["album"]; !present || v != nil { t.Errorf("album = %#v, want an explicit null", v) } if arts, ok := tr["artists"].([]any); !ok || len(arts) != 0 { t.Errorf("artists = %#v, want an empty array", tr["artists"]) } } func TestTrackCarriesItsReplayGain(t *testing.T) { g := func(v float64) *float64 { return &v } fc := &fakeCatalog{tracks: []catalog.Track{ {ID: 1, Title: "Tagged", ReplayGain: &catalog.ReplayGain{TrackGain: g(-6.5), TrackPeak: g(0.98)}}, {ID: 2, Title: "Plain"}, }} h, tok := catalogAPI(t, fc) items := do(t, h, "GET", "/api/v1/tracks", tok, nil).Body["items"].([]any) tagged := items[0].(map[string]any)["replay_gain"].(map[string]any) sameKeys(t, "replay_gain", tagged, "track_gain_db", "album_gain_db", "track_peak", "album_peak") if tagged["track_gain_db"] != -6.5 || tagged["track_peak"] != 0.98 { t.Errorf("replay_gain = %v, want the gain -6.5 and the peak 0.98", tagged) } if v, present := tagged["album_gain_db"]; !present || v != nil { t.Errorf("album_gain_db = %#v, want an explicit null: the file does not say", v) } if v, present := items[1].(map[string]any)["replay_gain"]; !present || v != nil { t.Errorf("replay_gain of a song with none = %#v, want an explicit null", v) } } func TestCatalogQueryParametersReachTheService(t *testing.T) { fc := &fakeCatalog{} h, tok := catalogAPI(t, fc) do(t, h, "GET", "/api/v1/tracks?q=black+sabbath&limit=25&offset=50&library_id=2&artist_id=3&album_id=4", tok, nil) want := catalog.Filter{Query: "black sabbath", Limit: 25, Offset: 50, LibraryID: 2, ArtistID: 3, AlbumID: 4} if fc.last != want { t.Errorf("filter = %+v, want %+v", fc.last, want) } do(t, h, "GET", "/api/v1/albums?artist_id=9", tok, nil) if fc.last.ArtistID != 9 || fc.last.Limit != 0 { t.Errorf("album filter = %+v (unset paging must stay 0 for the service to default)", fc.last) } do(t, h, "GET", "/api/v1/albums?sort=recent", tok, nil) if fc.last.Sort != "recent" { t.Errorf("album sort = %q", fc.last.Sort) } // Special characters survive URL decoding. do(t, h, "GET", "/api/v1/artists?q=100%25+%26+more", tok, nil) if fc.last.Query != "100% & more" { t.Errorf("q = %q", fc.last.Query) } } func TestCatalogRejectsBadParameters(t *testing.T) { fc := &fakeCatalog{} h, tok := catalogAPI(t, fc) for _, qs := range []string{"limit=abc", "offset=x", "library_id=1.5", "artist_id=-", "album_id=%20", "limit=99999999999999999999"} { r := do(t, h, "GET", "/api/v1/tracks?"+qs, tok, nil) if r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("?%s: %d %v", qs, r.Code, r.Body) } } // The service's own validation is a 400 too. fc.err = catalog.ErrInvalidQuery r := do(t, h, "GET", "/api/v1/tracks?limit=-1", tok, nil) if r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { t.Errorf("service rejection: %d %v", r.Code, r.Body) } } func TestCatalogDetails(t *testing.T) { h, tok := catalogAPI(t, &fakeCatalog{}) r := do(t, h, "GET", "/api/v1/artists/5", tok, nil) sameKeys(t, "artist", r.Body, "id", "name", "album_count", "track_count") if r.Code != http.StatusOK || r.Body["id"] != float64(5) { t.Errorf("artist: %d %v", r.Code, r.Body) } r = do(t, h, "GET", "/api/v1/albums/6", tok, nil) sameKeys(t, "album", r.Body, "id", "title", "artist", "track_count", "duration_ms") r = do(t, h, "GET", "/api/v1/tracks/7", tok, nil) sameKeys(t, "track", r.Body, "id", "title", "duration_ms", "track_no", "disc_no", "album", "artists", "format", "replay_gain") if r.Code != http.StatusOK || r.Body["id"] != float64(7) { t.Errorf("track: %d %v", r.Code, r.Body) } } func TestCatalogDetailErrors(t *testing.T) { fc := &fakeCatalog{err: catalog.ErrNotFound} h, tok := catalogAPI(t, fc) for path, code := range map[string]string{ "/api/v1/artists/1": "artist_not_found", "/api/v1/albums/1": "album_not_found", "/api/v1/tracks/1": "track_not_found", } { r := do(t, h, "GET", path, tok, nil) if r.Code != http.StatusNotFound || errCode(r) != code { t.Errorf("%s: %d %v, want 404 %s", path, r.Code, r.Body, code) } } for _, path := range []string{"/api/v1/artists/abc", "/api/v1/albums/0", "/api/v1/tracks/-1"} { if r := do(t, h, "GET", path, tok, nil); r.Code != http.StatusBadRequest { t.Errorf("%s: %d, want 400", path, r.Code) } } } // The stream route lives under /tracks/{id}: the detail route must not shadow it. func TestTrackDetailDoesNotShadowTheStreamRoute(t *testing.T) { h, tok := catalogAPI(t, &fakeCatalog{}) r := do(t, h, "GET", "/api/v1/tracks/1/stream", tok, nil) if r.Code == http.StatusOK && r.Body["title"] != nil { t.Fatal("the stream URL answered with track details") } }