sonda/internal/api/http/smart_test.go
tgiachi bf5c108785 feat(smart): the songs I play most, in rotation lately and over the year
- A smart playlist rule, plays_within_days, that counts only the plays of the last N days where plays are counted: the minimum of plays and the most and least played orders. The other listening rules are not changed.
- Two more suggested smart playlists on it: on-rotation (the most played of the last 30 days, at least twice) and top-year (the same over 365 days). most-played stays as the plays of all time.
- The editor has the new rule and the page says it in words. Texts in English and Italian.
2026-11-13 10:44:55 +01:00

399 lines
18 KiB
Go

package httpapi
import (
"fmt"
"net/http"
"slices"
"strings"
"testing"
)
const sp = "/api/v1/smart-playlists"
// smartMade makes a smart playlist of alice's and returns its id.
func smartMade(t *testing.T, m *mixAPI, body map[string]any) int {
t.Helper()
r := do(t, m.h, "POST", sp, m.alice, body)
if r.Code != http.StatusCreated {
t.Fatalf("create: %d %v", r.Code, r.Body)
}
return int(r.Body["id"].(float64))
}
func smartTracks(t *testing.T, m *mixAPI, id int, query string) []float64 {
t.Helper()
r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/tracks%s", sp, id, query), m.alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("tracks: %d %v", r.Code, r.Body)
}
return trackIDs(t, r)
}
func TestSmartPlaylistRoutesNeedASignedInUser(t *testing.T) {
m := newMixAPI(t)
for _, rt := range []struct{ method, path string }{
{"GET", "/api/v1/genres"}, {"GET", sp + "/suggested"}, {"GET", sp + "/suggested/never-played/tracks"}, {"POST", sp + "/suggested/never-played/playlist"}, {"GET", sp}, {"POST", sp}, {"POST", sp + "/preview"}, {"GET", sp + "/1"}, {"PATCH", sp + "/1"}, {"DELETE", sp + "/1"},
{"GET", sp + "/1/tracks"}, {"POST", sp + "/1/playlist"},
} {
if r := do(t, m.h, rt.method, rt.path, "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("%s %s without a token: %d", rt.method, rt.path, r.Code)
}
}
}
func TestASmartPlaylistIsMadeReadChangedAndDeleted(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "POST", sp, m.alice, map[string]any{
"name": " Rock, new ", "rules": map[string]any{"genres": []string{"Rock"}, "never_played": true, "formats": []string{"FLAC"}},
})
if r.Code != http.StatusCreated {
t.Fatalf("create: %d %v", r.Code, r.Body)
}
id := int(r.Body["id"].(float64))
rules := r.Body["rules"].(map[string]any)
if r.Body["name"] != "Rock, new" || r.Body["sort"] != "random" || r.Body["limit"] != float64(50) || r.Body["description"] != "" ||
r.Body["created_at"] == nil || r.Body["updated_at"] == nil ||
rules["never_played"] != true || fmt.Sprint(rules["genres"]) != "[rock]" || fmt.Sprint(rules["formats"]) != "[flac]" {
t.Errorf("created = %v", r.Body)
}
got := do(t, m.h, "GET", fmt.Sprintf("%s/%d", sp, id), m.alice, nil)
if got.Code != http.StatusOK || got.Body["name"] != "Rock, new" {
t.Errorf("get: %d %v", got.Code, got.Body)
}
list := do(t, m.h, "GET", sp, m.alice, nil)
if list.Body["total"] != float64(1) || list.Body["limit"] != float64(50) || list.Body["offset"] != float64(0) || len(list.Body["items"].([]any)) != 1 {
t.Errorf("list = %v", list.Body)
}
upd := do(t, m.h, "PATCH", fmt.Sprintf("%s/%d", sp, id), m.alice, map[string]any{
"name": "Rock, again", "sort": "title", "limit": 20, "rules": map[string]any{"min_plays": 3},
})
rules = upd.Body["rules"].(map[string]any)
if upd.Code != http.StatusOK || upd.Body["name"] != "Rock, again" || upd.Body["sort"] != "title" || upd.Body["limit"] != float64(20) ||
rules["min_plays"] != float64(3) || rules["never_played"] != nil || rules["genres"] != nil {
t.Errorf("update: %d %v: the rules are replaced whole", upd.Code, upd.Body)
}
// Only what is sent changes.
again := do(t, m.h, "PATCH", fmt.Sprintf("%s/%d", sp, id), m.alice, map[string]any{"description": "d"})
if again.Body["name"] != "Rock, again" || again.Body["description"] != "d" || again.Body["sort"] != "title" {
t.Errorf("a patch with one field: %v", again.Body)
}
if del := do(t, m.h, "DELETE", fmt.Sprintf("%s/%d", sp, id), m.alice, nil); del.Code != http.StatusNoContent {
t.Errorf("delete: %d", del.Code)
}
if r := do(t, m.h, "GET", fmt.Sprintf("%s/%d", sp, id), m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "smart_playlist_not_found" {
t.Errorf("get after delete: %d %v", r.Code, r.Body)
}
}
func TestWhatIsNotAcceptedIsSaidSo(t *testing.T) {
m := newMixAPI(t)
for name, body := range map[string]map[string]any{
"no name": {"rules": map[string]any{}},
"an unknown order": {"name": "a", "sort": "loudest"},
"a limit too big": {"name": "a", "limit": 501},
"days below zero": {"name": "a", "rules": map[string]any{"played_within_days": -1}},
"a genre that isn't": {"name": "a", "rules": map[string]any{"genres": []string{"unknown"}}},
"a bad format": {"name": "a", "rules": map[string]any{"formats": []string{"fl/ac"}}},
} {
if r := do(t, m.h, "POST", sp, m.alice, body); r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" {
t.Errorf("%s: %d %v", name, r.Code, r.Body)
}
}
for _, path := range []string{sp + "/0", sp + "/x", sp + "/1/tracks?variant=-1", sp + "/1/tracks?variant=x", sp + "?limit=-1"} {
if r := do(t, m.h, "GET", path, m.alice, nil); r.Code != http.StatusBadRequest {
t.Errorf("GET %s: %d %v", path, r.Code, r.Body)
}
}
if r := do(t, m.h, "POST", sp, m.alice, nil); r.Code != http.StatusBadRequest {
t.Errorf("no body: %d", r.Code)
}
}
func TestTheSongsAreWorkedOutFromTheRules(t *testing.T) {
m := newMixAPI(t)
id := smartMade(t, m, map[string]any{"name": "Hard", "sort": "title", "limit": 5, "rules": map[string]any{"genres": []string{"hard rock"}}})
r := do(t, m.h, "GET", fmt.Sprintf("%s/%d/tracks", sp, id), m.alice, nil)
ids := trackIDs(t, r)
if r.Code != http.StatusOK || r.Body["variant"] != float64(0) || len(ids) != 5 {
t.Fatalf("tracks: %d %v", r.Code, r.Body)
}
for _, x := range r.Body["tracks"].([]any) {
track := x.(map[string]any)
if !strings.HasPrefix(track["title"].(string), "hard song") || track["album"] == nil || len(track["artists"].([]any)) != 1 {
t.Errorf("a song = %v", track)
}
}
if again := smartTracks(t, m, id, ""); !slices.Equal(ids, again) {
t.Error("the same order twice is not the same")
}
// A rule that no song meets gives an empty list, which is no error.
none := smartMade(t, m, map[string]any{"name": "Polka", "rules": map[string]any{"genres": []string{"polka"}}})
if got := smartTracks(t, m, none, ""); len(got) != 0 {
t.Errorf("polka: %v", got)
}
}
func TestARandomOrderStaysTheSameForADayAndAVariantGivesAnother(t *testing.T) {
m := newMixAPI(t)
id := smartMade(t, m, map[string]any{"name": "Any", "limit": 10, "rules": map[string]any{"genres": []string{"rock"}}})
first := smartTracks(t, m, id, "")
if len(first) != 10 || !slices.Equal(first, smartTracks(t, m, id, "")) {
t.Fatalf("the random order of a day changed: %v", first)
}
if v := smartTracks(t, m, id, "?variant=1"); slices.Equal(first, v) {
t.Error("another variant gave the same songs")
}
}
func TestListeningRulesUseTheHistoryOfTheOwner(t *testing.T) {
m := newMixAPI(t)
var played []int64
rows, err := m.db.Query("SELECT id FROM tracks WHERE title LIKE 'hard song%' ORDER BY id LIMIT 4")
if err != nil {
t.Fatal(err)
}
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
t.Fatal(err)
}
played = append(played, id)
}
rows.Close()
for i, id := range played {
if _, err := m.db.Exec(`INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key)
VALUES (1, ?, 'complete', strftime('%s','now'), 60000, ?)`, id, fmt.Sprintf("k%d", i)); err != nil {
t.Skipf("cannot add listening events by hand here: %v", err)
}
}
never := smartMade(t, m, map[string]any{"name": "New hard", "limit": 500, "rules": map[string]any{"genres": []string{"hard rock"}, "never_played": true}})
if got := smartTracks(t, m, never, ""); len(got) != 36-4 {
t.Errorf("never played: %d songs, want 32", len(got))
}
heard := smartMade(t, m, map[string]any{"name": "Heard", "limit": 500, "rules": map[string]any{"played_within_days": 7}})
if got := smartTracks(t, m, heard, ""); len(got) != 4 {
t.Errorf("played this week: %d songs, want 4", len(got))
}
}
func TestPreviewTriesRulesWithoutKeepingAnything(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "POST", sp+"/preview", m.alice, map[string]any{"rules": map[string]any{"genres": []string{"hard rock"}}, "sort": "title", "limit": 3})
if r.Code != http.StatusOK || r.Body["variant"] != float64(0) || len(trackIDs(t, r)) != 3 {
t.Fatalf("preview: %d %v", r.Code, r.Body)
}
if list := do(t, m.h, "GET", sp, m.alice, nil); list.Body["total"] != float64(0) {
t.Errorf("a preview kept something: %v", list.Body)
}
r = do(t, m.h, "POST", sp+"/preview", m.alice, map[string]any{"rules": map[string]any{"genres": []string{"rock"}}, "limit": 10, "variant": 2})
if r.Code != http.StatusOK || r.Body["variant"] != float64(2) {
t.Errorf("preview with a variant: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/preview", m.alice, map[string]any{"sort": "loudest"}); r.Code != http.StatusBadRequest {
t.Errorf("preview of a bad order: %d", r.Code)
}
if r := do(t, m.h, "POST", sp+"/preview", m.alice, map[string]any{"variant": -1}); r.Code != http.StatusBadRequest {
t.Errorf("preview of a bad variant: %d", r.Code)
}
}
func TestASmartPlaylistIsKeptAsAPlaylistWithTheSongsShown(t *testing.T) {
m := newMixAPI(t)
id := smartMade(t, m, map[string]any{"name": "Hard, kept", "limit": 6, "rules": map[string]any{"genres": []string{"hard rock"}}})
shown := smartTracks(t, m, id, "?variant=3")
r := do(t, m.h, "POST", fmt.Sprintf("%s/%d/playlist", sp, id), m.alice, map[string]any{"variant": 3})
if r.Code != http.StatusCreated || r.Body["name"] != "Hard, kept" || r.Body["track_count"] != float64(6) {
t.Fatalf("save: %d %v", r.Code, r.Body)
}
items := do(t, m.h, "GET", fmt.Sprintf("/api/v1/playlists/%d/tracks", int(r.Body["id"].(float64))), m.alice, nil)
var kept []float64
for _, x := range items.Body["items"].([]any) {
kept = append(kept, x.(map[string]any)["track"].(map[string]any)["id"].(float64))
}
if !slices.Equal(kept, shown) {
t.Errorf("the playlist has %v, the smart playlist showed %v", kept, shown)
}
// It is a copy: the smart playlist is still there, and a name can be given.
named := do(t, m.h, "POST", fmt.Sprintf("%s/%d/playlist", sp, id), m.alice, map[string]any{"name": "Mine"})
if named.Code != http.StatusCreated || named.Body["name"] != "Mine" {
t.Errorf("named save: %d %v", named.Code, named.Body)
}
if r := do(t, m.h, "POST", fmt.Sprintf("%s/%d/playlist", sp, id), m.alice, nil); r.Code != http.StatusCreated {
t.Errorf("a save with no body: %d", r.Code)
}
}
func TestASmartPlaylistWithNoSongsIsNotKept(t *testing.T) {
m := newMixAPI(t)
id := smartMade(t, m, map[string]any{"name": "Polka", "rules": map[string]any{"genres": []string{"polka"}}})
r := do(t, m.h, "POST", fmt.Sprintf("%s/%d/playlist", sp, id), m.alice, nil)
if r.Code != http.StatusUnprocessableEntity || errCode(r) != "smart_playlist_empty" {
t.Errorf("save: %d %v", r.Code, r.Body)
}
if list := do(t, m.h, "GET", "/api/v1/playlists", m.alice, nil); list.Body["total"] != float64(0) {
t.Errorf("a playlist was made: %v", list.Body)
}
}
func TestASmartPlaylistIsItsOwnersAlone(t *testing.T) {
m := newMixAPI(t)
_, bob := addUser(t, m.h, m.alice, "bob", false)
id := smartMade(t, m, map[string]any{"name": "Mine", "rules": map[string]any{}})
path := fmt.Sprintf("%s/%d", sp, id)
for _, rt := range []struct {
method, path string
body any
}{
{"GET", path, nil}, {"PATCH", path, map[string]any{"name": "x"}}, {"DELETE", path, nil},
{"GET", path + "/tracks", nil}, {"POST", path + "/playlist", nil},
} {
if r := do(t, m.h, rt.method, rt.path, bob, rt.body); r.Code != http.StatusNotFound || errCode(r) != "smart_playlist_not_found" {
t.Errorf("bob %s %s: %d %v, want 404 smart_playlist_not_found", rt.method, rt.path, r.Code, r.Body)
}
}
if list := do(t, m.h, "GET", sp, bob, nil); list.Body["total"] != float64(0) {
t.Errorf("bob's list: %v", list.Body)
}
if r := do(t, m.h, "GET", path, m.alice, nil); r.Code != http.StatusOK || r.Body["name"] != "Mine" {
t.Errorf("alice's own changed: %d %v", r.Code, r.Body)
}
}
func TestTheGenresOfTheLibraryAreListedBiggestFirst(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", "/api/v1/genres", m.alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("genres: %d %v", r.Code, r.Body)
}
items := r.Body["items"].([]any)
if len(items) != 2 {
t.Fatalf("genres = %v", items)
}
first, second := items[0].(map[string]any), items[1].(map[string]any)
if first["name"] != "rock" || first["tracks"] != float64(40) || second["name"] != "hard rock" || second["tracks"] != float64(36) {
t.Errorf("genres = %v", items)
}
}
func TestSuggestedSmartPlaylistsAreThereForEveryoneWithTheirRules(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", sp+"/suggested", m.alice, nil)
if r.Code != http.StatusOK {
t.Fatalf("suggested: %d %v", r.Code, r.Body)
}
byKey := map[string]map[string]any{}
for _, x := range r.Body["items"].([]any) {
s := x.(map[string]any)
byKey[s["key"].(string)] = s
}
for _, key := range []string{"recently-added", "on-rotation", "top-year", "most-played", "never-played", "forgotten", "high-quality", "long-tracks"} {
if byKey[key] == nil {
t.Errorf("%s is missing from %v", key, byKey)
}
}
never := byKey["never-played"]
if never["sort"] != "random" || never["limit"] != float64(50) || never["rules"].(map[string]any)["never_played"] != true {
t.Errorf("never-played = %v", never)
}
// The list of mine does not have them: they are not stored.
if list := do(t, m.h, "GET", sp, m.alice, nil); list.Body["total"] != float64(0) {
t.Errorf("my smart playlists = %v", list.Body)
}
}
func TestTheSongsOfASuggestedSmartPlaylistAreWorkedOutForTheListener(t *testing.T) {
m := newMixAPI(t)
r := do(t, m.h, "GET", sp+"/suggested/never-played/tracks", m.alice, nil)
if r.Code != http.StatusOK || r.Body["variant"] != float64(0) || len(trackIDs(t, r)) != 50 {
t.Fatalf("never-played: %d, %d songs", r.Code, len(trackIDs(t, r)))
}
first := trackIDs(t, r)
if again := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/never-played/tracks", m.alice, nil)); !slices.Equal(first, again) {
t.Error("the same day gave other songs")
}
if v := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/never-played/tracks?variant=1", m.alice, nil)); slices.Equal(first, v) {
t.Error("another variant gave the same songs")
}
// Nothing was played, so there is no most played, and the library has no 900 kbps file.
if got := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/most-played/tracks", m.alice, nil)); len(got) != 0 {
t.Errorf("most-played with no history = %v", got)
}
if r := do(t, m.h, "GET", sp+"/suggested/nonsense/tracks", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "suggested_not_found" {
t.Errorf("unknown key: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "GET", sp+"/suggested/never-played/tracks?variant=-1", m.alice, nil); r.Code != http.StatusBadRequest {
t.Errorf("negative variant: %d", r.Code)
}
}
func TestASuggestedSmartPlaylistIsKeptAsAPlaylist(t *testing.T) {
m := newMixAPI(t)
shown := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/never-played/tracks?variant=2", m.alice, nil))
r := do(t, m.h, "POST", sp+"/suggested/never-played/playlist", m.alice, map[string]any{"name": "Fresh ears", "variant": 2})
if r.Code != http.StatusCreated || r.Body["name"] != "Fresh ears" || r.Body["track_count"] != float64(len(shown)) {
t.Fatalf("save: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/suggested/never-played/playlist", m.alice, nil); r.Code != http.StatusCreated || r.Body["name"] != "never-played" {
t.Errorf("save with no body: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/suggested/most-played/playlist", m.alice, nil); r.Code != http.StatusUnprocessableEntity || errCode(r) != "smart_playlist_empty" {
t.Errorf("save of an empty one: %d %v", r.Code, r.Body)
}
if r := do(t, m.h, "POST", sp+"/suggested/nonsense/playlist", m.alice, nil); r.Code != http.StatusNotFound || errCode(r) != "suggested_not_found" {
t.Errorf("unknown key: %d %v", r.Code, r.Body)
}
}
func TestPlaysInTheLastDaysAreCountedForTheListenerOnly(t *testing.T) {
m := newMixAPI(t)
var ids []int64
rows, err := m.db.Query("SELECT id FROM tracks WHERE title LIKE 'hard song%' ORDER BY id LIMIT 3")
if err != nil {
t.Fatal(err)
}
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
t.Fatal(err)
}
ids = append(ids, id)
}
rows.Close()
// Song 0: three listens long ago. Song 1: two listens this week. Song 2: one this week.
events := []struct {
track int64
days int
}{{ids[0], 200}, {ids[0], 201}, {ids[0], 202}, {ids[1], 1}, {ids[1], 2}, {ids[2], 3}}
for i, e := range events {
if _, err := m.db.Exec(`INSERT INTO listening_events (user_id, track_id, event_type, occurred_at, duration_played_ms, idempotency_key)
VALUES (1, ?, 'complete', strftime('%s','now') - ?, 60000, ?)`, e.track, e.days*86400, fmt.Sprintf("r%d", i)); err != nil {
t.Fatal(err)
}
}
rot := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/on-rotation/tracks", m.alice, nil))
if len(rot) != 1 || rot[0] != float64(ids[1]) {
t.Errorf("on rotation = %v, want only the song played twice this week (%d)", rot, ids[1])
}
year := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/top-year/tracks", m.alice, nil))
if len(year) != 2 || year[0] != float64(ids[0]) && year[0] != float64(ids[1]) {
t.Errorf("top of the year = %v", year)
}
all := trackIDs(t, do(t, m.h, "GET", sp+"/suggested/most-played/tracks", m.alice, nil))
if len(all) != 3 || all[0] != float64(ids[0]) {
t.Errorf("most played ever = %v, want song %d first (three listens)", all, ids[0])
}
// The rule is in the API for a smart playlist of one's own too.
id := smartMade(t, m, map[string]any{"name": "Lately", "sort": "most_played", "rules": map[string]any{"plays_within_days": 7, "min_plays": 1}})
got := smartTracks(t, m, id, "")
if len(got) != 2 || got[0] != float64(ids[1]) {
t.Errorf("a smart playlist with the window = %v, want %d then %d", got, ids[1], ids[2])
}
if r := do(t, m.h, "POST", sp, m.alice, map[string]any{"name": "x", "rules": map[string]any{"plays_within_days": -1}}); r.Code != http.StatusBadRequest {
t.Errorf("a negative window: %d", r.Code)
}
}