Files
minstrel/internal/playlists/service_test.go
T
bvandeusenandClaude Opus 5.5 a2dae7ec8c
release / go (push) Successful in 1m44s
release / web (push) Successful in 1m16s
release / govulncheck (push) Successful in 18s
release / integration (push) Successful in 2m45s
release / android (push) Successful in 4m29s
release / Build signed APK (push) Successful in 4m40s
release / Attach APK to the Release (tag releases only) (push) Skipped
release / Publish the release image to GHCR (dispatch only) (push) Skipped
release / Build + push container image (push) Successful in 14s
release / Verify release artifacts (tag releases only) (push) Skipped
test(playlists, recommendation): system-mix builds stop drawing covers no test reads; merge repeated cases (#8297)
Timings from one run of the integration lane with -v (39c5b1ed, reverted
here) put the system-mix builds at 1.4-3.8s each, most of the playlists
package's 35s. A build draws a JPEG collage per mix; under -race that is
most of its time, and no build test looked at a cover. The build tests now
pass no data folder, which skips drawing, except SufficientActivity, which
keeps drawing and now checks every mix got a cover: nothing tested that the
build wires covers before.

Merged:
- playlists service: 22 tests become 5 scenario tests (access, bad input,
  partial update, track-list edits, cover-file cleanup), one database
  reset each.
- ARebuildKeepsEachMixsID into DailyNonceDeterminism (both built twice in
  one day); the two You might like builds into one.
- capCandidatesByAlbumAndArtist, Score, Similarity, ContextualMatchScore
  and the session-vector seed rule: one table each.
- LoadCandidates' six contextual-like database tests: the max and seed
  rules are ContextualMatchScore's unit table; the database test keeps what
  only it can see, a like reaching its track and a withdrawn like ignored.

Dropped: Score determinism with a fixed RNG (a pure function), Score's
cold-start case (the same input as the base case), and recencyDecay(nil)
and skipRatio's two cases, which Score's table covers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 13:35:36 -05:00

268 lines
9.6 KiB
Go

package playlists_test
import (
"context"
"errors"
"os"
"path/filepath"
"testing"
"github.com/jackc/pgx/v5/pgtype"
"github.com/Fabled-Sword/minstrel/internal/dbtest"
"github.com/Fabled-Sword/minstrel/internal/playlists"
)
// A playlist is its owner's to change. Anyone may see a public one, only the
// owner a private one, and an unknown id is not found rather than forbidden.
// The REST API and the Subsonic endpoints both rely on these answers.
func TestService_WhoMaySeeAndChangeAPlaylist(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
bob := seedUser(t, pool, "bob")
track := seedTrack(t, pool, "T", "A")
svc := playlists.NewService(pool, nil, t.TempDir())
create := func(owner pgtype.UUID, name string, public bool) *playlists.PlaylistRow {
t.Helper()
row, err := svc.Create(ctx, owner, name, "", public)
if err != nil {
t.Fatalf("Create %q: %v", name, err)
}
return row
}
private := create(alice.ID, "Alice private", false)
public := create(alice.ID, "Alice public", true)
create(bob.ID, "Bob private", false)
create(bob.ID, "Bob public", true)
if private.OwnerUsername != "test-alice" || private.TrackCount != 0 || private.DurationSec != 0 {
t.Errorf("created row = %+v, want owner test-alice and empty rollups", private)
}
rename := "Renamed"
for _, tc := range []struct {
name string
do func() error
want error
}{
{"the owner sees her private playlist", func() error { _, err := svc.Get(ctx, alice.ID, private.ID); return err }, nil},
{"another user can't see it", func() error { _, err := svc.Get(ctx, bob.ID, private.ID); return err }, playlists.ErrForbidden},
{"another user sees a public one", func() error { _, err := svc.Get(ctx, bob.ID, public.ID); return err }, nil},
{"an unknown id is not found", func() error { _, err := svc.Get(ctx, alice.ID, randomUUID()); return err }, playlists.ErrNotFound},
{"another user can't rename it", func() error {
_, err := svc.Update(ctx, bob.ID, public.ID, playlists.UpdateInput{Name: &rename})
return err
}, playlists.ErrForbidden},
{"renaming an unknown id", func() error {
_, err := svc.Update(ctx, alice.ID, randomUUID(), playlists.UpdateInput{Name: &rename})
return err
}, playlists.ErrNotFound},
{"another user can't add to a public one", func() error {
return svc.AppendTracks(ctx, bob.ID, public.ID, []pgtype.UUID{track.ID})
}, playlists.ErrForbidden},
{"another user can't delete it", func() error { return svc.Delete(ctx, bob.ID, public.ID) }, playlists.ErrForbidden},
{"deleting an unknown id", func() error { return svc.Delete(ctx, alice.ID, randomUUID()) }, playlists.ErrNotFound},
} {
if err := tc.do(); !errors.Is(err, tc.want) {
t.Errorf("%s: err = %v, want %v", tc.name, err, tc.want)
}
}
rows, err := svc.List(ctx, alice.ID)
if err != nil {
t.Fatalf("List: %v", err)
}
names := map[string]bool{}
for _, r := range rows {
names[r.Name] = true
}
if len(rows) != 3 || !names["Alice private"] || !names["Alice public"] || !names["Bob public"] {
t.Errorf("alice's list = %v, want her two and bob's public one", names)
}
if updated, err := svc.Update(ctx, alice.ID, private.ID, playlists.UpdateInput{Name: &rename}); err != nil || updated.Name != "Renamed" {
t.Errorf("owner rename = %+v, %v; want Renamed", updated, err)
}
if err := svc.Delete(ctx, alice.ID, private.ID); err != nil {
t.Fatalf("owner Delete: %v", err)
}
// A second delete reports NotFound rather than silently succeeding.
if err := svc.Delete(ctx, alice.ID, private.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("repeat Delete err = %v, want ErrNotFound", err)
}
}
// Bad input is refused as ErrInvalidInput, which the API answers with 400:
// an empty name on create or rename, and a reorder that isn't a permutation
// of the playlist's positions. A track that doesn't exist is its own error.
func TestService_RefusesBadInput(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
t1 := seedTrack(t, pool, "T1", "A")
t2 := seedTrack(t, pool, "T2", "A")
svc := playlists.NewService(pool, nil, t.TempDir())
if _, err := svc.Create(ctx, alice.ID, "", "", false); !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("Create with no name: err = %v, want ErrInvalidInput", err)
}
pl, err := svc.Create(ctx, alice.ID, "Two", "", false)
if err != nil {
t.Fatal(err)
}
empty := ""
if _, err := svc.Update(ctx, alice.ID, pl.ID, playlists.UpdateInput{Name: &empty}); !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("rename to nothing: err = %v, want ErrInvalidInput", err)
}
if err := svc.AppendTracks(ctx, alice.ID, pl.ID, []pgtype.UUID{randomUUID()}); !errors.Is(err, playlists.ErrTrackNotFound) {
t.Errorf("append an unknown track: err = %v, want ErrTrackNotFound", err)
}
if err := svc.AppendTracks(ctx, alice.ID, pl.ID, []pgtype.UUID{t1.ID, t2.ID}); err != nil {
t.Fatal(err)
}
for _, order := range [][]int32{{0, 1, 2}, {0, 0}, {1}} {
if err := svc.Reorder(ctx, alice.ID, pl.ID, order); !errors.Is(err, playlists.ErrInvalidInput) {
t.Errorf("Reorder %v of two tracks: err = %v, want ErrInvalidInput", order, err)
}
}
}
// An update changes only the fields it carries.
func TestService_UpdateLeavesFieldsItDoesNotCarry(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
alice := seedUser(t, pool, "alice")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(ctx, alice.ID, "Original", "Long description", false)
if err != nil {
t.Fatalf("seed Create: %v", err)
}
pub := true
updated, err := svc.Update(ctx, alice.ID, pl.ID, playlists.UpdateInput{IsPublic: &pub})
if err != nil {
t.Fatalf("Update: %v", err)
}
if updated.Name != "Original" || updated.Description != "Long description" || !updated.IsPublic {
t.Errorf("after toggling public: %+v; want name and description unchanged", updated)
}
}
// A playlist's entries keep a snapshot of each track's title and artist, so an
// entry survives its track being deleted, shown by name with no track id.
// Removing an entry renumbers the rest, and a reorder applies a permutation.
func TestService_TrackListEdits(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
a := seedTrack(t, pool, "Prismatic", "Fields of Ontario")
b := seedTrack(t, pool, "B", "Artist")
c := seedTrack(t, pool, "C", "Artist")
d := seedTrack(t, pool, "D", "Artist")
svc := playlists.NewService(pool, nil, t.TempDir())
pl, err := svc.Create(ctx, user.ID, "Test", "", false)
if err != nil {
t.Fatal(err)
}
titles := func() []string {
t.Helper()
got, err := svc.Get(ctx, user.ID, pl.ID)
if err != nil {
t.Fatal(err)
}
out := make([]string, len(got.Tracks))
for i, pt := range got.Tracks {
if int(pt.Position) != i {
t.Errorf("entry %d has position %d", i, pt.Position)
}
out[i] = pt.Title
}
return out
}
expect := func(step string, want ...string) {
t.Helper()
if got := titles(); !equal(got, want) {
t.Errorf("after %s: %q, want %q", step, got, want)
}
}
if err := svc.AppendTracks(ctx, user.ID, pl.ID, []pgtype.UUID{a.ID, b.ID, c.ID, d.ID}); err != nil {
t.Fatalf("AppendTracks: %v", err)
}
got, _ := svc.Get(ctx, user.ID, pl.ID)
if got.TrackCount != 4 || got.Tracks[0].ArtistName != "Fields of Ontario" {
t.Errorf("after append: count %d, first artist %q; want 4 and the snapshot artist", got.TrackCount, got.Tracks[0].ArtistName)
}
if err := svc.RemoveTrack(ctx, user.ID, pl.ID, 1, pgtype.UUID{}); err != nil {
t.Fatalf("RemoveTrack: %v", err)
}
expect("removing position 1", "Prismatic", "C", "D")
if err := svc.Reorder(ctx, user.ID, pl.ID, []int32{2, 1, 0}); err != nil {
t.Fatalf("Reorder: %v", err)
}
expect("reversing", "D", "C", "Prismatic")
if _, err := pool.Exec(ctx, `DELETE FROM tracks WHERE id = $1`, a.ID); err != nil {
t.Fatalf("delete track: %v", err)
}
got, _ = svc.Get(ctx, user.ID, pl.ID)
if len(got.Tracks) != 3 || got.Tracks[2].Title != "Prismatic" || got.Tracks[2].TrackID != nil {
t.Errorf("after the track's deletion: %+v; want the entry kept by name, with no track id", got.Tracks)
}
}
// Deleting a playlist removes its cached cover from disk, and a cover file
// already gone is no obstacle.
func TestService_DeleteRemovesTheCoverFile(t *testing.T) {
ctx := context.Background()
pool := dbtest.Pool(t)
user := seedUser(t, pool, "alice")
dir := t.TempDir()
svc := playlists.NewService(pool, nil, dir)
if err := os.MkdirAll(filepath.Join(dir, "playlist_covers"), 0o755); err != nil {
t.Fatal(err)
}
withCover := func(name string, onDisk bool) (*playlists.PlaylistRow, string) {
t.Helper()
pl, err := svc.Create(ctx, user.ID, name, "", false)
if err != nil {
t.Fatal(err)
}
rel := filepath.Join("playlist_covers", uuidString(pl.ID)+".jpg")
if onDisk {
if err := os.WriteFile(filepath.Join(dir, rel), []byte("jpeg-bytes"), 0o644); err != nil {
t.Fatal(err)
}
}
if _, err := pool.Exec(ctx, `UPDATE playlists SET cover_path = $1 WHERE id = $2`, rel, pl.ID); err != nil {
t.Fatal(err)
}
return pl, filepath.Join(dir, rel)
}
pl, full := withCover("With a cover", true)
if err := svc.Delete(ctx, user.ID, pl.ID); err != nil {
t.Fatalf("Delete: %v", err)
}
if _, err := os.Stat(full); !errors.Is(err, os.ErrNotExist) {
t.Errorf("cover file still on disk after delete: %v", err)
}
gone, _ := withCover("Cover already gone", false)
if err := svc.Delete(ctx, user.ID, gone.ID); err != nil {
t.Errorf("Delete with its cover file already gone: %v", err)
}
}
func equal(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}