diff --git a/internal/api/admin_cover_sources_test.go b/internal/api/admin_cover_sources_test.go index 27a61d09..70d7d2ec 100644 --- a/internal/api/admin_cover_sources_test.go +++ b/internal/api/admin_cover_sources_test.go @@ -6,7 +6,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -59,9 +58,6 @@ func testHandlersWithCoverSettings(t *testing.T) (*handlers, *coverart.SettingsS } func TestAdminListCoverSources_ReturnsRegisteredProviders(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -112,9 +108,6 @@ func TestAdminListCoverSources_ReturnsRegisteredProviders(t *testing.T) { } func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -144,9 +137,6 @@ func TestAdminUpdateCoverSource_FlippingEnabledBumpsVersion(t *testing.T) { } func TestAdminUpdateCoverSource_ReplacingAKeyDoesNotBump(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -185,9 +175,6 @@ func TestAdminUpdateCoverSource_ReplacingAKeyDoesNotBump(t *testing.T) { } func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) @@ -208,9 +195,6 @@ func TestAdminUpdateCoverSource_UnknownProvider404(t *testing.T) { } func TestAdminTestCoverSource_NotTestableReturnsOkFalse(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) diff --git a/internal/api/admin_coverage_test.go b/internal/api/admin_coverage_test.go index 0f4da6c3..6e8ff794 100644 --- a/internal/api/admin_coverage_test.go +++ b/internal/api/admin_coverage_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -25,9 +24,6 @@ func newAdminCoverageRouter(h *handlers) chi.Router { } func TestAdminLibraryCoverage_EmptyLibraryReturnsZeros(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "covgauge1", "pw", true) @@ -49,9 +45,6 @@ func TestAdminLibraryCoverage_EmptyLibraryReturnsZeros(t *testing.T) { } func TestAdminLibraryCoverage_MixedRowsReturnCorrectBuckets(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "covgauge2", "pw", true) diff --git a/internal/api/admin_coverart_research_test.go b/internal/api/admin_coverart_research_test.go index 8e76ee61..c6306028 100644 --- a/internal/api/admin_coverart_research_test.go +++ b/internal/api/admin_coverart_research_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -23,9 +22,6 @@ func newResearchRouter(h *handlers) chi.Router { } func TestAdminResearchMissingArt_BumpsAndReturnsVersion(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } coverart.ResetRegistryForTests() t.Cleanup(coverart.ResetRegistryForTests) diff --git a/internal/api/admin_covers_test.go b/internal/api/admin_covers_test.go index ac29e80b..4fdde6f5 100644 --- a/internal/api/admin_covers_test.go +++ b/internal/api/admin_covers_test.go @@ -6,7 +6,6 @@ import ( "log/slog" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -57,9 +56,6 @@ func testHandlersWithCovers(t *testing.T) (*handlers, *coverart.Enricher) { } func TestAdminAlbumRefetchCover_AdminOK(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlersWithCovers(t) admin := seedUser(t, h.pool, "rootuser", "pw", true) artist := seedArtist(t, h.pool, "TestArtist") @@ -81,9 +77,6 @@ func TestAdminAlbumRefetchCover_AdminOK(t *testing.T) { } func TestAdminBulkRefetchCovers_AdminStartsRefetch(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlersWithCovers(t) admin := seedUser(t, h.pool, "rootuser2", "pw", true) artist := seedArtist(t, h.pool, "TestArtist") diff --git a/internal/api/admin_invites_test.go b/internal/api/admin_invites_test.go index 03c81734..89057c8b 100644 --- a/internal/api/admin_invites_test.go +++ b/internal/api/admin_invites_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -25,9 +24,6 @@ func newAdminInvitesRouter(h *handlers) chi.Router { } func TestAdminInvites_CreateListDelete(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "invadmin", "pw", true) diff --git a/internal/api/admin_scan_test.go b/internal/api/admin_scan_test.go index de3621f7..e65a6f04 100644 --- a/internal/api/admin_scan_test.go +++ b/internal/api/admin_scan_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -24,9 +23,6 @@ func newAdminScanRouter(h *handlers) chi.Router { } func TestAdminScanStatus_NoRowReturnsEmpty(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rootscan", "pw", true) req := httptest.NewRequest(http.MethodGet, "/api/admin/scan/status", nil) @@ -46,9 +42,6 @@ func TestAdminScanStatus_NoRowReturnsEmpty(t *testing.T) { } func TestAdminScanStatus_RowReturnsValues(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rootscan2", "pw", true) if _, err := pool.Exec(context.Background(), ` @@ -81,9 +74,6 @@ func TestAdminScanStatus_RowReturnsValues(t *testing.T) { } func TestAdminTriggerScan_InFlightReturns409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rootscan3", "pw", true) if _, err := pool.Exec(context.Background(), ` diff --git a/internal/api/admin_smtp_test.go b/internal/api/admin_smtp_test.go index 3b78d477..b7864bb7 100644 --- a/internal/api/admin_smtp_test.go +++ b/internal/api/admin_smtp_test.go @@ -6,7 +6,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -26,9 +25,6 @@ func newAdminSMTPRouter(h *handlers) chi.Router { } func TestSMTPConfig_GetMasksPassword(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpadmin", "pw", true) @@ -56,9 +52,6 @@ func TestSMTPConfig_GetMasksPassword(t *testing.T) { } func TestSMTPConfig_UpdatePreservesPasswordWhenEmpty(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpupd", "pw", true) @@ -100,9 +93,6 @@ func TestSMTPConfig_UpdatePreservesPasswordWhenEmpty(t *testing.T) { } func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "smtpvalid", "pw", true) @@ -119,9 +109,6 @@ func TestSMTPConfig_UpdateValidatesEnabled(t *testing.T) { } func TestSMTPConfig_TestRequiresEmail(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) // Admin without email on file. admin := seedUser(t, pool, "noemail", "pw", true) diff --git a/internal/api/admin_tag_sources_test.go b/internal/api/admin_tag_sources_test.go index 66dc847c..f7b57c01 100644 --- a/internal/api/admin_tag_sources_test.go +++ b/internal/api/admin_tag_sources_test.go @@ -6,7 +6,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -57,9 +56,6 @@ func testHandlersWithTagSettings(t *testing.T) *handlers { } func TestAdminListTagSources_ReturnsRegisteredProviders(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(&apiTestTagProvider{id: "test-tag-prov", display: "Test Tag Provider"}) @@ -97,9 +93,6 @@ func TestAdminListTagSources_ReturnsRegisteredProviders(t *testing.T) { } func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(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(&apiTestTagProvider{id: "flip-tag", display: "Flip Tag"}) @@ -128,9 +121,6 @@ func TestAdminUpdateTagSource_FlippingEnabledBumpsVersion(t *testing.T) { } func TestAdminUpdateTagSource_ReplacingAKeyDoesNotBump(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(&apiTestTagProvider{id: "key-tag", display: "Key Tag"}) @@ -168,9 +158,6 @@ func TestAdminUpdateTagSource_ReplacingAKeyDoesNotBump(t *testing.T) { } func TestAdminUpdateTagSource_UnknownProvider404(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } tags.ResetRegistryForTests() t.Cleanup(tags.ResetRegistryForTests) @@ -190,9 +177,6 @@ func TestAdminUpdateTagSource_UnknownProvider404(t *testing.T) { } func TestAdminTestTagSource_NotTestableReturnsOkFalse(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(&apiTestTagProvider{id: "nontestable-tag", display: "Non-Testable Tag"}) diff --git a/internal/api/admin_users_test.go b/internal/api/admin_users_test.go index 6a49ff0c..ce9320e4 100644 --- a/internal/api/admin_users_test.go +++ b/internal/api/admin_users_test.go @@ -6,13 +6,13 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" "golang.org/x/crypto/bcrypt" "github.com/Fabled-Sword/minstrel/internal/auth" + "github.com/Fabled-Sword/minstrel/internal/db/dbq" ) func newAdminUsersRouter(h *handlers) chi.Router { @@ -30,9 +30,6 @@ func newAdminUsersRouter(h *handlers) chi.Router { } func TestAdminUsers_List(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "listadmin", "pw", true) @@ -56,9 +53,6 @@ func TestAdminUsers_List(t *testing.T) { } func TestAdminUsers_Promote(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "promadmin", "pw", true) target := seedUser(t, pool, "promtarget", "pw", false) @@ -83,56 +77,7 @@ func TestAdminUsers_Promote(t *testing.T) { } } -func TestAdminUsers_Demote_LastAdmin_Refused(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - // Reset to ensure exactly one admin exists. - if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { - t.Fatalf("reset: %v", err) - } - soleAdmin := seedUser(t, pool, "soleadmin", "pw", true) - - body := `{"is_admin": false}` - req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(soleAdmin.ID)+"/admin", - bytes.NewReader([]byte(body))) - req = withUser(req, soleAdmin) - rec := httptest.NewRecorder() - newAdminUsersRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusConflict { - t.Errorf("status = %d, want 409 (last_admin guard)", rec.Code) - } -} - -func TestAdminUsers_Demote_OtherAdmin_Allowed(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { - t.Fatalf("reset: %v", err) - } - caller := seedUser(t, pool, "caller", "pw", true) - target := seedUser(t, pool, "targetadmin", "pw", true) - - body := `{"is_admin": false}` - req := httptest.NewRequest(http.MethodPut, "/api/admin/users/"+uuidToString(target.ID)+"/admin", - bytes.NewReader([]byte(body))) - req = withUser(req, caller) - rec := httptest.NewRecorder() - newAdminUsersRouter(h).ServeHTTP(rec, req) - - if rec.Code != http.StatusOK { - t.Errorf("status = %d, want 200 (two admins exist; demoting one is fine); body=%s", rec.Code, rec.Body.String()) - } -} - func TestAdminCreateUser_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "creator", "pw", true) @@ -155,9 +100,6 @@ func TestAdminCreateUser_Happy(t *testing.T) { } func TestAdminCreateUser_DuplicateUsername_409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "duper", "pw", true) seedUser(t, pool, "existing", "pw", false) @@ -177,9 +119,6 @@ func TestAdminCreateUser_DuplicateUsername_409(t *testing.T) { } func TestAdminDeleteUser_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "delcaller", "pw", true) target := seedUser(t, pool, "deltarget", "pw", false) @@ -203,9 +142,6 @@ func TestAdminDeleteUser_Happy(t *testing.T) { } func TestAdminDeleteUser_LastAdmin_Refused(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { t.Fatalf("reset: %v", err) @@ -223,9 +159,6 @@ func TestAdminDeleteUser_LastAdmin_Refused(t *testing.T) { } func TestAdminResetPassword_Happy(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rcaller", "pw", true) target := seedUser(t, pool, "rtarget", "oldpw1234", false) @@ -252,9 +185,6 @@ func TestAdminResetPassword_Happy(t *testing.T) { } func TestAdminResetPassword_TooShort_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rsadm", "pw", true) target := seedUser(t, pool, "rstgt", "pw", false) @@ -272,9 +202,6 @@ func TestAdminResetPassword_TooShort_400(t *testing.T) { } func TestAdminResetPassword_SignsOutSubsonicApps(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) admin := seedUser(t, pool, "rsubadm", "pw", true) target := seedUser(t, pool, "rsubtgt", "oldpw1234", false) @@ -290,3 +217,31 @@ func TestAdminResetPassword_SignsOutSubsonicApps(t *testing.T) { } assertSubsonicSignedOut(t, h, target, before) } + +// An admin can take admin away from another admin, but never from the last +// one: the server always keeps someone who can manage it. +func TestAdminUsers_DemotingStopsAtTheLastAdmin(t *testing.T) { + h, pool := testHandlers(t) + if _, err := pool.Exec(context.Background(), "DELETE FROM users"); err != nil { + t.Fatalf("reset: %v", err) + } + caller := seedUser(t, pool, "caller", "pw", true) + other := seedUser(t, pool, "otheradmin", "pw", true) + + for _, step := range []struct { + target dbq.User + status int + }{ + {other, http.StatusOK}, // two admins: one can go + {caller, http.StatusConflict}, // the last admin stays + } { + req := withUser(httptest.NewRequest(http.MethodPut, + "/api/admin/users/"+uuidToString(step.target.ID)+"/admin", + bytes.NewReader([]byte(`{"is_admin": false}`))), caller) + rec := httptest.NewRecorder() + newAdminUsersRouter(h).ServeHTTP(rec, req) + if rec.Code != step.status { + t.Errorf("demote %s: status %d, want %d; body=%s", step.target.Username, rec.Code, step.status, rec.Body.String()) + } + } +} diff --git a/internal/api/auth_forgot_test.go b/internal/api/auth_forgot_test.go index 1fc149bd..638375b8 100644 --- a/internal/api/auth_forgot_test.go +++ b/internal/api/auth_forgot_test.go @@ -6,7 +6,6 @@ import ( "errors" "net/http" "net/http/httptest" - "os" "strings" "testing" @@ -34,9 +33,6 @@ func withPublicURL(t *testing.T, h *handlers, pool *pgxpool.Pool, url string) { // With no public URL set, a reset email is not sent at all, and the response // is still the same opaque 200. func TestForgotPassword_NoPublicURL_SendsNothing(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) fake := &mailer.FakeSender{} h.mailer = fake @@ -61,9 +57,6 @@ func TestForgotPassword_NoPublicURL_SendsNothing(t *testing.T) { } func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) fake := &mailer.FakeSender{} h.mailer = fake @@ -111,9 +104,6 @@ func TestForgotPassword_KnownEmail_SendsMail(t *testing.T) { } func TestForgotPassword_UnknownEmail_Returns200_NoSend(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) fake := &mailer.FakeSender{} h.mailer = fake @@ -133,9 +123,6 @@ func TestForgotPassword_UnknownEmail_Returns200_NoSend(t *testing.T) { } func TestForgotPassword_MailerFailure_StillReturns200(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) fake := &mailer.FakeSender{FailNext: errors.New("simulated SMTP failure")} h.mailer = fake diff --git a/internal/api/auth_register_test.go b/internal/api/auth_register_test.go index cc01a736..1ae630a5 100644 --- a/internal/api/auth_register_test.go +++ b/internal/api/auth_register_test.go @@ -6,7 +6,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "sync" "testing" @@ -34,9 +33,6 @@ func resetInvites(t *testing.T, h *handlers) { } func TestRegister_FirstUserBecomesAdmin(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) resetUsers(t, h) @@ -69,91 +65,7 @@ func TestRegister_FirstUserBecomesAdmin(t *testing.T) { } } -func TestRegister_InviteOnlyMode_RequiresToken(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - // Seed an admin user so we're past the empty-users state. - seedUser(t, pool, "existingadmin", "pw", true) - - body := `{"username":"newuser","password":"abcd1234"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400 (invite_required)", rec.Code) - } -} - -func TestRegister_InviteOnlyMode_ValidTokenSucceeds(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - resetInvites(t, h) - admin := seedUser(t, pool, "admin1", "pw", true) - // Insert a fresh invite directly. - token := "test-invite-abc123" - if _, err := pool.Exec(context.Background(), - `INSERT INTO user_invites (token, invited_by, expires_at) - VALUES ($1, $2, now() + interval '24 hours')`, - token, admin.ID, - ); err != nil { - t.Fatalf("seed invite: %v", err) - } - - body := `{"username":"invitee1","password":"abcd1234","invite_token":"` + token + `"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusOK { - t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String()) - } - // Invite redeemed? - var redeemedAt *string - if err := pool.QueryRow(context.Background(), - `SELECT redeemed_at::text FROM user_invites WHERE token = $1`, token, - ).Scan(&redeemedAt); err != nil { - t.Fatalf("verify redeem: %v", err) - } - if redeemedAt == nil { - t.Errorf("invite not redeemed after successful registration") - } - // New user is_admin = false? - var isAdmin bool - if err := pool.QueryRow(context.Background(), - `SELECT is_admin FROM users WHERE username = 'invitee1'`).Scan(&isAdmin); err != nil { - t.Fatalf("verify user: %v", err) - } - if isAdmin { - t.Errorf("new invitee marked as admin; only first user should be admin") - } -} - -func TestRegister_InviteOnlyMode_InvalidTokenRejects(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } - h, pool := testHandlers(t) - seedUser(t, pool, "adm", "pw", true) - - body := `{"username":"baduser","password":"abcd1234","invite_token":"nonexistent-token"}` - req := httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body))) - rec := httptest.NewRecorder() - h.handleRegister(rec, req) - - if rec.Code != http.StatusBadRequest { - t.Errorf("status = %d, want 400 (invite_invalid)", rec.Code) - } -} - func TestRegister_DuplicateUsername_409(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) resetUsers(t, h) resetInvites(t, h) @@ -207,9 +119,6 @@ func TestRegister_FirstAdminRace(t *testing.T) { // usernames are different, so users.username uniqueness doesn't // arbitrate. Both will see "no users yet" and both insert as // admin. Test asserts the at-least-one-admin invariant. - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) resetUsers(t, h) @@ -243,9 +152,6 @@ func TestRegister_FirstAdminRace(t *testing.T) { // With the gate on (as Mount sets it), the first account needs the setup // token from the log; a missing or wrong one is refused and creates nothing. func TestRegister_FirstUserNeedsSetupToken(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) resetUsers(t, h) token, err := auth.NewSetupToken() @@ -307,9 +213,6 @@ func TestSetupToken_MatchesOnlyItself(t *testing.T) { // Sign-ups racing on one invite make exactly one account: the others are // told the invite is used, and nothing of theirs is left behind. func TestRegister_OneInviteMakesOneAccountUnderARace(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, pool := testHandlers(t) resetInvites(t, h) admin := seedUser(t, pool, "raceadmin", "pw", true) @@ -360,3 +263,56 @@ func TestRegister_OneInviteMakesOneAccountUnderARace(t *testing.T) { t.Fatalf("%d accounts exist after the race, want 1", made) } } + +// Once an account exists, an invite is the only way in: a sign-up without +// one, or with a token that was never issued, is refused and creates no +// account. A valid invite makes an ordinary (non-admin) account and is +// marked redeemed. +func TestRegister_AfterTheFirstAccountAnInviteIsTheOnlyWayIn(t *testing.T) { + h, pool := testHandlers(t) + resetInvites(t, h) + admin := seedUser(t, pool, "admin1", "pw", true) + const token = "test-invite-abc123" + if _, err := pool.Exec(context.Background(), + `INSERT INTO user_invites (token, invited_by, expires_at) + VALUES ($1, $2, now() + interval '24 hours')`, token, admin.ID); err != nil { + t.Fatalf("seed invite: %v", err) + } + + for _, tc := range []struct { + username, inviteToken string + status int + }{ + {"noinvite", "", http.StatusBadRequest}, + {"badinvite", "nonexistent-token", http.StatusBadRequest}, + {"invitee", token, http.StatusOK}, + } { + body := `{"username":"` + tc.username + `","password":"abcd1234","invite_token":"` + tc.inviteToken + `"}` + rec := httptest.NewRecorder() + h.handleRegister(rec, httptest.NewRequest(http.MethodPost, "/api/auth/register", bytes.NewReader([]byte(body)))) + if rec.Code != tc.status { + t.Errorf("%s: status %d, want %d; body=%s", tc.username, rec.Code, tc.status, rec.Body.String()) + } + var accounts, admins int + if err := pool.QueryRow(context.Background(), + `SELECT count(*), count(*) FILTER (WHERE is_admin) FROM users WHERE username = $1`, + tc.username).Scan(&accounts, &admins); err != nil { + t.Fatalf("count accounts: %v", err) + } + wantAccounts := 0 + if tc.status == http.StatusOK { + wantAccounts = 1 + } + if accounts != wantAccounts || admins != 0 { + t.Errorf("%s: %d accounts (%d admin), want %d (0 admin)", tc.username, accounts, admins, wantAccounts) + } + } + var redeemed bool + if err := pool.QueryRow(context.Background(), + `SELECT redeemed_at IS NOT NULL FROM user_invites WHERE token = $1`, token).Scan(&redeemed); err != nil { + t.Fatalf("read invite: %v", err) + } + if !redeemed { + t.Errorf("the invite was not marked redeemed") + } +} diff --git a/internal/api/auth_reset_test.go b/internal/api/auth_reset_test.go index bc0cd151..ab6a2c8f 100644 --- a/internal/api/auth_reset_test.go +++ b/internal/api/auth_reset_test.go @@ -5,7 +5,6 @@ import ( "context" "net/http" "net/http/httptest" - "os" "testing" "time" @@ -14,9 +13,6 @@ import ( ) func TestResetPassword_Happy(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, "resetuser", "oldpw1234", false) @@ -61,9 +57,6 @@ func TestResetPassword_Happy(t *testing.T) { } func TestResetPassword_AlreadyUsed_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, "alreadyused", "pw", false) @@ -87,9 +80,6 @@ func TestResetPassword_AlreadyUsed_400(t *testing.T) { } func TestResetPassword_Expired_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, "expiredreset", "pw", false) @@ -113,9 +103,6 @@ func TestResetPassword_Expired_400(t *testing.T) { } func TestResetPassword_PasswordTooShort_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) body := `{"token":"any-token","new_password":"abc"}` req := httptest.NewRequest(http.MethodPost, "/api/auth/reset-password", @@ -128,9 +115,6 @@ func TestResetPassword_PasswordTooShort_400(t *testing.T) { } func TestResetPassword_BogusToken_400(t *testing.T) { - if os.Getenv("MINSTREL_TEST_DATABASE_URL") == "" { - t.Skip("MINSTREL_TEST_DATABASE_URL not set") - } h, _ := testHandlers(t) body := `{"token":"bogus-token","new_password":"abcd1234"}` @@ -147,9 +131,6 @@ func TestResetPassword_BogusToken_400(t *testing.T) { // A reset ends Subsonic apps' access too: they sign in with the API key or // the Subsonic password, which whoever had the account could have made. func TestResetPassword_SignsOutSubsonicApps(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, "resetsubsonic", "oldpw1234", false) giveSubsonicPassword(t, h, user) diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index 845adf3a..f2288e69 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -128,34 +128,6 @@ func TestHandleLogin_SuccessSetsCookieAndReturnsToken(t *testing.T) { } } -func TestHandleLogin_WrongPasswordReturns401(t *testing.T) { - h, pool := testHandlers(t) - seedUser(t, pool, "alice", "hunter2", false) - - body := strings.NewReader(`{"username":"test-alice","password":"wrong"}`) - req := httptest.NewRequest(http.MethodPost, "/api/auth/login", body) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - h.handleLogin(w, req) - - if w.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", w.Code) - } -} - -func TestHandleLogin_UnknownUserReturns401(t *testing.T) { - h, _ := testHandlers(t) - body := strings.NewReader(`{"username":"ghost","password":"whatever"}`) - req := httptest.NewRequest(http.MethodPost, "/api/auth/login", body) - req.Header.Set("Content-Type", "application/json") - w := httptest.NewRecorder() - h.handleLogin(w, req) - - if w.Code != http.StatusUnauthorized { - t.Errorf("status = %d, want 401", w.Code) - } -} - // A guesser who reaches the account limit is refused with 429 before any // password check, so even the right password is turned away until the window // passes, and the response says when to come back. @@ -284,3 +256,28 @@ func TestHandleLogout_BearerHeaderWithTrailingWhitespaceDeletesSession(t *testin t.Error("session row still present after bearer logout with trailing whitespace") } } + +// A wrong password and an unknown username get the same 401 and the same +// body, so a failed sign-in never tells anyone whether an account exists. +func TestHandleLogin_AWrongPasswordAndAnUnknownUserLookAlike(t *testing.T) { + h, pool := testHandlers(t) + seedUser(t, pool, "alice", "hunter2", false) + + var bodies []string + for _, creds := range []string{ + `{"username":"test-alice","password":"wrong"}`, + `{"username":"ghost","password":"whatever"}`, + } { + req := httptest.NewRequest(http.MethodPost, "/api/auth/login", strings.NewReader(creds)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + h.handleLogin(w, req) + if w.Code != http.StatusUnauthorized { + t.Errorf("%s: status %d, want 401", creds, w.Code) + } + bodies = append(bodies, w.Body.String()) + } + if bodies[0] != bodies[1] { + t.Errorf("the refusals differ: %q vs %q", bodies[0], bodies[1]) + } +} diff --git a/internal/api/client_assets_test.go b/internal/api/client_assets_test.go index bb8f6fc2..9fc8ca18 100644 --- a/internal/api/client_assets_test.go +++ b/internal/api/client_assets_test.go @@ -211,20 +211,6 @@ func TestClientVersion_MalformedSidecarErrorsRatherThanReportingNothing(t *testi } } -func TestClientAPK_401WhenUnauthenticated(t *testing.T) { - withClientAPKDir(t) - testResetClientAPKRateLimit() - h := &handlers{logger: slog.New(slog.NewTextHandler(io.Discard, nil))} - rr := httptest.NewRecorder() - // No user in context — middleware would block in prod; handler also - // rejects defensively in case the route ever lands outside the - // authed group by accident. - h.handleClientAPK(rr, httptest.NewRequest(http.MethodGet, "/api/client/apk", nil)) - if rr.Code != http.StatusUnauthorized { - t.Errorf("want 401, got %d", rr.Code) - } -} - func TestClientAPK_404WhenMissing(t *testing.T) { withClientAPKDir(t) testResetClientAPKRateLimit() diff --git a/internal/api/likes_test.go b/internal/api/likes_test.go index 11814e6b..95b20eee 100644 --- a/internal/api/likes_test.go +++ b/internal/api/likes_test.go @@ -38,44 +38,6 @@ func likesRouter(h *handlers) http.Handler { return r } -func TestLikeTrack_Idempotent(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "Copper Lanterns") - album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) - track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) - - w := callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)) - if w.Code != http.StatusOK { - t.Fatalf("first like: status = %d body=%s", w.Code, w.Body.String()) - } - w = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(track.ID)) - if w.Code != http.StatusOK { - t.Errorf("second like (idempotent): status = %d", w.Code) - } - var count int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM general_likes WHERE user_id=$1", user.ID).Scan(&count) - if count != 1 { - t.Errorf("rows = %d, want 1", count) - } -} - -func TestUnlikeTrack_IdempotentEvenWhenAbsent(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "Copper Lanterns") - album := seedAlbum(t, pool, artist.ID, "Harbour Street", 1969) - track := seedTrack(t, pool, album.ID, artist.ID, "Something", 3, 183_000) - - w := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(track.ID)) - if w.Code != http.StatusOK { - t.Errorf("status = %d", w.Code) - } -} - // A like is on the song, so its answer names every copy it reached, and an // unlike every copy it cleared, the tapped one first. func TestLikeTrack_AnswersEveryCopyOfTheSong(t *testing.T) { @@ -259,86 +221,52 @@ func TestLikeTrack_NoOpenPlayEvent_NoContextualLike(t *testing.T) { } } -func TestLikeTrack_RepeatedLike_NoDuplicate(t *testing.T) { +// Liking and unliking a track can be repeated safely. Unliking a track that +// was never liked is fine. A second like adds no row. An unlike removes the +// like and closes, but keeps, the contextual like written during the open +// play. Liking again opens a new contextual like, so the history grows. +func TestLikeTrack_LikeAndUnlikeRepeatSafelyAndKeepTheHistory(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) user := seedUser(t, pool, "alice", "x", false) artist := seedArtist(t, pool, "X") album := seedAlbum(t, pool, artist.ID, "X", 1990) playing := seedTrack(t, pool, album.ID, artist.ID, "Playing", 1, 100_000) - other := seedTrack(t, pool, album.ID, artist.ID, "Other", 2, 100_000) + liked := seedTrack(t, pool, album.ID, artist.ID, "Liked", 2, 100_000) + path := "/api/likes/tracks/" + uuidToString(liked.ID) - // Open play. + count := func(query string) int { + t.Helper() + var n int + if err := pool.QueryRow(context.Background(), query, user.ID, liked.ID).Scan(&n); err != nil { + t.Fatalf("%s: %v", query, err) + } + return n + } + const ( + general = "SELECT count(*) FROM general_likes WHERE user_id=$1 AND track_id=$2" + ctxAll = "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2" + ctxOpen = "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2 AND deleted_at IS NULL" + ) _ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`)) - // First like — captures. - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - // Second like — :execrows=0, no contextual write. - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - var count int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&count) - if count != 1 { - t.Errorf("contextual_likes count = %d, want 1 (no duplicate from idempotent re-like)", count) - } -} - -func TestUnlikeTrack_SoftDeletesContextualLikes(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "X") - album := seedAlbum(t, pool, artist.ID, "X", 1990) - playing := seedTrack(t, pool, album.ID, artist.ID, "P", 1, 100_000) - other := seedTrack(t, pool, album.ID, artist.ID, "O", 2, 100_000) - - _ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`)) - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - if r := callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(other.ID)); r.Code != http.StatusOK { - t.Fatalf("unlike: %d", r.Code) - } - // general_likes deleted. - var glCount int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM general_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&glCount) - if glCount != 0 { - t.Errorf("general_likes count = %d, want 0", glCount) - } - // contextual_likes row exists but deleted_at is set. - var deletedAtValid bool - _ = pool.QueryRow(context.Background(), - "SELECT deleted_at IS NOT NULL FROM contextual_likes WHERE user_id=$1 AND track_id=$2 LIMIT 1", - user.ID, other.ID).Scan(&deletedAtValid) - if !deletedAtValid { - t.Errorf("deleted_at not set after unlike") - } -} - -func TestLikeUnlikeRelike_HistoryAccumulates(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - user := seedUser(t, pool, "alice", "x", false) - artist := seedArtist(t, pool, "X") - album := seedAlbum(t, pool, artist.ID, "X", 1990) - playing := seedTrack(t, pool, album.ID, artist.ID, "P", 1, 100_000) - other := seedTrack(t, pool, album.ID, artist.ID, "O", 2, 100_000) - - _ = callEvents(h, user, []byte(`{"type":"play_started","track_id":"`+uuidToString(playing.ID)+`"}`)) - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - _ = callLike(h, user, http.MethodDelete, "/api/likes/tracks/"+uuidToString(other.ID)) - // Re-like in same session — new row should be inserted. - _ = callLike(h, user, http.MethodPost, "/api/likes/tracks/"+uuidToString(other.ID)) - - var total, active int - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2", user.ID, other.ID).Scan(&total) - _ = pool.QueryRow(context.Background(), - "SELECT count(*) FROM contextual_likes WHERE user_id=$1 AND track_id=$2 AND deleted_at IS NULL", - user.ID, other.ID).Scan(&active) - if total != 2 { - t.Errorf("total = %d, want 2 (history accumulates)", total) - } - if active != 1 { - t.Errorf("active = %d, want 1", active) + for _, step := range []struct { + method string + general, ctxAll, ctxOpen int + }{ + {http.MethodDelete, 0, 0, 0}, + {http.MethodPost, 1, 1, 1}, + {http.MethodPost, 1, 1, 1}, + {http.MethodDelete, 0, 1, 0}, + {http.MethodPost, 1, 2, 1}, + } { + if w := callLike(h, user, step.method, path); w.Code != http.StatusOK { + t.Fatalf("%s: status %d body=%s", step.method, w.Code, w.Body.String()) + } + g, a, o := count(general), count(ctxAll), count(ctxOpen) + if g != step.general || a != step.ctxAll || o != step.ctxOpen { + t.Fatalf("after %s: likes=%d contextual=%d open=%d, want %d %d %d", + step.method, g, a, o, step.general, step.ctxAll, step.ctxOpen) + } } } diff --git a/internal/api/me_password_test.go b/internal/api/me_password_test.go index e88f528d..eedf19dc 100644 --- a/internal/api/me_password_test.go +++ b/internal/api/me_password_test.go @@ -5,7 +5,6 @@ import ( "context" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -19,9 +18,6 @@ func newMePasswordRouter(h *handlers) chi.Router { } func TestChangePassword_Happy(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, "chpw1", "oldpassword1", false) @@ -47,9 +43,6 @@ func TestChangePassword_Happy(t *testing.T) { } func TestChangePassword_WrongCurrent_401(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, "chpw2", "correctpw1", false) @@ -65,9 +58,6 @@ func TestChangePassword_WrongCurrent_401(t *testing.T) { } func TestChangePassword_TooShort_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, "chpw3", "somepassword1", false) @@ -85,9 +75,6 @@ func TestChangePassword_TooShort_400(t *testing.T) { // A change keeps Subsonic apps signed in unless the person asks for them to // be signed out as well. func TestChangePassword_SignsOutSubsonicAppsOnlyWhenAsked(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, "chpwsub", "oldpassword1", false) giveSubsonicPassword(t, h, user) diff --git a/internal/api/me_recommendation_metrics_test.go b/internal/api/me_recommendation_metrics_test.go index 1b29c465..f96a5629 100644 --- a/internal/api/me_recommendation_metrics_test.go +++ b/internal/api/me_recommendation_metrics_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "time" @@ -201,9 +200,6 @@ func TestBucketMetricsResponse_DiscoverBucketBreakdown(t *testing.T) { } func TestRecommendationMetrics_BucketsWithBaseline(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, "metrics", "pw", false) artist := seedArtist(t, pool, "MetricArtist") diff --git a/internal/api/me_subsonic_password_test.go b/internal/api/me_subsonic_password_test.go index cdfbeac8..83e37623 100644 --- a/internal/api/me_subsonic_password_test.go +++ b/internal/api/me_subsonic_password_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -45,9 +44,6 @@ func readSubsonicPassword(t *testing.T, h *handlers, user dbq.User) *string { } func TestSubsonicPassword_GenerateIsRandomAndNotTheLoginPassword(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, "sspw1", "login-pw", false) router := newMeSubsonicPasswordRouter(h) @@ -87,9 +83,6 @@ func TestSubsonicPassword_GenerateIsRandomAndNotTheLoginPassword(t *testing.T) { } func TestSubsonicPassword_StatusAndClear(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, "sspw2", "login-pw", false) router := newMeSubsonicPasswordRouter(h) diff --git a/internal/api/me_system_playlists_test.go b/internal/api/me_system_playlists_test.go index 82726335..6e59f9a9 100644 --- a/internal/api/me_system_playlists_test.go +++ b/internal/api/me_system_playlists_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -20,9 +19,6 @@ func newMeSystemPlaylistsRouter(h *handlers) chi.Router { } func TestMeSystemPlaylistsStatus_NoRowReturnsDefault(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, "alice", "pw", false) req := httptest.NewRequest(http.MethodGet, "/api/me/system-playlists-status", nil) @@ -48,9 +44,6 @@ func TestMeSystemPlaylistsStatus_NoRowReturnsDefault(t *testing.T) { } func TestMeSystemPlaylistsStatus_RowReturnsValues(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, "bob", "pw", false) errMsg := "fetch failed" diff --git a/internal/api/me_timezone_test.go b/internal/api/me_timezone_test.go index 5791ffda..b7897e9c 100644 --- a/internal/api/me_timezone_test.go +++ b/internal/api/me_timezone_test.go @@ -6,7 +6,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -21,9 +20,6 @@ func newMeTimezoneRouter(h *handlers) chi.Router { } func TestPutTimezone_ValidIANA(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, "tz1", "irrelevant1", false) @@ -52,9 +48,6 @@ func TestPutTimezone_ValidIANA(t *testing.T) { } func TestPutTimezone_InvalidIANA(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, "tz2", "irrelevant1", false) @@ -85,9 +78,6 @@ func TestPutTimezone_InvalidIANA(t *testing.T) { } func TestPutTimezone_EmptyTimezone(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, "tz3", "irrelevant1", false) diff --git a/internal/api/me_token_test.go b/internal/api/me_token_test.go index bdbf76f1..673b9d7e 100644 --- a/internal/api/me_token_test.go +++ b/internal/api/me_token_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/Fabled-Sword/minstrel/internal/auth" @@ -19,9 +18,6 @@ func newMeTokenRouter(h *handlers) chi.Router { } func TestRegenerateAPIToken_IssuesNewToken(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, "tok2", "pw", false) oldHash := user.ApiTokenHash diff --git a/internal/api/media_test.go b/internal/api/media_test.go index 27df589e..07d42632 100644 --- a/internal/api/media_test.go +++ b/internal/api/media_test.go @@ -10,9 +10,6 @@ import ( "path/filepath" "testing" - "github.com/jackc/pgx/v5/pgtype" - "github.com/jackc/pgx/v5/pgxpool" - "github.com/Fabled-Sword/minstrel/internal/apierror" "github.com/Fabled-Sword/minstrel/internal/coverart" "github.com/Fabled-Sword/minstrel/internal/db/dbq" @@ -70,72 +67,6 @@ func TestFindSidecarCover_NoneFound(t *testing.T) { } } -func TestResolveAlbumCoverPath_ExplicitPresent(t *testing.T) { - _, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - - dir := t.TempDir() - explicit := filepath.Join(dir, "explicit.jpg") - if err := os.WriteFile(explicit, []byte("e"), 0o644); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(context.Background(), - `UPDATE albums SET cover_art_path = $1 WHERE id = $2`, explicit, album.ID); err != nil { - t.Fatalf("UPDATE albums: %v", err) - } - got := resolveAlbumCoverPath(context.Background(), dbq.New(pool), fetchAlbum(t, pool, album.ID)) - if got != explicit { - t.Errorf("got %q, want %q", got, explicit) - } -} - -func TestResolveAlbumCoverPath_ExplicitMissingFallsThroughToSidecar(t *testing.T) { - _, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - - _, dir := seedTrackWithFile(t, pool, album.ID, artist.ID, "t", []byte("audio"), "mp3") - sidecar := filepath.Join(dir, "cover.jpg") - if err := os.WriteFile(sidecar, []byte("s"), 0o644); err != nil { - t.Fatal(err) - } - if _, err := pool.Exec(context.Background(), - `UPDATE albums SET cover_art_path = $1 WHERE id = $2`, - filepath.Join(dir, "does-not-exist.jpg"), album.ID); err != nil { - t.Fatalf("UPDATE albums: %v", err) - } - - got := resolveAlbumCoverPath(context.Background(), dbq.New(pool), fetchAlbum(t, pool, album.ID)) - if got != sidecar { - t.Errorf("got %q, want %q", got, sidecar) - } -} - -func TestResolveAlbumCoverPath_NoArt(t *testing.T) { - _, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - seedTrack(t, pool, album.ID, artist.ID, "t", 1, 1000) - got := resolveAlbumCoverPath(context.Background(), dbq.New(pool), album) - if got != "" { - t.Errorf("got %q, want empty string", got) - } -} - -// fetchAlbum reloads the album row so tests see updates made via raw SQL. -func fetchAlbum(t *testing.T, pool *pgxpool.Pool, id pgtype.UUID) dbq.Album { - t.Helper() - a, err := dbq.New(pool).GetAlbumByID(context.Background(), id) - if err != nil { - t.Fatalf("GetAlbumByID: %v", err) - } - return a -} - func TestHandleGetCover_SidecarHappyPath(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) @@ -285,30 +216,6 @@ func TestHandleGetStream_HappyPath(t *testing.T) { } } -func TestHandleGetStream_RangeFromStart(t *testing.T) { - h, pool := testHandlers(t) - truncateLibrary(t, pool) - artist := seedArtist(t, pool, "A") - album := seedAlbum(t, pool, artist.ID, "X", 0) - body := deterministicBytes(32 * 1024) - track, _ := seedTrackWithFile(t, pool, album.ID, artist.ID, "t", body, "mp3") - - req := httptest.NewRequest(http.MethodGet, "/api/tracks/"+uuidToString(track.ID)+"/stream", nil) - req.Header.Set("Range", "bytes=0-99") - w := httptest.NewRecorder() - newLibraryRouter(h).ServeHTTP(w, req) - - if w.Code != http.StatusPartialContent { - t.Fatalf("status = %d, want 206", w.Code) - } - if cr := w.Header().Get("Content-Range"); cr != "bytes 0-99/32768" { - t.Errorf("Content-Range = %q", cr) - } - if got := w.Body.Bytes(); !bytes.Equal(got, body[:100]) { - t.Errorf("body mismatch: len=%d, want 100", len(got)) - } -} - func TestHandleGetStream_RangeFromMiddleToEnd(t *testing.T) { h, pool := testHandlers(t) truncateLibrary(t, pool) diff --git a/internal/api/playlists_system_test.go b/internal/api/playlists_system_test.go index 3cd598cc..b4cd52f2 100644 --- a/internal/api/playlists_system_test.go +++ b/internal/api/playlists_system_test.go @@ -4,7 +4,6 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "os" "testing" "github.com/go-chi/chi/v5" @@ -26,9 +25,6 @@ func newSystemPlaylistRouter(h *handlers) chi.Router { } func TestSystemRefresh_ForYou_Returns200(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, "sysforyou", "pw", false) @@ -53,9 +49,6 @@ func TestSystemRefresh_ForYou_Returns200(t *testing.T) { } func TestSystemRefresh_Discover_Returns200(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, "sysdiscover", "pw", false) @@ -79,9 +72,6 @@ func TestSystemRefresh_Discover_Returns200(t *testing.T) { // A non-singleton (songs_like_artist) or unknown kind isn't // addressable by the generic endpoints → 404, not a build. func TestSystemRefresh_NonSingletonKind_Returns404(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, "sysbadkind", "pw", false)