sonda/internal/storage/playlists_test.go
tgiachi a1e192066c feat: playlists with a cover, a collage of the covers of their albums
- A playlist says which albums stand for it (album_ids): up to 4 albums that have a cover, in the order they first appear in it, each once, read for a whole page of playlists in one query. An empty one has an empty list.
- The Playlists page is a grid of cards with the collage, and the page of a playlist shows it in its header. The pages of a smart playlist and of a suggested one show a collage of the albums of their first songs.
- Nothing is fetched for it: the covers are the ones the library already has.
2026-11-13 11:32:01 +01:00

543 lines
19 KiB
Go

package storage
import (
"context"
"errors"
"slices"
"sync"
"testing"
"time"
"github.com/uptrace/bun"
"codeberg.org/squidd/sonda/internal/playlists"
)
// plEnv is two users and four tracks (a, b, c, d), each 60 seconds long.
type plEnv struct {
t *testing.T
db *bun.DB
repo *PlaylistRepo
alice int64
bob int64
tracks map[string]int64
now time.Time
}
func newPlEnv(t *testing.T, db *bun.DB) *plEnv {
t.Helper()
ctx := context.Background()
users := NewUserRepo(db)
a, err := users.CreateUser(ctx, "alice@example.org", "hash", false)
if err != nil {
t.Fatal(err)
}
b, err := users.CreateUser(ctx, "bob@example.org", "hash", false)
if err != nil {
t.Fatal(err)
}
lib := NewLibraryRepo(db)
l, err := lib.CreateLibrary(ctx, "m", "/lib/m")
if err != nil {
t.Fatal(err)
}
e := &plEnv{t: t, db: db, repo: NewPlaylistRepo(db), alice: a.ID, bob: b.ID, tracks: map[string]int64{}, now: time.Unix(1_700_000_000, 0)}
for i, title := range []string{"a", "b", "c", "d"} {
if _, err := lib.SaveFile(ctx, l.ID, pf("x/"+title+".flac", title, "Album", "Band", i+1, 1, "flac", "Band"), 0); err != nil {
t.Fatal(err)
}
var id int64
if err := db.QueryRow("SELECT id FROM tracks WHERE title = ?", title).Scan(&id); err != nil {
t.Fatal(err)
}
e.tracks[title] = id
}
return e
}
// tick moves the clock on, so "changed last" has an order.
func (e *plEnv) tick() time.Time { e.now = e.now.Add(time.Minute); return e.now }
func (e *plEnv) create(user int64, name string) playlists.Playlist {
e.t.Helper()
p, err := e.repo.Create(context.Background(), user, name, "", e.tick())
if err != nil {
e.t.Fatal(err)
}
return p
}
// add puts tracks by name (at the end when pos < 0).
func (e *plEnv) add(user, id int64, pos int, names ...string) (playlists.Playlist, error) {
e.t.Helper()
ids := make([]int64, len(names))
for i, n := range names {
ids[i] = e.tracks[n]
}
var p *int
if pos >= 0 {
p = &pos
}
return e.repo.AddTracks(context.Background(), user, id, ids, p, e.tick())
}
// order is the titles of a playlist in order.
func (e *plEnv) order(user, id int64) []string {
e.t.Helper()
items, total, err := e.repo.Items(context.Background(), user, id, 1000, 0)
if err != nil {
e.t.Fatal(err)
}
if total != len(items) {
e.t.Fatalf("total = %d, items = %d", total, len(items))
}
out := make([]string, len(items))
for i, it := range items {
if it.Position != i {
e.t.Fatalf("item %d has position %d: positions must count from 0 without gaps", i, it.Position)
}
out[i] = it.Track.Title
}
return out
}
func (e *plEnv) itemIDs(id int64) []int64 {
e.t.Helper()
items, _, err := e.repo.Items(context.Background(), e.alice, id, 1000, 0)
if err != nil {
e.t.Fatal(err)
}
ids := make([]int64, len(items))
for i, it := range items {
ids[i] = it.ID
}
return ids
}
func plBackends(t *testing.T, fn func(t *testing.T, e *plEnv)) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) { fn(t, newPlEnv(t, db)) })
}
func TestPlaylistsAreCreatedListedAndKeptApartPerUser(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
first := e.create(e.alice, "First")
second := e.create(e.alice, "Second")
other := e.create(e.bob, "Bobs")
if first.ID == 0 || first.Name != "First" || first.TrackCount != 0 || first.DurationMs != 0 || first.CreatedAt.IsZero() {
t.Errorf("first = %+v", first)
}
got, total, err := e.repo.List(ctx, e.alice, 10, 0)
if err != nil || total != 2 || len(got) != 2 || got[0].ID != second.ID || got[1].ID != first.ID {
t.Fatalf("list = %+v total %d err %v: the one changed last comes first", got, total, err)
}
// Changing the first one puts it on top.
if _, err := e.add(e.alice, first.ID, -1, "a"); err != nil {
t.Fatal(err)
}
got, _, _ = e.repo.List(ctx, e.alice, 10, 0)
if got[0].ID != first.ID || got[0].TrackCount != 1 || got[0].DurationMs != 60000 {
t.Errorf("after adding: %+v", got[0])
}
if page, total, _ := e.repo.List(ctx, e.alice, 1, 1); len(page) != 1 || total != 2 || page[0].ID != second.ID {
t.Errorf("page 2 = %+v total %d", page, total)
}
if _, err := e.repo.Get(ctx, e.alice, other.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user's playlist: err = %v, want ErrNotFound", err)
}
if _, err := e.repo.Get(ctx, e.alice, 99999); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
if mine, total, _ := e.repo.List(ctx, e.bob, 10, 0); total != 1 || mine[0].ID != other.ID {
t.Errorf("bob sees %+v", mine)
}
})
}
func TestAddingAtTheEndAndInTheMiddleKeepsTheOrderWithoutGaps(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
p := e.create(e.alice, "P")
got, err := e.add(e.alice, p.ID, -1, "a", "b", "a")
if err != nil || got.TrackCount != 3 || got.DurationMs != 180000 {
t.Fatalf("playlist = %+v err %v", got, err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "b", "a"}) {
t.Fatalf("order = %v: a track can be there twice", o)
}
if ids := e.itemIDs(p.ID); ids[0] == ids[2] {
t.Error("the same track twice must be two items")
}
if _, err := e.add(e.alice, p.ID, 1, "c", "d"); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "c", "d", "b", "a"}) {
t.Errorf("order = %v, want c and d at 1 and 2", o)
}
if _, err := e.add(e.alice, p.ID, 0, "d"); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"d", "a", "c", "d", "b", "a"}) {
t.Errorf("order = %v, want d first", o)
}
if _, err := e.add(e.alice, p.ID, 6, "b"); err != nil { // the end, as a position
t.Errorf("a position at the end: %v", err)
}
if _, err := e.add(e.alice, p.ID, 8, "b"); !errors.Is(err, playlists.ErrPosition) {
t.Errorf("a position beyond the end: err = %v, want ErrPosition", err)
}
})
}
func TestAddingAnUnknownTrackOrToAnotherUsersPlaylistChangesNothing(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.repo.AddTracks(ctx, e.alice, p.ID, []int64{e.tracks["a"], 99999}, nil, e.tick()); !errors.Is(err, playlists.ErrTrackNotFound) {
t.Errorf("unknown track: err = %v", err)
}
if o := e.order(e.alice, p.ID); len(o) != 0 {
t.Errorf("order = %v: nothing must be added when one track is unknown", o)
}
if _, err := e.add(e.bob, p.ID, -1, "a"); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user's playlist: err = %v", err)
}
if _, err := e.add(e.alice, 99999, -1, "a"); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
})
}
func TestRemovingAnItemClosesTheGap(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
other := e.create(e.alice, "Other")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
if _, err := e.add(e.alice, other.ID, -1, "a"); err != nil {
t.Fatal(err)
}
ids := e.itemIDs(p.ID)
if err := e.repo.RemoveItem(ctx, e.alice, p.ID, ids[1], e.tick()); err != nil {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, []string{"a", "c", "d"}) {
t.Errorf("order = %v", o)
}
if err := e.repo.RemoveItem(ctx, e.alice, p.ID, ids[1], e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("a second time: err = %v", err)
}
if err := e.repo.RemoveItem(ctx, e.alice, other.ID, ids[0], e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("an item of another playlist: err = %v", err)
}
if err := e.repo.RemoveItem(ctx, e.bob, p.ID, ids[0], e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != 3 || got.DurationMs != 180000 {
t.Errorf("after removing: %+v", got)
}
})
}
func TestMovingAnItem(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
move := func(from, to int) error {
return e.repo.MoveItem(ctx, e.alice, p.ID, e.itemIDs(p.ID)[from], to, e.tick())
}
for _, step := range []struct {
from, to int
want []string
}{
{0, 2, []string{"b", "c", "a", "d"}},
{3, 0, []string{"d", "b", "c", "a"}},
{1, 1, []string{"d", "b", "c", "a"}},
{2, 3, []string{"d", "b", "a", "c"}},
{3, 2, []string{"d", "b", "c", "a"}},
{0, 3, []string{"b", "c", "a", "d"}},
} {
if err := move(step.from, step.to); err != nil {
t.Fatalf("move %d to %d: %v", step.from, step.to, err)
}
if o := e.order(e.alice, p.ID); !slices.Equal(o, step.want) {
t.Fatalf("after %d to %d: order = %v, want %v", step.from, step.to, o, step.want)
}
}
if err := move(0, 4); !errors.Is(err, playlists.ErrPosition) {
t.Errorf("beyond the end: err = %v", err)
}
if err := e.repo.MoveItem(ctx, e.alice, p.ID, 99999, 0, e.tick()); !errors.Is(err, playlists.ErrItemNotFound) {
t.Errorf("unknown item: err = %v", err)
}
if err := e.repo.MoveItem(ctx, e.bob, p.ID, e.itemIDs(p.ID)[0], 0, e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
})
}
func TestATrackWithoutFilesStaysAndIsListedAsNotAvailable(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b"); err != nil {
t.Fatal(err)
}
if _, err := e.db.ExecContext(ctx, "UPDATE audio_files SET missing_at = ? WHERE track_id = ?", 1_700_000_100, e.tracks["a"]); err != nil {
t.Fatal(err)
}
items, total, err := e.repo.Items(ctx, e.alice, p.ID, 10, 0)
if err != nil || total != 2 || len(items) != 2 {
t.Fatalf("items = %+v total %d err %v: the track must stay", items, total, err)
}
if items[0].Available || items[0].Track.Title != "a" || items[0].Track.Album == nil || len(items[0].Track.Artists) != 1 {
t.Errorf("the missing one = %+v", items[0])
}
if !items[1].Available || items[1].Track.Format != "flac" {
t.Errorf("the other = %+v", items[1])
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != 2 {
t.Errorf("track count = %d, want both", got.TrackCount)
}
})
}
func TestItemsArePaged(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
if _, err := e.add(e.alice, p.ID, -1, "a", "b", "c", "d"); err != nil {
t.Fatal(err)
}
items, total, err := e.repo.Items(ctx, e.alice, p.ID, 2, 1)
if err != nil || total != 4 || len(items) != 2 || items[0].Track.Title != "b" || items[1].Position != 2 {
t.Errorf("page = %+v total %d err %v", items, total, err)
}
if items, total, _ := e.repo.Items(ctx, e.alice, p.ID, 2, 10); len(items) != 0 || total != 4 {
t.Errorf("beyond the end = %+v total %d", items, total)
}
if _, _, err := e.repo.Items(ctx, e.bob, p.ID, 2, 0); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user: err = %v", err)
}
})
}
func TestUpdatingAndDeletingAPlaylist(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p, err := e.repo.Create(ctx, e.alice, "Old", "about it", e.tick())
if err != nil {
t.Fatal(err)
}
if _, err := e.add(e.alice, p.ID, -1, "a", "b"); err != nil {
t.Fatal(err)
}
name, empty := "New", ""
got, err := e.repo.Update(ctx, e.alice, p.ID, &name, nil, e.tick())
if err != nil || got.Name != "New" || got.Description != "about it" || got.TrackCount != 2 {
t.Errorf("name only: %+v err %v", got, err)
}
got, err = e.repo.Update(ctx, e.alice, p.ID, nil, &empty, e.tick())
if err != nil || got.Name != "New" || got.Description != "" {
t.Errorf("description only: %+v err %v", got, err)
}
if _, err := e.repo.Update(ctx, e.bob, p.ID, &name, nil, e.tick()); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user updates: err = %v", err)
}
if err := e.repo.Delete(ctx, e.bob, p.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("another user deletes: err = %v", err)
}
if err := e.repo.Delete(ctx, e.alice, p.ID); err != nil {
t.Fatal(err)
}
if err := e.repo.Delete(ctx, e.alice, p.ID); !errors.Is(err, playlists.ErrNotFound) {
t.Errorf("a second time: err = %v", err)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM playlist_items"); n != 0 {
t.Errorf("%d items left", n)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM tracks"); n != 4 {
t.Errorf("%d tracks left, want all 4", n)
}
})
}
func TestDeletingAUserDeletesTheirPlaylists(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
p := e.create(e.alice, "P")
keep := e.create(e.bob, "Keep")
if _, err := e.add(e.alice, p.ID, -1, "a"); err != nil {
t.Fatal(err)
}
if err := NewUserRepo(e.db).DeleteUser(context.Background(), e.alice); err != nil {
t.Fatal(err)
}
if n := count(t, e.db, "SELECT COUNT(*) FROM playlists"); n != 1 {
t.Errorf("%d playlists, want only bob's", n)
}
if _, err := e.repo.Get(context.Background(), e.bob, keep.ID); err != nil {
t.Errorf("bob's: %v", err)
}
})
}
func TestThereAreLimitsOnPlaylistsAndOnTheirSize(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "Big")
// Fill the playlist up to the limit with a direct insert, 1,000 rows at a time.
for start := 0; start < playlists.MaxItems; start += 1000 {
rows := make([]playlistItemRow, 0, 1000)
for i := start; i < start+1000; i++ {
rows = append(rows, playlistItemRow{PlaylistID: p.ID, TrackID: e.tracks["a"], Position: i, AddedAt: 1})
}
if _, err := e.db.NewInsert().Model(&rows).Exec(ctx); err != nil {
t.Fatal(err)
}
}
if _, err := e.add(e.alice, p.ID, -1, "b"); !errors.Is(err, playlists.ErrTooMany) {
t.Errorf("one more than %d: err = %v, want ErrTooMany", playlists.MaxItems, err)
}
if got, _ := e.repo.Get(ctx, e.alice, p.ID); got.TrackCount != playlists.MaxItems {
t.Errorf("track count = %d", got.TrackCount)
}
for i := 1; i < playlists.MaxPlaylists; i++ {
if _, err := e.repo.Create(ctx, e.alice, "x", "", e.tick()); err != nil {
t.Fatalf("playlist %d: %v", i+1, err)
}
}
if _, err := e.repo.Create(ctx, e.alice, "one more", "", e.tick()); !errors.Is(err, playlists.ErrTooMany) {
t.Errorf("one more than %d playlists: err = %v", playlists.MaxPlaylists, err)
}
if _, err := e.repo.Create(ctx, e.bob, "bobs", "", e.tick()); err != nil {
t.Errorf("the limit is per user: %v", err)
}
})
}
func TestAddingAtTheSameTimeKeepsEveryPositionUnique(t *testing.T) {
plBackends(t, func(t *testing.T, e *plEnv) {
ctx := context.Background()
p := e.create(e.alice, "P")
var wg sync.WaitGroup
errs := make(chan error, 8)
for g := 0; g < 8; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 3; i++ {
if _, err := e.repo.AddTracks(ctx, e.alice, p.ID, []int64{e.tracks["a"], e.tracks["b"]}, nil, time.Now()); err != nil {
errs <- err
return
}
}
}()
}
wg.Wait()
close(errs)
for err := range errs {
t.Fatal(err)
}
if o := e.order(e.alice, p.ID); len(o) != 48 {
t.Errorf("%d items, want 48", len(o))
}
})
}
// ---- the albums that stand for a playlist ----
func TestAPlaylistSaysWhichAlbumsStandForItInTheOrderTheyAppear(t *testing.T) {
songs := []mixSong{
{"s1", "A1", nil}, {"s2", "A2", nil}, {"s3", "A3", nil}, {"s4", "A4", nil}, {"s5", "A5", nil}, {"s6", "A6", nil}, {"s7", "A7", nil},
}
mixBackends(t, songs, func(t *testing.T, e *mixEnv) {
ctx := context.Background()
repo := NewPlaylistRepo(e.db)
alb := func(title string) int64 { return e.albumOf(title) }
// A3 has no cover; a second song of A1 comes later; A7 has a cover but comes last, after four others.
for _, s := range []string{"s1", "s2", "s4", "s5", "s6", "s7"} {
e.cover(alb(s), "ok")
}
e.cover(alb("s3"), "none")
p, err := repo.Create(ctx, e.user, "Mixed", "", time.Unix(1_700_000_000, 0))
if err != nil {
t.Fatal(err)
}
if p.AlbumIDs == nil || len(p.AlbumIDs) != 0 {
t.Errorf("an empty playlist = %#v, want an empty list", p.AlbumIDs)
}
order := []string{"s3", "s2", "s1", "s2", "s4", "s5", "s6", "s7"} // s3 has no cover, s2 comes twice
ids := make([]int64, len(order))
for i, s := range order {
ids[i] = e.tracks[s]
}
got, err := repo.AddTracks(ctx, e.user, p.ID, ids, nil, time.Unix(1_700_000_100, 0))
if err != nil {
t.Fatal(err)
}
want := []int64{alb("s2"), alb("s1"), alb("s4"), alb("s5")}
if !slices.Equal(got.AlbumIDs, want) {
t.Errorf("after adding = %v, want %v: in order, each once, no cover skipped, four at most", got.AlbumIDs, want)
}
if again, _ := repo.Get(ctx, e.user, p.ID); !slices.Equal(again.AlbumIDs, want) {
t.Errorf("get = %v", again.AlbumIDs)
}
list, _, err := repo.List(ctx, e.user, 10, 0)
if err != nil || len(list) != 1 || !slices.Equal(list[0].AlbumIDs, want) {
t.Errorf("list = %+v, %v", list, err)
}
// Taking the first songs out moves the albums.
items, _, _ := repo.Items(ctx, e.user, p.ID, 100, 0)
if err := repo.RemoveItem(ctx, e.user, p.ID, items[1].ID, time.Unix(1_700_000_200, 0)); err != nil { // the first s2
t.Fatal(err)
}
if after, _ := repo.Get(ctx, e.user, p.ID); !slices.Equal(after.AlbumIDs, []int64{alb("s1"), alb("s2"), alb("s4"), alb("s5")}) {
t.Errorf("after taking a song out = %v", after.AlbumIDs)
}
})
}
func TestSeveralPlaylistsOfAPageEachGetTheirOwnAlbums(t *testing.T) {
songs := []mixSong{{"s1", "A1", nil}, {"s2", "A2", nil}, {"s3", "A3", nil}}
mixBackends(t, songs, func(t *testing.T, e *mixEnv) {
ctx := context.Background()
repo := NewPlaylistRepo(e.db)
for _, s := range []string{"s1", "s2", "s3"} {
e.cover(e.albumOf(s), "ok")
}
mk := func(name string, titles ...string) {
t.Helper()
p, err := repo.Create(ctx, e.user, name, "", time.Unix(1_700_000_000, 0))
if err != nil {
t.Fatal(err)
}
ids := make([]int64, len(titles))
for i, s := range titles {
ids[i] = e.tracks[s]
}
if len(ids) > 0 {
if _, err := repo.AddTracks(ctx, e.user, p.ID, ids, nil, time.Unix(1_700_000_000, 0)); err != nil {
t.Fatal(err)
}
}
}
mk("one", "s1", "s2")
mk("two", "s3")
mk("none")
list, _, err := repo.List(ctx, e.user, 10, 0)
if err != nil || len(list) != 3 {
t.Fatalf("%+v, %v", list, err)
}
byName := map[string][]int64{}
for _, p := range list {
byName[p.Name] = p.AlbumIDs
}
if !slices.Equal(byName["one"], []int64{e.albumOf("s1"), e.albumOf("s2")}) || !slices.Equal(byName["two"], []int64{e.albumOf("s3")}) || byName["none"] == nil || len(byName["none"]) != 0 {
t.Errorf("albums = %v", byName)
}
})
}