8c18e44d5b
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
77 lines
2.4 KiB
Go
77 lines
2.4 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
// newLibraryRouter builds a test-only chi router with the library handlers
|
|
// mounted at their path-style routes. Tests hit this router rather than
|
|
// calling handler methods directly so chi URL params populate correctly.
|
|
// RequireUser is NOT applied — library handlers don't read user context.
|
|
func newLibraryRouter(h *handlers) chi.Router {
|
|
r := chi.NewRouter()
|
|
r.Get("/api/artists", h.handleListArtists)
|
|
r.Get("/api/artists/{id}", h.handleGetArtist)
|
|
r.Get("/api/albums/{id}", h.handleGetAlbum)
|
|
r.Get("/api/tracks/{id}", h.handleGetTrack)
|
|
r.Get("/api/search", h.handleSearch)
|
|
return r
|
|
}
|
|
|
|
func TestHandleGetTrack_HappyPath(t *testing.T) {
|
|
h, pool := testHandlers(t)
|
|
truncateLibrary(t, pool)
|
|
artist := seedArtist(t, pool, "Beatles")
|
|
album := seedAlbum(t, pool, artist.ID, "Abbey Road", 1969)
|
|
track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000)
|
|
|
|
req := httptest.NewRequest(http.MethodGet, "/api/tracks/"+uuidToString(track.ID), nil)
|
|
w := httptest.NewRecorder()
|
|
newLibraryRouter(h).ServeHTTP(w, req)
|
|
|
|
if w.Code != http.StatusOK {
|
|
t.Fatalf("status = %d body = %s", w.Code, w.Body.String())
|
|
}
|
|
var got TrackRef
|
|
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
|
t.Fatalf("decode: %v body=%s", err, w.Body.String())
|
|
}
|
|
if got.Title != "Something" || got.AlbumTitle != "Abbey Road" || got.ArtistName != "Beatles" {
|
|
t.Errorf("ref = %+v", got)
|
|
}
|
|
if got.TrackNumber != 3 || got.DurationSec != 183 {
|
|
t.Errorf("positions = %+v", got)
|
|
}
|
|
want := "/api/tracks/" + uuidToString(track.ID) + "/stream"
|
|
if got.StreamURL != want {
|
|
t.Errorf("stream_url = %q, want %q", got.StreamURL, want)
|
|
}
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|