sonda/internal/api/http/taste_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

144 lines
4.8 KiB
Go

package httpapi
import (
"math"
"net/http"
"strconv"
"testing"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/providers"
"git.kmalloc.org/squid/sonda/internal/storage"
"git.kmalloc.org/squid/sonda/internal/taste"
)
func newTasteEnv(t *testing.T) *similarEnv {
t.Helper()
return newSimilarEnvWith(t, func(d *Deps, db *bun.DB, _ *providers.Service) {
d.Taste = taste.NewService(storage.NewTasteRepo(db), taste.Options{MinListen: 20 * time.Second, HalfLife: 90 * 24 * time.Hour})
})
}
func (e *similarEnv) trackOf(t *testing.T, artist string) int64 {
t.Helper()
var id int64
if err := e.db.QueryRow(`SELECT t.id FROM tracks t JOIN track_artists ta ON ta.track_id = t.id
JOIN artists a ON a.id = ta.artist_id WHERE a.name = ?`, artist).Scan(&id); err != nil {
t.Fatalf("track of %q: %v", artist, err)
}
return id
}
func (e *similarEnv) listen(t *testing.T, token string, track int64, typ string, ms int64, key string) {
t.Helper()
body := map[string]any{"track_id": track, "event_type": typ, "duration_played_ms": ms, "idempotency_key": key}
if r := do(t, e.h, "POST", "/api/v1/listens", token, body); r.Code != http.StatusCreated {
t.Fatalf("listen %s: %d %v", key, r.Code, r.Body)
}
}
func TestTasteNeedsASignedInUser(t *testing.T) {
e := newTasteEnv(t)
if r := do(t, e.h, "GET", "/api/v1/me/taste", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("no token: %d", r.Code)
}
}
func TestTasteOfANewListenerIsEmptyLists(t *testing.T) {
e := newTasteEnv(t)
r := do(t, e.h, "GET", "/api/v1/me/taste", e.admin, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
sameKeys(t, "taste", r.Body, "artists", "tags")
artists, ok1 := r.Body["artists"].([]any)
tags, ok2 := r.Body["tags"].([]any)
if !ok1 || !ok2 || len(artists) != 0 || len(tags) != 0 {
t.Errorf("taste = %v, want two empty lists", r.Body)
}
}
func TestTasteFollowsWhatIListenTo(t *testing.T) {
e := newTasteEnv(t)
alpha, beta := e.trackOf(t, "Alpha"), e.trackOf(t, "Beta")
for i := 0; i < 3; i++ {
e.listen(t, e.admin, alpha, "complete", 1000, "a"+strconv.Itoa(i))
}
e.listen(t, e.admin, beta, "skip", 1000, "b1") // too soon: against Beta
if _, err := e.db.Exec("INSERT INTO track_genres (track_id, genre) VALUES (?, 'shoegaze')", alpha); err != nil {
t.Fatal(err)
}
r := do(t, e.h, "GET", "/api/v1/me/taste", e.admin, nil)
if r.Code != http.StatusOK {
t.Fatalf("%d %v", r.Code, r.Body)
}
artists := r.Body["artists"].([]any)
if len(artists) != 1 {
t.Fatalf("artists = %v, want only the one I like", artists)
}
a := artists[0].(map[string]any)
sameKeys(t, "artist", a, "id", "name", "preference", "listens", "last_listened_at")
if a["name"] != "Alpha" || a["id"] != float64(e.alpha) || a["listens"] != float64(3) {
t.Errorf("artist = %v", a)
}
if p, _ := a["preference"].(float64); math.Abs(p-math.Tanh(1)) > 0.001 { // three listens, just now
t.Errorf("preference = %v, want about %v", p, math.Tanh(1))
}
if _, err := time.Parse(time.RFC3339, a["last_listened_at"].(string)); err != nil {
t.Errorf("last_listened_at = %v", a["last_listened_at"])
}
tags := r.Body["tags"].([]any)
if len(tags) != 1 {
t.Fatalf("tags = %v", tags)
}
tg := tags[0].(map[string]any)
sameKeys(t, "tag", tg, "tag", "weight")
if tg["tag"] != "shoegaze" || tg["weight"] != float64(1) {
t.Errorf("tag = %v", tg)
}
}
func TestTasteIsPrivate(t *testing.T) {
e := newTasteEnv(t)
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
body := map[string]any{"email": "bob@example.org", "password": "longenough"}
if r := do(t, e.h, "POST", "/api/v1/users", e.admin, body); r.Code != http.StatusCreated {
t.Fatalf("create bob: %d %v", r.Code, r.Body)
}
login := do(t, e.h, "POST", "/api/v1/auth/login", "", body)
bob, _ := login.Body["access_token"].(string)
r := do(t, e.h, "GET", "/api/v1/me/taste", bob, nil)
if r.Code != http.StatusOK || len(r.Body["artists"].([]any)) != 0 {
t.Errorf("bob sees %d %v, want nothing of alice's listening", r.Code, r.Body)
}
}
func TestTasteLimit(t *testing.T) {
e := newTasteEnv(t)
e.listen(t, e.admin, e.trackOf(t, "Alpha"), "complete", 1000, "a1")
e.listen(t, e.admin, e.trackOf(t, "Beta"), "complete", 1000, "b1")
for _, tt := range []struct {
query string
code int
n int
}{
{"", 200, 2}, {"?limit=1", 200, 1}, {"?limit=0", 200, 2}, {"?limit=1000", 200, 2},
{"?limit=abc", 400, 0}, {"?limit=-1", 400, 0},
} {
r := do(t, e.h, "GET", "/api/v1/me/taste"+tt.query, e.admin, nil)
if r.Code != tt.code {
t.Errorf("%q: %d %v, want %d", tt.query, r.Code, r.Body, tt.code)
continue
}
if tt.code == 200 && len(r.Body["artists"].([]any)) != tt.n {
t.Errorf("%q: %d artists, want %d", tt.query, len(r.Body["artists"].([]any)), tt.n)
}
if tt.code == 400 && errCode(r) != "invalid_input" {
t.Errorf("%q: error %v", tt.query, r.Body)
}
}
}