sonda/internal/api/http/waveform_test.go
tgiachi a880b87a9e chore: move the module path to git.kmalloc.org/squid/sonda
Migrating hosting from Codeberg to git.kmalloc.org. Renames the
module path in go.mod, every internal import, and the OCI image
source label in the Dockerfile. Build and full test suite verified
green after the rename.
2026-11-15 17:30:29 +01:00

111 lines
3.8 KiB
Go

package httpapi
import (
"context"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"git.kmalloc.org/squid/sonda/internal/storage"
"git.kmalloc.org/squid/sonda/internal/streaming"
"git.kmalloc.org/squid/sonda/internal/waveform"
"github.com/uptrace/bun"
)
func TestThePeaksOfATrackNeedALoginAndAreItsWaveform(t *testing.T) {
root, err := filepath.Abs(filepath.Join("..", "..", "waveform", "testdata"))
if err != nil {
t.Fatal(err)
}
h, _ := newTestEnvDB(t, func(d *Deps, db *bun.DB) {
// Track 1 is made by the test environment; the second one is made here.
if _, err := db.Exec("INSERT INTO tracks (title) VALUES ('two')"); err != nil {
t.Fatal(err)
}
d.Waveform = waveform.NewService(storage.NewWaveformRepo(db), streaming.NewService(mapSource{
1: {Root: root, RelPath: "ramp.mp3"},
2: {Root: root, RelPath: "ramp.flac"},
}))
})
if r := do(t, h, "GET", "/api/v1/tracks/1/peaks", "", nil); r.Code != http.StatusUnauthorized {
t.Errorf("without a login: %d", r.Code)
}
tok := registerAndLogin(t, h)
for _, id := range []string{"1", "2"} {
r := do(t, h, "GET", "/api/v1/tracks/"+id+"/peaks", tok, nil)
if r.Code != http.StatusOK {
t.Fatalf("track %s: %d %v", id, r.Code, r.Body)
}
sameKeys(t, "peaks", r.Body, "count", "peaks")
peaks := r.Body["peaks"].([]any)
if r.Body["count"] != float64(waveform.Count) || len(peaks) != waveform.Count {
t.Fatalf("count = %v, %d levels", r.Body["count"], len(peaks))
}
if peaks[0].(float64) > 40 || peaks[len(peaks)-1].(float64) < 230 {
t.Errorf("track %s starts at %v and ends at %v: it is a tone that rises", id, peaks[0], peaks[len(peaks)-1])
}
for _, v := range peaks {
if v.(float64) < 0 || v.(float64) > 255 {
t.Fatalf("a level of %v", v)
}
}
}
}
type fakeWaveform struct {
peaks []byte
err error
}
func (f fakeWaveform) Peaks(context.Context, int64) ([]byte, error) { return f.peaks, f.err }
func TestWhileTheShapeIsBeingWorkedOutThePageIsToldToAskAgain(t *testing.T) {
h := newTestAPIWith(t, func(d *Deps) { d.Waveform = fakeWaveform{err: waveform.ErrNotReady} })
tok := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/tracks/1/peaks", tok, nil)
if r.Code != http.StatusAccepted || r.Body["status"] != "working" {
t.Fatalf("while it works: %d %v", r.Code, r.Body)
}
rec := doRaw(t, h, "GET", "/api/v1/tracks/1/peaks", tok)
if rec.Header().Get("Retry-After") == "" {
t.Error("no Retry-After: the page would not know when to ask again")
}
}
func TestATrackWithNoWaveformIsSaidInWords(t *testing.T) {
for name, tc := range map[string]struct {
err error
status int
code string
}{
"a track that is not there": {streaming.ErrNotFound, http.StatusNotFound, "track_not_found"},
"a file that is gone": {streaming.ErrFileMissing, http.StatusNotFound, "file_missing"},
"a format not decoded": {waveform.ErrUnsupported, http.StatusNotFound, "waveform_unavailable"},
} {
h := newTestAPIWith(t, func(d *Deps) { d.Waveform = fakeWaveform{err: tc.err} })
tok := registerAndLogin(t, h)
r := do(t, h, "GET", "/api/v1/tracks/1/peaks", tok, nil)
if r.Code != tc.status || errCode(r) != tc.code {
t.Errorf("%s: %d %v", name, r.Code, r.Body)
}
}
h := newTestAPIWith(t, func(d *Deps) { d.Waveform = fakeWaveform{} })
tok := registerAndLogin(t, h)
if r := do(t, h, "GET", "/api/v1/tracks/abc/peaks", tok, nil); r.Code != http.StatusBadRequest {
t.Errorf("a track that is no number: %d", r.Code)
}
}
// doRaw sends a request and returns the whole answer, headers included.
func doRaw(t *testing.T, h http.Handler, method, path, token string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, path, nil)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}