test(coverart, subsonic, server): merge repeated cases into tables (#8298)
release / web (push) Successful in 1m35s
release / go (push) Successful in 1m58s
release / govulncheck (push) Successful in 19s
release / integration (push) Successful in 3m0s
release / android (push) Successful in 4m26s
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 / Build signed APK (push) Canceled after 5m8s

- coverart: the four providers' identity and default tests, Last.fm's five
  not-found-without-asking tests, the four "which artists are asked again"
  database tests (now one reset over four artists), and the thumbnail-only
  and fanart-only tests.
- subsonic: getUser's six tests and decodePassword's three, one table each.
  Dropped TestTokenMD5Derivation: it checked crypto/md5 against a constant
  and called no Minstrel code.
- server: the four web-app-versus-API path tests start one server, not four.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-02 13:58:07 -05:00
co-authored by Claude Opus 5.5
parent bd95cdb105
commit 10b10b8179
9 changed files with 214 additions and 540 deletions
+85 -225
View File
@@ -2,6 +2,7 @@ package coverart
import ( import (
"context" "context"
"fmt"
"os" "os"
"path/filepath" "path/filepath"
"testing" "testing"
@@ -45,256 +46,115 @@ func insertArtist(t *testing.T, q *dbq.Queries, ctx context.Context, name, mbid
return a.ID return a.ID
} }
// --- Eligibility tests --- // An artist is asked about when it has no art source yet, or when it was
// settled as "none" under an older set of providers (the version counts
func TestEnrichArtist_NullSource_Eligible(t *testing.T) { // provider changes). One with art, or settled "none" under the current
// providers, is left alone, and no file is written for it.
func TestEnrichArtist_WhichArtistsAreAsked(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
ctx := context.Background() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
resetRegistryForTests() resetRegistryForTests()
t.Cleanup(resetRegistryForTests) t.Cleanup(resetRegistryForTests)
Register(&stubArtistProvider{
stub := &stubArtistProvider{
fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true},
thumb: []byte("thumb_bytes"), thumb: []byte("thumb_bytes"),
fanart: []byte("fanart_bytes"), fanart: []byte("fanart_bytes"),
} })
Register(stub)
e := newTestEnricher(t, pool) e := newTestEnricher(t, pool)
artistID := insertArtist(t, q, ctx, "Null Artist", "11111111-1111-1111-1111-111111111111") current := e.settings.CurrentVersion()
dataDir := t.TempDir() dataDir := t.TempDir()
if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Fatalf("EnrichArtist: %v", err)
}
row, err := q.GetArtistByID(ctx, artistID) for i, tc := range []struct {
if err != nil { name string
t.Fatalf("GetArtistByID: %v", err) source string // "" leaves it NULL
} version int32
if row.ArtistArtSource == nil || *row.ArtistArtSource != "stub-artist" { wantSource string
t.Errorf("source = %v, want 'stub-artist'", row.ArtistArtSource) wantAsked bool
} }{
} {"no source yet", "", 0, "stub-artist", true},
{"art already found", "theaudiodb", current, "theaudiodb", false},
func TestEnrichArtist_FoundSource_Skip(t *testing.T) { {"none under the current providers", "none", current, "none", false},
pool := dbtest.Pool(t) {"none under older providers", "none", current - 1, "stub-artist", true},
ctx := context.Background() } {
q := dbq.New(pool) artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("0000000%d-1111-1111-1111-111111111111", i))
if tc.source != "" {
resetRegistryForTests() src := tc.source
t.Cleanup(resetRegistryForTests) if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{
ID: artistID, ArtistArtSource: &src, ArtistArtSourcesVersion: tc.version,
stub := &stubArtistProvider{ }); err != nil {
fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, t.Fatalf("%s: set: %v", tc.name, err)
thumb: []byte("should_not_write"), }
}
Register(stub)
e := newTestEnricher(t, pool)
artistID := insertArtist(t, q, ctx, "Found Artist", "22222222-2222-2222-2222-222222222222")
// Pre-mark with a "found" source.
src := "theaudiodb"
if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{
ID: artistID,
ArtistArtSource: &src,
ArtistArtSourcesVersion: e.settings.CurrentVersion(),
}); err != nil {
t.Fatalf("set: %v", err)
}
dataDir := t.TempDir()
if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Fatalf("EnrichArtist: %v", err)
}
// Source must remain 'theaudiodb'; no files should have been written.
row, err := q.GetArtistByID(ctx, artistID)
if err != nil {
t.Fatalf("GetArtistByID: %v", err)
}
if row.ArtistArtSource == nil || *row.ArtistArtSource != "theaudiodb" {
t.Errorf("source = %v, want 'theaudiodb' (preserved)", row.ArtistArtSource)
}
thumbPath := filepath.Join(dataDir, "artist-art", uuidString(artistID), "thumb.jpg")
if _, err := os.Stat(thumbPath); !os.IsNotExist(err) {
t.Errorf("expected no thumb.jpg (skip), got stat err = %v", err)
}
}
func TestEnrichArtist_NoneCurrentVersion_Skip(t *testing.T) {
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
resetRegistryForTests()
t.Cleanup(resetRegistryForTests)
stub := &stubArtistProvider{
fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true},
thumb: []byte("should_not_write"),
}
Register(stub)
e := newTestEnricher(t, pool)
artistID := insertArtist(t, q, ctx, "None Current Artist", "33333333-3333-3333-3333-333333333333")
src := "none"
if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{
ID: artistID,
ArtistArtSource: &src,
ArtistArtSourcesVersion: e.settings.CurrentVersion(),
}); err != nil {
t.Fatalf("set: %v", err)
}
dataDir := t.TempDir()
if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Fatalf("EnrichArtist: %v", err)
}
// Source must remain 'none' at current version.
row, err := q.GetArtistByID(ctx, artistID)
if err != nil {
t.Fatalf("GetArtistByID: %v", err)
}
if row.ArtistArtSource == nil || *row.ArtistArtSource != "none" {
t.Errorf("source = %v, want 'none' (skip — current version)", row.ArtistArtSource)
}
}
func TestEnrichArtist_NoneStaleVersion_FlipAndRetry(t *testing.T) {
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
resetRegistryForTests()
t.Cleanup(resetRegistryForTests)
stub := &stubArtistProvider{
fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true},
thumb: []byte("retry_thumb"),
fanart: []byte("retry_fanart"),
}
Register(stub)
e := newTestEnricher(t, pool)
artistID := insertArtist(t, q, ctx, "Stale None Artist", "44444444-4444-4444-4444-444444444444")
// Set 'none' with a stale version (currentVersion - 1).
staleVersion := e.settings.CurrentVersion() - 1
src := "none"
if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{
ID: artistID,
ArtistArtSource: &src,
ArtistArtSourcesVersion: staleVersion,
}); err != nil {
t.Fatalf("set stale none: %v", err)
}
dataDir := t.TempDir()
if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Fatalf("EnrichArtist: %v", err)
}
row, err := q.GetArtistByID(ctx, artistID)
if err != nil {
t.Fatalf("GetArtistByID: %v", err)
}
// Stale 'none' should be flipped and re-enriched; stub succeeds so
// source becomes the provider ID.
if row.ArtistArtSource == nil || *row.ArtistArtSource != "stub-artist" {
t.Errorf("source = %v, want 'stub-artist' (stale none flipped and retried)", row.ArtistArtSource)
}
}
// --- Atomicity: thumb-only / fanart-only ---
func TestEnrichArtist_ThumbOnly_ThumbPathSetFanartNull(t *testing.T) {
pool := dbtest.Pool(t)
ctx := context.Background()
q := dbq.New(pool)
resetRegistryForTests()
t.Cleanup(resetRegistryForTests)
stub := &stubArtistProvider{
fakeProvider: fakeProvider{id: "thumb-only-provider", defaultOn: true},
thumb: []byte("thumb_only"),
fanart: nil,
}
Register(stub)
e := newTestEnricher(t, pool)
artistID := insertArtist(t, q, ctx, "Thumb Only Artist", "55555555-5555-5555-5555-555555555555")
dataDir := t.TempDir()
if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Fatalf("EnrichArtist: %v", err)
}
row, err := q.GetArtistByID(ctx, artistID)
if err != nil {
t.Fatalf("GetArtistByID: %v", err)
}
if row.ArtistArtSource == nil || *row.ArtistArtSource != "thumb-only-provider" {
t.Errorf("source = %v, want 'thumb-only-provider'", row.ArtistArtSource)
}
if row.ArtistThumbPath == nil {
t.Errorf("artist_thumb_path is nil, want a path")
}
if row.ArtistFanartPath != nil {
t.Errorf("artist_fanart_path = %v, want nil (fanart not provided)", row.ArtistFanartPath)
}
if row.ArtistThumbPath != nil {
body, rerr := os.ReadFile(*row.ArtistThumbPath)
if rerr != nil {
t.Fatalf("read thumb: %v", rerr)
} }
if string(body) != "thumb_only" { if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Errorf("thumb content = %q, want 'thumb_only'", string(body)) t.Fatalf("%s: EnrichArtist: %v", tc.name, err)
}
row, err := q.GetArtistByID(ctx, artistID)
if err != nil {
t.Fatal(err)
}
if row.ArtistArtSource == nil || *row.ArtistArtSource != tc.wantSource {
t.Errorf("%s: source = %v, want %q", tc.name, row.ArtistArtSource, tc.wantSource)
}
_, statErr := os.Stat(filepath.Join(dataDir, "artist-art", uuidString(artistID), "thumb.jpg"))
if asked := statErr == nil; asked != tc.wantAsked {
t.Errorf("%s: thumb written = %v, want %v", tc.name, asked, tc.wantAsked)
} }
} }
} }
func TestEnrichArtist_FanartOnly_FanartPathSetThumbNull(t *testing.T) { // A provider with only one of the two pictures still settles the artist as
// found: the picture it has is written and its path set, and the other path
// stays NULL so the clients fall back rather than load a missing file.
func TestEnrichArtist_OnePictureOfTwo(t *testing.T) {
pool := dbtest.Pool(t) pool := dbtest.Pool(t)
ctx := context.Background() ctx := context.Background()
q := dbq.New(pool) q := dbq.New(pool)
resetRegistryForTests() resetRegistryForTests()
t.Cleanup(resetRegistryForTests) t.Cleanup(resetRegistryForTests)
stub := &stubArtistProvider{fakeProvider: fakeProvider{id: "one-picture", defaultOn: true}}
stub := &stubArtistProvider{
fakeProvider: fakeProvider{id: "fanart-only-provider", defaultOn: true},
thumb: nil,
fanart: []byte("fanart_only"),
}
Register(stub) Register(stub)
e := newTestEnricher(t, pool) e := newTestEnricher(t, pool)
artistID := insertArtist(t, q, ctx, "Fanart Only Artist", "66666666-6666-6666-6666-666666666666")
dataDir := t.TempDir() dataDir := t.TempDir()
if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
t.Fatalf("EnrichArtist: %v", err)
}
row, err := q.GetArtistByID(ctx, artistID) for i, tc := range []struct {
if err != nil { name string
t.Fatalf("GetArtistByID: %v", err) thumb, fanart []byte
} }{
if row.ArtistArtSource == nil || *row.ArtistArtSource != "fanart-only-provider" { {"a thumbnail only", []byte("thumb_only"), nil},
t.Errorf("source = %v, want 'fanart-only-provider'", row.ArtistArtSource) {"fanart only", nil, []byte("fanart_only")},
} } {
if row.ArtistThumbPath != nil { stub.thumb, stub.fanart = tc.thumb, tc.fanart
t.Errorf("artist_thumb_path = %v, want nil (thumb not provided)", row.ArtistThumbPath) artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("5555555%d-5555-5555-5555-555555555555", i))
} if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil {
if row.ArtistFanartPath == nil { t.Fatalf("%s: EnrichArtist: %v", tc.name, err)
t.Errorf("artist_fanart_path is nil, want a path") }
row, err := q.GetArtistByID(ctx, artistID)
if err != nil {
t.Fatal(err)
}
if row.ArtistArtSource == nil || *row.ArtistArtSource != "one-picture" {
t.Errorf("%s: source = %v, want one-picture", tc.name, row.ArtistArtSource)
}
for _, pic := range []struct {
kind string
path *string
want []byte
}{{"thumbnail", row.ArtistThumbPath, tc.thumb}, {"fanart", row.ArtistFanartPath, tc.fanart}} {
if pic.want == nil {
if pic.path != nil {
t.Errorf("%s: %s path = %q, want NULL", tc.name, pic.kind, *pic.path)
}
continue
}
if pic.path == nil {
t.Errorf("%s: %s path is NULL", tc.name, pic.kind)
continue
}
if body, err := os.ReadFile(*pic.path); err != nil || string(body) != string(pic.want) {
t.Errorf("%s: %s file = %q, %v; want %q", tc.name, pic.kind, body, err, pic.want)
}
}
} }
} }
-13
View File
@@ -25,19 +25,6 @@ func newDeezerTestProvider(t *testing.T, baseURL string) *deezerProvider {
return p return p
} }
func TestDeezer_ID(t *testing.T) {
p := &deezerProvider{}
if p.ID() != "deezer" {
t.Errorf("ID = %q, want deezer", p.ID())
}
if p.RequiresAPIKey() {
t.Error("RequiresAPIKey = true, want false")
}
if !p.DefaultEnabled() {
t.Error("DefaultEnabled = false, want true")
}
}
func TestDeezer_FetchArtistArt_Success(t *testing.T) { func TestDeezer_FetchArtistArt_Success(t *testing.T) {
mux := http.NewServeMux() mux := http.NewServeMux()
srv := httptest.NewServer(mux) srv := httptest.NewServer(mux)
+24 -89
View File
@@ -29,19 +29,6 @@ func newLastfmTestProvider(t *testing.T, baseURL, key string) *lastfmProvider {
// ── Identity / metadata ────────────────────────────────────────────────────── // ── Identity / metadata ──────────────────────────────────────────────────────
func TestLastfm_ID(t *testing.T) {
p := &lastfmProvider{}
if p.ID() != "lastfm" {
t.Errorf("ID = %q, want lastfm", p.ID())
}
if !p.RequiresAPIKey() {
t.Error("RequiresAPIKey = false, want true")
}
if p.DefaultEnabled() {
t.Error("DefaultEnabled = true, want false")
}
}
// ── FetchArtistArt — happy paths ───────────────────────────────────────────── // ── FetchArtistArt — happy paths ─────────────────────────────────────────────
func TestLastfm_FetchArtistArt_ByMBID(t *testing.T) { func TestLastfm_FetchArtistArt_ByMBID(t *testing.T) {
@@ -131,23 +118,6 @@ func TestLastfm_FetchArtistArt_PlaceholderImage(t *testing.T) {
} }
} }
func TestLastfm_FetchArtistArt_AlbumPlaceholderImage(t *testing.T) {
// Second known placeholder hash (album cover default).
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"artist":{"name":"Y","image":[
{"#text":"https://lastfm.freetls.fastly.net/i/u/300x300/c6f59c1e5e7240a4c0d427abd71f3dbb.jpg","size":"extralarge"}
]}}`))
}))
defer srv.Close()
p := newLastfmTestProvider(t, srv.URL+"/", "test-key")
_, _, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "Y"})
if !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound for album placeholder hash", err)
}
}
func TestLastfm_FetchArtistArt_EmptyImageArray(t *testing.T) { func TestLastfm_FetchArtistArt_EmptyImageArray(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json") w.Header().Set("Content-Type", "application/json")
@@ -177,42 +147,31 @@ func TestLastfm_FetchArtistArt_ErrorResponse(t *testing.T) {
} }
} }
func TestLastfm_FetchArtistArt_EmptyAPIKey(t *testing.T) { // Last.fm answers "not found" without a request when it is switched off, has
// Enabled but no key: every call must return ErrNotFound, not a network error. // no key, or is given nothing to look up, rather than failing on the network.
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})} func TestLastfm_AnswersNotFoundWithoutAsking(t *testing.T) {
p.enabled.Store(true) provider := func(enabled bool, key string) *lastfmProvider {
emptyKey := "" p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm",
p.apiKey.Store(&emptyKey) HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
p.enabled.Store(enabled)
_, _, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "X"}) p.apiKey.Store(&key)
if !errors.Is(err, ErrNotFound) { return p
t.Errorf("err = %v, want ErrNotFound when API key is empty", err)
} }
} ctx := context.Background()
album := AlbumRef{ArtistName: "X", AlbumTitle: "Y"}
func TestLastfm_FetchArtistArt_Disabled(t *testing.T) { for _, tc := range []struct {
// Key set but disabled. name string
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})} call func() error
// enabled defaults to false }{
key := "some-key" {"artist art with no key", func() error { _, _, err := provider(true, "").FetchArtistArt(ctx, ArtistRef{Name: "X"}); return err }},
p.apiKey.Store(&key) {"artist art while off", func() error { _, _, err := provider(false, "k").FetchArtistArt(ctx, ArtistRef{Name: "X"}); return err }},
{"artist art with no name or MBID", func() error { _, _, err := provider(true, "k").FetchArtistArt(ctx, ArtistRef{}); return err }},
_, _, err := p.FetchArtistArt(context.Background(), ArtistRef{Name: "X"}) {"album cover with no key", func() error { _, err := provider(true, "").FetchAlbumCover(ctx, album); return err }},
if !errors.Is(err, ErrNotFound) { {"album cover while off", func() error { _, err := provider(false, "k").FetchAlbumCover(ctx, album); return err }},
t.Errorf("err = %v, want ErrNotFound when disabled", err) } {
} if err := tc.call(); !errors.Is(err, ErrNotFound) {
} t.Errorf("%s: err = %v, want ErrNotFound", tc.name, err)
}
func TestLastfm_FetchArtistArt_EmptyRefs(t *testing.T) {
// Neither MBID nor Name: ErrNotFound without making any HTTP call.
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
p.enabled.Store(true)
key := "test-key"
p.apiKey.Store(&key)
_, _, err := p.FetchArtistArt(context.Background(), ArtistRef{})
if !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound for empty ArtistRef", err)
} }
} }
@@ -321,30 +280,6 @@ func TestLastfm_FetchAlbumCover_MissingFields(t *testing.T) {
} }
} }
func TestLastfm_FetchAlbumCover_EmptyAPIKey(t *testing.T) {
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
p.enabled.Store(true)
emptyKey := ""
p.apiKey.Store(&emptyKey)
_, err := p.FetchAlbumCover(context.Background(), AlbumRef{ArtistName: "X", AlbumTitle: "Y"})
if !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound when API key is empty", err)
}
}
func TestLastfm_FetchAlbumCover_Disabled(t *testing.T) {
p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})}
// enabled defaults to false
key := "some-key"
p.apiKey.Store(&key)
_, err := p.FetchAlbumCover(context.Background(), AlbumRef{ArtistName: "X", AlbumTitle: "Y"})
if !errors.Is(err, ErrNotFound) {
t.Errorf("err = %v, want ErrNotFound when disabled", err)
}
}
// ── Rate-limit serialization ───────────────────────────────────────────────── // ── Rate-limit serialization ─────────────────────────────────────────────────
// lastfmTestPeriod is providers.LastfmPacer's spacing. // lastfmTestPeriod is providers.LastfmPacer's spacing.
-18
View File
@@ -28,24 +28,6 @@ func newMBCAAProviderForTest(t *testing.T, mockURL string) *mbcaaProvider {
return p return p
} }
func TestMBCAAProvider_ID(t *testing.T) {
resetRegistryForTests()
defer resetRegistryForTests()
p := newMBCAAProvider(FetcherConfig{})
if p.ID() != "mbcaa" {
t.Errorf("ID = %q, want mbcaa", p.ID())
}
if p.DisplayName() != "Cover Art Archive" {
t.Errorf("DisplayName = %q, want Cover Art Archive", p.DisplayName())
}
if p.RequiresAPIKey() {
t.Error("RequiresAPIKey = true, want false")
}
if !p.DefaultEnabled() {
t.Error("DefaultEnabled = false, want true")
}
}
func TestMBCAAProvider_FetchAlbumCover_Success(t *testing.T) { func TestMBCAAProvider_FetchAlbumCover_Success(t *testing.T) {
imageBody := []byte("FAKE_JPEG") imageBody := []byte("FAKE_JPEG")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+23
View File
@@ -114,3 +114,26 @@ func TestCapabilityFiltering(t *testing.T) {
t.Errorf("AlbumCoverProvider[0].ID = %q, want %q", albumProviders[0].ID(), "alb") t.Errorf("AlbumCoverProvider[0].ID = %q, want %q", albumProviders[0].ID(), "alb")
} }
} }
// Each provider's identity and out-of-the-box state. Settings boot reads
// DefaultEnabled to decide which providers a new server asks, and the admin
// screen reads RequiresAPIKey to decide which ask for a key.
func TestProviders_IdentityAndDefaults(t *testing.T) {
resetRegistryForTests()
defer resetRegistryForTests()
for _, tc := range []struct {
p Provider
id string
needsKey, enabledNew bool
}{
{newMBCAAProvider(FetcherConfig{}), "mbcaa", false, true},
{&theAudioDBProvider{}, "theaudiodb", true, true},
{&deezerProvider{}, "deezer", false, true},
{&lastfmProvider{}, "lastfm", true, false},
} {
if tc.p.ID() != tc.id || tc.p.RequiresAPIKey() != tc.needsKey || tc.p.DefaultEnabled() != tc.enabledNew {
t.Errorf("%s: id %q, needs a key %v, on by default %v; want %q, %v, %v", tc.id,
tc.p.ID(), tc.p.RequiresAPIKey(), tc.p.DefaultEnabled(), tc.id, tc.needsKey, tc.enabledNew)
}
}
}
@@ -39,21 +39,6 @@ func newTheAudioDBProviderForTest(t *testing.T, mockURL string) *theAudioDBProvi
return p return p
} }
func TestTheAudioDB_ID(t *testing.T) {
resetRegistryForTests()
defer resetRegistryForTests()
p := &theAudioDBProvider{}
if p.ID() != "theaudiodb" {
t.Errorf("ID = %q, want theaudiodb", p.ID())
}
if !p.RequiresAPIKey() {
t.Error("RequiresAPIKey = false, want true")
}
if !p.DefaultEnabled() {
t.Error("DefaultEnabled = false, want true")
}
}
func TestTheAudioDB_FetchAlbumCover_Success(t *testing.T) { func TestTheAudioDB_FetchAlbumCover_Success(t *testing.T) {
imageBody := []byte("FAKE_JPEG") imageBody := []byte("FAKE_JPEG")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+23 -70
View File
@@ -70,79 +70,32 @@ func TestHealthz_IncludesMinClientVersion(t *testing.T) {
} }
} }
func TestRouter_ServesSPAAtRoot(t *testing.T) { // The web app is served at / and at any deep link the client router owns,
// but an unknown /api or /rest path is a 404 that is never HTML, so an API
// client never parses the web app as an answer.
func TestRouter_TheWebAppAndTheAPIsKeepTheirOwnPaths(t *testing.T) {
s := New(slog.New(slog.NewTextHandler(io.Discard, nil)), nil, nil, subsonic.Config{}, config.EventsConfig{}, config.RecommendationConfig{}, "", config.BrandingConfig{}, nil, nil, nil, library.RunScanConfig{}) s := New(slog.New(slog.NewTextHandler(io.Discard, nil)), nil, nil, subsonic.Config{}, config.EventsConfig{}, config.RecommendationConfig{}, "", config.BrandingConfig{}, nil, nil, nil, library.RunScanConfig{})
ts := httptest.NewServer(s.Router()) ts := httptest.NewServer(s.Router())
defer ts.Close() defer ts.Close()
for _, tc := range []struct {
resp, err := http.Get(ts.URL + "/") path string
if err != nil { wantCode int
t.Fatalf("GET /: %v", err) wantHTML bool
} }{
defer func() { _ = resp.Body.Close() }() {"/", http.StatusOK, true},
{"/artists/00000000-0000-0000-0000-000000000001", http.StatusOK, true},
if resp.StatusCode != http.StatusOK { {"/api/does-not-exist", http.StatusNotFound, false},
t.Errorf("status = %d, want 200", resp.StatusCode) {"/rest/does-not-exist", http.StatusNotFound, false},
} } {
if ct := resp.Header.Get("Content-Type"); !strings.Contains(ct, "text/html") { resp, err := http.Get(ts.URL + tc.path)
t.Errorf("Content-Type = %q, want text/html*", ct) if err != nil {
} t.Fatalf("GET %s: %v", tc.path, err)
} }
_ = resp.Body.Close()
func TestRouter_DeepLinkFallbackReturnsSPA(t *testing.T) { isHTML := strings.Contains(resp.Header.Get("Content-Type"), "text/html")
s := New(slog.New(slog.NewTextHandler(io.Discard, nil)), nil, nil, subsonic.Config{}, config.EventsConfig{}, config.RecommendationConfig{}, "", config.BrandingConfig{}, nil, nil, nil, library.RunScanConfig{}) if resp.StatusCode != tc.wantCode || isHTML != tc.wantHTML {
ts := httptest.NewServer(s.Router()) t.Errorf("GET %s: status %d, HTML %v; want %d, HTML %v", tc.path, resp.StatusCode, isHTML, tc.wantCode, tc.wantHTML)
defer ts.Close() }
resp, err := http.Get(ts.URL + "/artists/00000000-0000-0000-0000-000000000001")
if err != nil {
t.Fatalf("GET deep link: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
t.Errorf("status = %d, want 200", resp.StatusCode)
}
if ct := resp.Header.Get("Content-Type"); !strings.Contains(ct, "text/html") {
t.Errorf("Content-Type = %q, want text/html*", ct)
}
}
func TestRouter_APIPathNotSwallowedBySPA(t *testing.T) {
s := New(slog.New(slog.NewTextHandler(io.Discard, nil)), nil, nil, subsonic.Config{}, config.EventsConfig{}, config.RecommendationConfig{}, "", config.BrandingConfig{}, nil, nil, nil, library.RunScanConfig{})
ts := httptest.NewServer(s.Router())
defer ts.Close()
resp, err := http.Get(ts.URL + "/api/does-not-exist")
if err != nil {
t.Fatalf("GET /api/does-not-exist: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("status = %d, want 404", resp.StatusCode)
}
if ct := resp.Header.Get("Content-Type"); strings.Contains(ct, "text/html") {
t.Errorf("Content-Type = %q; /api/* must never return text/html", ct)
}
}
func TestRouter_RestPathNotSwallowedBySPA(t *testing.T) {
s := New(slog.New(slog.NewTextHandler(io.Discard, nil)), nil, nil, subsonic.Config{}, config.EventsConfig{}, config.RecommendationConfig{}, "", config.BrandingConfig{}, nil, nil, nil, library.RunScanConfig{})
ts := httptest.NewServer(s.Router())
defer ts.Close()
resp, err := http.Get(ts.URL + "/rest/does-not-exist")
if err != nil {
t.Fatalf("GET /rest/does-not-exist: %v", err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("status = %d, want 404", resp.StatusCode)
}
if ct := resp.Header.Get("Content-Type"); strings.Contains(ct, "text/html") {
t.Errorf("Content-Type = %q; /rest/* must never return text/html", ct)
} }
} }
+16 -39
View File
@@ -1,44 +1,21 @@
package subsonic package subsonic
import ( import "testing"
"crypto/md5"
"encoding/hex"
"testing"
)
func TestDecodePasswordEnc(t *testing.T) { // A Subsonic app sends its password as plain text or hex-encoded behind
out, err := decodePassword("enc:68656c6c6f") // "enc:"; malformed hex is an error rather than a wrong password.
if err != nil { func TestDecodePassword(t *testing.T) {
t.Fatalf("decode: %v", err) for _, tc := range []struct {
} in, want string
if out != "hello" { err bool
t.Errorf("decode = %q, want hello", out) }{
} {"enc:68656c6c6f", "hello", false},
} {"hunter2", "hunter2", false},
{"enc:zzzz", "", true},
func TestDecodePasswordPlain(t *testing.T) { } {
out, err := decodePassword("hunter2") out, err := decodePassword(tc.in)
if err != nil || out != "hunter2" { if (err != nil) != tc.err || (!tc.err && out != tc.want) {
t.Errorf("plain passthrough = %q, %v", out, err) t.Errorf("decodePassword(%q) = %q, %v; want %q (error %v)", tc.in, out, err, tc.want, tc.err)
} }
}
func TestDecodePasswordBadHex(t *testing.T) {
if _, err := decodePassword("enc:zzzz"); err == nil {
t.Error("expected error for malformed enc: prefix")
}
}
// TestTokenMD5Derivation documents the t = md5(password + salt) construction
// so regressions in the auth path surface as a failing checksum rather than a
// 40/wrong-credentials response that could be mistaken for bad inputs.
func TestTokenMD5Derivation(t *testing.T) {
password := "hunter2"
salt := "NaClz"
sum := md5.Sum([]byte(password + salt))
want := hex.EncodeToString(sum[:])
const expected = "91b894c3c9af9c16bec1b3f771e31462"
if want != expected {
t.Errorf("md5(password+salt) = %s, want %s", want, expected)
} }
} }
+43 -71
View File
@@ -13,78 +13,50 @@ import (
"github.com/Fabled-Sword/minstrel/internal/db/dbq" "github.com/Fabled-Sword/minstrel/internal/db/dbq"
) )
func TestHandleGetUser_Self(t *testing.T) { // getUser describes the caller, or for an admin any user asked about. The
user := dbq.User{Username: "alice", IsAdmin: false} // stream role is always on, since clients disable playback without it; admin
w, body := callGetUser(t, user, "") // and settings roles follow the user described, not the caller. A non-admin
// asking about someone else is refused, an unknown name is not found, and
if w.Code != http.StatusOK { // asking about yourself by name needs no lookup (none of the cases below
t.Fatalf("status = %d, want 200", w.Code) // that name the caller supply a known user).
} func TestHandleGetUser(t *testing.T) {
if body.Resp.Status != "ok" { alice := dbq.User{Username: "alice"}
t.Errorf("status = %q, want ok", body.Resp.Status)
}
if body.Resp.User.Username != "alice" {
t.Errorf("username = %q, want alice", body.Resp.User.Username)
}
if body.Resp.User.AdminRole {
t.Error("non-admin should not have admin role")
}
if !body.Resp.User.StreamRole {
t.Error("stream role must be on so clients enable playback")
}
}
func TestHandleGetUser_AdminGetsAdminRole(t *testing.T) {
admin := dbq.User{Username: "admin", IsAdmin: true} admin := dbq.User{Username: "admin", IsAdmin: true}
_, body := callGetUser(t, admin, "") bob := dbq.User{Username: "bob"}
if !body.Resp.User.AdminRole || !body.Resp.User.SettingsRole { for _, tc := range []struct {
t.Errorf("admin/settings roles = %v/%v, want true/true", name string
body.Resp.User.AdminRole, body.Resp.User.SettingsRole) caller dbq.User
} asked string
} known []dbq.User
wantErr int // 0 for success
func TestHandleGetUser_NonAdminCannotLookupOthers(t *testing.T) { wantUser string
user := dbq.User{Username: "alice", IsAdmin: false} wantAdmin bool
_, body := callGetUser(t, user, "bob") }{
if body.Resp.Status != "failed" || body.Resp.Error == nil || {"yourself", alice, "", nil, 0, "alice", false},
body.Resp.Error.Code != ErrNotAuthorized { {"yourself by name", alice, "alice", nil, 0, "alice", false},
t.Errorf("expected ErrNotAuthorized, got status=%q err=%+v", {"an admin, yourself", admin, "", nil, 0, "admin", true},
body.Resp.Status, body.Resp.Error) {"a non-admin asking about another", alice, "bob", []dbq.User{bob}, ErrNotAuthorized, "", false},
} {"an admin asking about another", admin, "bob", []dbq.User{bob}, 0, "bob", false},
} {"an admin asking about nobody", admin, "nobody", nil, ErrDataNotFound, "", false},
} {
func TestHandleGetUser_AdminLooksUpAnotherUser(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
admin := dbq.User{Username: "admin", IsAdmin: true} w, body := callGetUser(t, tc.caller, tc.asked, tc.known...)
bob := dbq.User{Username: "bob", IsAdmin: false} if w.Code != http.StatusOK {
_, body := callGetUser(t, admin, "bob", bob) t.Fatalf("HTTP status = %d, want 200 (Subsonic errors ride in the body)", w.Code)
if body.Resp.Status != "ok" { }
t.Fatalf("status = %q, want ok (err=%+v)", body.Resp.Status, body.Resp.Error) if tc.wantErr != 0 {
} if body.Resp.Status != "failed" || body.Resp.Error == nil || body.Resp.Error.Code != tc.wantErr {
if body.Resp.User.Username != "bob" { t.Errorf("status %q, error %+v; want error %d", body.Resp.Status, body.Resp.Error, tc.wantErr)
t.Errorf("username = %q, want bob: the answer must describe the user asked about, not the caller", body.Resp.User.Username) }
} return
if body.Resp.User.AdminRole || body.Resp.User.SettingsRole { }
t.Errorf("bob is not an admin, but the answer carries admin/settings roles %v/%v", u := body.Resp.User
body.Resp.User.AdminRole, body.Resp.User.SettingsRole) if body.Resp.Status != "ok" || u.Username != tc.wantUser || !u.StreamRole ||
} u.AdminRole != tc.wantAdmin || u.SettingsRole != tc.wantAdmin {
} t.Errorf("got status %q, user %+v; want %q, stream role, admin and settings roles %v",
body.Resp.Status, u, tc.wantUser, tc.wantAdmin)
func TestHandleGetUser_AdminLooksUpUnknownUser(t *testing.T) { }
admin := dbq.User{Username: "admin", IsAdmin: true} })
_, body := callGetUser(t, admin, "nobody")
if body.Resp.Status != "failed" || body.Resp.Error == nil ||
body.Resp.Error.Code != ErrDataNotFound {
t.Errorf("expected ErrDataNotFound, got status=%q err=%+v",
body.Resp.Status, body.Resp.Error)
}
}
func TestHandleGetUser_OwnUsernameNeedsNoLookup(t *testing.T) {
// No known users: a lookup would fail, so success proves none was made.
user := dbq.User{Username: "alice", IsAdmin: false}
_, body := callGetUser(t, user, "alice")
if body.Resp.Status != "ok" || body.Resp.User.Username != "alice" {
t.Errorf("status=%q username=%q, want ok/alice", body.Resp.Status, body.Resp.User.Username)
} }
} }