sonda/internal/smart/smart_test.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

829 lines
31 KiB
Go

package smart
import (
"context"
"errors"
"slices"
"strings"
"testing"
"time"
"git.kmalloc.org/squid/sonda/internal/catalog"
"git.kmalloc.org/squid/sonda/internal/mixes"
"git.kmalloc.org/squid/sonda/internal/taste"
)
var now = time.Date(2026, 11, 12, 10, 0, 0, 0, time.UTC)
func daysAgo(n int) time.Time { return now.Add(-time.Duration(n) * 24 * time.Hour) }
// ---- a store in memory ----
type fakeStore struct {
genres []mixes.Genre
cands []Candidate
history map[int64]History
asked []Filter
windowed map[int64]int // plays inside the window asked for
since []time.Time // the starts of the windows asked for
albumOf map[int64]int64 // the album of a song that has a cover
coverAsk [][]int64 // the songs asked about
saved map[int64]SmartPlaylist // by id
nextID int64
listened int // how many times history was read
}
func newStore() *fakeStore {
return &fakeStore{saved: map[int64]SmartPlaylist{}, history: map[int64]History{}}
}
func (f *fakeStore) Genres(context.Context) ([]mixes.Genre, error) { return f.genres, nil }
func (f *fakeStore) Candidates(_ context.Context, flt Filter) ([]Candidate, error) {
f.asked = append(f.asked, flt)
return f.cands, nil
}
func (f *fakeStore) History(context.Context, int64, time.Duration) (map[int64]History, error) {
f.listened++
return f.history, nil
}
func (f *fakeStore) Plays(_ context.Context, _ int64, _ time.Duration, since time.Time) (map[int64]int, error) {
f.since = append(f.since, since)
return f.windowed, nil
}
func (f *fakeStore) AlbumCovers(_ context.Context, trackIDs []int64, limit int) ([]int64, error) {
f.coverAsk = append(f.coverAsk, trackIDs)
out := []int64{}
for _, id := range trackIDs {
a, ok := f.albumOf[id]
if ok && !slices.Contains(out, a) && len(out) < limit {
out = append(out, a)
}
}
return out, nil
}
func (f *fakeStore) Tracks(_ context.Context, ids []int64) ([]catalog.Track, error) {
out := make([]catalog.Track, len(ids))
for i, id := range ids {
out[i] = catalog.Track{ID: id, Title: "t"}
}
return out, nil
}
func (f *fakeStore) Create(_ context.Context, userID int64, p SmartPlaylist, at time.Time) (SmartPlaylist, error) {
f.nextID++
p.ID, p.CreatedAt, p.UpdatedAt = f.nextID, at, at
f.saved[p.ID] = p
return p, nil
}
func (f *fakeStore) List(context.Context, int64, int, int) ([]SmartPlaylist, int, error) {
return nil, 0, nil
}
func (f *fakeStore) Get(_ context.Context, _ int64, id int64) (SmartPlaylist, error) {
p, ok := f.saved[id]
if !ok {
return SmartPlaylist{}, ErrNotFound
}
return p, nil
}
func (f *fakeStore) Update(_ context.Context, _ int64, id int64, p SmartPlaylist, at time.Time) (SmartPlaylist, error) {
if _, ok := f.saved[id]; !ok {
return SmartPlaylist{}, ErrNotFound
}
p.ID, p.UpdatedAt = id, at
f.saved[id] = p
return p, nil
}
func (f *fakeStore) Delete(context.Context, int64, int64) error { return nil }
type fakeTaster struct{ learned taste.Learned }
func (f fakeTaster) Learn(context.Context, int64) (taste.Learned, error) { return f.learned, nil }
func newService(s *fakeStore, learned taste.Learned) *Service {
svc := NewService(s, fakeTaster{learned}, 20*time.Second)
svc.now = func() time.Time { return now }
return svc
}
// songs makes n candidates, numbered from 1: song i is by artist i, is i minutes long and was added i days ago.
func songs(n int) []Candidate {
out := make([]Candidate, n)
for i := range out {
k := i + 1
out[i] = Candidate{TrackID: int64(k), ArtistID: int64(k), Title: string(rune('a' + i)), DurationMs: int64(k) * 60_000, AddedAt: daysAgo(k)}
}
return out
}
func ids(tracks []catalog.Track) []int64 {
out := make([]int64, len(tracks))
for i, t := range tracks {
out[i] = t.ID
}
return out
}
// preview runs rules in the order given, with a limit big enough for every song.
func preview(t *testing.T, svc *Service, r Rules, sort Sort) []int64 {
t.Helper()
tracks, err := svc.Preview(context.Background(), 1, Input{Rules: r, Sort: sort, Limit: 500}, 0)
if err != nil {
t.Fatal(err)
}
return ids(tracks)
}
// ---- what the rules keep ----
func TestRulesAboutListening(t *testing.T) {
st := newStore()
st.cands = songs(6)
st.history = map[int64]History{
1: {Plays: 5, LastPlayed: daysAgo(2)}, // played lately, a lot
2: {Plays: 1, LastPlayed: daysAgo(40)}, // played long ago
3: {Plays: 0, SkippedAt: daysAgo(3)}, // only skipped, lately
4: {Plays: 2, LastPlayed: daysAgo(10), SkippedAt: daysAgo(1)}, // played, then skipped yesterday
// 5 and 6 were never touched
}
svc := newService(st, taste.Learned{})
for name, tc := range map[string]struct {
rules Rules
want []int64
}{
"no rule keeps every song": {Rules{}, []int64{1, 2, 3, 4, 5, 6}},
"never played": {Rules{NeverPlayed: true}, []int64{3, 5, 6}},
"played in the last 7 days": {Rules{PlayedWithinDays: 7}, []int64{1}},
"played in the last 30 days": {Rules{PlayedWithinDays: 30}, []int64{1, 4}},
"not played for 30 days": {Rules{NotPlayedWithinDays: 30}, []int64{2, 3, 5, 6}},
"played at least twice": {Rules{MinPlays: 2}, []int64{1, 4}},
"skipped in the last 2 days": {Rules{SkippedWithinDays: 2}, []int64{4}},
"skipped in the last 7 days": {Rules{SkippedWithinDays: 7}, []int64{3, 4}},
"not skipped in the last 7 days": {Rules{NotSkippedWithinDays: 7}, []int64{1, 2, 5, 6}},
"two rules must both hold": {Rules{NotPlayedWithinDays: 30, MinPlays: 1}, []int64{2}},
} {
t.Run(name, func(t *testing.T) {
got := preview(t, svc, tc.rules, SortTitle)
if !slices.Equal(got, tc.want) {
t.Errorf("got %v, want %v", got, tc.want)
}
})
}
}
func TestRulesAboutTheSongItself(t *testing.T) {
st := newStore()
st.cands = songs(6) // song k: k minutes, added k days ago
svc := newService(st, taste.Learned{})
for name, tc := range map[string]struct {
rules Rules
want []int64
}{
"added in the last 3 days": {Rules{AddedWithinDays: 3}, []int64{1, 2, 3}},
"at least 4 minutes": {Rules{MinDurationSec: 240}, []int64{4, 5, 6}},
"at most 2 minutes": {Rules{MaxDurationSec: 120}, []int64{1, 2}},
"between 2 and 4 minutes": {Rules{MinDurationSec: 120, MaxDurationSec: 240}, []int64{2, 3, 4}},
"added lately and long": {Rules{AddedWithinDays: 5, MinDurationSec: 180}, []int64{3, 4, 5}},
} {
t.Run(name, func(t *testing.T) {
got := preview(t, svc, tc.rules, SortTitle)
if !slices.Equal(got, tc.want) {
t.Errorf("got %v, want %v", got, tc.want)
}
})
}
}
func TestRulesAboutTaste(t *testing.T) {
st := newStore()
st.cands = songs(4)
learned := taste.Learned{Prefs: map[int64]taste.ArtistPref{
1: {ArtistID: 1, Preference: 0.8}, // loved
2: {ArtistID: 2, Preference: -0.5}, // avoided
3: {ArtistID: 3, Preference: 0}, // neutral
}}
svc := newService(st, learned) // artist 4 was never listened to
if got := preview(t, svc, Rules{LikedArtistsOnly: true}, SortTitle); !slices.Equal(got, []int64{1}) {
t.Errorf("liked artists only: %v, want [1]", got)
}
if got := preview(t, svc, Rules{WithoutAvoidedArtists: true}, SortTitle); !slices.Equal(got, []int64{1, 3, 4}) {
t.Errorf("without avoided artists: %v, want [1 3 4]", got)
}
if got := preview(t, svc, Rules{}, SortTitle); !slices.Equal(got, []int64{1, 2, 3, 4}) {
t.Errorf("no rule keeps the avoided artists too: %v", got)
}
}
// ---- the order ----
func TestTheOrders(t *testing.T) {
st := newStore()
st.cands = []Candidate{
{TrackID: 1, Title: "delta", AddedAt: daysAgo(10)},
{TrackID: 2, Title: "alpha", AddedAt: daysAgo(30)},
{TrackID: 3, Title: "charlie", AddedAt: daysAgo(1)},
{TrackID: 4, Title: "bravo", AddedAt: daysAgo(20)},
}
st.history = map[int64]History{1: {Plays: 3}, 2: {Plays: 9}, 4: {Plays: 3}}
svc := newService(st, taste.Learned{})
for name, tc := range map[string]struct {
sort Sort
want []int64
}{
"by title": {SortTitle, []int64{2, 4, 3, 1}},
"most played first": {SortMostPlayed, []int64{2, 1, 4, 3}}, // a tie goes to the lower id
"least played first": {SortLeastPlayed, []int64{3, 1, 4, 2}},
"recently added first": {SortRecentlyAdded, []int64{3, 1, 4, 2}},
} {
t.Run(name, func(t *testing.T) {
if got := preview(t, svc, Rules{}, tc.sort); !slices.Equal(got, tc.want) {
t.Errorf("got %v, want %v", got, tc.want)
}
})
}
}
func TestTheLimitCutsTheEndOfTheOrder(t *testing.T) {
st := newStore()
st.cands = songs(10)
svc := newService(st, taste.Learned{})
tracks, err := svc.Preview(context.Background(), 1, Input{Sort: SortTitle, Limit: 3}, 0)
if err != nil {
t.Fatal(err)
}
if got := ids(tracks); !slices.Equal(got, []int64{1, 2, 3}) {
t.Errorf("got %v, want the first three", got)
}
}
func TestRandomIsTheSameAllDayAndAnotherForAnotherVariantOrDay(t *testing.T) {
st := newStore()
st.cands = songs(40)
svc := newService(st, taste.Learned{})
run := func(variant int) []int64 {
tracks, err := svc.Preview(context.Background(), 1, Input{Sort: SortRandom, Limit: 10}, variant)
if err != nil {
t.Fatal(err)
}
return ids(tracks)
}
a := run(0)
if len(a) != 10 {
t.Fatalf("%d songs, want 10", len(a))
}
if b := run(0); !slices.Equal(a, b) {
t.Errorf("the same day and variant gave %v then %v", a, b)
}
if b := run(1); slices.Equal(a, b) {
t.Errorf("another variant gave the same songs: %v", a)
}
seen := map[int64]bool{}
for _, id := range a {
if seen[id] {
t.Errorf("song %d twice in %v", id, a)
}
seen[id] = true
}
svc.now = func() time.Time { return now.Add(24 * time.Hour) }
if b := run(0); slices.Equal(a, b) {
t.Errorf("the next day gave the same songs: %v", a)
}
// Another listener gets their own.
svc.now = func() time.Time { return now }
other, err := svc.Preview(context.Background(), 2, Input{Sort: SortRandom, Limit: 10}, 0)
if err != nil {
t.Fatal(err)
}
if slices.Equal(a, ids(other)) {
t.Errorf("another listener got the same songs: %v", a)
}
}
// ---- genres, as the files spell them ----
func TestAGenreIsAskedInEverySpellingTheFilesHave(t *testing.T) {
st := newStore()
st.genres = []mixes.Genre{{Name: "Jazz+Funk"}, {Name: "jazz-funk"}, {Name: "Jazz"}, {Name: "Rock"}, {Name: "Hard Rock"}, {Name: "other"}}
st.cands = songs(2)
svc := newService(st, taste.Learned{})
preview(t, svc, Rules{Genres: []string{"Jazz Funk", "rock"}, NotGenres: []string{"hard rock"}}, SortTitle)
got := st.asked[0]
slices.Sort(got.Genres)
if want := []string{"Jazz+Funk", "Rock", "jazz-funk"}; !slices.Equal(got.Genres, want) {
t.Errorf("genres asked = %v, want %v", got.Genres, want)
}
if want := []string{"Hard Rock"}; !slices.Equal(got.NotGenres, want) {
t.Errorf("genres left out = %v, want %v", got.NotGenres, want)
}
}
func TestAGenreNoFileHasGivesNoSongsAndAsksNothing(t *testing.T) {
st := newStore()
st.genres = []mixes.Genre{{Name: "Rock"}}
st.cands = songs(3)
svc := newService(st, taste.Learned{})
if got := preview(t, svc, Rules{Genres: []string{"polka"}}, SortTitle); len(got) != 0 {
t.Errorf("got %v, want no songs", got)
}
if len(st.asked) != 0 {
t.Errorf("the store was asked for songs: %v", st.asked)
}
// A genre to leave out that no file has leaves out nothing.
if got := preview(t, svc, Rules{NotGenres: []string{"polka"}}, SortTitle); len(got) != 3 {
t.Errorf("got %v, want every song", got)
}
}
func TestTheOtherRulesGoToTheStoreAsTheyAre(t *testing.T) {
st := newStore()
st.cands = songs(1)
svc := newService(st, taste.Learned{})
preview(t, svc, Rules{
ArtistIDs: []int64{1, 2}, NotArtistIDs: []int64{3}, AlbumIDs: []int64{4}, NotAlbumIDs: []int64{5, 6},
Formats: []string{"FLAC", " mpeg "}, MinBitrateKbps: 900,
}, SortTitle)
f := st.asked[0]
if !slices.Equal(f.ArtistIDs, []int64{1, 2}) || !slices.Equal(f.NotArtistIDs, []int64{3}) ||
!slices.Equal(f.AlbumIDs, []int64{4}) || !slices.Equal(f.NotAlbumIDs, []int64{5, 6}) {
t.Errorf("filter = %+v", f)
}
if !slices.Equal(f.Formats, []string{"flac", "mpeg"}) || f.MinBitrateKbps != 900 {
t.Errorf("formats = %v, bitrate = %d", f.Formats, f.MinBitrateKbps)
}
}
func TestHistoryIsReadOnlyWhenARuleNeedsIt(t *testing.T) {
st := newStore()
st.cands = songs(3)
svc := newService(st, taste.Learned{})
preview(t, svc, Rules{AddedWithinDays: 30}, SortTitle)
preview(t, svc, Rules{}, SortRandom)
if st.listened != 0 {
t.Errorf("history was read %d times for rules that do not use it", st.listened)
}
preview(t, svc, Rules{}, SortMostPlayed)
preview(t, svc, Rules{NeverPlayed: true}, SortTitle)
if st.listened != 2 {
t.Errorf("history was read %d times, want 2", st.listened)
}
}
// ---- what is accepted ----
func TestCreateFillsInTheDefaultsAndCleansTheText(t *testing.T) {
st := newStore()
svc := newService(st, taste.Learned{})
p, err := svc.Create(context.Background(), 1, Input{Name: " Fresh ", Description: " lately added ", Rules: Rules{AddedWithinDays: 30, Genres: []string{" Rock "}}})
if err != nil {
t.Fatal(err)
}
if p.Name != "Fresh" || p.Description != "lately added" || p.Sort != SortRandom || p.Limit != DefaultLimit {
t.Errorf("playlist = %+v", p)
}
if !slices.Equal(p.Rules.Genres, []string{"rock"}) {
t.Errorf("genres = %v: they are kept as they are compared", p.Rules.Genres)
}
if p.CreatedAt != now {
t.Errorf("created at %v, want %v", p.CreatedAt, now)
}
}
func TestWhatIsRefused(t *testing.T) {
long := make([]string, MaxListed+1)
for i := range long {
long[i] = "x"
}
longIDs := make([]int64, MaxListed+1)
for i := range longIDs {
longIDs[i] = int64(i + 1)
}
aboutTheName := map[string]bool{"no name": true, "a name that is too long": true}
for name, in := range map[string]Input{
"no name": {Name: " "},
"a name that is too long": {Name: string(make([]byte, MaxNameLen+1))},
"a description too long": {Name: "a", Description: string(make([]rune, MaxDescriptionLen+1))},
"an unknown order": {Name: "a", Sort: "loudest"},
"a limit below 1": {Name: "a", Limit: -1},
"a limit over the maximum": {Name: "a", Limit: MaxLimit + 1},
"too many genres": {Name: "a", Rules: Rules{Genres: long}},
"too many artists": {Name: "a", Rules: Rules{ArtistIDs: longIDs}},
"a blank genre": {Name: "a", Rules: Rules{Genres: []string{" "}}},
"a genre that is not one": {Name: "a", Rules: Rules{Genres: []string{"unknown"}}},
"an id below 1": {Name: "a", Rules: Rules{AlbumIDs: []int64{0}}},
"a format with a symbol": {Name: "a", Rules: Rules{Formats: []string{"fl/ac"}}},
"a negative number of days": {Name: "a", Rules: Rules{PlayedWithinDays: -1}},
"too many days": {Name: "a", Rules: Rules{AddedWithinDays: MaxDays + 1}},
"a negative minimum": {Name: "a", Rules: Rules{MinPlays: -1}},
"a negative bitrate": {Name: "a", Rules: Rules{MinBitrateKbps: -1}},
"a minimum over a maximum": {Name: "a", Rules: Rules{MinDurationSec: 200, MaxDurationSec: 100}},
} {
t.Run(name, func(t *testing.T) {
if _, err := newService(newStore(), taste.Learned{}).Create(context.Background(), 1, in); !errors.Is(err, ErrInvalidInput) {
t.Errorf("err = %v, want ErrInvalidInput", err)
}
if aboutTheName[name] {
return // a preview has no name
}
if _, err := newService(newStore(), taste.Learned{}).Preview(context.Background(), 1, in, 0); !errors.Is(err, ErrInvalidInput) {
t.Errorf("preview: err = %v, want ErrInvalidInput", err)
}
})
}
if _, err := newService(newStore(), taste.Learned{}).Preview(context.Background(), 1, Input{}, mixes.MaxVariant+1); !errors.Is(err, ErrInvalidInput) {
t.Errorf("a variant that is too big: err = %v", err)
}
}
func TestAPreviewNeedsNoName(t *testing.T) {
st := newStore()
st.cands = songs(2)
if _, err := newService(st, taste.Learned{}).Preview(context.Background(), 1, Input{Sort: SortTitle}, 0); err != nil {
t.Errorf("err = %v", err)
}
}
// ---- keeping and reading a smart playlist ----
func TestTracksRunsTheRulesOfASavedPlaylist(t *testing.T) {
st := newStore()
st.cands = songs(8)
svc := newService(st, taste.Learned{})
p, err := svc.Create(context.Background(), 1, Input{Name: "Short", Rules: Rules{MaxDurationSec: 240}, Sort: SortTitle, Limit: 3})
if err != nil {
t.Fatal(err)
}
got, tracks, err := svc.Tracks(context.Background(), 1, p.ID, 0)
if err != nil {
t.Fatal(err)
}
if got.ID != p.ID || !slices.Equal(ids(tracks), []int64{1, 2, 3}) {
t.Errorf("playlist %d, songs %v", got.ID, ids(tracks))
}
if _, _, err := svc.Tracks(context.Background(), 1, 99, 0); !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound", err)
}
}
func TestUpdateChangesWhatWasSentAndChecksIt(t *testing.T) {
st := newStore()
svc := newService(st, taste.Learned{})
p, _ := svc.Create(context.Background(), 1, Input{Name: "A", Description: "d", Rules: Rules{NeverPlayed: true}, Sort: SortTitle, Limit: 20})
name, sort, limit := "B", SortMostPlayed, 30
got, err := svc.Update(context.Background(), 1, p.ID, Patch{Name: &name, Sort: &sort, Limit: &limit, Rules: &Rules{MinPlays: 3}})
if err != nil {
t.Fatal(err)
}
if got.Name != "B" || got.Description != "d" || got.Sort != SortMostPlayed || got.Limit != 30 || got.Rules.MinPlays != 3 || got.Rules.NeverPlayed {
t.Errorf("playlist = %+v: the rules are replaced whole, the rest only when sent", got)
}
if !got.UpdatedAt.Equal(now) {
t.Errorf("updated at %v", got.UpdatedAt)
}
bad := ""
if _, err := svc.Update(context.Background(), 1, p.ID, Patch{Name: &bad}); !errors.Is(err, ErrInvalidInput) {
t.Errorf("blank name: err = %v", err)
}
if _, err := svc.Update(context.Background(), 1, p.ID, Patch{Rules: &Rules{MinPlays: -1}}); !errors.Is(err, ErrInvalidInput) {
t.Errorf("bad rules: err = %v", err)
}
if _, err := svc.Update(context.Background(), 1, 99, Patch{Name: &name}); !errors.Is(err, ErrNotFound) {
t.Errorf("unknown playlist: err = %v", err)
}
}
func TestListLowersAPageThatIsTooBigAndRefusesNegatives(t *testing.T) {
svc := newService(newStore(), taste.Learned{})
for _, tc := range []struct{ in, want int }{{0, DefaultPageLimit}, {10, 10}, {MaxPageLimit + 1, MaxPageLimit}} {
l, err := svc.List(context.Background(), 1, tc.in, 0)
if err != nil || l.Limit != tc.want {
t.Errorf("limit %d: got %d, %v; want %d", tc.in, l.Limit, err, tc.want)
}
}
if _, err := svc.List(context.Background(), 1, -1, 0); !errors.Is(err, ErrInvalidInput) {
t.Errorf("a negative limit: %v", err)
}
if _, err := svc.List(context.Background(), 1, 10, -1); !errors.Is(err, ErrInvalidInput) {
t.Errorf("a negative offset: %v", err)
}
}
func TestGenresMergeSpellingsLeaveOutWhatIsNotAGenreAndCountTheBiggestFirst(t *testing.T) {
st := newStore()
st.genres = []mixes.Genre{
{Name: "Rock", Tracks: 30}, {Name: "rock", Tracks: 10},
{Name: "Jazz+Funk", Tracks: 5}, {Name: "jazz-funk", Tracks: 7},
{Name: "metal", Tracks: 12}, {Name: "Blues", Tracks: 12},
{Name: "other", Tracks: 99}, {Name: " ", Tracks: 4},
}
got, err := newService(st, taste.Learned{}).Genres(context.Background())
if err != nil {
t.Fatal(err)
}
want := []GenreCount{{"rock", 40}, {"blues", 12}, {"jazz funk", 12}, {"metal", 12}} // a tie goes to the name
if !slices.Equal(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}
// ---- the suggested ones ----
func TestSuggestedAreAFixedSetOfValidRules(t *testing.T) {
list := Suggested()
if len(list) < 5 {
t.Fatalf("%d suggested smart playlists", len(list))
}
seen := map[string]bool{}
for _, s := range list {
if s.Key == "" || seen[s.Key] {
t.Errorf("key %q is empty or repeated", s.Key)
}
seen[s.Key] = true
in, err := clean(Input{Rules: s.Rules, Sort: s.Sort, Limit: s.Limit})
if err != nil {
t.Errorf("%s: %v", s.Key, err)
}
if in.Sort != s.Sort || in.Limit != s.Limit || s.Limit < 1 {
t.Errorf("%s: shape changed by cleaning: %+v", s.Key, in)
}
}
for _, want := range []string{"recently-added", "on-rotation", "top-year", "most-played", "never-played", "forgotten", "high-quality", "long-tracks"} {
if !seen[want] {
t.Errorf("%s is missing", want)
}
}
// A caller cannot change the set by changing what it was given.
list[0].Rules.Genres = []string{"x"}
if got := Suggested()[0].Rules.Genres; len(got) != 0 {
t.Errorf("the set was changed: %v", got)
}
}
func TestSuggestedSongsAreWorkedOutFromTheirRulesForTheListener(t *testing.T) {
st := newStore()
st.cands = songs(6)
st.history = map[int64]History{1: {Plays: 4, LastPlayed: daysAgo(2)}, 2: {Plays: 1, LastPlayed: daysAgo(200)}}
svc := newService(st, taste.Learned{})
got, tracks, err := svc.SuggestedTracks(context.Background(), 1, "never-played", 0)
if err != nil || got.Key != "never-played" {
t.Fatalf("%+v, %v", got, err)
}
if ids := ids(tracks); slices.Contains(ids, 1) || slices.Contains(ids, 2) || len(ids) != 4 {
t.Errorf("never played = %v: songs 1 and 2 were played", ids)
}
_, tracks, _ = svc.SuggestedTracks(context.Background(), 1, "forgotten", 0)
if got := ids(tracks); !slices.Equal(got, []int64{2}) {
t.Errorf("forgotten = %v, want the song played once 200 days ago", got)
}
_, tracks, _ = svc.SuggestedTracks(context.Background(), 1, "most-played", 0)
if got := ids(tracks); !slices.Equal(got, []int64{1, 2}) {
t.Errorf("most played = %v, want the played ones, the most first", got)
}
_, tracks, _ = svc.SuggestedTracks(context.Background(), 1, "recently-added", 0)
if got := ids(tracks); len(got) == 0 || got[0] != 1 {
t.Errorf("recently added = %v, want the newest first", got)
}
if _, _, err := svc.SuggestedTracks(context.Background(), 1, "nonsense", 0); !errors.Is(err, ErrNotFound) {
t.Errorf("unknown key: %v", err)
}
if _, _, err := svc.SuggestedTracks(context.Background(), 1, "never-played", MaxVariant+1); !errors.Is(err, ErrInvalidInput) {
t.Errorf("variant: %v", err)
}
}
func TestEachSuggestedRandomOrderIsItsOwn(t *testing.T) {
st := newStore()
st.cands = songs(60)
svc := newService(st, taste.Learned{})
_, a, _ := svc.SuggestedTracks(context.Background(), 1, "never-played", 0)
_, b, _ := svc.SuggestedTracks(context.Background(), 1, "long-tracks", 0)
st.cands = songs(60)
if slices.Equal(ids(a), ids(b)) {
t.Error("two suggested playlists with the same candidates gave the same order")
}
}
func TestSummaryOfRulesIsAFewWordsInEnglish(t *testing.T) {
if got := (Rules{}).Summary(); got != "" {
t.Errorf("no rules: %q", got)
}
r := Rules{Genres: []string{"rock", "metal"}, NotGenres: []string{"pop"}, Formats: []string{"flac"}, MinBitrateKbps: 900, AddedWithinDays: 30,
NeverPlayed: true, NotPlayedWithinDays: 90, MinPlays: 2, LikedArtistsOnly: true, MinDurationSec: 360}
want := "genres: rock, metal; not genres: pop; formats: flac; at least 900 kbps; added in the last 30 days; never played; " +
"not played for 90 days; played at least 2 times; only liked artists; at least 6 minutes long"
if got := r.Summary(); got != want {
t.Errorf("summary =\n%q\nwant\n%q", got, want)
}
// Artists and albums are ids: they say nothing to a reader, so they are not said.
if got := (Rules{ArtistIDs: []int64{3}, AlbumIDs: []int64{4}}).Summary(); got != "" {
t.Errorf("ids: %q", got)
}
}
// ---- plays inside a window ----
func TestPlaysCanBeCountedOverTheLastDaysOnly(t *testing.T) {
st := newStore()
st.cands = songs(5)
// Over all time song 1 is the most played; in the last 30 days it is song 3.
st.history = map[int64]History{1: {Plays: 40, LastPlayed: daysAgo(100)}, 2: {Plays: 9, LastPlayed: daysAgo(3)}, 3: {Plays: 8, LastPlayed: daysAgo(1)}, 4: {Plays: 2, LastPlayed: daysAgo(2)}}
st.windowed = map[int64]int{2: 3, 3: 7, 4: 1}
svc := newService(st, taste.Learned{})
got := preview(t, svc, Rules{}, SortMostPlayed)
if !slices.Equal(got[:3], []int64{1, 2, 3}) {
t.Fatalf("over all time = %v, want 1, 2, 3 first", got)
}
if len(st.since) != 0 {
t.Errorf("a window was asked for with no rule that wants one: %v", st.since)
}
got = preview(t, svc, Rules{PlaysWithinDays: 30}, SortMostPlayed)
if want := []int64{3, 2, 4, 1, 5}; !slices.Equal(got, want) {
t.Errorf("in the last 30 days = %v, want %v: 40 old plays count for nothing", got, want)
}
if len(st.since) != 1 || !st.since[0].Equal(daysAgo(30)) {
t.Errorf("window starts = %v, want %v", st.since, daysAgo(30))
}
got = preview(t, svc, Rules{PlaysWithinDays: 30}, SortLeastPlayed)
if got[0] != 1 && got[0] != 5 {
t.Errorf("least played in the window = %v, want a song with no plays in it first", got)
}
}
func TestTheMinimumOfPlaysCountsOnlyTheWindowWhenThereIsOne(t *testing.T) {
st := newStore()
st.cands = songs(4)
st.history = map[int64]History{1: {Plays: 40}, 2: {Plays: 9}, 3: {Plays: 8}, 4: {Plays: 2}}
st.windowed = map[int64]int{2: 3, 3: 7, 4: 1}
svc := newService(st, taste.Learned{})
if got := preview(t, svc, Rules{MinPlays: 3}, SortTitle); !slices.Equal(got, []int64{1, 2, 3}) {
t.Errorf("at least 3 plays, ever = %v", got)
}
if got := preview(t, svc, Rules{MinPlays: 3, PlaysWithinDays: 30}, SortTitle); !slices.Equal(got, []int64{2, 3}) {
t.Errorf("at least 3 plays in the last 30 days = %v, want 2 and 3", got)
}
// Never played still means never, in the window or not.
if got := preview(t, svc, Rules{NeverPlayed: true, PlaysWithinDays: 30}, SortTitle); len(got) != 0 {
t.Errorf("never played = %v: every song has been played", got)
}
}
func TestOnRotationAndTheTopOfTheYearCountTheirOwnWindows(t *testing.T) {
st := newStore()
st.cands = songs(6)
st.windowed = map[int64]int{1: 1, 2: 5, 3: 9, 4: 2}
svc := newService(st, taste.Learned{})
sug, tracks, err := svc.SuggestedTracks(context.Background(), 1, "on-rotation", 0)
if err != nil {
t.Fatal(err)
}
if got := ids(tracks); !slices.Equal(got, []int64{3, 2, 4}) {
t.Errorf("on rotation = %v, want the songs played at least twice lately, the most first", got)
}
if sug.Rules.PlaysWithinDays != 30 || sug.Sort != SortMostPlayed {
t.Errorf("on-rotation = %+v", sug)
}
st.since = nil
if _, _, err := svc.SuggestedTracks(context.Background(), 1, "top-year", 0); err != nil {
t.Fatal(err)
}
if len(st.since) != 1 || !st.since[0].Equal(daysAgo(365)) {
t.Errorf("top-year window = %v", st.since)
}
}
func TestAWindowOfDaysIsChecked(t *testing.T) {
for _, n := range []int{-1, MaxDays + 1} {
if _, err := newService(newStore(), taste.Learned{}).Preview(context.Background(), 1, Input{Rules: Rules{PlaysWithinDays: n}}, 0); !errors.Is(err, ErrInvalidInput) {
t.Errorf("plays_within_days %d: %v", n, err)
}
}
if got := (Rules{PlaysWithinDays: 30, MinPlays: 2}).Summary(); got != "played at least 2 times; plays counted over the last 30 days" {
t.Errorf("summary = %q", got)
}
}
// ---- the albums that stand for a smart playlist ----
func TestTheAlbumsOfASmartPlaylistAreThoseOfTheSongsItGivesInOrder(t *testing.T) {
st := newStore()
st.cands = songs(8)
// Songs 3, 4, 5, 6 and 7 have albums with a cover; songs 1 and 2 do not. Songs 3 and 5 share an album.
st.albumOf = map[int64]int64{3: 30, 4: 40, 5: 30, 6: 60, 7: 70}
svc := newService(st, taste.Learned{})
p, err := svc.Create(context.Background(), 1, Input{Name: "All", Sort: SortTitle, Limit: 8})
if err != nil {
t.Fatal(err)
}
got, err := svc.Covers(context.Background(), 1, p.ID, 0)
if err != nil || !slices.Equal(got, []int64{30, 40, 60, 70}) {
t.Fatalf("covers = %v, %v: in the order of the songs, each album once, four at most", got, err)
}
// The songs asked about are the ones the playlist gives, no more.
if len(st.coverAsk) != 1 || !slices.Equal(st.coverAsk[0], []int64{1, 2, 3, 4, 5, 6, 7, 8}) {
t.Errorf("asked about %v", st.coverAsk)
}
short, _ := svc.Create(context.Background(), 1, Input{Name: "Three", Sort: SortTitle, Limit: 3})
if got, _ := svc.Covers(context.Background(), 1, short.ID, 0); !slices.Equal(got, []int64{30}) {
t.Errorf("the limit counts, only song 3 of the first three has a cover: %v", got)
}
}
func TestTheCoversFollowTheVariantOfARandomOrderAndAreEmptyNotMissing(t *testing.T) {
st := newStore()
st.cands = songs(40)
st.albumOf = map[int64]int64{}
for i := int64(1); i <= 40; i++ {
st.albumOf[i] = 100 + i
}
svc := newService(st, taste.Learned{})
p, _ := svc.Create(context.Background(), 1, Input{Name: "Any", Sort: SortRandom, Limit: 10})
a, _ := svc.Covers(context.Background(), 1, p.ID, 0)
b, _ := svc.Covers(context.Background(), 1, p.ID, 0)
c, _ := svc.Covers(context.Background(), 1, p.ID, 1)
if !slices.Equal(a, b) || slices.Equal(a, c) {
t.Errorf("covers of the day = %v and %v, of variant 1 = %v", a, b, c)
}
// They are the covers of the songs that the playlist shows for the same variant.
_, tracks, _ := svc.Tracks(context.Background(), 1, p.ID, 1)
var want []int64
for _, tr := range tracks[:4] {
want = append(want, st.albumOf[tr.ID])
}
if !slices.Equal(c, want) {
t.Errorf("variant 1 covers = %v, its first songs have %v", c, want)
}
st.albumOf = nil
if none, err := svc.Covers(context.Background(), 1, p.ID, 0); err != nil || none == nil || len(none) != 0 {
t.Errorf("no cover at all = %#v, %v", none, err)
}
if _, err := svc.Covers(context.Background(), 1, 999, 0); !errors.Is(err, ErrNotFound) {
t.Errorf("unknown playlist: %v", err)
}
if _, err := svc.Covers(context.Background(), 1, p.ID, MaxVariant+1); !errors.Is(err, ErrInvalidInput) {
t.Errorf("variant: %v", err)
}
}
func TestTheCoversOfASuggestedOneAreThoseOfItsSongs(t *testing.T) {
st := newStore()
st.cands = songs(6)
st.albumOf = map[int64]int64{1: 11, 2: 12, 4: 14}
svc := newService(st, taste.Learned{})
got, err := svc.SuggestedCovers(context.Background(), 1, "recently-added", 0)
if err != nil || !slices.Equal(got, []int64{11, 12, 14}) {
t.Errorf("covers = %v, %v: the newest songs first", got, err)
}
if _, err := svc.SuggestedCovers(context.Background(), 1, "nonsense", 0); !errors.Is(err, ErrNotFound) {
t.Errorf("unknown key: %v", err)
}
}
func TestTheYearRulesGoToTheIndexAndAreChecked(t *testing.T) {
st := newStore()
st.cands = songs(3)
svc := newService(st, taste.Learned{})
preview(t, svc, Rules{MinYear: 1980, MaxYear: 1989}, SortTitle)
if len(st.asked) != 1 || st.asked[0].MinYear != 1980 || st.asked[0].MaxYear != 1989 {
t.Errorf("the index was asked %+v", st.asked)
}
for name, r := range map[string]Rules{
"a year before 1000": {MinYear: 999},
"a year after 2999": {MaxYear: 3000},
"a negative year": {MinYear: -1},
"from after up to": {MinYear: 1990, MaxYear: 1980},
} {
if _, err := svc.Preview(context.Background(), 1, Input{Rules: r}, 0); !errors.Is(err, ErrInvalidInput) {
t.Errorf("%s: err = %v, want ErrInvalidInput", name, err)
}
}
for name, r := range map[string]Rules{
"one year": {MinYear: 1985, MaxYear: 1985},
"only a start": {MinYear: 1950},
"only an end": {MaxYear: 2024},
} {
if _, err := svc.Preview(context.Background(), 1, Input{Rules: r}, 0); err != nil {
t.Errorf("%s: %v", name, err)
}
}
if got := (Rules{MinYear: 1980, MaxYear: 1989}).Summary(); !strings.Contains(got, "from 1980") || !strings.Contains(got, "up to 1989") {
t.Errorf("summary = %q", got)
}
}