From 10b10b81798078b87f82c7df91237f3192b3ea6f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 13:58:07 -0500 Subject: [PATCH] test(coverart, subsonic, server): merge repeated cases into tables (#8298) - 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 --- internal/coverart/artist_enricher_test.go | 310 +++++------------- internal/coverart/provider_deezer_test.go | 13 - internal/coverart/provider_lastfm_test.go | 113 ++----- internal/coverart/provider_mbcaa_test.go | 18 - internal/coverart/provider_test.go | 23 ++ internal/coverart/provider_theaudiodb_test.go | 15 - internal/server/server_test.go | 93 ++---- internal/subsonic/auth_test.go | 55 +--- internal/subsonic/user_test.go | 114 +++---- 9 files changed, 214 insertions(+), 540 deletions(-) diff --git a/internal/coverart/artist_enricher_test.go b/internal/coverart/artist_enricher_test.go index 8cc6e58c..84e2ac4b 100644 --- a/internal/coverart/artist_enricher_test.go +++ b/internal/coverart/artist_enricher_test.go @@ -2,6 +2,7 @@ package coverart import ( "context" + "fmt" "os" "path/filepath" "testing" @@ -45,256 +46,115 @@ func insertArtist(t *testing.T, q *dbq.Queries, ctx context.Context, name, mbid return a.ID } -// --- Eligibility tests --- - -func TestEnrichArtist_NullSource_Eligible(t *testing.T) { +// 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 +// 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) ctx := context.Background() q := dbq.New(pool) - resetRegistryForTests() t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ + Register(&stubArtistProvider{ fakeProvider: fakeProvider{id: "stub-artist", defaultOn: true}, thumb: []byte("thumb_bytes"), fanart: []byte("fanart_bytes"), - } - Register(stub) - + }) e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Null Artist", "11111111-1111-1111-1111-111111111111") - + current := e.settings.CurrentVersion() 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 != "stub-artist" { - t.Errorf("source = %v, want 'stub-artist'", row.ArtistArtSource) - } -} - -func TestEnrichArtist_FoundSource_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, "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) + for i, tc := range []struct { + name string + source string // "" leaves it NULL + version int32 + wantSource string + wantAsked bool + }{ + {"no source yet", "", 0, "stub-artist", true}, + {"art already found", "theaudiodb", current, "theaudiodb", false}, + {"none under the current providers", "none", current, "none", false}, + {"none under older providers", "none", current - 1, "stub-artist", true}, + } { + artistID := insertArtist(t, q, ctx, tc.name, fmt.Sprintf("0000000%d-1111-1111-1111-111111111111", i)) + if tc.source != "" { + src := tc.source + if err := q.SetArtistArtWithVersion(ctx, dbq.SetArtistArtWithVersionParams{ + ID: artistID, ArtistArtSource: &src, ArtistArtSourcesVersion: tc.version, + }); err != nil { + t.Fatalf("%s: set: %v", tc.name, err) + } } - if string(body) != "thumb_only" { - t.Errorf("thumb content = %q, want 'thumb_only'", string(body)) + if err := e.EnrichArtist(ctx, artistID, dataDir); err != nil { + 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) ctx := context.Background() q := dbq.New(pool) - resetRegistryForTests() t.Cleanup(resetRegistryForTests) - - stub := &stubArtistProvider{ - fakeProvider: fakeProvider{id: "fanart-only-provider", defaultOn: true}, - thumb: nil, - fanart: []byte("fanart_only"), - } + stub := &stubArtistProvider{fakeProvider: fakeProvider{id: "one-picture", defaultOn: true}} Register(stub) - e := newTestEnricher(t, pool) - artistID := insertArtist(t, q, ctx, "Fanart Only Artist", "66666666-6666-6666-6666-666666666666") - 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 != "fanart-only-provider" { - t.Errorf("source = %v, want 'fanart-only-provider'", row.ArtistArtSource) - } - if row.ArtistThumbPath != nil { - t.Errorf("artist_thumb_path = %v, want nil (thumb not provided)", row.ArtistThumbPath) - } - if row.ArtistFanartPath == nil { - t.Errorf("artist_fanart_path is nil, want a path") + for i, tc := range []struct { + name string + thumb, fanart []byte + }{ + {"a thumbnail only", []byte("thumb_only"), nil}, + {"fanart only", nil, []byte("fanart_only")}, + } { + stub.thumb, stub.fanart = tc.thumb, tc.fanart + 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 { + 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 != "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) + } + } } } diff --git a/internal/coverart/provider_deezer_test.go b/internal/coverart/provider_deezer_test.go index f9da4bbb..f388b3b8 100644 --- a/internal/coverart/provider_deezer_test.go +++ b/internal/coverart/provider_deezer_test.go @@ -25,19 +25,6 @@ func newDeezerTestProvider(t *testing.T, baseURL string) *deezerProvider { 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) { mux := http.NewServeMux() srv := httptest.NewServer(mux) diff --git a/internal/coverart/provider_lastfm_test.go b/internal/coverart/provider_lastfm_test.go index c356f316..390546a3 100644 --- a/internal/coverart/provider_lastfm_test.go +++ b/internal/coverart/provider_lastfm_test.go @@ -29,19 +29,6 @@ func newLastfmTestProvider(t *testing.T, baseURL, key string) *lastfmProvider { // ── 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 ───────────────────────────────────────────── 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) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { 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) { - // Enabled but no key: every call must return ErrNotFound, not a network error. - 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.FetchArtistArt(context.Background(), ArtistRef{Name: "X"}) - if !errors.Is(err, ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound when API key is empty", err) +// Last.fm answers "not found" without a request when it is switched off, has +// no key, or is given nothing to look up, rather than failing on the network. +func TestLastfm_AnswersNotFoundWithoutAsking(t *testing.T) { + provider := func(enabled bool, key string) *lastfmProvider { + p := &lastfmProvider{client: providers.NewHTTPClient(providers.HTTPOptions{Name: "lastfm", + HTTPClient: &http.Client{Timeout: 5 * time.Second}, TreatAuthAsTransient: true, BaseBackoff: time.Millisecond})} + p.enabled.Store(enabled) + p.apiKey.Store(&key) + return p } -} - -func TestLastfm_FetchArtistArt_Disabled(t *testing.T) { - // Key set but disabled. - 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.FetchArtistArt(context.Background(), ArtistRef{Name: "X"}) - if !errors.Is(err, ErrNotFound) { - t.Errorf("err = %v, want ErrNotFound when disabled", 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) + ctx := context.Background() + album := AlbumRef{ArtistName: "X", AlbumTitle: "Y"} + for _, tc := range []struct { + name string + call func() error + }{ + {"artist art with no key", func() error { _, _, err := provider(true, "").FetchArtistArt(ctx, ArtistRef{Name: "X"}); return err }}, + {"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 }}, + {"album cover with no key", func() error { _, err := provider(true, "").FetchAlbumCover(ctx, album); return err }}, + {"album cover while off", func() error { _, err := provider(false, "k").FetchAlbumCover(ctx, album); return err }}, + } { + if err := tc.call(); !errors.Is(err, ErrNotFound) { + t.Errorf("%s: err = %v, want ErrNotFound", tc.name, 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 ───────────────────────────────────────────────── // lastfmTestPeriod is providers.LastfmPacer's spacing. diff --git a/internal/coverart/provider_mbcaa_test.go b/internal/coverart/provider_mbcaa_test.go index b837617e..0c2ad31e 100644 --- a/internal/coverart/provider_mbcaa_test.go +++ b/internal/coverart/provider_mbcaa_test.go @@ -28,24 +28,6 @@ func newMBCAAProviderForTest(t *testing.T, mockURL string) *mbcaaProvider { 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) { imageBody := []byte("FAKE_JPEG") srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/coverart/provider_test.go b/internal/coverart/provider_test.go index 4c828106..e668c56c 100644 --- a/internal/coverart/provider_test.go +++ b/internal/coverart/provider_test.go @@ -114,3 +114,26 @@ func TestCapabilityFiltering(t *testing.T) { 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) + } + } +} diff --git a/internal/coverart/provider_theaudiodb_test.go b/internal/coverart/provider_theaudiodb_test.go index b37c08b0..495f586b 100644 --- a/internal/coverart/provider_theaudiodb_test.go +++ b/internal/coverart/provider_theaudiodb_test.go @@ -39,21 +39,6 @@ func newTheAudioDBProviderForTest(t *testing.T, mockURL string) *theAudioDBProvi 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) { imageBody := []byte("FAKE_JPEG") srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/internal/server/server_test.go b/internal/server/server_test.go index 1aefc4a0..c218242d 100644 --- a/internal/server/server_test.go +++ b/internal/server/server_test.go @@ -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{}) ts := httptest.NewServer(s.Router()) defer ts.Close() - - resp, err := http.Get(ts.URL + "/") - if err != nil { - t.Fatalf("GET /: %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_DeepLinkFallbackReturnsSPA(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 + "/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) + for _, tc := range []struct { + path string + wantCode int + wantHTML bool + }{ + {"/", http.StatusOK, true}, + {"/artists/00000000-0000-0000-0000-000000000001", http.StatusOK, true}, + {"/api/does-not-exist", http.StatusNotFound, false}, + {"/rest/does-not-exist", http.StatusNotFound, false}, + } { + resp, err := http.Get(ts.URL + tc.path) + if err != nil { + t.Fatalf("GET %s: %v", tc.path, err) + } + _ = resp.Body.Close() + isHTML := strings.Contains(resp.Header.Get("Content-Type"), "text/html") + if resp.StatusCode != tc.wantCode || isHTML != tc.wantHTML { + t.Errorf("GET %s: status %d, HTML %v; want %d, HTML %v", tc.path, resp.StatusCode, isHTML, tc.wantCode, tc.wantHTML) + } } } diff --git a/internal/subsonic/auth_test.go b/internal/subsonic/auth_test.go index e2d0f3a1..c5030683 100644 --- a/internal/subsonic/auth_test.go +++ b/internal/subsonic/auth_test.go @@ -1,44 +1,21 @@ package subsonic -import ( - "crypto/md5" - "encoding/hex" - "testing" -) +import "testing" -func TestDecodePasswordEnc(t *testing.T) { - out, err := decodePassword("enc:68656c6c6f") - if err != nil { - t.Fatalf("decode: %v", err) - } - if out != "hello" { - t.Errorf("decode = %q, want hello", out) - } -} - -func TestDecodePasswordPlain(t *testing.T) { - out, err := decodePassword("hunter2") - if err != nil || out != "hunter2" { - t.Errorf("plain passthrough = %q, %v", out, 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) +// A Subsonic app sends its password as plain text or hex-encoded behind +// "enc:"; malformed hex is an error rather than a wrong password. +func TestDecodePassword(t *testing.T) { + for _, tc := range []struct { + in, want string + err bool + }{ + {"enc:68656c6c6f", "hello", false}, + {"hunter2", "hunter2", false}, + {"enc:zzzz", "", true}, + } { + out, err := decodePassword(tc.in) + if (err != nil) != tc.err || (!tc.err && out != tc.want) { + t.Errorf("decodePassword(%q) = %q, %v; want %q (error %v)", tc.in, out, err, tc.want, tc.err) + } } } diff --git a/internal/subsonic/user_test.go b/internal/subsonic/user_test.go index df2b4371..c9fa2008 100644 --- a/internal/subsonic/user_test.go +++ b/internal/subsonic/user_test.go @@ -13,78 +13,50 @@ import ( "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) -func TestHandleGetUser_Self(t *testing.T) { - user := dbq.User{Username: "alice", IsAdmin: false} - w, body := callGetUser(t, user, "") - - if w.Code != http.StatusOK { - t.Fatalf("status = %d, want 200", w.Code) - } - if body.Resp.Status != "ok" { - 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) { +// getUser describes the caller, or for an admin any user asked about. The +// stream role is always on, since clients disable playback without it; admin +// 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 +// asking about yourself by name needs no lookup (none of the cases below +// that name the caller supply a known user). +func TestHandleGetUser(t *testing.T) { + alice := dbq.User{Username: "alice"} admin := dbq.User{Username: "admin", IsAdmin: true} - _, body := callGetUser(t, admin, "") - if !body.Resp.User.AdminRole || !body.Resp.User.SettingsRole { - t.Errorf("admin/settings roles = %v/%v, want true/true", - body.Resp.User.AdminRole, body.Resp.User.SettingsRole) - } -} - -func TestHandleGetUser_NonAdminCannotLookupOthers(t *testing.T) { - user := dbq.User{Username: "alice", IsAdmin: false} - _, body := callGetUser(t, user, "bob") - if body.Resp.Status != "failed" || body.Resp.Error == nil || - body.Resp.Error.Code != ErrNotAuthorized { - t.Errorf("expected ErrNotAuthorized, got status=%q err=%+v", - body.Resp.Status, body.Resp.Error) - } -} - -func TestHandleGetUser_AdminLooksUpAnotherUser(t *testing.T) { - admin := dbq.User{Username: "admin", IsAdmin: true} - bob := dbq.User{Username: "bob", IsAdmin: false} - _, body := callGetUser(t, admin, "bob", bob) - if body.Resp.Status != "ok" { - t.Fatalf("status = %q, want ok (err=%+v)", body.Resp.Status, body.Resp.Error) - } - if body.Resp.User.Username != "bob" { - t.Errorf("username = %q, want bob: the answer must describe the user asked about, not the caller", body.Resp.User.Username) - } - 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", - body.Resp.User.AdminRole, body.Resp.User.SettingsRole) - } -} - -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) + bob := dbq.User{Username: "bob"} + for _, tc := range []struct { + name string + caller dbq.User + asked string + known []dbq.User + wantErr int // 0 for success + wantUser string + wantAdmin bool + }{ + {"yourself", alice, "", nil, 0, "alice", false}, + {"yourself by name", alice, "alice", nil, 0, "alice", false}, + {"an admin, yourself", admin, "", nil, 0, "admin", true}, + {"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}, + } { + t.Run(tc.name, func(t *testing.T) { + w, body := callGetUser(t, tc.caller, tc.asked, tc.known...) + if w.Code != http.StatusOK { + t.Fatalf("HTTP status = %d, want 200 (Subsonic errors ride in the body)", w.Code) + } + if tc.wantErr != 0 { + if body.Resp.Status != "failed" || body.Resp.Error == nil || body.Resp.Error.Code != tc.wantErr { + t.Errorf("status %q, error %+v; want error %d", body.Resp.Status, body.Resp.Error, tc.wantErr) + } + return + } + u := body.Resp.User + 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) + } + }) } }