test(backup, scrobble, playevents, recsettings, apierror, auth, providers): merge repeated cases (#8299)
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m4s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 3m5s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 4m35s
release / Build signed APK (push) Canceled after 3m53s
release / web (push) Successful in 1m41s
release / go (push) Successful in 2m4s
release / govulncheck (push) Successful in 23s
release / integration (push) Successful in 3m5s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Publish the release image to GHCR (dispatch only) (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / android (push) Canceled after 4m35s
release / Build signed APK (push) Canceled after 3m53s
- backup: schema coverage's three tests and the three AWS signing examples, one table each. - scrobble: Qualifies' six boundary tests; the ListenBrainz client's refusal mapping, twelve tests of the same rule across three calls, one table over call x status; the two similarity lookups' success and URL tests, one table. - playevents: the skip rule's three plays share one fixture. Dropped TestRecordPlayEnded_SubThreshold_NoEnqueue: the writer only calls scrobble.MaybeEnqueue, whose own test and Qualifies' table hold that case; the qualifying-play test still proves the writer calls it. - recsettings: the three tag-scale tests share one database reset. - apierror: Error() and From, one test each; auth: RequireAdmin's three. - providers: GetJSON's not-found and transient answers, one table. Its two 401 tests expected the same answer with and without TreatAuthAsTransient, which changes only the error's text; the table says so. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -9,17 +9,17 @@ import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestError_ErrorString_NoCause(t *testing.T) {
|
||||
e := &Error{Message: "x"}
|
||||
if got := e.Error(); got != "x" {
|
||||
t.Fatalf("Error() = %q, want %q", got, "x")
|
||||
}
|
||||
}
|
||||
|
||||
func TestError_ErrorString_WithCause(t *testing.T) {
|
||||
e := &Error{Message: "x", Cause: errors.New("y")}
|
||||
if got := e.Error(); got != "x: y" {
|
||||
t.Fatalf("Error() = %q, want %q", got, "x: y")
|
||||
func TestError_ErrorString(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
e *Error
|
||||
want string
|
||||
}{
|
||||
{&Error{Message: "x"}, "x"},
|
||||
{&Error{Message: "x", Cause: errors.New("y")}, "x: y"},
|
||||
} {
|
||||
if got := tc.e.Error(); got != tc.want {
|
||||
t.Errorf("Error() = %q, want %q", got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,46 +36,23 @@ func TestError_Unwrap(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrom_NilReturnsNil(t *testing.T) {
|
||||
// From turns any error into the answer a handler writes: nil stays nil, an
|
||||
// *Error (wrapped or not) is kept as it is, and anything else is a 500 that
|
||||
// keeps the error as its cause for the log.
|
||||
func TestFrom(t *testing.T) {
|
||||
if got := From(nil); got != nil {
|
||||
t.Fatalf("From(nil) = %v, want nil", got)
|
||||
t.Errorf("From(nil) = %v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrom_PreservesAPIError(t *testing.T) {
|
||||
orig := NotFound("track")
|
||||
got := From(orig)
|
||||
if got != orig {
|
||||
t.Fatalf("From(orig) returned different pointer: got %p, want %p", got, orig)
|
||||
if got := From(orig); got != orig {
|
||||
t.Errorf("From(*Error) = %p, want the same %p", got, orig)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrom_PreservesWrappedAPIError(t *testing.T) {
|
||||
inner := NotFound("track")
|
||||
wrapped := fmt.Errorf("ctx: %w", inner)
|
||||
got := From(wrapped)
|
||||
if got == nil {
|
||||
t.Fatal("From(wrapped) = nil, want *Error")
|
||||
if got := From(fmt.Errorf("ctx: %w", orig)); got != orig {
|
||||
t.Errorf("From(wrapped *Error) = %v, want the *Error it wraps", got)
|
||||
}
|
||||
if got.Code != "track_not_found" {
|
||||
t.Fatalf("got.Code = %q, want %q", got.Code, "track_not_found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFrom_WrapsPlainError(t *testing.T) {
|
||||
plain := errors.New("boom")
|
||||
got := From(plain)
|
||||
if got == nil {
|
||||
t.Fatal("From(plain) = nil, want *Error")
|
||||
}
|
||||
if got.Status != 500 {
|
||||
t.Errorf("Status = %d, want 500", got.Status)
|
||||
}
|
||||
if got.Code != "server_error" {
|
||||
t.Errorf("Code = %q, want %q", got.Code, "server_error")
|
||||
}
|
||||
if got.Cause != plain {
|
||||
t.Errorf("Cause = %v, want %v", got.Cause, plain)
|
||||
if got := From(plain); got == nil || got.Status != 500 || got.Code != "server_error" || got.Cause != plain {
|
||||
t.Errorf("From(plain) = %+v, want a 500 server_error caused by it", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+36
-67
@@ -32,72 +32,41 @@ func assertErrorCode(t *testing.T, w *httptest.ResponseRecorder, code string) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAdmin_AdminPasses(t *testing.T) {
|
||||
called := false
|
||||
stub := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
called = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
h := RequireAdmin()(stub)
|
||||
|
||||
req := injectUser(
|
||||
httptest.NewRequest(http.MethodGet, "/api/admin/test", nil),
|
||||
dbq.User{IsAdmin: true},
|
||||
)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200", w.Code)
|
||||
}
|
||||
if !called {
|
||||
t.Error("stub handler was not called for admin user")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAdmin_NonAdminReturns403(t *testing.T) {
|
||||
stub := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||||
t.Fatal("stub handler must not be called for non-admin user")
|
||||
})
|
||||
|
||||
h := RequireAdmin()(stub)
|
||||
|
||||
req := injectUser(
|
||||
httptest.NewRequest(http.MethodGet, "/api/admin/test", nil),
|
||||
dbq.User{IsAdmin: false},
|
||||
)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403", w.Code)
|
||||
}
|
||||
assertErrorCode(t, w, "not_authorized")
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if !strings.HasPrefix(ct, "application/json") {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequireAdmin_NoUserContextReturns500(t *testing.T) {
|
||||
stub := http.HandlerFunc(func(_ http.ResponseWriter, _ *http.Request) {
|
||||
t.Fatal("stub handler must not be called when no user is in context")
|
||||
})
|
||||
|
||||
h := RequireAdmin()(stub)
|
||||
|
||||
// Do NOT inject a user — simulate RequireUser being bypassed.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusInternalServerError {
|
||||
t.Errorf("status = %d, want 500", w.Code)
|
||||
}
|
||||
assertErrorCode(t, w, "server_error")
|
||||
ct := w.Header().Get("Content-Type")
|
||||
if !strings.HasPrefix(ct, "application/json") {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
// RequireAdmin passes an admin through, answers anyone else 403, and answers
|
||||
// 500 when no user is in the context at all (RequireUser was not mounted in
|
||||
// front of it), always as the /api error envelope.
|
||||
func TestRequireAdmin(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
user *dbq.User
|
||||
wantCode int
|
||||
wantErr string // "" when the handler is reached
|
||||
}{
|
||||
{"an admin", &dbq.User{IsAdmin: true}, http.StatusOK, ""},
|
||||
{"a listener", &dbq.User{}, http.StatusForbidden, "not_authorized"},
|
||||
{"no user in the context", nil, http.StatusInternalServerError, "server_error"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
reached := false
|
||||
h := RequireAdmin()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
reached = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/test", nil)
|
||||
if tc.user != nil {
|
||||
req = injectUser(req, *tc.user)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != tc.wantCode || reached != (tc.wantErr == "") {
|
||||
t.Fatalf("status %d, handler reached %v; want %d, %v", w.Code, reached, tc.wantCode, tc.wantErr == "")
|
||||
}
|
||||
if tc.wantErr != "" {
|
||||
assertErrorCode(t, w, tc.wantErr)
|
||||
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||
t.Errorf("Content-Type = %q, want application/json", ct)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+30
-30
@@ -22,37 +22,37 @@ const (
|
||||
|
||||
var awsTime = time.Date(2013, 5, 24, 0, 0, 0, 0, time.UTC)
|
||||
|
||||
func TestSignMatchesAWSsGetObjectExample(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, "http://examplebucket.s3.amazonaws.com/test.txt", nil)
|
||||
req.Header.Set("Range", "bytes=0-9")
|
||||
sign(req, emptySHA256, awsAccessKey, awsSecretKey, "us-east-1", awsTime)
|
||||
want := awsCred + ", SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
|
||||
if got := req.Header.Get("Authorization"); got != want {
|
||||
t.Errorf("Authorization =\n%s\nwant\n%s", got, want)
|
||||
func TestSignMatchesAWSsExamples(t *testing.T) {
|
||||
put := "Welcome to Amazon S3."
|
||||
if got := hexSHA256([]byte(put)); got != "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072" {
|
||||
t.Fatalf("payload hash = %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignMatchesAWSsPutObjectExample(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodPut, "http://examplebucket.s3.amazonaws.com/test$file.text", strings.NewReader("Welcome to Amazon S3."))
|
||||
req.Header.Set("Date", "Fri, 24 May 2013 00:00:00 GMT")
|
||||
req.Header.Set("X-Amz-Storage-Class", "REDUCED_REDUNDANCY")
|
||||
payload := hexSHA256([]byte("Welcome to Amazon S3."))
|
||||
if payload != "44ce7dd67c959e0d3524ffac1771dfbba87d2b6b4b4e99e42034a8b803f8b072" {
|
||||
t.Fatalf("payload hash = %s", payload)
|
||||
}
|
||||
sign(req, payload, awsAccessKey, awsSecretKey, "us-east-1", awsTime)
|
||||
want := awsCred + ", SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class, Signature=98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"
|
||||
if got := req.Header.Get("Authorization"); got != want {
|
||||
t.Errorf("Authorization =\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignMatchesAWSsListObjectsExample(t *testing.T) {
|
||||
req, _ := http.NewRequest(http.MethodGet, "http://examplebucket.s3.amazonaws.com/?max-keys=2&prefix=J", nil)
|
||||
sign(req, emptySHA256, awsAccessKey, awsSecretKey, "us-east-1", awsTime)
|
||||
want := awsCred + ", SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"
|
||||
if got := req.Header.Get("Authorization"); got != want {
|
||||
t.Errorf("Authorization =\n%s\nwant\n%s", got, want)
|
||||
for _, tc := range []struct {
|
||||
name, method, url, body string
|
||||
headers map[string]string
|
||||
want string // after the credential
|
||||
}{
|
||||
{"GET object", http.MethodGet, "http://examplebucket.s3.amazonaws.com/test.txt", "",
|
||||
map[string]string{"Range": "bytes=0-9"},
|
||||
"SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"},
|
||||
{"PUT object", http.MethodPut, "http://examplebucket.s3.amazonaws.com/test$file.text", put,
|
||||
map[string]string{"Date": "Fri, 24 May 2013 00:00:00 GMT", "X-Amz-Storage-Class": "REDUCED_REDUNDANCY"},
|
||||
"SignedHeaders=date;host;x-amz-content-sha256;x-amz-date;x-amz-storage-class, Signature=98ad721746da40c64f1a55b78f14c238d841ea1380cd77a1b5971af0ece108bd"},
|
||||
{"list objects", http.MethodGet, "http://examplebucket.s3.amazonaws.com/?max-keys=2&prefix=J", "", nil,
|
||||
"SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=34b48302e7b5fa45bde8084f4b7868a86f0a534bc59db6670ed5711ef69dc6f7"},
|
||||
} {
|
||||
req, _ := http.NewRequest(tc.method, tc.url, strings.NewReader(tc.body))
|
||||
for k, v := range tc.headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
payload := emptySHA256
|
||||
if tc.body != "" {
|
||||
payload = hexSHA256([]byte(tc.body))
|
||||
}
|
||||
sign(req, payload, awsAccessKey, awsSecretKey, "us-east-1", awsTime)
|
||||
if got, want := req.Header.Get("Authorization"), awsCred+", "+tc.want; got != want {
|
||||
t.Errorf("%s: Authorization =\n%s\nwant\n%s", tc.name, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,24 +17,31 @@ func everyListedTable() []string {
|
||||
return names
|
||||
}
|
||||
|
||||
func TestCoverageAcceptsASchemaThatMatchesTheLists(t *testing.T) {
|
||||
if problems := Coverage(everyListedTable()); len(problems) != 0 {
|
||||
t.Fatalf("problems = %v, want none", problems)
|
||||
// Coverage holds the schema against the two lists: every table is backed up
|
||||
// or excluded with a reason, and every listed table exists. A migration that
|
||||
// adds or drops a table without updating the lists fails here.
|
||||
func TestCoverage(t *testing.T) {
|
||||
without := func(drop ...string) []string {
|
||||
return slices.DeleteFunc(everyListedTable(), func(n string) bool { return slices.Contains(drop, n) })
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageNamesATableInNeitherList(t *testing.T) {
|
||||
problems := Coverage(append(everyListedTable(), "new_table"))
|
||||
if len(problems) != 1 || !strings.HasPrefix(problems[0], "new_table: neither") {
|
||||
t.Fatalf("problems = %v, want one naming new_table", problems)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCoverageNamesAListedTableTheSchemaLacks(t *testing.T) {
|
||||
schema := slices.DeleteFunc(everyListedTable(), func(n string) bool { return n == "playlists" || n == "scan_runs" })
|
||||
problems := Coverage(schema)
|
||||
if len(problems) != 2 {
|
||||
t.Fatalf("problems = %v, want playlists and scan_runs named", problems)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
schema []string
|
||||
want []string // a prefix of each problem, in order
|
||||
}{
|
||||
{"the schema matches the lists", everyListedTable(), nil},
|
||||
{"a table in neither list", append(everyListedTable(), "new_table"), []string{"new_table: neither"}},
|
||||
{"listed tables the schema lacks", without("playlists", "scan_runs"), []string{"playlists", "scan_runs"}},
|
||||
} {
|
||||
problems := Coverage(tc.schema)
|
||||
slices.Sort(problems)
|
||||
ok := len(problems) == len(tc.want)
|
||||
for i := 0; ok && i < len(problems); i++ {
|
||||
ok = strings.HasPrefix(problems[i], tc.want[i])
|
||||
}
|
||||
if !ok {
|
||||
t.Errorf("%s: problems = %q, want ones starting %q", tc.name, problems, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -138,61 +138,41 @@ func TestRecordPlayStarted_AutoCloseCapsAtTrackDuration(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordPlayEnded_AppliesSkipRule_BothFail_NotSkip(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
t1 := time.Now().UTC()
|
||||
res, _ := f.w.RecordPlayStarted(context.Background(), f.user, f.track, "c", t1)
|
||||
// 15% completion (30_000ms), 30s duration -> 30s satisfies "duration >= 30s"
|
||||
// so the rule's AND fails -> NOT a skip.
|
||||
t2 := t1.Add(30 * time.Second)
|
||||
if err := f.w.RecordPlayEnded(context.Background(), res.PlayEventID, 30_000, t2); err != nil {
|
||||
t.Fatalf("RecordPlayEnded: %v", err)
|
||||
// A play that ends is a skip only when it played under half the track AND
|
||||
// under 30 seconds (the writer's thresholds here, 0.5 and 30000 ms), and
|
||||
// only a skip writes a skip_events row. Either condition alone is a play.
|
||||
func TestRecordPlayEnded_AppliesTheSkipRule(t *testing.T) {
|
||||
f := newFixture(t, 200_000) // a 200 s track
|
||||
ctx := context.Background()
|
||||
t0 := time.Now().UTC().Add(-time.Hour)
|
||||
for i, tc := range []struct {
|
||||
name string
|
||||
playedMs int32
|
||||
want bool
|
||||
}{
|
||||
{"10 s, 5%: both under", 10_000, true},
|
||||
{"30 s, 15%: the duration reaches 30 s", 30_000, false},
|
||||
{"100 s, 50%: the completion reaches half", 100_000, false},
|
||||
} {
|
||||
start := t0.Add(time.Duration(i) * 10 * time.Minute)
|
||||
res, err := f.w.RecordPlayStarted(ctx, f.user, f.track, "c", start)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: start: %v", tc.name, err)
|
||||
}
|
||||
if err := f.w.RecordPlayEnded(ctx, res.PlayEventID, tc.playedMs, start.Add(time.Duration(tc.playedMs)*time.Millisecond)); err != nil {
|
||||
t.Fatalf("%s: end: %v", tc.name, err)
|
||||
}
|
||||
got, _ := f.q.GetPlayEventByID(ctx, res.PlayEventID)
|
||||
if got.WasSkipped != tc.want {
|
||||
t.Errorf("%s: was_skipped = %v, want %v", tc.name, got.WasSkipped, tc.want)
|
||||
}
|
||||
}
|
||||
got, _ := f.q.GetPlayEventByID(context.Background(), res.PlayEventID)
|
||||
if got.WasSkipped {
|
||||
t.Errorf("was_skipped = true, want false (duration_played_ms == 30000 fails the AND)")
|
||||
var skips int
|
||||
if err := f.pool.QueryRow(ctx, `SELECT count(*) FROM skip_events WHERE user_id = $1`, f.user).Scan(&skips); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordPlayEnded_AppliesSkipRule_BothPass_IsSkip(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
t1 := time.Now().UTC()
|
||||
res, _ := f.w.RecordPlayStarted(context.Background(), f.user, f.track, "c", t1)
|
||||
// 5% completion (10_000ms), 10s duration -> both conditions hold -> SKIP.
|
||||
t2 := t1.Add(10 * time.Second)
|
||||
if err := f.w.RecordPlayEnded(context.Background(), res.PlayEventID, 10_000, t2); err != nil {
|
||||
t.Fatalf("RecordPlayEnded: %v", err)
|
||||
}
|
||||
got, _ := f.q.GetPlayEventByID(context.Background(), res.PlayEventID)
|
||||
if !got.WasSkipped {
|
||||
t.Errorf("expected was_skipped=true")
|
||||
}
|
||||
rows, err := f.pool.Query(context.Background(),
|
||||
"SELECT id FROM skip_events WHERE user_id=$1 AND track_id=$2", f.user, f.track)
|
||||
if err != nil {
|
||||
t.Fatalf("query skips: %v", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
count++
|
||||
}
|
||||
if count != 1 {
|
||||
t.Errorf("skip_events count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordPlayEnded_DurationOver50Percent_NotSkip(t *testing.T) {
|
||||
f := newFixture(t, 200_000) // 200s track
|
||||
t1 := time.Now().UTC()
|
||||
res, _ := f.w.RecordPlayStarted(context.Background(), f.user, f.track, "c", t1)
|
||||
// 50% completion (100_000ms), 5s duration. Completion fails the "< 0.5"
|
||||
// check — so AND fails, NOT a skip.
|
||||
t2 := t1.Add(5 * time.Second)
|
||||
_ = f.w.RecordPlayEnded(context.Background(), res.PlayEventID, 100_000, t2)
|
||||
got, _ := f.q.GetPlayEventByID(context.Background(), res.PlayEventID)
|
||||
if got.WasSkipped {
|
||||
t.Errorf("expected was_skipped=false at completion >= 0.5")
|
||||
if skips != 1 {
|
||||
t.Errorf("skip_events rows = %d, want 1, for the one skip", skips)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -392,31 +372,6 @@ func TestRecordPlayEnded_QualifyingPlay_EnqueuesScrobble(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordPlayEnded_SubThreshold_NoEnqueue(t *testing.T) {
|
||||
f := newFixture(t, 300_000)
|
||||
ctx := context.Background()
|
||||
|
||||
tk := "tk"
|
||||
_ = f.q.SetListenBrainzToken(ctx, dbq.SetListenBrainzTokenParams{ID: f.user, ListenbrainzToken: &tk})
|
||||
_ = f.q.SetListenBrainzEnabled(ctx, dbq.SetListenBrainzEnabledParams{ID: f.user, ListenbrainzEnabled: true})
|
||||
|
||||
res, err := f.w.RecordPlayStarted(ctx, f.user, f.track, "test", time.Now().Add(-1*time.Minute))
|
||||
if err != nil {
|
||||
t.Fatalf("start: %v", err)
|
||||
}
|
||||
// 60s played, 20% — well below threshold.
|
||||
if err := f.w.RecordPlayEnded(ctx, res.PlayEventID, 60_000, time.Now()); err != nil {
|
||||
t.Fatalf("end: %v", err)
|
||||
}
|
||||
|
||||
var n int
|
||||
_ = f.pool.QueryRow(ctx,
|
||||
`SELECT count(*) FROM scrobble_queue WHERE play_event_id = $1`, res.PlayEventID).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Errorf("expected 0 queue rows for sub-threshold play, got %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordPlayStartedWithSource_AppendsRotation(t *testing.T) {
|
||||
f := newFixture(t, 200_000)
|
||||
now := time.Now().UTC()
|
||||
|
||||
@@ -28,17 +28,33 @@ func TestHTTPClient_GetJSON_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_404IsNotFound(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrNotFound) {
|
||||
t.Errorf("err = %v, want ErrNotFound", err)
|
||||
// A 404 settles the lookup as not found; any other failure, including a
|
||||
// refused key and a body that isn't JSON, is transient and asked again later.
|
||||
// A 401 is transient with or without TreatAuthAsTransient.
|
||||
func TestHTTPClient_GetJSON_AnswersNotFoundOrTransient(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
authAsRetry bool
|
||||
want error
|
||||
}{
|
||||
{"404", http.StatusNotFound, "", false, ErrNotFound},
|
||||
{"401", http.StatusUnauthorized, "", false, ErrTransient},
|
||||
{"401 with TreatAuthAsTransient", http.StatusUnauthorized, "", true, ErrTransient},
|
||||
{"a body that isn't JSON", http.StatusOK, "not json", false, ErrTransient},
|
||||
} {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(tc.status)
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
}))
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test", TreatAuthAsTransient: tc.authAsRetry})
|
||||
var out struct{ Name string }
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
srv.Close()
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Errorf("%s: err = %v, want %v", tc.name, err, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,52 +106,6 @@ func TestHTTPClient_GetJSON_RetryOn5xxThenExhausted(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_AuthAsTransient(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{
|
||||
Name: "test",
|
||||
TreatAuthAsTransient: true,
|
||||
})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_AuthPassthroughByDefault(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var out any
|
||||
err := c.GetJSON(context.Background(), srv.URL, &out)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
// 401 is non-2xx so it falls into the generic transient bucket.
|
||||
t.Errorf("err = %v, want ErrTransient (generic non-2xx)", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_MalformedBody(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`not json`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := NewHTTPClient(HTTPOptions{Name: "test"})
|
||||
var got struct{ Name string }
|
||||
err := c.GetJSON(context.Background(), srv.URL, &got)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTTPClient_GetJSON_ContextCancel(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
|
||||
@@ -158,64 +158,28 @@ func TestUpdateTaste_CurveOrderingEnforced(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateTaste_EnrichedTagScale(t *testing.T) {
|
||||
pool := dbtest.Pool(t)
|
||||
s := newService(t, pool)
|
||||
// In-range update persists into cache + the assembled taste config.
|
||||
if err := s.UpdateTaste(context.Background(),
|
||||
map[string]float64{"enriched_tag_scale": 0.8}); err != nil {
|
||||
t.Fatalf("UpdateTaste: %v", err)
|
||||
}
|
||||
if got := s.Taste().EnrichedTagScale; got != 0.8 {
|
||||
t.Errorf("Taste().EnrichedTagScale = %v, want 0.8", got)
|
||||
}
|
||||
if got := s.TasteConfig().EnrichedTagScale; got != 0.8 {
|
||||
t.Errorf("TasteConfig().EnrichedTagScale = %v, want 0.8", got)
|
||||
}
|
||||
// Out of [0,1] rejects.
|
||||
if err := s.UpdateTaste(context.Background(),
|
||||
map[string]float64{"enriched_tag_scale": 1.5}); !errors.Is(err, ErrOutOfRange) {
|
||||
t.Errorf("err = %v, want ErrOutOfRange for 1.5", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateTaste_EraScale(t *testing.T) {
|
||||
pool := dbtest.Pool(t)
|
||||
s := newService(t, pool)
|
||||
// In-range update persists into cache + the assembled taste config.
|
||||
if err := s.UpdateTaste(context.Background(),
|
||||
map[string]float64{"era_scale": 0.8}); err != nil {
|
||||
t.Fatalf("UpdateTaste: %v", err)
|
||||
}
|
||||
if got := s.Taste().EraScale; got != 0.8 {
|
||||
t.Errorf("Taste().EraScale = %v, want 0.8", got)
|
||||
}
|
||||
if got := s.TasteConfig().EraScale; got != 0.8 {
|
||||
t.Errorf("TasteConfig().EraScale = %v, want 0.8", got)
|
||||
}
|
||||
// Out of [0,1] rejects.
|
||||
if err := s.UpdateTaste(context.Background(),
|
||||
map[string]float64{"era_scale": 1.5}); !errors.Is(err, ErrOutOfRange) {
|
||||
t.Errorf("err = %v, want ErrOutOfRange for 1.5", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateTaste_MoodScale(t *testing.T) {
|
||||
pool := dbtest.Pool(t)
|
||||
s := newService(t, pool)
|
||||
if err := s.UpdateTaste(context.Background(),
|
||||
map[string]float64{"mood_scale": 0.8}); err != nil {
|
||||
t.Fatalf("UpdateTaste: %v", err)
|
||||
}
|
||||
if got := s.Taste().MoodScale; got != 0.8 {
|
||||
t.Errorf("Taste().MoodScale = %v, want 0.8", got)
|
||||
}
|
||||
if got := s.TasteConfig().MoodScale; got != 0.8 {
|
||||
t.Errorf("TasteConfig().MoodScale = %v, want 0.8", got)
|
||||
}
|
||||
if err := s.UpdateTaste(context.Background(),
|
||||
map[string]float64{"mood_scale": 1.5}); !errors.Is(err, ErrOutOfRange) {
|
||||
t.Errorf("err = %v, want ErrOutOfRange for 1.5", err)
|
||||
// The three tag scales take a value in [0, 1]: an in-range one reaches both
|
||||
// the stored settings and the taste config the profile builder reads, and
|
||||
// one outside it is refused.
|
||||
func TestUpdateTaste_TagScales(t *testing.T) {
|
||||
s := newService(t, dbtest.Pool(t))
|
||||
for _, tc := range []struct {
|
||||
key string
|
||||
stored, built func() float64
|
||||
}{
|
||||
{"enriched_tag_scale", func() float64 { return s.Taste().EnrichedTagScale }, func() float64 { return s.TasteConfig().EnrichedTagScale }},
|
||||
{"era_scale", func() float64 { return s.Taste().EraScale }, func() float64 { return s.TasteConfig().EraScale }},
|
||||
{"mood_scale", func() float64 { return s.Taste().MoodScale }, func() float64 { return s.TasteConfig().MoodScale }},
|
||||
} {
|
||||
if err := s.UpdateTaste(context.Background(), map[string]float64{tc.key: 0.8}); err != nil {
|
||||
t.Fatalf("%s = 0.8: %v", tc.key, err)
|
||||
}
|
||||
if tc.stored() != 0.8 || tc.built() != 0.8 {
|
||||
t.Errorf("%s: stored %v, taste config %v; want 0.8 in both", tc.key, tc.stored(), tc.built())
|
||||
}
|
||||
if err := s.UpdateTaste(context.Background(), map[string]float64{tc.key: 1.5}); !errors.Is(err, ErrOutOfRange) {
|
||||
t.Errorf("%s = 1.5: err = %v, want ErrOutOfRange", tc.key, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,55 +54,6 @@ func TestClient_SubmitListens_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SubmitListens_401_ReturnsErrAuth(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
})
|
||||
defer srv.Close()
|
||||
err := c.SubmitListens(context.Background(), "bad", []Listen{{}})
|
||||
if !errors.Is(err, ErrAuth) {
|
||||
t.Errorf("err = %v, want ErrAuth", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SubmitListens_400_ReturnsErrPermanent(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
})
|
||||
defer srv.Close()
|
||||
err := c.SubmitListens(context.Background(), "tk", []Listen{{}})
|
||||
if !errors.Is(err, ErrPermanent) {
|
||||
t.Errorf("err = %v, want ErrPermanent", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SubmitListens_503_ReturnsErrTransient(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
})
|
||||
defer srv.Close()
|
||||
err := c.SubmitListens(context.Background(), "tk", []Listen{{}})
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SubmitListens_429_ReturnsRetryAfter(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
})
|
||||
defer srv.Close()
|
||||
err := c.SubmitListens(context.Background(), "tk", []Listen{{}})
|
||||
var ra *RetryAfterError
|
||||
if !errors.As(err, &ra) {
|
||||
t.Fatalf("err = %v, want *RetryAfterError", err)
|
||||
}
|
||||
if ra.Wait != 60*time.Second {
|
||||
t.Errorf("Wait = %v, want 60s", ra.Wait)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SubmitListens_NetworkFailure_ReturnsErrTransient(t *testing.T) {
|
||||
c := &Client{BaseURL: "http://127.0.0.1:1", HTTP: &http.Client{Timeout: 100 * time.Millisecond}}
|
||||
err := c.SubmitListens(context.Background(), "tk", []Listen{{}})
|
||||
@@ -163,200 +114,102 @@ func TestClient_SubmitListens_OmitsEmptyMBIDs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_Success(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`[
|
||||
{"recording_mbid": "11111111-1111-1111-1111-111111111111", "score": 0.95},
|
||||
{"recording_mbid": "22222222-2222-2222-2222-222222222222", "score": 0.80}
|
||||
]`))
|
||||
})
|
||||
defer srv.Close()
|
||||
out, err := c.SimilarRecordings(context.Background(), "aaaa", 100)
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
// Each call answers ListenBrainz's refusals the same way, and the scrobble
|
||||
// worker acts on that answer: a bad token disables the user's scrobbling, a
|
||||
// bad request drops the listen, a server error retries with backoff, and a
|
||||
// rate limit waits as long as Retry-After says without counting an attempt.
|
||||
func TestClient_RefusalsMapToWhatTheWorkerDoes(t *testing.T) {
|
||||
calls := map[string]func(*Client) error{
|
||||
"submit": func(c *Client) error { return c.SubmitListens(context.Background(), "tk", []Listen{{}}) },
|
||||
"similar recordings": func(c *Client) error {
|
||||
_, err := c.SimilarRecordings(context.Background(), "abc", 100)
|
||||
return err
|
||||
},
|
||||
"similar artists": func(c *Client) error {
|
||||
_, err := c.SimilarArtists(context.Background(), "abc", 100)
|
||||
return err
|
||||
},
|
||||
}
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("got %d results, want 2", len(out))
|
||||
}
|
||||
if out[0].MBID != "11111111-1111-1111-1111-111111111111" || out[0].Score != 0.95 {
|
||||
t.Errorf("first result wrong: %+v", out[0])
|
||||
for name, call := range calls {
|
||||
for _, tc := range []struct {
|
||||
status int
|
||||
want error
|
||||
}{
|
||||
{http.StatusUnauthorized, ErrAuth},
|
||||
{http.StatusBadRequest, ErrPermanent},
|
||||
{http.StatusServiceUnavailable, ErrTransient},
|
||||
{http.StatusTooManyRequests, nil}, // a *RetryAfterError
|
||||
} {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
w.WriteHeader(tc.status)
|
||||
})
|
||||
err := call(c)
|
||||
srv.Close()
|
||||
if tc.want != nil {
|
||||
if !errors.Is(err, tc.want) {
|
||||
t.Errorf("%s, HTTP %d: err = %v, want %v", name, tc.status, err, tc.want)
|
||||
}
|
||||
continue
|
||||
}
|
||||
var ra *RetryAfterError
|
||||
if !errors.As(err, &ra) || ra.Wait != 60*time.Second {
|
||||
t.Errorf("%s, HTTP %d: err = %v, want a 60s RetryAfterError", name, tc.status, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_AlgorithmParamSet(t *testing.T) {
|
||||
var seenURL string
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, r *http.Request) {
|
||||
seenURL = r.URL.String()
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
})
|
||||
defer srv.Close()
|
||||
_, _ = c.SimilarRecordings(context.Background(), "abc", 50)
|
||||
if !strings.Contains(seenURL, "algorithm=") {
|
||||
t.Errorf("URL missing algorithm param: %q", seenURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_MbidParamSet(t *testing.T) {
|
||||
var seenURL string
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, r *http.Request) {
|
||||
seenURL = r.URL.String()
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
})
|
||||
defer srv.Close()
|
||||
_, _ = c.SimilarRecordings(context.Background(), "abc", 50)
|
||||
// Labs API takes the MBID as a query param, not a path segment; the
|
||||
// result count is fixed by the algorithm (no count/limit param).
|
||||
if !strings.Contains(seenURL, "recording_mbids=abc") {
|
||||
t.Errorf("URL missing recording_mbids param: %q", seenURL)
|
||||
}
|
||||
if !strings.Contains(seenURL, "/similar-recordings/json") {
|
||||
t.Errorf("URL not the Labs similar-recordings endpoint: %q", seenURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_401_ReturnsErrAuth(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarRecordings(context.Background(), "abc", 100)
|
||||
if !errors.Is(err, ErrAuth) {
|
||||
t.Errorf("err = %v, want ErrAuth", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_400_ReturnsErrPermanent(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarRecordings(context.Background(), "abc", 100)
|
||||
if !errors.Is(err, ErrPermanent) {
|
||||
t.Errorf("err = %v, want ErrPermanent", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_503_ReturnsErrTransient(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarRecordings(context.Background(), "abc", 100)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarRecordings_429_ReturnsRetryAfter(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Retry-After", "120")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarRecordings(context.Background(), "abc", 100)
|
||||
var ra *RetryAfterError
|
||||
if !errors.As(err, &ra) {
|
||||
t.Fatalf("err = %v, want *RetryAfterError", err)
|
||||
}
|
||||
if ra.Wait != 120*time.Second {
|
||||
t.Errorf("Wait = %v, want 120s", ra.Wait)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_Success(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = w.Write([]byte(`[
|
||||
{"artist_mbid": "33333333-3333-3333-3333-333333333333", "score": 0.91},
|
||||
{"artist_mbid": "44444444-4444-4444-4444-444444444444", "score": 0.72}
|
||||
]`))
|
||||
})
|
||||
defer srv.Close()
|
||||
out, err := c.SimilarArtists(context.Background(), "aaaa", 100)
|
||||
if err != nil {
|
||||
t.Fatalf("err: %v", err)
|
||||
}
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("got %d, want 2", len(out))
|
||||
}
|
||||
if out[0].MBID != "33333333-3333-3333-3333-333333333333" || out[0].Score != 0.91 {
|
||||
t.Errorf("first result wrong: %+v", out[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_AlgorithmParamSet(t *testing.T) {
|
||||
var seenURL string
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, r *http.Request) {
|
||||
seenURL = r.URL.String()
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
})
|
||||
defer srv.Close()
|
||||
_, _ = c.SimilarArtists(context.Background(), "abc", 50)
|
||||
if !strings.Contains(seenURL, "algorithm=") {
|
||||
t.Errorf("URL missing algorithm param: %q", seenURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_MbidParamSet(t *testing.T) {
|
||||
var seenURL string
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, r *http.Request) {
|
||||
seenURL = r.URL.String()
|
||||
_, _ = w.Write([]byte(`[]`))
|
||||
})
|
||||
defer srv.Close()
|
||||
_, _ = c.SimilarArtists(context.Background(), "abc", 50)
|
||||
if !strings.Contains(seenURL, "artist_mbids=abc") {
|
||||
t.Errorf("URL missing artist_mbids param: %q", seenURL)
|
||||
}
|
||||
if !strings.Contains(seenURL, "/similar-artists/json") {
|
||||
t.Errorf("URL not the Labs similar-artists endpoint: %q", seenURL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_401_ReturnsErrAuth(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarArtists(context.Background(), "abc", 100)
|
||||
if !errors.Is(err, ErrAuth) {
|
||||
t.Errorf("err = %v, want ErrAuth", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_400_ReturnsErrPermanent(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarArtists(context.Background(), "abc", 100)
|
||||
if !errors.Is(err, ErrPermanent) {
|
||||
t.Errorf("err = %v, want ErrPermanent", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_503_ReturnsErrTransient(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarArtists(context.Background(), "abc", 100)
|
||||
if !errors.Is(err, ErrTransient) {
|
||||
t.Errorf("err = %v, want ErrTransient", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_SimilarArtists_429_ReturnsRetryAfter(t *testing.T) {
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Retry-After", "60")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
})
|
||||
defer srv.Close()
|
||||
_, err := c.SimilarArtists(context.Background(), "abc", 100)
|
||||
var ra *RetryAfterError
|
||||
if !errors.As(err, &ra) {
|
||||
t.Fatalf("err = %v, want *RetryAfterError", err)
|
||||
}
|
||||
if ra.Wait != 60*time.Second {
|
||||
t.Errorf("Wait = %v, want 60s", ra.Wait)
|
||||
// The similarity lookups ask ListenBrainz Labs for one MBID by query
|
||||
// parameter, name the algorithm, and read each result's MBID and score.
|
||||
func TestClient_SimilarLookupsAskLabsAndReadTheScores(t *testing.T) {
|
||||
type first struct {
|
||||
mbid string
|
||||
score float64
|
||||
n int
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name, path, param, body string
|
||||
call func(*Client) (first, error)
|
||||
want first
|
||||
}{
|
||||
{"recordings", "/similar-recordings/json", "recording_mbids=abc",
|
||||
`[{"recording_mbid": "11111111-1111-1111-1111-111111111111", "score": 0.95},
|
||||
{"recording_mbid": "22222222-2222-2222-2222-222222222222", "score": 0.80}]`,
|
||||
func(c *Client) (first, error) {
|
||||
out, err := c.SimilarRecordings(context.Background(), "abc", 100)
|
||||
if err != nil || len(out) == 0 {
|
||||
return first{n: len(out)}, err
|
||||
}
|
||||
return first{out[0].MBID, out[0].Score, len(out)}, nil
|
||||
},
|
||||
first{"11111111-1111-1111-1111-111111111111", 0.95, 2}},
|
||||
{"artists", "/similar-artists/json", "artist_mbids=abc",
|
||||
`[{"artist_mbid": "33333333-3333-3333-3333-333333333333", "score": 0.91},
|
||||
{"artist_mbid": "44444444-4444-4444-4444-444444444444", "score": 0.72}]`,
|
||||
func(c *Client) (first, error) {
|
||||
out, err := c.SimilarArtists(context.Background(), "abc", 100)
|
||||
if err != nil || len(out) == 0 {
|
||||
return first{n: len(out)}, err
|
||||
}
|
||||
return first{out[0].MBID, out[0].Score, len(out)}, nil
|
||||
},
|
||||
first{"33333333-3333-3333-3333-333333333333", 0.91, 2}},
|
||||
} {
|
||||
var seenURL string
|
||||
c, srv := newTestClient(func(w http.ResponseWriter, r *http.Request) {
|
||||
seenURL = r.URL.String()
|
||||
_, _ = w.Write([]byte(tc.body))
|
||||
})
|
||||
got, err := tc.call(c)
|
||||
srv.Close()
|
||||
if err != nil || got != tc.want {
|
||||
t.Errorf("%s: got %+v, %v; want %+v", tc.name, got, err, tc.want)
|
||||
}
|
||||
for _, part := range []string{tc.path, tc.param, "algorithm="} {
|
||||
if !strings.Contains(seenURL, part) {
|
||||
t.Errorf("%s: URL %q lacks %q", tc.name, seenURL, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,41 +2,24 @@ package scrobble
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestQualifies_NeverPlayed(t *testing.T) {
|
||||
if Qualifies(0, 0) {
|
||||
t.Error("0/0 should not qualify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualifies_AtLeast240Seconds(t *testing.T) {
|
||||
if !Qualifies(240_000, 0.0) {
|
||||
t.Error("240_000 ms played should qualify regardless of ratio")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualifies_AtLeastHalfRatio(t *testing.T) {
|
||||
if !Qualifies(0, 0.5) {
|
||||
t.Error("ratio=0.5 should qualify regardless of duration")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualifies_BelowBoth(t *testing.T) {
|
||||
if Qualifies(120_000, 0.49) {
|
||||
t.Error("120s + 49% should not qualify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualifies_BoundaryJustUnder(t *testing.T) {
|
||||
if Qualifies(239_999, 0.4999) {
|
||||
t.Error("just-under both thresholds should not qualify")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQualifies_BoundaryExactly(t *testing.T) {
|
||||
if !Qualifies(240_000, 0.4999) {
|
||||
t.Error("exactly 240s should qualify")
|
||||
}
|
||||
if !Qualifies(239_999, 0.5) {
|
||||
t.Error("exactly 50% should qualify")
|
||||
// A play is scrobbled once it ran four minutes or half the track, whichever
|
||||
// comes first, the rule ListenBrainz and Last.fm both use.
|
||||
func TestQualifies(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
playedMs int
|
||||
ratio float64
|
||||
want bool
|
||||
}{
|
||||
{0, 0, false},
|
||||
{240_000, 0, true},
|
||||
{0, 0.5, true},
|
||||
{120_000, 0.49, false},
|
||||
{239_999, 0.4999, false},
|
||||
{240_000, 0.4999, true},
|
||||
{239_999, 0.5, true},
|
||||
} {
|
||||
if got := Qualifies(tc.playedMs, tc.ratio); got != tc.want {
|
||||
t.Errorf("Qualifies(%d ms, %.4f) = %v, want %v", tc.playedMs, tc.ratio, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user