test(api): one walk over the mounted router checks access and id errors (#8295)
release / go (push) Successful in 2m3s
release / web (push) Successful in 1m29s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m29s
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 3m28s
release / Build signed APK (push) Canceled after 3m3s

The access tests checked hand-built routers that applied RequireAdmin
themselves, so none could catch a production route mounted outside its
group. One test now walks every route Mount registers: each non-public
route answers 401 without a session, and each admin route 403 to a
listener. The per-endpoint malformed-id (400) and unknown-id (404) tests
become one table over the real routes. Profile updates, playlist kind
filters and empty searches each fold into one table; writeErr's envelope
tests move to apierror.Write, which they were testing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 10:29:59 -05:00
co-authored by Claude Opus 5.5
parent 877e1d2631
commit 81cc29595b
21 changed files with 329 additions and 967 deletions
+39 -177
View File
@@ -3,10 +3,8 @@ package api
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/go-chi/chi/v5"
@@ -18,187 +16,51 @@ func newMeProfileRouter(h *handlers) chi.Router {
return r
}
func TestUpdateProfile_DisplayNameOnly(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
// A profile update changes only the fields it sends: an empty display name
// clears it, an email is stored lowercased, and an invalid email or one
// another account holds is refused with the profile unchanged.
func TestUpdateProfile_ChangesOnlyTheFieldsSent(t *testing.T) {
h, pool := testHandlers(t)
user := seedUser(t, pool, "prof1", "pw", false)
body := `{"display_name":"My Name"}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
var resp meProfileResp
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp.DisplayName == nil || *resp.DisplayName != "My Name" {
t.Errorf("display_name = %v, want 'My Name'", resp.DisplayName)
}
}
func TestUpdateProfile_EmailOnly_Lowercased(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "prof2", "pw", false)
body := `{"email":"User@Example.COM"}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
// Verify DB row is lowercased.
var email *string
if err := pool.QueryRow(context.Background(),
"SELECT email FROM users WHERE id = $1", user.ID).Scan(&email); err != nil {
t.Fatalf("read email: %v", err)
}
if email == nil || *email != "user@example.com" {
t.Errorf("DB email = %v, want 'user@example.com'", email)
}
}
func TestUpdateProfile_BothFields(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "prof3", "pw", false)
body := `{"display_name":"Both Fields","email":"both@example.com"}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
var resp meProfileResp
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
if resp.DisplayName == nil || *resp.DisplayName != "Both Fields" {
t.Errorf("display_name = %v, want 'Both Fields'", resp.DisplayName)
}
if resp.Email == nil || *resp.Email != "both@example.com" {
t.Errorf("email = %v, want 'both@example.com'", resp.Email)
}
}
func TestUpdateProfile_EmptyBody_NoOp(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "prof4", "pw", false)
body := `{}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (no-op); body=%s", rec.Code, rec.Body.String())
}
var resp meProfileResp
if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
t.Fatalf("decode: %v", err)
}
// Neither field should have been set (seeded without them).
if resp.DisplayName != nil {
t.Errorf("display_name = %v, want nil (no-op)", resp.DisplayName)
}
}
func TestUpdateProfile_InvalidEmail_400(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "prof5", "pw", false)
body := `{"email":"notanemail"}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400 (email_invalid)", rec.Code)
}
}
func TestUpdateProfile_EmailTaken_409(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
other := seedUser(t, pool, "prof6other", "pw", false)
user := seedUser(t, pool, "prof6user", "pw", false)
// Give the other user an email directly.
other := seedUser(t, pool, "profother", "pw", false)
if _, err := pool.Exec(context.Background(),
"UPDATE users SET email = 'taken@example.com' WHERE id = $1", other.ID); err != nil {
t.Fatalf("setup email: %v", err)
t.Fatalf("give the other account an email: %v", err)
}
user := seedUser(t, pool, "prof", "pw", false)
body := `{"email":"taken@example.com"}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusConflict {
t.Errorf("status = %d, want 409 (email_taken)", rec.Code)
str := func(s string) *string { return &s }
for _, step := range []struct {
body string
status int
wantName, wantMail *string // the stored profile after the request
}{
{`{"display_name":"My Name"}`, http.StatusOK, str("My Name"), nil},
{`{"email":"User@Example.COM"}`, http.StatusOK, str("My Name"), str("user@example.com")},
{`{}`, http.StatusOK, str("My Name"), str("user@example.com")},
{`{"display_name":"Both","email":"both@example.com"}`, http.StatusOK, str("Both"), str("both@example.com")},
{`{"display_name":""}`, http.StatusOK, nil, str("both@example.com")},
{`{"email":"notanemail"}`, http.StatusBadRequest, nil, str("both@example.com")},
{`{"email":"taken@example.com"}`, http.StatusConflict, nil, str("both@example.com")},
} {
req := withUser(httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(step.body))), user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != step.status {
t.Fatalf("%s: status %d, want %d; body=%s", step.body, rec.Code, step.status, rec.Body.String())
}
var name, mail *string
if err := pool.QueryRow(context.Background(),
"SELECT display_name, email FROM users WHERE id = $1", user.ID).Scan(&name, &mail); err != nil {
t.Fatalf("read profile: %v", err)
}
if !sameOptional(name, step.wantName) || !sameOptional(mail, step.wantMail) {
t.Errorf("after %s: profile = (%q, %q), want (%q, %q)",
step.body, deref(name), deref(mail), deref(step.wantName), deref(step.wantMail))
}
}
}
func TestUpdateProfile_ClearDisplayName(t *testing.T) {
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
}
h, pool := testHandlers(t)
user := seedUser(t, pool, "prof7", "pw", false)
// First, set a display name.
if _, err := pool.Exec(context.Background(),
"UPDATE users SET display_name = 'Will Be Cleared' WHERE id = $1", user.ID); err != nil {
t.Fatalf("setup display_name: %v", err)
}
// Clear it by sending empty string.
body := `{"display_name":""}`
req := httptest.NewRequest(http.MethodPut, "/api/me/profile", bytes.NewReader([]byte(body)))
req = withUser(req, user)
rec := httptest.NewRecorder()
newMeProfileRouter(h).ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
// DB should now have NULL display_name.
var dn *string
if err := pool.QueryRow(context.Background(),
"SELECT display_name FROM users WHERE id = $1", user.ID).Scan(&dn); err != nil {
t.Fatalf("read display_name: %v", err)
}
if dn != nil {
t.Errorf("display_name = %v, want nil (cleared)", dn)
}
// sameOptional reports whether two optional strings are both unset or equal.
func sameOptional(a, b *string) bool {
return (a == nil && b == nil) || (a != nil && b != nil && *a == *b)
}