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
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:
@@ -0,0 +1,210 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/Fabled-Sword/minstrel/internal/apierror"
|
||||
"github.com/Fabled-Sword/minstrel/internal/auth"
|
||||
"github.com/Fabled-Sword/minstrel/internal/backup"
|
||||
"github.com/Fabled-Sword/minstrel/internal/config"
|
||||
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
|
||||
"github.com/Fabled-Sword/minstrel/internal/eventbus"
|
||||
"github.com/Fabled-Sword/minstrel/internal/playevents"
|
||||
)
|
||||
|
||||
// publicRoutes are the API routes a request without a session may reach.
|
||||
// Every other route answers 401 to it. The stream routes take a session or
|
||||
// a signed token and check it themselves.
|
||||
var publicRoutes = map[string]bool{
|
||||
"POST /api/auth/login": true,
|
||||
"POST /api/auth/register": true,
|
||||
"GET /api/auth/setup-status": true,
|
||||
"POST /api/auth/restore": true,
|
||||
"POST /api/auth/forgot-password": true,
|
||||
"POST /api/auth/reset-password": true,
|
||||
"GET /api/tracks/{id}/stream": true,
|
||||
"GET /api/tracks/{id}/stream.{ext}": true,
|
||||
"GET /api/tracks/{id}/leveled.flac": true,
|
||||
}
|
||||
|
||||
// mountedAPI is the production router: every route Mount registers, behind
|
||||
// the middleware it registers them with.
|
||||
func mountedAPI(t *testing.T) (chi.Router, *handlers) {
|
||||
t.Helper()
|
||||
h, _ := testHandlers(t)
|
||||
r := chi.NewRouter()
|
||||
w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
30*time.Minute, 0.5, 30000)
|
||||
Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil)
|
||||
return r, h
|
||||
}
|
||||
|
||||
// mountedRoute is one registered method and pattern, with a request path
|
||||
// that fills each {param} in.
|
||||
type mountedRoute struct{ method, pattern, path string }
|
||||
|
||||
func mountedRoutes(t *testing.T, r chi.Router) []mountedRoute {
|
||||
t.Helper()
|
||||
var out []mountedRoute
|
||||
err := chi.Walk(r, func(method, pattern string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
|
||||
path := pattern
|
||||
for strings.Contains(path, "{") {
|
||||
open := strings.Index(path, "{")
|
||||
end := strings.Index(path[open:], "}")
|
||||
path = path[:open] + "00000000-0000-0000-0000-000000000001" + path[open+end+1:]
|
||||
}
|
||||
out = append(out, mountedRoute{method, pattern, strings.TrimSuffix(path, "/*")})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("walk routes: %v", err)
|
||||
}
|
||||
if len(out) < 50 {
|
||||
t.Fatalf("walked %d routes; Mount registers far more, so the walk is not seeing them", len(out))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// sessionCookie signs user in the way the web app does.
|
||||
func sessionCookie(t *testing.T, pool *pgxpool.Pool, user dbq.User) *http.Cookie {
|
||||
t.Helper()
|
||||
token, err := auth.MintSessionToken()
|
||||
if err != nil {
|
||||
t.Fatalf("mint session: %v", err)
|
||||
}
|
||||
if _, err := dbq.New(pool).InsertSession(context.Background(), dbq.InsertSessionParams{
|
||||
UserID: user.ID, TokenHash: auth.HashSessionToken(token), UserAgent: "test-agent", Ip: "192.0.2.1",
|
||||
}); err != nil {
|
||||
t.Fatalf("insert session: %v", err)
|
||||
}
|
||||
return &http.Cookie{Name: auth.SessionCookieName, Value: token}
|
||||
}
|
||||
|
||||
// Every API route but the public ones answers 401 without a session, and
|
||||
// every admin route answers 403 to a signed-in user who is not an admin.
|
||||
// The routes come from the production router, so a route registered outside
|
||||
// its group fails here.
|
||||
func TestMountedRoutes_RequireASessionAndAdminRoutesAnAdmin(t *testing.T) {
|
||||
r, h := mountedAPI(t)
|
||||
listener := seedUser(t, h.pool, "listener", "pw", false)
|
||||
cookie := sessionCookie(t, h.pool, listener)
|
||||
|
||||
var admin int
|
||||
public := map[string]bool{}
|
||||
for _, rt := range mountedRoutes(t, r) {
|
||||
key := rt.method + " " + rt.pattern
|
||||
if publicRoutes[key] {
|
||||
public[key] = true
|
||||
continue
|
||||
}
|
||||
anon := httptest.NewRecorder()
|
||||
r.ServeHTTP(anon, httptest.NewRequest(rt.method, rt.path, nil))
|
||||
if anon.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s answered %d without a session, want 401", key, anon.Code)
|
||||
}
|
||||
if !strings.HasPrefix(rt.pattern, "/api/admin/") {
|
||||
continue
|
||||
}
|
||||
admin++
|
||||
req := httptest.NewRequest(rt.method, rt.path, nil)
|
||||
req.AddCookie(cookie)
|
||||
signedIn := httptest.NewRecorder()
|
||||
r.ServeHTTP(signedIn, req)
|
||||
if signedIn.Code != http.StatusForbidden {
|
||||
t.Errorf("%s answered %d to a non-admin, want 403", key, signedIn.Code)
|
||||
}
|
||||
}
|
||||
if admin < 50 {
|
||||
t.Errorf("only %d admin routes walked; the admin group is not being reached", admin)
|
||||
}
|
||||
for key := range publicRoutes {
|
||||
if !public[key] {
|
||||
t.Errorf("public route %s is not registered", key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An id that is not a UUID answers 400, and one that names nothing answers
|
||||
// 404, on every route that looks a record up by id. The error message names
|
||||
// what was not found where the clients show it.
|
||||
func TestMountedRoutes_AMalformedIDIs400AndAnUnknownOneIs404(t *testing.T) {
|
||||
r, h := mountedAPI(t)
|
||||
listener := seedUser(t, h.pool, "listener", "pw", false)
|
||||
cookie := sessionCookie(t, h.pool, listener)
|
||||
const unknown = "00000000-0000-0000-0000-000000000099"
|
||||
|
||||
for _, tc := range []struct {
|
||||
method, path string // path holds %s where the id goes
|
||||
wantMessage string // on the 404, when the clients show it
|
||||
}{
|
||||
{http.MethodGet, "/api/tracks/%s", ""},
|
||||
{http.MethodGet, "/api/albums/%s", ""},
|
||||
{http.MethodGet, "/api/artists/%s", ""},
|
||||
{http.MethodGet, "/api/artists/%s/tracks", ""},
|
||||
{http.MethodGet, "/api/albums/%s/cover", "album not found"},
|
||||
{http.MethodGet, "/api/tracks/%s/stream", "track not found"},
|
||||
{http.MethodGet, "/api/playlists/%s", ""},
|
||||
{http.MethodPost, "/api/likes/tracks/%s", ""},
|
||||
{http.MethodGet, "/api/radio?seed_track=%s", ""},
|
||||
} {
|
||||
for _, id := range []string{"not-a-uuid", unknown} {
|
||||
req := httptest.NewRequest(tc.method, fmt.Sprintf(tc.path, id), nil)
|
||||
req.AddCookie(cookie)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
want := http.StatusBadRequest
|
||||
if id == unknown {
|
||||
want = http.StatusNotFound
|
||||
}
|
||||
if w.Code != want {
|
||||
t.Errorf("%s %s answered %d, want %d", tc.method, fmt.Sprintf(tc.path, id), w.Code, want)
|
||||
continue
|
||||
}
|
||||
if id == unknown && tc.wantMessage != "" {
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Message != tc.wantMessage {
|
||||
t.Errorf("%s %s message = %q, want %q", tc.method, tc.path, body.Error.Message, tc.wantMessage)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The routes the web app and the phone call are registered: a missing one
|
||||
// answers 404 rather than reaching the session check.
|
||||
func TestMountedRoutes_TheClientsRoutesAreRegistered(t *testing.T) {
|
||||
r, _ := mountedAPI(t)
|
||||
for _, p := range []string{
|
||||
"/api/artists",
|
||||
"/api/artists/00000000-0000-0000-0000-000000000001",
|
||||
"/api/albums/00000000-0000-0000-0000-000000000001",
|
||||
"/api/albums/00000000-0000-0000-0000-000000000001/cover",
|
||||
"/api/tracks/00000000-0000-0000-0000-000000000001",
|
||||
"/api/search?q=x",
|
||||
"/api/library/genres",
|
||||
"/api/library/years",
|
||||
"/api/admin/library/missing",
|
||||
"/api/admin/library/fingerprints",
|
||||
"/api/admin/library/fingerprint-settings",
|
||||
"/api/admin/library/duplicates",
|
||||
} {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, p, nil))
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("GET %s answered %d, want 401 (404 means the route is not registered)", p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,14 +31,6 @@ func (p *apiTestAlbumProvider) FetchAlbumCover(_ context.Context, _ coverart.Alb
|
||||
return []byte("img"), nil
|
||||
}
|
||||
|
||||
// apiTestTestableProvider is an AlbumCoverProvider that also implements
|
||||
// TestableProvider (so the test connection button exercises the success path).
|
||||
type apiTestTestableProvider struct {
|
||||
apiTestAlbumProvider
|
||||
}
|
||||
|
||||
func (p *apiTestTestableProvider) TestConnection(_ context.Context) error { return nil }
|
||||
|
||||
func newAdminCoverSourcesRouter(h *handlers) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Route("/api/admin", func(admin chi.Router) {
|
||||
@@ -215,28 +207,6 @@ func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminTestCoverSource_NonAdminReturns403(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
coverart.ResetRegistryForTests()
|
||||
t.Cleanup(coverart.ResetRegistryForTests)
|
||||
|
||||
coverart.Register(&apiTestTestableProvider{apiTestAlbumProvider{id: "testable-prov", display: "Testable"}})
|
||||
|
||||
h, _ := testHandlersWithCoverSettings(t)
|
||||
nonAdmin := seedUser(t, h.pool, "csnoadmin", "pw", false)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/cover-sources/testable-prov/test", nil)
|
||||
req = withUser(req, nonAdmin)
|
||||
rec := httptest.NewRecorder()
|
||||
newAdminCoverSourcesRouter(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminTestCoverSource_NotTestableReturnsOkFalse(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
|
||||
@@ -138,20 +138,3 @@ func TestAdminLibraryCoverage_MixedRowsReturnCorrectBuckets(t *testing.T) {
|
||||
resp.WithArt, resp.Pending, resp.Settled, resp.Total)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminLibraryCoverage_NonAdminReturns403(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, "covgauge3", "pw", false)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/admin/library/coverage", nil)
|
||||
req = withUser(req, user)
|
||||
rec := httptest.NewRecorder()
|
||||
newAdminCoverageRouter(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,25 +50,3 @@ func TestAdminResearchMissingArt_BumpsAndReturnsVersion(t *testing.T) {
|
||||
t.Errorf("response missing 'version' field; got %v", resp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminResearchMissingArt_NonAdmin_403(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
coverart.ResetRegistryForTests()
|
||||
t.Cleanup(coverart.ResetRegistryForTests)
|
||||
|
||||
coverart.Register(&apiTestAlbumProvider{id: "research-prov2", display: "Research Provider 2"})
|
||||
|
||||
h, _ := testHandlersWithCoverSettings(t)
|
||||
user := seedUser(t, h.pool, "researchnonadmin", "pw", false)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/cover-sources/research", nil)
|
||||
req = withUser(req, user)
|
||||
rec := httptest.NewRecorder()
|
||||
newResearchRouter(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,22 +56,6 @@ func testHandlersWithCovers(t *testing.T) (*handlers, *coverart.Enricher) {
|
||||
return h, enricher
|
||||
}
|
||||
|
||||
func TestAdminAlbumRefetchCover_NonAdminReturns403(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
h, _ := testHandlersWithCovers(t)
|
||||
user := seedUser(t, h.pool, "alice", "pw", false)
|
||||
artist := seedArtist(t, h.pool, "TestArtist")
|
||||
album := seedAlbum(t, h.pool, artist.ID, "TestAlbum", 0)
|
||||
|
||||
w := doAdminCoversReq(t, h, http.MethodPost,
|
||||
"/api/admin/albums/"+uuidToString(album.ID)+"/cover/refetch", user)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminAlbumRefetchCover_AdminOK(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
@@ -118,16 +102,3 @@ func TestAdminBulkRefetchCovers_AdminStartsRefetch(t *testing.T) {
|
||||
t.Errorf("started = false, want true (bulk refetch should acknowledge)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminBulkRefetchCovers_NonAdminReturns403(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
h, _ := testHandlersWithCovers(t)
|
||||
user := seedUser(t, h.pool, "alicebulk", "pw", false)
|
||||
|
||||
w := doAdminCoversReq(t, h, http.MethodPost, "/api/admin/covers/refetch-missing", user)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,19 +93,3 @@ func TestAdminInvites_CreateListDelete(t *testing.T) {
|
||||
t.Errorf("invite still exists after delete (count=%d)", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminInvites_NonAdmin_403(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, "invnonadmin", "pw", false)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/invites", nil)
|
||||
req = withUser(req, user)
|
||||
rec := httptest.NewRecorder()
|
||||
newAdminInvitesRouter(h).ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,32 +206,3 @@ func TestDeleteQuarantineFile_HappyPath(t *testing.T) {
|
||||
t.Error("track row still exists")
|
||||
}
|
||||
}
|
||||
|
||||
// TestQuarantineAdminEndpointsRequire403ForNonAdmin verifies all five admin
|
||||
// endpoints reject non-admin callers with 403.
|
||||
func TestQuarantineAdminEndpointsRequire403ForNonAdmin(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
|
||||
nonAdmin := seedUser(t, pool, "regular", "pw", false)
|
||||
fakeID := "00000000-0000-0000-0000-000000000001"
|
||||
|
||||
cases := []struct {
|
||||
method string
|
||||
path string
|
||||
}{
|
||||
{http.MethodGet, "/api/admin/quarantine"},
|
||||
{http.MethodPost, "/api/admin/quarantine/" + fakeID + "/resolve"},
|
||||
{http.MethodPost, "/api/admin/quarantine/" + fakeID + "/delete-file"},
|
||||
{http.MethodGet, "/api/admin/quarantine/actions"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.method+" "+tc.path, func(t *testing.T) {
|
||||
w := doAdminQuarantineReq(t, h, tc.method, tc.path, nil, nonAdmin)
|
||||
if w.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,13 +31,6 @@ func (p *apiTestTagProvider) FetchTrackTags(_ context.Context, _ tags.TrackRef)
|
||||
return []tags.Tag{{Name: "x", Weight: 1}}, nil
|
||||
}
|
||||
|
||||
// apiTestTestableTagProvider also implements TestableProvider.
|
||||
type apiTestTestableTagProvider struct {
|
||||
apiTestTagProvider
|
||||
}
|
||||
|
||||
func (p *apiTestTestableTagProvider) TestConnection(_ context.Context) error { return nil }
|
||||
|
||||
func newAdminTagSourcesRouter(h *handlers) chi.Router {
|
||||
r := chi.NewRouter()
|
||||
r.Route("/api/admin", func(admin chi.Router) {
|
||||
@@ -196,27 +189,6 @@ func TestAdminUpdateTagSource_UnknownProvider404(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminTestTagSource_NonAdminReturns403(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
tags.ResetRegistryForTests()
|
||||
t.Cleanup(tags.ResetRegistryForTests)
|
||||
tags.Register(&apiTestTestableTagProvider{apiTestTagProvider{id: "testable-tag", display: "Testable Tag"}})
|
||||
|
||||
h := testHandlersWithTagSettings(t)
|
||||
nonAdmin := seedUser(t, h.pool, "tsnoadmin", "pw", false)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/admin/tag-sources/testable-tag/test", nil)
|
||||
req = withUser(req, nonAdmin)
|
||||
rec := httptest.NewRecorder()
|
||||
newAdminTagSourcesRouter(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminTestTagSource_NotTestableReturnsOkFalse(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Fabled-Sword/minstrel/internal/apierror"
|
||||
)
|
||||
|
||||
func decodeEnvelope(t *testing.T, body []byte) apierror.Body {
|
||||
t.Helper()
|
||||
var env apierror.Body
|
||||
if err := json.Unmarshal(body, &env); err != nil {
|
||||
t.Fatalf("decode envelope: %v (body=%s)", err, string(body))
|
||||
}
|
||||
return env
|
||||
}
|
||||
|
||||
func TestWriteErr_APIError(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeErr(rec, apierror.NotFound("track"))
|
||||
|
||||
if rec.Code != 404 {
|
||||
t.Fatalf("status: want 404, got %d", rec.Code)
|
||||
}
|
||||
env := decodeEnvelope(t, rec.Body.Bytes())
|
||||
if env.Error.Code != "track_not_found" {
|
||||
t.Errorf("code: want track_not_found, got %q", env.Error.Code)
|
||||
}
|
||||
if env.Error.Message != "track not found" {
|
||||
t.Errorf("message: want %q, got %q", "track not found", env.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErr_Sentinel(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeErr(rec, apierror.ErrUnauthorized)
|
||||
|
||||
if rec.Code != 401 {
|
||||
t.Fatalf("status: want 401, got %d", rec.Code)
|
||||
}
|
||||
env := decodeEnvelope(t, rec.Body.Bytes())
|
||||
if env.Error.Code != "unauthorized" {
|
||||
t.Errorf("code: want unauthorized, got %q", env.Error.Code)
|
||||
}
|
||||
if env.Error.Message != "authentication required" {
|
||||
t.Errorf("message: want %q, got %q", "authentication required", env.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErr_PlainError(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeErr(rec, errors.New("boom"))
|
||||
|
||||
if rec.Code != 500 {
|
||||
t.Fatalf("status: want 500, got %d", rec.Code)
|
||||
}
|
||||
env := decodeEnvelope(t, rec.Body.Bytes())
|
||||
if env.Error.Code != "server_error" {
|
||||
t.Errorf("code: want server_error, got %q", env.Error.Code)
|
||||
}
|
||||
if env.Error.Message != "internal server error" {
|
||||
t.Errorf("message: want %q, got %q", "internal server error", env.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErr_WrappedAPIError(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeErr(rec, fmt.Errorf("ctx: %w", apierror.BadRequest("bad", "no good")))
|
||||
|
||||
if rec.Code != 400 {
|
||||
t.Fatalf("status: want 400, got %d", rec.Code)
|
||||
}
|
||||
env := decodeEnvelope(t, rec.Body.Bytes())
|
||||
if env.Error.Code != "bad" {
|
||||
t.Errorf("code: want bad, got %q", env.Error.Code)
|
||||
}
|
||||
if env.Error.Message != "no good" {
|
||||
t.Errorf("message: want %q, got %q", "no good", env.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErr_EnvelopeShape(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeErr(rec, apierror.BadRequest("x", "y"))
|
||||
|
||||
var raw map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &raw); err != nil {
|
||||
t.Fatalf("decode raw: %v", err)
|
||||
}
|
||||
if len(raw) != 1 {
|
||||
t.Fatalf("top-level keys: want 1, got %d (%v)", len(raw), raw)
|
||||
}
|
||||
inner, ok := raw["error"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("error: want object, got %T", raw["error"])
|
||||
}
|
||||
if len(inner) != 2 {
|
||||
t.Fatalf("inner keys: want 2, got %d (%v)", len(inner), inner)
|
||||
}
|
||||
if _, ok := inner["code"]; !ok {
|
||||
t.Errorf("inner.code missing")
|
||||
}
|
||||
if _, ok := inner["message"]; !ok {
|
||||
t.Errorf("inner.message missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteErr_ContentType(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
writeErr(rec, apierror.BadRequest("x", "y"))
|
||||
|
||||
if got := rec.Header().Get("Content-Type"); got != "application/json" {
|
||||
t.Errorf("Content-Type: want application/json, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -3,21 +3,14 @@ package api
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"github.com/Fabled-Sword/minstrel/internal/auth"
|
||||
"github.com/Fabled-Sword/minstrel/internal/backup"
|
||||
"github.com/Fabled-Sword/minstrel/internal/config"
|
||||
"github.com/Fabled-Sword/minstrel/internal/db/dbq"
|
||||
"github.com/Fabled-Sword/minstrel/internal/eventbus"
|
||||
"github.com/Fabled-Sword/minstrel/internal/playevents"
|
||||
)
|
||||
|
||||
// newLibraryRouter builds a test-only chi router with the library handlers
|
||||
@@ -87,28 +80,6 @@ func TestHandleGetTrack_HappyPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetTrack_BadUUID(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/tracks/not-a-uuid", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetTrack_NotFound(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/api/tracks/00000000-0000-0000-0000-000000000001", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetAlbum_HappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
@@ -206,28 +177,6 @@ func TestHandleGetAlbum_NoTracks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetAlbum_BadUUID(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/albums/not-a-uuid", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetAlbum_NotFound(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/api/albums/00000000-0000-0000-0000-000000000001", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetArtist_HappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
@@ -297,28 +246,6 @@ func TestHandleGetArtist_NoAlbums(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetArtist_BadUUID(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/artists/not-a-uuid", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetArtist_NotFound(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/api/artists/00000000-0000-0000-0000-000000000001", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d, want 404", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListArtists_DefaultAlpha(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
@@ -420,35 +347,6 @@ func TestHandleListArtists_Pagination(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListArtists_LimitClamped(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
seedArtist(t, pool, "One")
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/artists?limit=9999", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var got Page[ArtistRef]
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &got)
|
||||
if got.Limit != 200 {
|
||||
t.Errorf("limit = %d, want 200 (max clamp)", got.Limit)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListArtists_LimitNonNumeric(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/artists?limit=abc", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleListArtists_AlbumCount(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
@@ -488,51 +386,6 @@ func TestHandleListArtists_EmptyDB(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutesRegisteredInMount verifies the production Mount() wires every
|
||||
// library route. We hit each path through the real Mount (no RequireUser
|
||||
// stripped — we expect 401 from the middleware, which is fine — that
|
||||
// proves the route reached the authenticated group).
|
||||
func TestRoutesRegisteredInMount(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
r := chi.NewRouter()
|
||||
w := playevents.NewWriter(h.pool, slog.New(slog.NewTextHandler(io.Discard, nil)),
|
||||
30*time.Minute, 0.5, 30000)
|
||||
Mount(r, h.pool, h.logger, w, config.RecommendationConfig{RadioSize: 50, RadioSizeMax: 200, RecentlyPlayedHours: 1}, h.recSettings, h.quarantine, h.tracks, h.playlists, h.coverart, h.coverSettings, h.tagSettings, h.scanner, h.scanCfg, h.dataDir, nil, eventbus.New(), nil, nil, h.netSettings, nil, nil, nil, nil, backup.NewService(h.pool, h.logger, "test"), nil)
|
||||
|
||||
paths := []string{
|
||||
"/api/artists",
|
||||
"/api/artists/00000000-0000-0000-0000-000000000001",
|
||||
"/api/albums/00000000-0000-0000-0000-000000000001",
|
||||
"/api/albums/00000000-0000-0000-0000-000000000001/cover",
|
||||
"/api/tracks/00000000-0000-0000-0000-000000000001",
|
||||
"/api/tracks/00000000-0000-0000-0000-000000000001/stream",
|
||||
"/api/search?q=x",
|
||||
// Browse indexes.
|
||||
"/api/library/genres",
|
||||
"/api/library/years",
|
||||
// Admin surfaces for the missing-file lifecycle. Both must
|
||||
// 401 at the middleware rather than 404 — they live inside the
|
||||
// admin group, so reaching the auth check is what proves they are
|
||||
// wired.
|
||||
"/api/admin/library/missing",
|
||||
"/api/admin/library/fingerprints",
|
||||
"/api/admin/library/fingerprint-settings",
|
||||
"/api/admin/library/duplicates",
|
||||
}
|
||||
for _, p := range paths {
|
||||
req := httptest.NewRequest(http.MethodGet, p, nil)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
// Unauthenticated → 401. What we must NOT see is 404 (route missing).
|
||||
if w.Code == http.StatusNotFound {
|
||||
t.Errorf("path %s returned 404 — route not registered", p)
|
||||
}
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("path %s status = %d, want 401 (unauth)", p, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetArtistTracks_HappyPath(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "pw", false)
|
||||
@@ -614,21 +467,3 @@ func TestGetArtistTracks_HonorsQuarantine(t *testing.T) {
|
||||
t.Errorf("len = %d, want 0 (quarantined)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetArtistTracks_NotFound(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "pw", false)
|
||||
|
||||
r := chi.NewRouter()
|
||||
r.Get("/api/artists/{id}/tracks", h.handleGetArtistTracks)
|
||||
// Random UUID — no such artist exists.
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/artists/00000000-0000-0000-0000-000000000000/tracks", nil)
|
||||
req = withUser(req, user)
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d, want 404", w.Code)
|
||||
}
|
||||
_ = pool
|
||||
}
|
||||
|
||||
@@ -62,25 +62,6 @@ func TestLikeTrack_Idempotent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLikeTrack_BadUUIDIs400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "x", false)
|
||||
w := callLike(h, user, http.MethodPost, "/api/likes/tracks/not-a-uuid")
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLikeTrack_UnknownTrackIs404(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
user := seedUser(t, pool, "alice", "x", false)
|
||||
w := callLike(h, user, http.MethodPost, "/api/likes/tracks/00000000-0000-0000-0000-000000000000")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnlikeTrack_IdempotentEvenWhenAbsent(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
|
||||
+39
-177
@@ -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)
|
||||
}
|
||||
|
||||
@@ -39,16 +39,6 @@ func seedSourcedPlay(
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecommendationMetrics_NoSession401(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/me/recommendation-metrics", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
newMetricsRouter(h).ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// findSurface returns the named family from any group, or nil.
|
||||
func findSurface(resp recommendationMetricsResp, key string) *surfaceMetric {
|
||||
for _, g := range resp.Groups {
|
||||
|
||||
@@ -19,16 +19,6 @@ func newMeSystemPlaylistsRouter(h *handlers) chi.Router {
|
||||
return r
|
||||
}
|
||||
|
||||
func TestMeSystemPlaylistsStatus_NoSession401(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
newMeSystemPlaylistsRouter(h).ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMeSystemPlaylistsStatus_NoRowReturnsDefault(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
|
||||
@@ -245,33 +245,6 @@ func TestHandleGetCover_NoArt(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetCover_BadUUID(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/albums/not-a-uuid/cover", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetCover_UnknownAlbum(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/api/albums/00000000-0000-0000-0000-000000000001/cover", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Message != "album not found" {
|
||||
t.Errorf("message = %q, want \"album not found\"", body.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
// deterministicBytes returns n bytes whose values cycle 0..255. Using a
|
||||
// fixed pattern (not crypto/rand) makes assertions easy and the test
|
||||
// reproducible.
|
||||
@@ -385,33 +358,6 @@ func TestHandleGetStream_IfModifiedSinceReturns304(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetStream_BadUUID(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/tracks/not-a-uuid/stream", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetStream_UnknownTrack(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/api/tracks/00000000-0000-0000-0000-000000000001/stream", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d", w.Code)
|
||||
}
|
||||
var body apierror.Body
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &body)
|
||||
if body.Error.Message != "track not found" {
|
||||
t.Errorf("message = %q, want \"track not found\"", body.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleGetStream_VanishedFile(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
|
||||
@@ -95,18 +95,3 @@ func TestSystemRefresh_NonSingletonKind_Returns404(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSystemRefresh_NoAuth_Returns401(t *testing.T) {
|
||||
if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" {
|
||||
t.Skip("MINSTREL_TEST_DATABASE_URL not set")
|
||||
}
|
||||
h, _ := testHandlers(t)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/playlists/system/for_you/refresh", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
newSystemPlaylistRouter(h).ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Errorf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
+39
-151
@@ -6,6 +6,8 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -64,29 +66,6 @@ func seedSimpleTrack(t *testing.T, pool *pgxpool.Pool, title, artist string) dbq
|
||||
return seedTrack(t, pool, al.ID, a.ID, title, 1, 1000)
|
||||
}
|
||||
|
||||
// TestPlaylists_NoSession401 verifies the handler-owned defensive 401
|
||||
// path on each route. Real traffic hits RequireUser upstream, but the
|
||||
// handler also defends against routing misconfigurations.
|
||||
func TestPlaylists_NoSession401(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
r := newPlaylistsRouter(h)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/playlists", nil)
|
||||
w := httptest.NewRecorder()
|
||||
// Note: NO user in context.
|
||||
r.ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
var env apierror.Body
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &env); err != nil {
|
||||
t.Fatalf("decode: %v; body = %s", err, w.Body.String())
|
||||
}
|
||||
if env.Error.Code != "unauthenticated" {
|
||||
t.Errorf("error.code = %q, want unauthenticated", env.Error.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaylists_CreateThenGet exercises the happy-path end-to-end:
|
||||
// POST creates a row, the response carries the id, GET round-trips
|
||||
// the same fields.
|
||||
@@ -190,20 +169,6 @@ func TestPlaylists_PatchOwnerOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaylists_GetNotFound verifies a well-formed UUID with no row
|
||||
// surfaces as 404 not_found.
|
||||
func TestPlaylists_GetNotFound(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
user := seedUser(t, pool, "alice", "pw", false)
|
||||
|
||||
missing := "00000000-0000-0000-0000-000000000099"
|
||||
w := doPlaylistsReq(h, user, http.MethodGet, "/api/playlists/"+missing, nil)
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaylists_ListSplitsOwnedAndPublic verifies the response carries
|
||||
// owned vs. public buckets correctly. Alice owns one private + one
|
||||
// public; Bob sees only Alice's public.
|
||||
@@ -397,19 +362,6 @@ func TestPlaylists_DeleteOwnerOnly(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaylists_BadUUID400 verifies a malformed playlist id returns
|
||||
// bad_request rather than reaching the service layer.
|
||||
func TestPlaylists_BadUUID400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
user := seedUser(t, pool, "alice", "pw", false)
|
||||
|
||||
w := doPlaylistsReq(h, user, http.MethodGet, "/api/playlists/not-a-uuid", nil)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPlaylists_AppendInvalidTrackUUID400 verifies a malformed track id
|
||||
// in the append body returns bad_request before reaching the DB.
|
||||
func TestPlaylists_AppendInvalidTrackUUID400(t *testing.T) {
|
||||
@@ -456,53 +408,14 @@ func TestPlaylists_CoverNoneReturns404(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestListPlaylists_KindFilterDefaultsToUser verifies that an absent ?kind=
|
||||
// parameter defaults to "user" and excludes system-kind playlists.
|
||||
func TestListPlaylists_KindFilterDefaultsToUser(t *testing.T) {
|
||||
// The playlist list filters by kind: the person's own playlists by default,
|
||||
// the system mixes with kind=system, both with kind=all, and any other kind
|
||||
// is a 400.
|
||||
func TestListPlaylists_FiltersByKind(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
u := seedUser(t, pool, "klistdefault", "pw", false)
|
||||
|
||||
// Create one user-kind playlist via the service.
|
||||
userPL, err := h.playlists.Create(context.Background(), u.ID, "My PL", "", false)
|
||||
if err != nil {
|
||||
t.Fatalf("create user playlist: %v", err)
|
||||
}
|
||||
// Insert a system-kind playlist directly via SQL.
|
||||
if _, err := pool.Exec(context.Background(), `
|
||||
INSERT INTO playlists (user_id, name, description, is_public, kind, system_variant)
|
||||
VALUES ($1, 'For You', '', false, 'system', 'for_you')
|
||||
`, u.ID); err != nil {
|
||||
t.Fatalf("seed system playlist: %v", err)
|
||||
}
|
||||
|
||||
w := doPlaylistsReq(h, u, "GET", "/api/playlists", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want 200; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp listPlaylistsResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(resp.Owned) != 1 {
|
||||
t.Fatalf("default should return 1 user-kind playlist; got %d", len(resp.Owned))
|
||||
}
|
||||
if resp.Owned[0].Kind != "user" {
|
||||
t.Errorf("expected kind=user; got %q", resp.Owned[0].Kind)
|
||||
}
|
||||
if resp.Owned[0].ID != uuidToString(userPL.ID) {
|
||||
t.Errorf("returned wrong playlist id")
|
||||
}
|
||||
}
|
||||
|
||||
// TestListPlaylists_KindSystem verifies ?kind=system returns only
|
||||
// system-generated playlists and excludes user-created ones.
|
||||
func TestListPlaylists_KindSystem(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
u := seedUser(t, pool, "klistsys", "pw", false)
|
||||
|
||||
if _, err := h.playlists.Create(context.Background(), u.ID, "User PL", "", false); err != nil {
|
||||
u := seedUser(t, pool, "klist", "pw", false)
|
||||
if _, err := h.playlists.Create(context.Background(), u.ID, "My PL", "", false); err != nil {
|
||||
t.Fatalf("create user playlist: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(context.Background(), `
|
||||
@@ -512,62 +425,37 @@ func TestListPlaylists_KindSystem(t *testing.T) {
|
||||
t.Fatalf("seed system playlist: %v", err)
|
||||
}
|
||||
|
||||
w := doPlaylistsReq(h, u, "GET", "/api/playlists?kind=system", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want 200; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp listPlaylistsResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(resp.Owned) != 1 {
|
||||
t.Fatalf("kind=system should return 1 system playlist; got %d", len(resp.Owned))
|
||||
}
|
||||
if resp.Owned[0].Kind != "system" {
|
||||
t.Errorf("expected kind=system; got %q", resp.Owned[0].Kind)
|
||||
}
|
||||
}
|
||||
|
||||
// TestListPlaylists_KindAll verifies ?kind=all returns all playlists
|
||||
// regardless of kind.
|
||||
func TestListPlaylists_KindAll(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
u := seedUser(t, pool, "klistall", "pw", false)
|
||||
|
||||
if _, err := h.playlists.Create(context.Background(), u.ID, "User PL", "", false); err != nil {
|
||||
t.Fatalf("create user playlist: %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(context.Background(), `
|
||||
INSERT INTO playlists (user_id, name, description, is_public, kind, system_variant)
|
||||
VALUES ($1, 'For You', '', false, 'system', 'for_you')
|
||||
`, u.ID); err != nil {
|
||||
t.Fatalf("seed system playlist: %v", err)
|
||||
}
|
||||
|
||||
w := doPlaylistsReq(h, u, "GET", "/api/playlists?kind=all", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status: got %d, want 200; body=%s", w.Code, w.Body.String())
|
||||
}
|
||||
var resp listPlaylistsResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if len(resp.Owned) != 2 {
|
||||
t.Fatalf("kind=all should return both playlists; got %d", len(resp.Owned))
|
||||
}
|
||||
}
|
||||
|
||||
// TestListPlaylists_BadKindReturns400 verifies an unrecognised kind value
|
||||
// is rejected with 400 bad_kind.
|
||||
func TestListPlaylists_BadKindReturns400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
u := seedUser(t, pool, "klistbad", "pw", false)
|
||||
_ = pool
|
||||
|
||||
w := doPlaylistsReq(h, u, "GET", "/api/playlists?kind=garbage", nil)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400; got %d, body=%s", w.Code, w.Body.String())
|
||||
for _, tc := range []struct {
|
||||
query string
|
||||
kinds []string // the kinds listed, in any order; nil means a 400
|
||||
}{
|
||||
{"", []string{"user"}},
|
||||
{"?kind=system", []string{"system"}},
|
||||
{"?kind=all", []string{"system", "user"}},
|
||||
{"?kind=garbage", nil},
|
||||
} {
|
||||
w := doPlaylistsReq(h, u, "GET", "/api/playlists"+tc.query, nil)
|
||||
if tc.kinds == nil {
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("%q: status %d, want 400", tc.query, w.Code)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("%q: status %d, want 200; body=%s", tc.query, w.Code, w.Body.String())
|
||||
}
|
||||
var resp listPlaylistsResponse
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("%q: decode: %v", tc.query, err)
|
||||
}
|
||||
var got []string
|
||||
for _, p := range resp.Owned {
|
||||
got = append(got, p.Kind)
|
||||
}
|
||||
sort.Strings(got)
|
||||
if !reflect.DeepEqual(got, tc.kinds) {
|
||||
t.Errorf("%q listed kinds %v, want %v", tc.query, got, tc.kinds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -262,44 +261,3 @@ func TestListMine_OK(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestQuarantineEndpointsRequireAuth verifies the /api/quarantine endpoints
|
||||
// return 401 when no user is in context (covers RequireUser failure mode
|
||||
// uniformly across the three handlers).
|
||||
func TestQuarantineEndpointsRequireAuth(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
truncateLibrary(t, pool)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
method string
|
||||
path string
|
||||
body string
|
||||
}{
|
||||
{"flag", http.MethodPost, "/api/quarantine", `{"track_id":"00000000-0000-0000-0000-000000000001","reason":"bad_rip"}`},
|
||||
{"unflag", http.MethodDelete, "/api/quarantine/00000000-0000-0000-0000-000000000001", ""},
|
||||
{"mine", http.MethodGet, "/api/quarantine/mine", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
tc := tc
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var reqBody *bytes.Buffer
|
||||
if tc.body != "" {
|
||||
reqBody = bytes.NewBufferString(tc.body)
|
||||
} else {
|
||||
reqBody = bytes.NewBuffer(nil)
|
||||
}
|
||||
req := httptest.NewRequest(tc.method, tc.path, reqBody)
|
||||
if tc.body != "" {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
// No user injected into context.
|
||||
req = req.WithContext(context.Background())
|
||||
w := httptest.NewRecorder()
|
||||
newQuarantineRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("%s: status = %d, want 401; body = %s", tc.name, w.Code, w.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,24 +66,6 @@ func TestHandleRadio_Typical_SeedFirstPlusPicks(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRadio_UnknownSeedIs404(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "x", false)
|
||||
w := callRadio(h, user, "seed_track=00000000-0000-0000-0000-000000000000")
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRadio_BadSeedIs400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "x", false)
|
||||
w := callRadio(h, user, "seed_track=not-a-uuid")
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleRadio_MissingSeedIs400(t *testing.T) {
|
||||
h, pool := testHandlers(t)
|
||||
user := seedUser(t, pool, "alice", "x", false)
|
||||
|
||||
@@ -68,23 +68,15 @@ func TestHandleSearch_NoMatches(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSearch_EmptyQuery(t *testing.T) {
|
||||
// A search with no query, or only spaces, is a 400.
|
||||
func TestHandleSearch_AnEmptyQueryIs400(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/search", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleSearch_BlankQuery(t *testing.T) {
|
||||
h, _ := testHandlers(t)
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/search?q=%20%20", nil)
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("status = %d, want 400", w.Code)
|
||||
for _, path := range []string{"/api/search", "/api/search?q=%20%20"} {
|
||||
w := httptest.NewRecorder()
|
||||
newLibraryRouter(h).ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Errorf("%s: status = %d, want 400", path, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user