sonda/internal/storage/repos_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

312 lines
11 KiB
Go

package storage
import (
"context"
"errors"
"testing"
"time"
"github.com/uptrace/bun"
"git.kmalloc.org/squid/sonda/internal/auth"
"git.kmalloc.org/squid/sonda/internal/listening"
)
func TestUserRepo(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewUserRepo(db)
n, err := repo.CountUsers(ctx)
if err != nil || n != 0 {
t.Fatalf("CountUsers = %d, %v", n, err)
}
u, err := repo.CreateUser(ctx, "Alice", "hash1", false)
if err != nil {
t.Fatal(err)
}
if u.ID <= 0 || u.Email != "Alice" || u.CreatedAt.IsZero() {
t.Errorf("user = %+v", u)
}
// Lookup is case-insensitive and returns the stored hash.
got, hash, err := repo.UserByEmail(ctx, "alice")
if err != nil {
t.Fatal(err)
}
if got.ID != u.ID || hash != "hash1" {
t.Errorf("got %+v hash %q", got, hash)
}
// Same name in another case is a duplicate.
if _, err := repo.CreateUser(ctx, "ALICE", "hash2", false); !errors.Is(err, auth.ErrEmailTaken) {
t.Errorf("duplicate: err = %v, want ErrEmailTaken", err)
}
if _, _, err := repo.UserByEmail(ctx, "nobody"); !errors.Is(err, auth.ErrUserNotFound) {
t.Errorf("missing: err = %v, want ErrUserNotFound", err)
}
if n, _ := repo.CountUsers(ctx); n != 1 {
t.Errorf("CountUsers = %d, want 1", n)
}
})
}
func TestListeningRepo(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
users := NewUserRepo(db)
repo := NewListeningRepo(db)
u1, err := users.CreateUser(ctx, "alice", "h", false)
if err != nil {
t.Fatal(err)
}
u2, err := users.CreateUser(ctx, "bob", "h", false)
if err != nil {
t.Fatal(err)
}
var trackID int64
if err := db.QueryRow("INSERT INTO tracks (title) VALUES ('song') RETURNING id").Scan(&trackID); err != nil {
t.Fatal(err)
}
ev := listening.Event{
UserID: u1.ID, TrackID: trackID, Type: listening.Complete,
OccurredAt: time.Unix(1_700_000_000, 0), DurationPlayedMs: 180000, IdempotencyKey: "k1",
}
created, err := repo.Record(ctx, ev)
if err != nil || !created {
t.Fatalf("first Record: created=%v err=%v", created, err)
}
// Retry with the same key is a no-op.
created, err = repo.Record(ctx, ev)
if err != nil || created {
t.Fatalf("retry: created=%v err=%v, want false/nil", created, err)
}
// Same key from another user is a different event.
ev2 := ev
ev2.UserID = u2.ID
if created, err = repo.Record(ctx, ev2); err != nil || !created {
t.Fatalf("other user: created=%v err=%v", created, err)
}
var count int
if err := db.QueryRow("SELECT COUNT(*) FROM listening_events").Scan(&count); err != nil {
t.Fatal(err)
}
if count != 2 {
t.Errorf("rows = %d, want 2", count)
}
var typ string
var dur, at int64
err = db.QueryRow(
"SELECT event_type, duration_played_ms, occurred_at FROM listening_events WHERE user_id = ?", u1.ID).
Scan(&typ, &dur, &at)
if err != nil {
t.Fatal(err)
}
if typ != "complete" || dur != 180000 || at != 1_700_000_000 {
t.Errorf("stored = %q %d %d", typ, dur, at)
}
// Unknown track.
bad := ev
bad.TrackID = trackID + 1000
bad.IdempotencyKey = "k2"
if _, err := repo.Record(ctx, bad); !errors.Is(err, listening.ErrTrackNotFound) {
t.Errorf("unknown track: err = %v, want ErrTrackNotFound", err)
}
})
}
func TestListeningRepoRefusesADeletedUser(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
users := NewUserRepo(db)
u, err := users.CreateUser(ctx, "gone", "h", false)
if err != nil {
t.Fatal(err)
}
var trackID int64
if err := db.QueryRow("INSERT INTO tracks (title) VALUES ('t') RETURNING id").Scan(&trackID); err != nil {
t.Fatal(err)
}
if err := users.DeleteUser(ctx, u.ID); err != nil {
t.Fatal(err)
}
_, err = NewListeningRepo(db).Record(ctx, listening.Event{
UserID: u.ID, TrackID: trackID, Type: listening.Play,
OccurredAt: time.Unix(1_700_000_000, 0), IdempotencyKey: "k",
})
if !errors.Is(err, listening.ErrUserNotFound) {
t.Fatalf("err = %v, want ErrUserNotFound (not a foreign-key failure)", err)
}
})
}
func TestListeningRepoTrackDuration(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
repo := NewListeningRepo(db)
var withLen, withoutLen int64
if err := db.QueryRow("INSERT INTO tracks (title, duration_ms) VALUES ('long', 90000) RETURNING id").Scan(&withLen); err != nil {
t.Fatal(err)
}
if err := db.QueryRow("INSERT INTO tracks (title) VALUES ('unknown length') RETURNING id").Scan(&withoutLen); err != nil {
t.Fatal(err)
}
if got, err := repo.TrackDurationMs(ctx, withLen); err != nil || got != 90000 {
t.Errorf("known length: %d, %v", got, err)
}
if got, err := repo.TrackDurationMs(ctx, withoutLen); err != nil || got != 0 {
t.Errorf("unknown length: %d, %v (want 0, nil)", got, err)
}
if _, err := repo.TrackDurationMs(ctx, 99999); !errors.Is(err, listening.ErrTrackNotFound) {
t.Errorf("unknown track: %v", err)
}
})
}
func TestListeningRepoListEvents(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
users, repo := NewUserRepo(db), NewListeningRepo(db)
alice, _ := users.CreateUser(ctx, "alice", "h", false)
bob, _ := users.CreateUser(ctx, "bob", "h", false)
var a, b int64
if err := db.QueryRow("INSERT INTO tracks (title) VALUES ('Track A') RETURNING id").Scan(&a); err != nil {
t.Fatal(err)
}
if err := db.QueryRow("INSERT INTO tracks (title) VALUES ('Track B') RETURNING id").Scan(&b); err != nil {
t.Fatal(err)
}
record := func(user, track int64, typ listening.EventType, at int64, ms int64, key string) {
t.Helper()
_, err := repo.Record(ctx, listening.Event{
UserID: user, TrackID: track, Type: typ,
OccurredAt: time.Unix(at, 0), DurationPlayedMs: ms, IdempotencyKey: key,
})
if err != nil {
t.Fatal(err)
}
}
record(alice.ID, a, listening.Play, 100, 5_000, "e1")
record(alice.ID, a, listening.Play, 200, 25_000, "e2")
record(alice.ID, b, listening.Complete, 300, 1_000, "e3")
record(alice.ID, b, listening.Skip, 400, 30_000, "e4")
record(bob.ID, a, listening.Play, 250, 40_000, "b1")
titles := func(recs []listening.Record) []string {
var out []string
for _, r := range recs {
out = append(out, r.TrackTitle+"/"+string(r.Type))
}
return out
}
all, total, err := repo.ListEvents(ctx, listening.ListQuery{UserID: alice.ID, Limit: 50})
if err != nil || total != 4 {
t.Fatalf("total = %d err=%v", total, err)
}
if !equal(titles(all), []string{"Track B/skip", "Track B/complete", "Track A/play", "Track A/play"}) {
t.Errorf("order = %v, want newest first", titles(all))
}
if all[0].DurationPlayedMs != 30_000 || !all[0].OccurredAt.Equal(time.Unix(400, 0)) || all[0].TrackID != b || all[0].ID == 0 {
t.Errorf("first record = %+v", all[0])
}
page, total, _ := repo.ListEvents(ctx, listening.ListQuery{UserID: alice.ID, Limit: 2, Offset: 1})
if total != 4 || !equal(titles(page), []string{"Track B/complete", "Track A/play"}) {
t.Errorf("page 2 = %v (total %d)", titles(page), total)
}
past, total, err := repo.ListEvents(ctx, listening.ListQuery{UserID: alice.ID, Limit: 2, Offset: 50})
if err != nil || total != 4 || len(past) != 0 {
t.Errorf("past the end: %v, total %d, err %v", titles(past), total, err)
}
// OnlyCounted keeps `complete` and plays of at least the minimum.
counted, total, _ := repo.ListEvents(ctx, listening.ListQuery{UserID: alice.ID, Limit: 50, OnlyCounted: true, MinPlayedMs: 20_000})
if total != 3 || !equal(titles(counted), []string{"Track B/skip", "Track B/complete", "Track A/play"}) {
t.Errorf("counted = %v (total %d), want the 5 s play left out", titles(counted), total)
}
strict, total, _ := repo.ListEvents(ctx, listening.ListQuery{UserID: alice.ID, Limit: 50, OnlyCounted: true, MinPlayedMs: 60_000})
if total != 1 || !equal(titles(strict), []string{"Track B/complete"}) {
t.Errorf("with a 60 s minimum = %v, want only the complete", titles(strict))
}
// Nobody sees anybody else's history.
mine, total, _ := repo.ListEvents(ctx, listening.ListQuery{UserID: bob.ID, Limit: 50})
if total != 1 || !equal(titles(mine), []string{"Track A/play"}) {
t.Errorf("bob's history = %v (total %d)", titles(mine), total)
}
})
}
func TestListeningRepoUserExists(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
users, repo := NewUserRepo(db), NewListeningRepo(db)
u, _ := users.CreateUser(ctx, "here", "h", false)
if ok, err := repo.UserExists(ctx, u.ID); err != nil || !ok {
t.Errorf("existing user: %v, %v", ok, err)
}
if ok, err := repo.UserExists(ctx, 99999); err != nil || ok {
t.Errorf("unknown user: %v, %v", ok, err)
}
_ = users.DeleteUser(ctx, u.ID)
if ok, _ := repo.UserExists(ctx, u.ID); ok {
t.Error("a deleted user still exists")
}
})
}
// The SQL filter must agree with the Go rule exactly at the threshold, and
// events of the same second must come out in a fixed order.
func TestListeningRepoThresholdBoundaryAndTies(t *testing.T) {
forEachBackend(t, func(t *testing.T, db *bun.DB, _ string) {
ctx := context.Background()
u, _ := NewUserRepo(db).CreateUser(ctx, "alice", "h", false)
repo := NewListeningRepo(db)
var track int64
if err := db.QueryRow("INSERT INTO tracks (title) VALUES ('T') RETURNING id").Scan(&track); err != nil {
t.Fatal(err)
}
add := func(typ listening.EventType, ms int64, key string) {
t.Helper()
if _, err := repo.Record(ctx, listening.Event{
UserID: u.ID, TrackID: track, Type: typ,
OccurredAt: time.Unix(1_700_000_000, 0), // the same second for all
DurationPlayedMs: ms, IdempotencyKey: key,
}); err != nil {
t.Fatal(err)
}
}
add(listening.Play, 19_999, "under")
add(listening.Play, 20_000, "exactly")
add(listening.Play, 20_001, "over")
counted, total, err := repo.ListEvents(ctx, listening.ListQuery{UserID: u.ID, Limit: 50, OnlyCounted: true, MinPlayedMs: 20_000})
if err != nil || total != 2 {
t.Fatalf("counted total = %d err=%v, want the event at exactly 20 s included and 19.999 s left out", total, err)
}
if counted[0].DurationPlayedMs != 20_001 || counted[1].DurationPlayedMs != 20_000 {
t.Errorf("same-second events came out as %d, %d; want the later insert first (id DESC)",
counted[0].DurationPlayedMs, counted[1].DurationPlayedMs)
}
all, _, _ := repo.ListEvents(ctx, listening.ListQuery{UserID: u.ID, Limit: 50})
if len(all) != 3 || all[0].DurationPlayedMs != 20_001 || all[2].DurationPlayedMs != 19_999 {
t.Errorf("order of all three = %+v", all)
}
})
}