From f78929da2ea6bcddf4ed3fa0a1b60391c76f28a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deluan=20Quint=C3=A3o?= Date: Sun, 22 Nov 2026 15:41:43 -0500 Subject: [PATCH] test: replace shared repository fakes with a real per-suite database (#6519) --- adapters/deezer/deezer_test.go | 11 +- adapters/lastfm/agent_test.go | 7 +- adapters/lastfm/auth_router_test.go | 15 +- adapters/lastfm/lastfm_suite_test.go | 3 + adapters/listenbrainz/agent_test.go | 9 +- .../listenbrainz/listenbrainz_suite_test.go | 3 + cmd/artwork_test.go | 77 +- cmd/cmd_suite_test.go | 3 + cmd/root_test.go | 45 +- conf/configtest/configtest.go | 10 +- conf/configtest/configtest_test.go | 15 +- core/agents/agents_suite_test.go | 3 + core/agents/agents_test.go | 24 +- core/agents/local_agent_test.go | 109 +- core/agents/session_keys_test.go | 27 +- core/archiver_test.go | 233 +-- core/artwork/agent_images_test.go | 5 +- core/artwork/artwork_suite_test.go | 142 +- core/artwork/artwork_test.go | 172 +- core/artwork/e2e/acquire_serve_test.go | 105 +- core/artwork/e2e/e2e_suite_test.go | 17 - core/artwork/e2e/resolution_harness_test.go | 9 +- core/artwork/folders_album_test.go | 143 +- core/artwork/folders_artist_paths_test.go | 35 +- core/artwork/housekeeping_test.go | 69 +- core/artwork/library_fs_test.go | 12 +- core/artwork/processor_test.go | 177 +- core/artwork/prune_test.go | 40 +- core/artwork/resolve_test.go | 267 +-- core/artwork/trace_test.go | 239 ++- core/artwork/uploader_test.go | 11 +- core/artwork/worker_soak_test.go | 29 +- core/artwork/worker_test.go | 443 ++--- core/artwork/worker_timing_test.go | 6 +- core/auth/auth_test.go | 11 +- core/common_test.go | 13 +- core/core_suite_test.go | 3 + core/external/extdata_helper_test.go | 183 +-- core/external/extdata_suite_test.go | 3 + core/external/provider_refreshinfo_test.go | 43 +- core/external/provider_similarsongs_test.go | 841 +++------- core/external/provider_topsongs_test.go | 332 +--- .../external/provider_updatealbuminfo_test.go | 56 +- .../provider_updateartistinfo_test.go | 51 +- core/library_test.go | 307 ++-- core/lyrics/lyrics_suite_test.go | 3 + core/lyrics/lyrics_test.go | 87 +- core/maintenance_test.go | 599 +++---- core/matcher/matcher_internal_test.go | 12 +- core/matcher/matcher_suite_test.go | 3 + core/matcher/matcher_test.go | 380 ++--- core/players_test.go | 116 +- core/playlists/import_test.go | 467 ++---- core/playlists/parse_m3u_test.go | 17 +- core/playlists/playlists_suite_test.go | 73 + core/playlists/playlists_test.go | 269 ++- core/playlists/rest_adapter_test.go | 215 +-- core/scrobbler/buffered_scrobbler_test.go | 48 +- core/scrobbler/play_tracker_test.go | 215 +-- core/scrobbler/scrobbler_suite_test.go | 44 + core/share_test.go | 47 +- core/sonic/sonic_suite_test.go | 4 + core/sonic/sonic_test.go | 31 +- core/stream/decider_test.go | 40 +- core/stream/legacy_client_test.go | 16 +- core/stream/media_streamer_test.go | 14 +- core/stream/stream_suite_test.go | 3 + core/stream/token_test.go | 9 +- core/user_test.go | 31 +- model/get_entity_test.go | 32 +- model/model_suite_test.go | 3 + persistence/e2e/e2e_suite_test.go | 55 +- persistence/library_repository.go | 8 + persistence/persistencetest/overlay.go | 164 ++ persistence/persistencetest/overlay_test.go | 144 ++ .../persistencetest/persistencetest.go | 143 ++ .../persistencetest_suite_test.go | 23 + .../persistencetest/persistencetest_test.go | 138 ++ persistence/persistencetest/seed.go | 100 ++ persistence/user_repository_test.go | 26 +- plugins/host_artwork_test.go | 18 +- plugins/host_cache_test.go | 9 +- plugins/host_config_test.go | 9 +- plugins/host_kvstore_test.go | 9 +- plugins/host_library_test.go | 114 +- plugins/host_matcher_test.go | 176 +- plugins/host_scheduler_test.go | 9 +- plugins/host_scrobbleretriever_test.go | 24 +- plugins/host_storage_test.go | 25 +- plugins/host_subsonicapi_test.go | 79 +- plugins/host_taskqueue_test.go | 9 +- plugins/host_users_test.go | 103 +- plugins/host_websocket_test.go | 9 +- plugins/manager_loader_load_test.go | 9 +- plugins/manager_readonly_test.go | 14 +- plugins/manager_sync_test.go | 37 +- plugins/manager_test.go | 1 + plugins/manager_watcher_test.go | 10 +- plugins/plugins_suite_test.go | 77 +- plugins/sandbox_fs_test.go | 13 +- scanner/controller_test.go | 29 +- scanner/phase_2_missing_tracks_test.go | 351 ++-- scanner/phase_3_refresh_albums_test.go | 80 +- scanner/phase_4_playlists_test.go | 155 +- scanner/scanner_benchmark_test.go | 3 + scanner/scanner_multilibrary_test.go | 71 +- scanner/scanner_selective_test.go | 33 +- scanner/scanner_suite_test.go | 6 +- scanner/scanner_test.go | 134 +- scanner/watcher_test.go | 17 +- server/apiv1/api_test.go | 5 +- server/apiv1/apiv1_suite_test.go | 3 + server/apiv1/server_info_test.go | 25 +- server/apiv1/spec_test.go | 8 +- server/auth_test.go | 41 +- server/initial_setup_test.go | 64 +- server/jellyfin/annotations_test.go | 239 +-- server/jellyfin/api_test.go | 19 +- server/jellyfin/auth_test.go | 22 +- server/jellyfin/browsing_test.go | 314 ++-- server/jellyfin/e2e/e2e_suite_test.go | 4 +- server/jellyfin/images_test.go | 44 +- server/jellyfin/items_test.go | 1455 +++++++---------- server/jellyfin/jellyfin_suite_test.go | 80 + server/jellyfin/lyrics_test.go | 17 +- server/jellyfin/middlewares_test.go | 19 +- server/jellyfin/playlists_test.go | 187 +-- server/jellyfin/quickconnect_test.go | 16 +- server/jellyfin/routing_test.go | 8 +- server/jellyfin/sessions_test.go | 5 +- server/jellyfin/similar_test.go | 29 +- server/jellyfin/socket_test.go | 11 +- server/jellyfin/stream_test.go | 133 +- server/jellyfin/system_test.go | 18 +- server/jellyfin/users_test.go | 31 +- server/middlewares_test.go | 25 +- server/nativeapi/config_test.go | 12 +- server/nativeapi/library_test.go | 84 +- server/nativeapi/metadata_test.go | 71 +- server/nativeapi/missing_test.go | 19 +- server/nativeapi/native_api_song_test.go | 143 +- server/nativeapi/native_api_suite_test.go | 32 + server/nativeapi/playlists_test.go | 145 +- server/nativeapi/plugin_test.go | 13 +- server/nativeapi/queue_test.go | 234 ++- .../user_password_token_refresh_test.go | 19 +- server/public/handle_downloads_test.go | 36 +- server/public/handle_images_test.go | 13 +- server/public/handle_shares_test.go | 22 +- server/public/handle_streams_test.go | 67 +- server/public/public_suite_test.go | 35 + server/serve_index_test.go | 23 +- server/server_suite_test.go | 3 + server/server_test.go | 6 +- server/subsonic/album_lists_test.go | 331 ++-- server/subsonic/api_suite_test.go | 32 + server/subsonic/bookmarks_test.go | 48 +- server/subsonic/browsing_test.go | 68 +- server/subsonic/e2e/e2e_suite_test.go | 4 +- server/subsonic/e2e/subsonic_artwork_test.go | 3 +- server/subsonic/helpers_test.go | 5 +- server/subsonic/library_scanning_test.go | 64 +- server/subsonic/lyrics_test.go | 93 +- server/subsonic/media_annotation_test.go | 69 +- server/subsonic/media_retrieval_test.go | 98 +- server/subsonic/middlewares_test.go | 78 +- server/subsonic/playlists_test.go | 7 +- server/subsonic/radio_test.go | 48 +- server/subsonic/searching_test.go | 94 +- server/subsonic/transcode_test.go | 68 +- tests/harness/harness.go | 49 +- tests/mock_album_repo.go | 225 --- tests/mock_artist_repo.go | 203 --- tests/mock_artwork_queue_repo.go | 364 ----- tests/mock_artwork_repo.go | 190 --- tests/mock_data_store.go | 342 ---- tests/mock_genre_repo.go | 74 - tests/mock_library_repo.go | 312 ---- tests/mock_library_service.go | 47 - tests/mock_mediafile_repo.go | 392 ----- tests/mock_player_repo.go | 75 - tests/mock_playlist_repo.go | 189 --- tests/mock_playlist_track_repo.go | 138 -- tests/mock_playqueue_repo.go | 74 - tests/mock_plugin_repo.go | 166 -- tests/mock_property_repo.go | 63 - tests/mock_radio_repository.go | 84 - tests/mock_scrobble_buffer_repo.go | 112 -- tests/mock_scrobble_repo.go | 57 - tests/mock_share_repo.go | 57 - tests/mock_tag_repo.go | 26 - tests/mock_transcoding_repo.go | 32 - tests/mock_user_props_repo.go | 63 - tests/mock_user_repo.go | 186 --- tests/mock_user_service.go | 29 - 195 files changed, 7059 insertions(+), 10969 deletions(-) create mode 100644 persistence/persistencetest/overlay.go create mode 100644 persistence/persistencetest/overlay_test.go create mode 100644 persistence/persistencetest/persistencetest.go create mode 100644 persistence/persistencetest/persistencetest_suite_test.go create mode 100644 persistence/persistencetest/persistencetest_test.go create mode 100644 persistence/persistencetest/seed.go delete mode 100644 tests/mock_album_repo.go delete mode 100644 tests/mock_artist_repo.go delete mode 100644 tests/mock_artwork_queue_repo.go delete mode 100644 tests/mock_artwork_repo.go delete mode 100644 tests/mock_data_store.go delete mode 100644 tests/mock_genre_repo.go delete mode 100644 tests/mock_library_repo.go delete mode 100644 tests/mock_library_service.go delete mode 100644 tests/mock_mediafile_repo.go delete mode 100644 tests/mock_player_repo.go delete mode 100644 tests/mock_playlist_repo.go delete mode 100644 tests/mock_playlist_track_repo.go delete mode 100644 tests/mock_playqueue_repo.go delete mode 100644 tests/mock_plugin_repo.go delete mode 100644 tests/mock_property_repo.go delete mode 100644 tests/mock_radio_repository.go delete mode 100644 tests/mock_scrobble_buffer_repo.go delete mode 100644 tests/mock_scrobble_repo.go delete mode 100644 tests/mock_share_repo.go delete mode 100644 tests/mock_tag_repo.go delete mode 100644 tests/mock_transcoding_repo.go delete mode 100644 tests/mock_user_props_repo.go delete mode 100644 tests/mock_user_repo.go delete mode 100644 tests/mock_user_service.go diff --git a/adapters/deezer/deezer_test.go b/adapters/deezer/deezer_test.go index ba229f413..893caaf27 100644 --- a/adapters/deezer/deezer_test.go +++ b/adapters/deezer/deezer_test.go @@ -12,7 +12,7 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/agents" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -28,7 +28,7 @@ var _ = Describe("deezerAgent", func() { Describe("deezerConstructor", func() { It("uses configured languages", func() { conf.Update(func(c *conf.Options) { c.Deezer.Languages = []string{"pt", "en"} }) - agent := deezerConstructor(&tests.MockDataStore{}).(*deezerAgent) + agent := deezerConstructor(struct{ model.DataStore }{}).(*deezerAgent) Expect(agent.languages).To(Equal([]string{"pt", "en"})) }) }) @@ -40,8 +40,7 @@ var _ = Describe("deezerAgent", func() { BeforeEach(func() { httpClient = &fakeHttpClient{} agent = &deezerAgent{ - dataStore: &tests.MockDataStore{}, - client: newClient(httpClient), + client: newClient(httpClient), } }) @@ -116,8 +115,7 @@ var _ = Describe("deezerAgent", func() { BeforeEach(func() { httpClient = &fakeHttpClient{} agent = &deezerAgent{ - dataStore: &tests.MockDataStore{}, - client: newClient(httpClient), + client: newClient(httpClient), } }) @@ -179,7 +177,6 @@ var _ = Describe("deezerAgent", func() { setupAgent := func(languages []string) { conf.Update(func(c *conf.Options) { c.Deezer.Languages = languages }) agent = &deezerAgent{ - dataStore: &tests.MockDataStore{}, client: newClient(httpClient), languages: languages, } diff --git a/adapters/lastfm/agent_test.go b/adapters/lastfm/agent_test.go index f5169580f..30da09723 100644 --- a/adapters/lastfm/agent_test.go +++ b/adapters/lastfm/agent_test.go @@ -14,7 +14,9 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/scrobbler" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -30,7 +32,7 @@ var _ = Describe("lastfmAgent", func() { var ctx context.Context BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) conf.Update(func(c *conf.Options) { c.LastFM.Enabled = true c.LastFM.ApiKey = "123" @@ -354,7 +356,8 @@ var _ = Describe("lastfmAgent", func() { var httpClient *tests.FakeHttpClient var track *model.MediaFile BeforeEach(func() { - _ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1") + Expect(ds.User().Put(ctx, &model.User{ID: "user-1", UserName: "user-1"})).To(Succeed()) + Expect(ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")).To(Succeed()) httpClient = &tests.FakeHttpClient{} client := newClient("API_KEY", "SECRET", httpClient) agent = lastFMConstructor(ds) diff --git a/adapters/lastfm/auth_router_test.go b/adapters/lastfm/auth_router_test.go index 3bdf0fa43..bcc423eb7 100644 --- a/adapters/lastfm/auth_router_test.go +++ b/adapters/lastfm/auth_router_test.go @@ -10,8 +10,10 @@ import ( "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -19,8 +21,7 @@ import ( var _ = Describe("auth_router", func() { var ( - ds *tests.MockDataStore - userProps *tests.MockedUserPropsRepo + ds model.DataStore httpClient *tests.FakeHttpClient router *Router ) @@ -31,10 +32,10 @@ var _ = Describe("auth_router", func() { ) BeforeEach(func() { - userProps = &tests.MockedUserPropsRepo{} - ds = &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedUserProps: userProps, + ctx := GinkgoT().Context() + ds = persistence.New(db.Db()) + for _, id := range []string{victimID, attackerID} { + Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: id})).To(Succeed()) } auth.Init(ds) @@ -50,7 +51,7 @@ var _ = Describe("auth_router", func() { }) storedSessionKey := func(userID string) string { - key, _ := userProps.Get(GinkgoT().Context(), userID, sessionKeyProperty) + key, _ := ds.UserProps().Get(GinkgoT().Context(), userID, sessionKeyProperty) return key } diff --git a/adapters/lastfm/lastfm_suite_test.go b/adapters/lastfm/lastfm_suite_test.go index 35e57535c..20a385c7d 100644 --- a/adapters/lastfm/lastfm_suite_test.go +++ b/adapters/lastfm/lastfm_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestLastFM(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "LastFM Test Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/adapters/listenbrainz/agent_test.go b/adapters/listenbrainz/agent_test.go index 939ee1019..614ef3834 100644 --- a/adapters/listenbrainz/agent_test.go +++ b/adapters/listenbrainz/agent_test.go @@ -15,7 +15,9 @@ import ( "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/scrobbler" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -31,8 +33,9 @@ var _ = Describe("listenBrainzAgent", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - _ = ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1") + ds = persistence.New(db.Db()) + Expect(ds.User().Put(ctx, &model.User{ID: "user-1", UserName: "user-1"})).To(Succeed()) + Expect(ds.UserProps().Put(ctx, "user-1", sessionKeyProperty, "SK-1")).To(Succeed()) httpClient = &tests.FakeHttpClient{} agent = listenBrainzConstructor(ds) agent.client = newClient("http://localhost:8080", httpClient) @@ -484,7 +487,7 @@ var _ = Describe("register", func() { var ds model.DataStore BeforeEach(func() { - ds = &tests.MockDataStore{} + ds = struct{ model.DataStore }{} delete(agents.Map, listenBrainzAgentName) scrobbler.Unregister(listenBrainzAgentName) }) diff --git a/adapters/listenbrainz/listenbrainz_suite_test.go b/adapters/listenbrainz/listenbrainz_suite_test.go index 4d1b8f710..c8dd89e15 100644 --- a/adapters/listenbrainz/listenbrainz_suite_test.go +++ b/adapters/listenbrainz/listenbrainz_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestListenBrainz(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "ListenBrainz Test Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/cmd/artwork_test.go b/cmd/artwork_test.go index c44800e84..db46a868b 100644 --- a/cmd/artwork_test.go +++ b/cmd/artwork_test.go @@ -10,8 +10,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/artwork" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -54,14 +56,13 @@ var _ = Describe("parseArtworkKind", func() { }) var _ = Describe("resolveArtworkTargets", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ctx context.Context BeforeEach(func() { ctx = GinkgoT().Context() - artists := tests.CreateMockArtistRepo() - artists.SetData(model.Artists{{ID: "artist1"}}) - ds = &tests.MockDataStore{MockedArtist: artists} + ds = persistence.New(db.Db()) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist1", Name: "artist1"}) }) It("accepts the explicit leader shared by every id", func() { @@ -493,8 +494,8 @@ var _ = Describe("explain/reprocess source round trip", func() { } It("names the absent state as reprocess --source accepts it", func() { - ds := &tests.MockDataStore{} - art := ds.Artwork().(*tests.MockArtworkRepo) + ds := persistence.New(db.Db()) + art := ds.Artwork() Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: model.KindArtistArtwork.Prefix(), ItemID: "ar-1", ImageType: model.ImageTypePrimary})).To(Succeed()) @@ -565,9 +566,9 @@ var _ = Describe("confirmUnlessYes", func() { }) var _ = Describe("reprocessArtwork", func() { - var ds *tests.MockDataStore - var art *tests.MockArtworkRepo - var queue *tests.MockArtworkQueueRepo + var ds model.DataStore + var art model.ArtworkRepository + var queue model.ArtworkQueueRepository var out strings.Builder var imageAgents artwork.ImageAgentCount var ctx context.Context @@ -588,9 +589,9 @@ var _ = Describe("reprocessArtwork", func() { c.EnableM3UExternalAlbumArt = false }) imageAgents = artwork.ImageAgentCount{Artist: 1, Album: 1} - ds = &tests.MockDataStore{} - art = ds.Artwork().(*tests.MockArtworkRepo) - queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) + ds = persistence.New(db.Db()) + art = ds.Artwork() + queue = ds.ArtworkQueue() out.Reset() put(model.KindArtistArtwork, "ar-1", "external:deezer") put(model.KindArtistArtwork, "ar-2", "") @@ -816,16 +817,16 @@ var _ = Describe("artwork status command", func() { }) var _ = Describe("collectStatus", func() { - var ds *tests.MockDataStore - var art *tests.MockArtworkRepo - var queue *tests.MockArtworkQueueRepo + var ds model.DataStore + var art model.ArtworkRepository + var queue model.ArtworkQueueRepository var ctx context.Context BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - art = ds.Artwork().(*tests.MockArtworkRepo) - queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) + ds = persistence.New(db.Db()) + art = ds.Artwork() + queue = ds.ArtworkQueue() put := func(kind model.Kind, id, source, hash string, attempted time.Time) { Expect(art.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id, ImageType: model.ImageTypePrimary, Source: source, Hash: hash, AttemptedAt: attempted})).To(Succeed()) @@ -971,19 +972,20 @@ var _ = Describe("formatStatus", func() { }) var _ = Describe("refreshItems", func() { - var ds *tests.MockDataStore - var queue *tests.MockArtworkQueueRepo - var art *tests.MockArtworkRepo + var ds model.DataStore + var queue model.ArtworkQueueRepository + var art model.ArtworkRepository var out strings.Builder var ctx context.Context BeforeEach(func() { ctx = GinkgoT().Context() - albums := tests.CreateMockAlbumRepo() - albums.SetData(model.Albums{{ID: "al-1"}, {ID: "al-3"}}) - ds = &tests.MockDataStore{MockedAlbum: albums} - art = ds.Artwork().(*tests.MockArtworkRepo) - queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) + ds = persistence.New(db.Db()) + for _, id := range []string{"al-1", "al-3"} { + Expect(ds.Album().Put(ctx, &model.Album{ID: id, Name: id, LibraryID: model.DefaultLibraryID})).To(Succeed()) + } + art = ds.Artwork() + queue = ds.ArtworkQueue() out.Reset() }) @@ -1147,8 +1149,8 @@ var _ = Describe("artwork cancel selection", func() { }) var _ = Describe("cancelArtwork", func() { - var ds *tests.MockDataStore - var queue *tests.MockArtworkQueueRepo + var ds model.DataStore + var queue model.ArtworkQueueRepository var out strings.Builder var ctx context.Context accept := func(io.Writer, int64, int64) bool { return true } @@ -1156,8 +1158,8 @@ var _ = Describe("cancelArtwork", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - queue = ds.ArtworkQueue().(*tests.MockArtworkQueueRepo) + ds = persistence.New(db.Db()) + queue = ds.ArtworkQueue() out.Reset() Expect(queue.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar-1", ImageType: model.ImageTypePrimary, @@ -1212,7 +1214,18 @@ var _ = Describe("cancelArtwork", func() { }) It("reports a queue read failure instead of reporting nothing to cancel", func() { - queue.Err = errors.New("read failed") + ds = persistencetest.Stub(ds, persistencetest.Repos{ArtworkQueue: func(r model.ArtworkQueueRepository) model.ArtworkQueueRepository { + return failingQueueRepo{ArtworkQueueRepository: r, err: errors.New("read failed")} + }}) Expect(cancelArtwork(ctx, ds, nil, nil, false, accept, &out)).To(MatchError(ContainSubstring("read failed"))) }) }) + +type failingQueueRepo struct { + model.ArtworkQueueRepository + err error +} + +func (r failingQueueRepo) CountQueued(context.Context, []model.Kind, []int) ([]model.ArtworkQueueStat, error) { + return nil, r.err +} diff --git a/cmd/cmd_suite_test.go b/cmd/cmd_suite_test.go index 8deef25e6..e008e62b1 100644 --- a/cmd/cmd_suite_test.go +++ b/cmd/cmd_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestCmd(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Cmd Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/cmd/root_test.go b/cmd/root_test.go index 0724fff6d..f423f720c 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -1,6 +1,7 @@ package cmd import ( + "context" "errors" "net/http" "net/http/httptest" @@ -9,8 +10,10 @@ import ( "github.com/go-chi/chi/v5" "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -43,28 +46,44 @@ var _ = Describe("profilerHandler", func() { ) }) +type failingLibraryRepo struct { + model.LibraryRepository + err error +} + +func (r failingLibraryRepo) GetAll(context.Context, ...model.QueryOptions) (model.Libraries, error) { + return nil, r.err +} + var _ = Describe("librariesWithChangedPID", func() { - var ds *tests.MockDataStore - var libs *tests.MockLibraryRepo + var ctx context.Context + var ds model.DataStore BeforeEach(func() { - libs = &tests.MockLibraryRepo{} - ds = &tests.MockDataStore{MockedLibrary: libs} + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) It("returns only the libraries whose PID config changed", func() { pid := model.Library{}.EffectivePID() - libs.SetData(model.Libraries{ - {ID: 1, Name: "Same", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track}, - {ID: 2, Name: "Changed", PIDAlbum: "folder", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track}, - {ID: 3, Name: "Never scanned"}, - }) - Expect(librariesWithChangedPID(GinkgoT().Context(), ds)).To(ConsistOf("Changed", "Never scanned")) + persistencetest.SetLibraries(ctx, ds, "/music/same", "/music/changed", "/music/never") + same, err := ds.Library().Get(ctx, 1) + Expect(err).ToNot(HaveOccurred()) + same.Name = "Same" + Expect(ds.Library().Put(ctx, same)).To(Succeed()) + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Changed", Path: "/music/changed", PIDAlbum: "folder"})).To(Succeed()) + Expect(ds.Library().Put(ctx, &model.Library{ID: 3, Name: "Never scanned", Path: "/music/never"})).To(Succeed()) + Expect(ds.Library().SetScannedPID(ctx, 1, pid)).To(Succeed()) + Expect(ds.Library().SetScannedPID(ctx, 2, pid)).To(Succeed()) + + Expect(librariesWithChangedPID(ctx, ds)).To(ConsistOf("Changed", "Never scanned")) }) It("returns the error from the repository", func() { - libs.Err = errors.New("db down") - _, err := librariesWithChangedPID(GinkgoT().Context(), ds) + ds = persistencetest.Stub(ds, persistencetest.Repos{Library: func(r model.LibraryRepository) model.LibraryRepository { + return failingLibraryRepo{LibraryRepository: r, err: errors.New("db down")} + }}) + _, err := librariesWithChangedPID(ctx, ds) Expect(err).To(MatchError("db down")) }) }) diff --git a/conf/configtest/configtest.go b/conf/configtest/configtest.go index 7712f4d59..9dc8f0248 100644 --- a/conf/configtest/configtest.go +++ b/conf/configtest/configtest.go @@ -5,12 +5,10 @@ import ( "github.com/onsi/ginkgo/v2" ) -// RestoreAfterEachSpec restores the config after every spec. Call it at the top level of a suite. -// Ordered specs are skipped so a BeforeAll can set config for its whole container. +// RestoreAfterEachSpec restores the config after every spec, and after each Ordered container as a +// whole, so its BeforeAll can set config for all its specs. Call it at the top level of a suite. func RestoreAfterEachSpec() bool { - return ginkgo.BeforeEach(func() { - if !ginkgo.CurrentSpecReport().IsInOrderedContainer { - ginkgo.DeferCleanup(conf.SnapshotConfig()) - } + return ginkgo.BeforeEach(ginkgo.OncePerOrdered, func() { + ginkgo.DeferCleanup(conf.SnapshotConfig()) }) } diff --git a/conf/configtest/configtest_test.go b/conf/configtest/configtest_test.go index 7e3259837..62efada88 100644 --- a/conf/configtest/configtest_test.go +++ b/conf/configtest/configtest_test.go @@ -18,9 +18,22 @@ var _ = Describe("RestoreAfterEachSpec", func() { conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "B" }) }) + // Either container can run first: the second one sees the first one's change if it leaks. + for _, name := range []string{"first", "second"} { + Describe("in the "+name+" Ordered container", Ordered, func() { + It("starts with the original value", func() { + Expect(conf.Server().UIWelcomeMessage).To(BeEmpty()) + conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = name }) + }) + + It("keeps the change for the rest of the container", func() { + Expect(conf.Server().UIWelcomeMessage).To(Equal(name)) + }) + }) + } + Describe("in an Ordered container", Ordered, func() { BeforeAll(func() { - DeferCleanup(conf.SnapshotConfig()) conf.Update(func(c *conf.Options) { c.UIWelcomeMessage = "ordered" }) }) diff --git a/core/agents/agents_suite_test.go b/core/agents/agents_suite_test.go index 78551fc5f..8dcfc065c 100644 --- a/core/agents/agents_suite_test.go +++ b/core/agents/agents_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestAgents(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Agents Test Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/core/agents/agents_test.go b/core/agents/agents_test.go index 276120813..6d41557b1 100644 --- a/core/agents/agents_test.go +++ b/core/agents/agents_test.go @@ -7,8 +7,10 @@ import ( "time" "github.com/navidrome/navidrome/consts" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/conf" . "github.com/onsi/ginkgo/v2" @@ -42,11 +44,9 @@ var _ = Describe("Agents", func() { var ctx context.Context var cancel context.CancelFunc var ds model.DataStore - var mfRepo *tests.MockMediaFileRepo BeforeEach(func() { ctx, cancel = context.WithCancel(GinkgoT().Context()) - mfRepo = tests.CreateMockMediaFileRepo() - ds = &tests.MockDataStore{MockedMediaFile: mfRepo} + ds = persistence.New(db.Db()) }) Describe("Local", func() { @@ -57,8 +57,20 @@ var _ = Describe("Agents", func() { }) It("calls the placeholder GetArtistImages", func() { - mfRepo.SetData(model.MediaFiles{{ID: "1", Title: "One"}, {ID: "2", Title: "Two"}}) - songs, err := ag.GetArtistTopSongs(ctx, "123", "John Doe", "mb123", 2) + user := model.User{ID: "user-1", UserName: "user-1"} + Expect(ds.User().Put(ctx, &user)).To(Succeed()) + ctx = request.WithUser(ctx, user) + putSongs(ctx, ds, + model.MediaFile{ID: "1", Title: "One", ArtistID: "123"}, + model.MediaFile{ID: "2", Title: "Two", ArtistID: "123"}, + model.MediaFile{ID: "3", Title: "Not a favourite", ArtistID: "123"}, + model.MediaFile{ID: "4", Title: "Other artist", ArtistID: "456"}, + ) + Expect(ds.MediaFile().SetStar(ctx, true, "1", "4")).To(Succeed()) + Expect(ds.MediaFile().SetRating(ctx, 5, "2")).To(Succeed()) + Expect(ds.MediaFile().SetRating(ctx, 4, "3")).To(Succeed()) + + songs, err := ag.GetArtistTopSongs(ctx, "123", "John Doe", "mb123", 3) Expect(err).ToNot(HaveOccurred()) Expect(songs).To(ConsistOf([]Song{{ID: "1", Name: "One"}, {ID: "2", Name: "Two"}})) }) diff --git a/core/agents/local_agent_test.go b/core/agents/local_agent_test.go index 95135a058..a7de0d0ca 100644 --- a/core/agents/local_agent_test.go +++ b/core/agents/local_agent_test.go @@ -3,64 +3,66 @@ package agents import ( "context" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("localAgent GetSimilarSongsByTrack", func() { - var ds *tests.MockDataStore - var mfRepo *tests.MockMediaFileRepo + var ds *getRandomSpy var agent *localAgent var ctx context.Context + rock := model.Tags{model.TagGenre: []string{"Rock"}} + BeforeEach(func() { ctx = GinkgoT().Context() - mfRepo = &tests.MockMediaFileRepo{} - ds = &tests.MockDataStore{MockedMediaFile: mfRepo} + ds = &getRandomSpy{DataStore: persistence.New(db.Db())} agent = &localAgent{ds: ds} }) It("excludes the seed track from its own similars", func() { - seed := model.MediaFile{ID: "seed-1", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} - related := model.MediaFile{ID: "rel-1", Title: "Related", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} - // SetData keys by ID; a duplicate "seed-1" entry would clobber the real seed. - mfRepo.SetData(model.MediaFiles{seed, related}) + putSongs(ctx, ds, + model.MediaFile{ID: "seed-1", Title: "Seed", Tags: rock}, + model.MediaFile{ID: "rel-1", Title: "Related", Tags: rock}, + ) songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-1", "Seed", "", "", 10) Expect(err).ToNot(HaveOccurred()) names := slice.Map(songs, func(s Song) string { return s.Name }) - Expect(names).ToNot(ContainElement("Seed")) + Expect(names).To(ConsistOf("Related")) }) - // The mock ignores QueryOptions.Filters, so assert the predicate itself: otherwise this spec - // would pass just as well with no genre filter at all. It("queries the indexed genre join for the seed's own genres, skipping missing files", func() { - rock := model.NewTag(model.TagGenre, "Rock") - seed := model.MediaFile{ID: "seed-4", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} - mfRepo.SetData(model.MediaFiles{seed}) + putSongs(ctx, ds, + model.MediaFile{ID: "seed-4", Title: "Seed", Tags: rock}, + model.MediaFile{ID: "rock", Title: "Rock", Tags: rock}, + model.MediaFile{ID: "jazz", Title: "Jazz", Tags: model.Tags{model.TagGenre: []string{"Jazz"}}}, + model.MediaFile{ID: "gone", Title: "Missing Rock", Tags: rock, Missing: true}, + ) - _, err := agent.GetSimilarSongsByTrack(ctx, "seed-4", "Seed", "", "", 10) + songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-4", "Seed", "", "", 10) Expect(err).ToNot(HaveOccurred()) + Expect(songs).To(ConsistOf(Song{ID: "rock", Name: "Rock"})) - sql, args, sqlErr := mfRepo.Options.Filters.ToSql() + Expect(ds.options).To(HaveLen(1)) + sql, _, sqlErr := ds.options[0].Filters.ToSql() Expect(sqlErr).ToNot(HaveOccurred()) Expect(sql).To(ContainSubstring("media_file_tags"), "must use the indexed join, not a json_tree scan") - Expect(sql).To(ContainSubstring("missing")) - Expect(args).To(ContainElement(false), "must exclude missing files, not select them") - Expect(args).To(ContainElement(rock.ID), "must filter on the seed's own genre tag id") - Expect(args).ToNot(ContainElement(model.NewTag(model.TagGenre, "Jazz").ID)) }) It("returns the library id so the matcher can resolve the song", func() { - seed := model.MediaFile{ID: "seed-3", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} // Without the id the matcher falls through to its MBID/title phases and resolves nothing, // so the local fallback silently returns an empty mix. - related := model.MediaFile{ID: "rel-3", Title: "Related", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} - mfRepo.SetData(model.MediaFiles{seed, related}) + putSongs(ctx, ds, + model.MediaFile{ID: "seed-3", Title: "Seed", Tags: rock}, + model.MediaFile{ID: "rel-3", Title: "Related", Tags: rock}, + ) songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-3", "Seed", "", "", 10) @@ -69,28 +71,63 @@ var _ = Describe("localAgent GetSimilarSongsByTrack", func() { }) It("asks for one extra candidate so dropping the seed still fills the count", func() { - // The mock returns rows sorted by id, so the seed comes first and would consume the only - // slot if the query did not over-fetch. - seed := model.MediaFile{ID: "a-seed", Title: "Seed", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} - related := model.MediaFile{ID: "b-rel", Title: "Related", Tags: model.Tags{model.TagGenre: []string{"Rock"}}} - mfRepo.SetData(model.MediaFiles{seed, related}) + putSongs(ctx, ds, + model.MediaFile{ID: "a-seed", Title: "Seed", Tags: rock}, + model.MediaFile{ID: "b-rel", Title: "Related", Tags: rock}, + ) - songs, err := agent.GetSimilarSongsByTrack(ctx, "a-seed", "Seed", "", "", 1) + // Candidates come back in random order, so repeat until the seed has surely been drawn first. + for range 20 { + songs, err := agent.GetSimilarSongsByTrack(ctx, "a-seed", "Seed", "", "", 1) - Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].Name).To(Equal("Related")) + Expect(err).ToNot(HaveOccurred()) + Expect(songs).To(HaveLen(1)) + Expect(songs[0].Name).To(Equal("Related")) + } }) It("returns nil when the seed track has no genres", func() { - seed := model.MediaFile{ID: "seed-2", Title: "NoGenre"} - mfRepo.SetData(model.MediaFiles{seed}) + putSongs(ctx, ds, + model.MediaFile{ID: "seed-2", Title: "NoGenre"}, + model.MediaFile{ID: "other", Title: "Other", Tags: rock}, + ) songs, err := agent.GetSimilarSongsByTrack(ctx, "seed-2", "NoGenre", "", "", 10) Expect(err).ToNot(HaveOccurred()) Expect(songs).To(BeEmpty()) // Without the early return an empty tag filter would scan the whole library. - Expect(mfRepo.Options).To(Equal(model.QueryOptions{}), "must not query at all") + Expect(ds.options).To(BeEmpty(), "must not query at all") }) }) + +// getRandomSpy records the options of every MediaFile().GetRandom call, which still reaches the real repository. +type getRandomSpy struct { + model.DataStore + options []model.QueryOptions +} + +func (s *getRandomSpy) MediaFile() model.MediaFileRepository { + return getRandomSpyRepo{MediaFileRepository: s.DataStore.MediaFile(), spy: s} +} + +type getRandomSpyRepo struct { + model.MediaFileRepository + spy *getRandomSpy +} + +func (r getRandomSpyRepo) GetRandom(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { + r.spy.options = append(r.spy.options, options...) + return r.MediaFileRepository.GetRandom(ctx, options...) +} + +// putSongs stores the songs in library 1, along with the tags they carry. +func putSongs(ctx context.Context, ds model.DataStore, songs ...model.MediaFile) { + GinkgoHelper() + for _, mf := range songs { + if tags := mf.Tags.FlattenAll(); len(tags) > 0 { + Expect(ds.Tag().Add(ctx, model.DefaultLibraryID, tags...)).To(Succeed()) + } + } + persistencetest.PutMediaFiles(ctx, ds, songs...) +} diff --git a/core/agents/session_keys_test.go b/core/agents/session_keys_test.go index e68f1181e..355db7567 100644 --- a/core/agents/session_keys_test.go +++ b/core/agents/session_keys_test.go @@ -3,8 +3,9 @@ package agents import ( "context" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -12,27 +13,43 @@ import ( var _ = Describe("SessionKeys", func() { var ctx context.Context - user := model.User{ID: "u-1"} - ds := &tests.MockDataStore{MockedUserProps: &tests.MockedUserPropsRepo{}} - sk := SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"} + var ds model.DataStore + var sk SessionKeys + user := model.User{ID: "u-1", UserName: "u-1"} BeforeEach(func() { ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + Expect(ds.User().Put(ctx, &user)).To(Succeed()) + sk = SessionKeys{DataStore: ds, KeyName: "fakeSessionKey"} }) It("uses the assigned key name", func() { - Expect(sk.KeyName).To(Equal("fakeSessionKey")) + other := SessionKeys{DataStore: ds, KeyName: "otherSessionKey"} + Expect(sk.Put(ctx, user.ID, "mine")).To(Succeed()) + Expect(other.Put(ctx, user.ID, "theirs")).To(Succeed()) + + Expect(sk.Get(ctx, user.ID)).To(Equal("mine")) }) It("stores a value in the DB", func() { Expect(sk.Put(ctx, user.ID, "test-stored-value")).To(Succeed()) + + Expect(ds.UserProps().Get(ctx, user.ID, "fakeSessionKey")).To(Equal("test-stored-value")) }) It("fetches the stored value", func() { + Expect(ds.UserProps().Put(ctx, user.ID, "fakeSessionKey", "test-stored-value")).To(Succeed()) + value, err := sk.Get(ctx, user.ID) Expect(err).ToNot(HaveOccurred()) Expect(value).To(Equal("test-stored-value")) }) It("deletes the stored value", func() { + Expect(ds.UserProps().Put(ctx, user.ID, "fakeSessionKey", "test-stored-value")).To(Succeed()) + Expect(sk.Delete(ctx, user.ID)).To(Succeed()) + + _, err := ds.UserProps().Get(ctx, user.ID, "fakeSessionKey") + Expect(err).To(MatchError(model.ErrNotFound)) }) It("handles a not found value", func() { _, err := sk.Get(ctx, "u-2") diff --git a/core/archiver_test.go b/core/archiver_test.go index 30c611e90..351f9009f 100644 --- a/core/archiver_test.go +++ b/core/archiver_test.go @@ -8,14 +8,16 @@ import ( "io" "strings" - "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/stream" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" @@ -27,35 +29,54 @@ var _ = Describe("Archiver", func() { arch core.Archiver ms *mockMediaStreamer dc *fakeDecider - ds *mockDataStore + ds model.DataStore sh *mockShare ca *mockCoverArt ) + putTracks := func(mfs ...model.MediaFile) []string { + GinkgoHelper() + return slice.Map(persistencetest.PutMediaFiles(ctx, ds, mfs...), func(mf model.MediaFile) string { return mf.ID }) + } + + byArtist := func(id string, mfs ...model.MediaFile) []model.MediaFile { + for i := range mfs { + mfs[i].Participants = model.Participants{model.RoleAlbumArtist: {{ID: id, Name: "Artist " + id}}} + } + return mfs + } + + putPlaylist := func(id, name string, tracks ...model.MediaFile) { + GinkgoHelper() + ids := putTracks(tracks...) + Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: id, Name: name, OwnerID: "user-1"})).To(Succeed()) + _, err := ds.Playlist().Tracks(ctx, id, false).Add(ctx, ids) + Expect(err).ToNot(HaveOccurred()) + } + BeforeEach(func() { ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + user := model.User{ID: "user-1", UserName: "user-1"} + Expect(ds.User().Put(ctx, &user)).To(Succeed()) + ctx = request.WithUser(ctx, user) + for _, id := range []string{"1", "2"} { + Expect(ds.Artist().Put(ctx, &model.Artist{ID: id, Name: "Artist " + id})).To(Succeed()) + } ms = &mockMediaStreamer{} dc = &fakeDecider{} sh = &mockShare{} - ds = &mockDataStore{} ca = &mockCoverArt{images: map[string][]byte{}} arch = core.NewArchiver(ms, dc, ds, sh, ca) }) Context("ZipAlbum", func() { It("zips an album correctly", func() { - mfs := model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1}, - {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1}, - } - - mfRepo := &mockMediaFileRepository{} - mfRepo.On("GetAll", []model.QueryOptions{{ - Filters: squirrel.Eq{"album_id": "1"}, - Sort: "album", - }}).Return(mfs, nil) - - ds.On("MediaFile").Return(mfRepo) + putTracks( + model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1, TrackNumber: 2}, + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1, TrackNumber: 1}, + model.MediaFile{Path: "other/01 - other.mp3", Suffix: "mp3", AlbumID: "2", Album: "Other", DiscNumber: 1}, + ) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(3) out := new(bytes.Buffer) @@ -71,15 +92,13 @@ var _ = Describe("Archiver", func() { }) It("streams the request resolved by the transcode decider and names the entry after its format", func() { - mfRepo := &mockMediaFileRepository{} - mfRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{Path: "test_data/01 - track1.flac", Suffix: "flac", AlbumID: "1"}}, nil) - ds.On("MediaFile").Return(mfRepo) + putTracks(model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", AlbumID: "1"}) resolved := stream.Request{Format: "opus", BitRate: 128, SampleRate: 48000, Channels: 2} dc.resolved = &resolved ms.On("NewStream", mock.Anything, mock.Anything, resolved).Return(io.NopCloser(strings.NewReader("test")), nil).Once() out := new(bytes.Buffer) - Expect(arch.ZipAlbum(GinkgoT().Context(), "1", "mp3", 128, out)).To(Succeed()) + Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed()) ms.AssertExpectations(GinkgoT()) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) @@ -90,21 +109,14 @@ var _ = Describe("Archiver", func() { Context("ZipArtist", func() { It("zips an artist's albums correctly", func() { - mfs := model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumArtistID: "1", AlbumID: "1", Album: "Album 1", DiscNumber: 1}, - {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumArtistID: "1", AlbumID: "1", Album: "Album 1", DiscNumber: 1}, - } - - mfRepo := &mockMediaFileRepository{} - mfRepo.On("GetAll", []model.QueryOptions{{ - Filters: squirrel.And{ - persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist), - squirrel.Eq{"missing": false}, - }, - Sort: "album", - }}).Return(mfs, nil) - - ds.On("MediaFile").Return(mfRepo) + putTracks(byArtist("1", + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 1}, + model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 2}, + model.MediaFile{Path: "test_data/03 - missing.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, TrackNumber: 3, Missing: true}, + )...) + putTracks(byArtist("2", + model.MediaFile{Path: "other/01 - other.mp3", Suffix: "mp3", AlbumID: "2", Album: "Other", DiscNumber: 1}, + )...) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2) out := new(bytes.Buffer) @@ -123,9 +135,7 @@ var _ = Describe("Archiver", func() { // zipArtistEntries zips the given tracks as artist "1" and returns the entry names in zip order. zipArtistEntries := func(mfs model.MediaFiles) []string { - mfRepo := &mockMediaFileRepository{} - mfRepo.On("GetAll", mock.Anything).Return(mfs, nil) - ds.On("MediaFile", mock.Anything).Return(mfRepo) + putTracks(byArtist("1", mfs...)...) ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil) out := new(bytes.Buffer) @@ -141,10 +151,10 @@ var _ = Describe("Archiver", func() { It("keeps the albums in query order", func() { names := zipArtistEntries(model.MediaFiles{ - {Path: "a/01.mp3", Suffix: "mp3", AlbumID: "3", Album: "Album C"}, - {Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A"}, - {Path: "a/02.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A"}, - {Path: "a/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album B"}, + {Path: "c/01.mp3", Suffix: "mp3", AlbumID: "3", Album: "Album C", OrderAlbumName: "1"}, + {Path: "a/01.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A", OrderAlbumName: "2", TrackNumber: 1}, + {Path: "a/02.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album A", OrderAlbumName: "2", TrackNumber: 2}, + {Path: "b/01.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album B", OrderAlbumName: "3"}, }) Expect(names).To(Equal([]string{"Album C/01.mp3", "Album A/01.mp3", "Album A/02.mp3", "Album B/01.mp3"})) }) @@ -253,17 +263,10 @@ var _ = Describe("Archiver", func() { Context("when the transcode limiter rejects a file", func() { It("aborts the archive instead of continuing with empty entries", func() { - mfs := model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1}, - {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1}, - } - - mfRepo := &mockMediaFileRepository{} - mfRepo.On("GetAll", []model.QueryOptions{{ - Filters: squirrel.Eq{"album_id": "1"}, - Sort: "album", - }}).Return(mfs, nil) - ds.On("MediaFile").Return(mfRepo) + putTracks( + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1, TrackNumber: 1}, + model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1, TrackNumber: 2}, + ) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}). Return(nil, stream.ErrTooManyTranscodes).Once() @@ -314,17 +317,14 @@ var _ = Describe("Archiver", func() { Context("ZipPlaylist", func() { It("names the entries and the M3U lines after the resolved format", func() { - pls := &model.Playlist{ID: "1", Name: "Test Playlist", Tracks: []model.PlaylistTrack{ - {Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"}, - }} - plRepo := &mockPlaylistRepository{} - plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil) - ds.On("Playlist").Return(plRepo) + putPlaylist("1", "Test Playlist", + model.MediaFile{Path: "test_data/01 - track1.flac", Suffix: "flac", Artist: "Artist 1", Title: "track1"}, + ) dc.resolved = &stream.Request{Format: "opus", BitRate: 128} ms.On("NewStream", mock.Anything, mock.Anything, *dc.resolved).Return(io.NopCloser(strings.NewReader("test")), nil) out := new(bytes.Buffer) - Expect(arch.ZipPlaylist(GinkgoT().Context(), "1", "mp3", 128, out)).To(Succeed()) + Expect(arch.ZipPlaylist(ctx, "1", "mp3", 128, out)).To(Succeed()) zr, err := zip.NewReader(bytes.NewReader(out.Bytes()), int64(out.Len())) Expect(err).ToNot(HaveOccurred()) @@ -338,20 +338,10 @@ var _ = Describe("Archiver", func() { }) It("zips a playlist correctly", func() { - tracks := []model.PlaylistTrack{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"}, - {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"}, - } - - pls := &model.Playlist{ - ID: "1", - Name: "Test Playlist", - Tracks: tracks, - } - - plRepo := &mockPlaylistRepository{} - plRepo.On("GetWithTracks", "1", true, false).Return(pls, nil) - ds.On("Playlist").Return(plRepo) + putPlaylist("1", "Test Playlist", + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "AC/DC", Title: "track1"}, + model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1, Artist: "Artist 2", Title: "track2"}, + ) ms.On("NewStream", mock.Anything, mock.Anything, stream.Request{Format: "mp3", BitRate: 128}).Return(io.NopCloser(strings.NewReader("test")), nil).Times(2) out := new(bytes.Buffer) @@ -384,18 +374,15 @@ var _ = Describe("Archiver", func() { pngData = []byte("\x89PNG\x0d\x0a\x1a\x0a fake png") ) - mockAlbumTracks := func(filter squirrel.Sqlizer, mfs model.MediaFiles) { - mfRepo := &mockMediaFileRepository{} - mfRepo.On("GetAll", []model.QueryOptions{{Filters: filter, Sort: "album"}}).Return(mfs, nil) - ds.On("MediaFile", mock.Anything).Return(mfRepo) + putAlbumTracks := func(mfs ...model.MediaFile) { + GinkgoHelper() + putTracks(mfs...) ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil) } It("adds the album cover to the album folder", func() { ca.images["al-1"] = jpegData - mockAlbumTracks(squirrel.Eq{"album_id": "1"}, model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1}, - }) + putAlbumTracks(model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album/Promo", DiscNumber: 1}) out := new(bytes.Buffer) Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed()) @@ -410,13 +397,10 @@ var _ = Describe("Archiver", func() { ca.images["ar-1"] = pngData ca.images["al-1"] = jpegData ca.images["al-2"] = jpegData - mockAlbumTracks(squirrel.And{ - persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist), - squirrel.Eq{"missing": false}, - }, model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1}, - {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album 2", DiscNumber: 1}, - }) + putAlbumTracks(byArtist("1", + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album 1", DiscNumber: 1}, + model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Album 2", DiscNumber: 1}, + )...) out := new(bytes.Buffer) Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed()) @@ -431,13 +415,10 @@ var _ = Describe("Archiver", func() { It("puts each same-named album's cover in that album's own folder", func() { ca.images["al-1"] = jpegData ca.images["al-2"] = pngData - mockAlbumTracks(squirrel.And{ - persistence.ParticipantIDFilter("media_file", "1", model.RoleAlbumArtist), - squirrel.Eq{"missing": false}, - }, model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001, DiscNumber: 1}, - {Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005, DiscNumber: 1}, - }) + putAlbumTracks(byArtist("1", + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Greatest Hits", Year: 2001, DiscNumber: 1}, + model.MediaFile{Path: "test_data/02 - track2.mp3", Suffix: "mp3", AlbumID: "2", Album: "Greatest Hits", Year: 2005, DiscNumber: 1}, + )...) out := new(bytes.Buffer) Expect(arch.ZipArtist(ctx, "1", "mp3", 128, out)).To(Succeed()) @@ -449,15 +430,9 @@ var _ = Describe("Archiver", func() { It("adds the playlist cover to the root", func() { ca.images["pl-1"] = jpegData - plRepo := &mockPlaylistRepository{} - plRepo.On("GetWithTracks", "1", true, false).Return(&model.Playlist{ - ID: "1", - Name: "Test Playlist", - Tracks: []model.PlaylistTrack{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"}, - }, - }, nil) - ds.On("Playlist", mock.Anything).Return(plRepo) + putPlaylist("1", "Test Playlist", + model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Artist: "Artist 1", Title: "track1"}, + ) ms.On("NewStream", mock.Anything, mock.Anything, mock.Anything).Return(io.NopCloser(strings.NewReader("test")), nil) out := new(bytes.Buffer) @@ -495,9 +470,7 @@ var _ = Describe("Archiver", func() { It("still builds the archive when the cover cannot be read", func() { ca.err = errors.New("boom") - mockAlbumTracks(squirrel.Eq{"album_id": "1"}, model.MediaFiles{ - {Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1}, - }) + putAlbumTracks(model.MediaFile{Path: "test_data/01 - track1.mp3", Suffix: "mp3", AlbumID: "1", Album: "Album", DiscNumber: 1}) out := new(bytes.Buffer) Expect(arch.ZipAlbum(ctx, "1", "mp3", 128, out)).To(Succeed()) @@ -551,54 +524,6 @@ func (m *mockCoverArt) Get(ctx context.Context, artID model.ArtworkID, size int, return &artwork.Image{ReadCloser: io.NopCloser(bytes.NewReader(data))}, nil } -type mockDataStore struct { - mock.Mock - model.DataStore -} - -func (m *mockDataStore) MediaFile() model.MediaFileRepository { - args := m.Called() - return args.Get(0).(model.MediaFileRepository) -} - -func (m *mockDataStore) Playlist() model.PlaylistRepository { - args := m.Called() - return args.Get(0).(model.PlaylistRepository) -} - -func (m *mockDataStore) Library() model.LibraryRepository { - return &mockLibraryRepository{} -} - -type mockLibraryRepository struct { - mock.Mock - model.LibraryRepository -} - -func (m *mockLibraryRepository) GetPath(_ context.Context, id int) (string, error) { - return "/music", nil -} - -type mockMediaFileRepository struct { - mock.Mock - model.MediaFileRepository -} - -func (m *mockMediaFileRepository) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { - args := m.Called(options) - return args.Get(0).(model.MediaFiles), args.Error(1) -} - -type mockPlaylistRepository struct { - mock.Mock - model.PlaylistRepository -} - -func (m *mockPlaylistRepository) GetWithTracks(_ context.Context, id string, refreshSmartPlaylists, includeMissing bool) (*model.Playlist, error) { - args := m.Called(id, refreshSmartPlaylists, includeMissing) - return args.Get(0).(*model.Playlist), args.Error(1) -} - type mockMediaStreamer struct { mock.Mock stream.MediaStreamer diff --git a/core/artwork/agent_images_test.go b/core/artwork/agent_images_test.go index 71ee79273..08a76490b 100644 --- a/core/artwork/agent_images_test.go +++ b/core/artwork/agent_images_test.go @@ -13,8 +13,9 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/utils/str" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -65,7 +66,7 @@ func imageAgents(fakes ...*fakeImageAgent) *agents.Agents { names = append(names, fake.name) } conf.Update(func(c *conf.Options) { c.Agents = strings.Join(names, ",") }) - return agents.GetAgents(&tests.MockDataStore{}, nil) + return agents.GetAgents(persistence.New(db.Db()), nil) } var _ = Describe("agent images", func() { diff --git a/core/artwork/artwork_suite_test.go b/core/artwork/artwork_suite_test.go index 4106a5d38..fdfd9aa46 100644 --- a/core/artwork/artwork_suite_test.go +++ b/core/artwork/artwork_suite_test.go @@ -1,7 +1,9 @@ package artwork import ( + "cmp" "context" + "errors" "io/fs" "net/netip" "net/url" @@ -14,9 +16,13 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/core/storage" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/metadata" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/httpclient" . "github.com/onsi/ginkgo/v2" @@ -27,22 +33,27 @@ import ( func TestArtwork(t *testing.T) { // Runs unconditionally: the two leaks below are pre-existing and out of this // package's control, so they're ignored by exact top-function instead. - defer goleak.VerifyNone(t, - goleak.IgnoreTopFunction("github.com/onsi/ginkgo/v2/internal/interrupt_handler.(*InterruptHandler).registerForInterrupts.func2"), - // notify's own init() starts a singleton tree the moment it's imported (via - // core/storage/local or plugins); recursive on darwin, nonrecursive on linux. - goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*recursiveTree).dispatch"), - goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).dispatch"), - goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).internal"), - ) + // A cleanup rather than a defer, so it runs after persistencetest closes the database. + t.Cleanup(func() { + goleak.VerifyNone(t, + goleak.IgnoreTopFunction("github.com/onsi/ginkgo/v2/internal/interrupt_handler.(*InterruptHandler).registerForInterrupts.func2"), + // notify's own init() starts a singleton tree the moment it's imported (via + // core/storage/local or plugins); recursive on darwin, nonrecursive on linux. + goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*recursiveTree).dispatch"), + goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).dispatch"), + goleak.IgnoreTopFunction("github.com/rjeczalik/notify.(*nonrecursiveTree).internal"), + ) + }) tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Artwork Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() // productionImageClient keeps the guarded client for the specs that assert it refuses loopback. var productionImageClient = remoteImageClient @@ -97,36 +108,103 @@ func (s *osDirStorage) FS() (storage.MusicFS, error) { return osDirFS{os.DirFS(s.root)}, nil } -// fakeFolderRepo covers the three FolderRepository methods the resolvers reach for. The zero value -// answers as an unremarkable library does; the fields drive the album-root lookup and its failures. -type fakeFolderRepo struct { - model.FolderRepository - result []model.Folder - err error - parentResult *model.Folder - getErr error - getCallCount int - // hasOtherAudio is returned by HasAudioOutsideFolders (the album-root check). - // False means the parent qualifies as an album root. - hasOtherAudio bool - otherAudioErr error +// fixtureAlbumDir is relative to the repo root, which tests.Init makes the working directory. +const fixtureAlbumDir = "tests/fixtures/artist/an-album" + +var testAdmin = model.User{ID: "admin-1", UserName: "admin", IsAdmin: true} + +func asAdmin(ctx context.Context) context.Context { + return request.WithUser(ctx, testAdmin) } -func (f *fakeFolderRepo) GetAll(context.Context, ...model.QueryOptions) ([]model.Folder, error) { - return f.result, f.err +// newTestDS returns a store over the suite database, with testAdmin stored. +func newTestDS(ctx context.Context) model.DataStore { + GinkgoHelper() + ds := persistence.New(db.Db()) + admin := testAdmin + Expect(ds.User().Put(ctx, &admin)).To(Succeed()) + return ds } -func (f *fakeFolderRepo) HasAudioOutsideFolders(context.Context, model.Folder, []string) (bool, error) { - return f.hasOtherAudio, f.otherAudioErr +// useLibrary moves library 1 to root, read through the testfile scheme. +func useLibrary(ctx context.Context, ds model.DataStore, root string) { + GinkgoHelper() + persistencetest.SetLibraries(ctx, ds, testFileLibPath(root)) } -func (f *fakeFolderRepo) Get(context.Context, string) (*model.Folder, error) { - f.getCallCount++ - if f.getErr != nil { - return nil, f.getErr +// putFolder stores library 1's folder at rel holding images, and returns its ID. +func putFolder(ctx context.Context, ds model.DataStore, rel string, images ...string) string { + GinkgoHelper() + lib, err := ds.Library().Get(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + f := model.NewFolder(*lib, rel) + f.ImageFiles = images + f.ImagesUpdatedAt = time.Now().Truncate(time.Second) + Expect(ds.Folder().Put(ctx, f)).To(Succeed()) + return f.ID +} + +// putArtistAlbums stores the artist and makes it the sole album artist of albums. +func putArtistAlbums(ctx context.Context, ds model.DataStore, ar model.Artist, albums ...model.Album) { + GinkgoHelper() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, ar) + for i := range albums { + albums[i].Participants = model.Participants{model.RoleAlbumArtist: {{Artist: ar}}} } - if f.parentResult != nil { - return f.parentResult, nil + persistencetest.PutAlbums(ctx, ds, albums...) +} + +// putRadio stores the radio without the artwork request its Put enqueues. +func putRadio(ctx context.Context, ds model.DataStore, rd model.Radio) { + GinkgoHelper() + Expect(ds.Radio().Put(asAdmin(ctx), &rd)).To(Succeed()) + unqueue(model.KindRadioArtwork, rd.ID) +} + +// putPlaylist stores a testAdmin playlist with one track per album, without the cover rebuild its +// Put enqueues. +func putPlaylist(ctx context.Context, ds model.DataStore, pls model.Playlist, albumIDs ...string) { + GinkgoHelper() + pls.OwnerID = cmp.Or(pls.OwnerID, testAdmin.ID) + for _, albumID := range albumIDs { + mf := model.MediaFile{ID: pls.ID + "-" + albumID, AlbumID: albumID, Path: pls.ID + "/" + albumID + ".mp3"} + persistencetest.PutMediaFiles(ctx, ds, mf) + pls.Tracks = append(pls.Tracks, model.PlaylistTrack{MediaFileID: mf.ID, MediaFile: mf}) } - return nil, model.ErrNotFound + Expect(ds.Playlist().Put(asAdmin(ctx), &pls)).To(Succeed()) + unqueue(model.KindPlaylistArtwork, pls.ID) +} + +func unqueue(kind model.Kind, id string) { + GinkgoHelper() + _, err := db.Db().Exec("DELETE FROM artwork_queue WHERE item_kind = ? AND item_id = ?", kind.Prefix(), id) + Expect(err).ToNot(HaveOccurred()) +} + +// queued returns the primary image's queue row, or nil when there is none. +func queued(ctx context.Context, ds model.DataStore, kind, id string) *model.ArtworkQueueItem { + GinkgoHelper() + k, ok := model.ParseKind(kind) + Expect(ok).To(BeTrue(), kind) + it, err := ds.ArtworkQueue().Get(ctx, k, id, model.ImageTypePrimary) + if errors.Is(err, model.ErrNotFound) { + return nil + } + Expect(err).ToNot(HaveOccurred()) + return it +} + +func queueCount(ctx context.Context, ds model.DataStore) int64 { + GinkgoHelper() + n, err := ds.ArtworkQueue().Count(ctx) + Expect(err).ToNot(HaveOccurred()) + return n +} + +// expireQueued ages a row past the retry budget, so the next drain settles it instead of retrying. +func expireQueued(kind, id string) { + GinkgoHelper() + _, err := db.Db().Exec("UPDATE artwork_queue SET enqueued_at = ? WHERE item_kind = ? AND item_id = ?", + time.Now().Add(-(giveUpAfter + time.Hour)), kind, id) + Expect(err).ToNot(HaveOccurred()) } diff --git a/core/artwork/artwork_test.go b/core/artwork/artwork_test.go index 00a72cecf..0e5f82b1a 100644 --- a/core/artwork/artwork_test.go +++ b/core/artwork/artwork_test.go @@ -3,6 +3,7 @@ package artwork import ( "bytes" "context" + "errors" "image" "io" "os" @@ -11,7 +12,9 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/resources" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/cache" @@ -22,13 +25,8 @@ import ( var _ = Describe("Artwork", func() { var ( ctx context.Context - ds *tests.MockDataStore - artRepo *tests.MockArtworkRepo - queueRepo *tests.MockArtworkQueueRepo - albumRepo *tests.MockAlbumRepo - mfRepo *tests.MockMediaFileRepo - folderRepo *fakeFolderRepo - libRepo *tests.MockLibraryRepo + ds model.DataStore + artRepo model.ArtworkRepository ffm *tests.MockFFmpeg store *ImageStore imgCache cache.FileCache @@ -38,7 +36,18 @@ var _ = Describe("Artwork", func() { seedEntity func(kind, id string) ) - primaryKey := func(kind, id string) string { return kind + "|" + id + "|" + model.ImageTypePrimary } + queuedPriority := func(kind, id string) int { + GinkgoHelper() + it := queued(ctx, ds, kind, id) + Expect(it).ToNot(BeNil(), "%s-%s must be queued", kind, id) + return it.Priority + } + + setImagesUpdatedAt := func(folderID string, t time.Time) { + GinkgoHelper() + _, err := db.Db().Exec("UPDATE folder SET images_updated_at = ? WHERE id = ?", t, folderID) + Expect(err).ToNot(HaveOccurred()) + } seedFoundStore := func(kind, id string, imgBytes []byte) string { hash, err := hashImage(bytes.NewReader(imgBytes)) @@ -50,14 +59,19 @@ var _ = Describe("Artwork", func() { return hash } - // Without its owning entity, a state row is not served at all. + // Without its owning entity, a state row is not served at all. An entity a spec already + // stored is kept as is. seedEntity = func(kind, id string) { GinkgoHelper() switch kind { case "al": - Expect(albumRepo.Put(ctx, &model.Album{ID: id, Name: "Album"})).To(Succeed()) + if _, err := ds.Album().Get(ctx, id); errors.Is(err, model.ErrNotFound) { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: id, Name: "Album"}) + } case "mf": - Expect(mfRepo.Put(ctx, &model.MediaFile{ID: id})).To(Succeed()) + if _, err := ds.MediaFile().Get(ctx, id); errors.Is(err, model.ErrNotFound) { + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: id, Path: id + ".mp3"}) + } } } @@ -85,21 +99,9 @@ var _ = Describe("Artwork", func() { c.CacheFolder = conf.NewDir(GinkgoT().TempDir()) }) - artRepo = tests.CreateMockArtworkRepo() - queueRepo = tests.CreateMockArtworkQueueRepo() - albumRepo = tests.CreateMockAlbumRepo() - mfRepo = tests.CreateMockMediaFileRepo() - folderRepo = &fakeFolderRepo{} - libRepo = &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - ds = &tests.MockDataStore{ - MockedArtwork: artRepo, - MockedArtworkQueue: queueRepo, - MockedAlbum: albumRepo, - MockedMediaFile: mfRepo, - MockedFolder: folderRepo, - MockedLibrary: libRepo, - } + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) + artRepo = ds.Artwork() ffm = tests.NewMockFFmpeg("") store = NewImageStore(GinkgoT().TempDir()) imgCache = cache.NewFileCache("ServingTest", "100MB", "images", 0, @@ -172,7 +174,7 @@ var _ = Describe("Artwork", func() { _, err := svc.Get(ctx, tests.MustParseArtworkID("al-alni"), 0, false) Expect(err).To(MatchError(ErrUnavailable)) - Expect(queueRepo.Data[primaryKey("al", "alni")].Priority).To(Equal(model.ArtworkPriorityScan)) + Expect(queuedPriority("al", "alni")).To(Equal(model.ArtworkPriorityScan)) }) It("refuses a non-image file-backed row even when a resized copy is already cached", func() { @@ -203,7 +205,7 @@ var _ = Describe("Artwork", func() { _, err = svc.Get(ctx, tests.MustParseArtworkID("al-alnic"), 100, false) Expect(err).To(MatchError(ErrUnavailable)) - Expect(queueRepo.Data[primaryKey("al", "alnic")].Priority).To(Equal(model.ArtworkPriorityScan)) + Expect(queuedPriority("al", "alnic")).To(Equal(model.ArtworkPriorityScan)) }) It("treats a full-size mtime mismatch as dangling: unavailable, re-enqueued at Scan, state untouched", func() { @@ -219,7 +221,7 @@ var _ = Describe("Artwork", func() { _, err := svc.Get(ctx, tests.MustParseArtworkID("al-al3"), 0, false) Expect(err).To(MatchError(ErrUnavailable)) - Expect(queueRepo.Data[primaryKey("al", "al3")].Priority).To(Equal(model.ArtworkPriorityScan)) + Expect(queuedPriority("al", "al3")).To(Equal(model.ArtworkPriorityScan)) ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Hash).To(Equal("bbbbbbbbbbbbbbbb")) @@ -238,16 +240,17 @@ var _ = Describe("Artwork", func() { _, err := svc.Get(ctx, tests.MustParseArtworkID("al-al3b"), 100, false) Expect(err).To(MatchError(ErrUnavailable)) - Expect(queueRepo.Data[primaryKey("al", "al3b")].Priority).To(Equal(model.ArtworkPriorityScan)) + Expect(queuedPriority("al", "al3b")).To(Equal(model.ArtworkPriorityScan)) }) // State rows outlive a deleted entity until the next prune. It("refuses to serve a found row whose entity is gone", func() { hash := seedFoundStore("al", "alzz", coverBytes) Expect(hash).ToNot(BeEmpty()) - albumRepo.SetData(model.Albums{}) // the album is deleted; its artwork row survives + _, err := db.Db().Exec("DELETE FROM album WHERE id = ?", "alzz") // its artwork row survives + Expect(err).ToNot(HaveOccurred()) - _, err := svc.Get(ctx, tests.MustParseArtworkID("al-alzz"), 0, false) + _, err = svc.Get(ctx, tests.MustParseArtworkID("al-alzz"), 0, false) Expect(err).To(MatchError(ErrUnavailable)) }) @@ -258,31 +261,30 @@ var _ = Describe("Artwork", func() { _, err := svc.Get(ctx, tests.MustParseArtworkID("al-al4"), 0, false) Expect(err).To(MatchError(ErrUnavailable)) - Expect(queueRepo.Data).To(BeEmpty()) + Expect(queueCount(ctx, ds)).To(BeZero()) }) }) Describe("provisional read-through", func() { It("serves local folder art, enqueues a Bump, and writes no state row", func() { - folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{{ID: "al5", Name: "Album", FolderIDs: []string{"f1"}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al5", Name: "Album", FolderIDs: []string{fid}}) img, err := svc.Get(ctx, tests.MustParseArtworkID("al-al5"), 0, false) Expect(err).ToNot(HaveOccurred()) Expect(readAll(img)).To(Equal(coverBytes)) - Expect(queueRepo.Data[primaryKey("al", "al5")].Priority).To(Equal(model.ArtworkPriorityBump)) + Expect(queuedPriority("al", "al5")).To(Equal(model.ArtworkPriorityBump)) _, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al5", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound)) }) It("returns ErrUnavailable and enqueues a Bump when nothing local resolves", func() { - folderRepo.result = nil - albumRepo.SetData(model.Albums{{ID: "al6", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al6", Name: "Album"}) _, err := svc.Get(ctx, tests.MustParseArtworkID("al-al6"), 0, false) Expect(err).To(MatchError(ErrUnavailable)) - Expect(queueRepo.Data[primaryKey("al", "al6")].Priority).To(Equal(model.ArtworkPriorityBump)) + Expect(queuedPriority("al", "al6")).To(Equal(model.ArtworkPriorityBump)) _, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al6", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound)) }) @@ -301,7 +303,7 @@ var _ = Describe("Artwork", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false }) seedFoundStore("mf", "mf7", []byte("stale embedded track art")) seedFoundStore("al", "albz", coverBytes) - mfRepo.SetData(model.MediaFiles{{ID: "mf7", AlbumID: "albz"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf7", AlbumID: "albz", Path: "mf7.mp3"}) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf7"), 0, false) Expect(err).ToNot(HaveOccurred()) @@ -311,47 +313,44 @@ var _ = Describe("Artwork", func() { It("delegates to the album when the track's state is absent", func() { seedFoundStore("al", "albm", coverBytes) Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "mf", ItemID: "mf2"})).To(Succeed()) - mfRepo.SetData(model.MediaFiles{{ID: "mf2", AlbumID: "albm"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf2", AlbumID: "albm", Path: "mf2.mp3"}) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf2"), 0, false) Expect(err).ToNot(HaveOccurred()) Expect(readAll(img)).To(Equal(coverBytes)) - _, mfEnq := queueRepo.Data[primaryKey("mf", "mf2")] - Expect(mfEnq).To(BeFalse()) + Expect(queued(ctx, ds, "mf", "mf2")).To(BeNil()) }) It("delegates to the album (no enqueue) when the track is not embedded-eligible", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) seedFoundStore("al", "albn", coverBytes) - mfRepo.SetData(model.MediaFiles{{ID: "mf3", AlbumID: "albn", HasCoverArt: false}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf3", AlbumID: "albn", Path: "mf3.mp3", HasCoverArt: false}) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf3"), 0, false) Expect(err).ToNot(HaveOccurred()) Expect(readAll(img)).To(Equal(coverBytes)) - _, mfEnq := queueRepo.Data[primaryKey("mf", "mf3")] - Expect(mfEnq).To(BeFalse()) + Expect(queued(ctx, ds, "mf", "mf3")).To(BeNil()) }) It("extracts embedded art provisionally and enqueues the track when eligible", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) - mfRepo.SetData(model.MediaFiles{{ - ID: "mf4", AlbumID: "albo", HasCoverArt: true, - Path: "tests/fixtures/artist/an-album/test.mp3", LibraryID: 0, - }}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ + ID: "mf4", AlbumID: "albo", HasCoverArt: true, Path: fixtureAlbumDir + "/test.mp3", + }) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf4"), 0, false) Expect(err).ToNot(HaveOccurred()) Expect(readAll(img)).ToNot(BeEmpty()) - Expect(queueRepo.Data[primaryKey("mf", "mf4")].Priority).To(Equal(model.ArtworkPriorityBump)) + Expect(queuedPriority("mf", "mf4")).To(Equal(model.ArtworkPriorityBump)) _, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf4", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound)) }) It("delegates a multi-disc track to its disc art, not straight to the album", func() { - folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{{ID: "aldd", Name: "Album", FolderIDs: []string{"f1"}, Discs: model.Discs{1: "One", 2: "Two"}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldd", Name: "Album", FolderIDs: []string{fid}, Discs: model.Discs{1: "One", 2: "Two"}}) seedFoundStore("al", "aldd", []byte("album-art-distinct")) // album's own found art differs - mfRepo.SetData(model.MediaFiles{{ID: "mf5", AlbumID: "aldd", DiscNumber: 1, HasCoverArt: false}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf5", AlbumID: "aldd", DiscNumber: 1, FolderID: fid, Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: false}) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf5"), 0, false) Expect(err).ToNot(HaveOccurred()) @@ -362,11 +361,10 @@ var _ = Describe("Artwork", func() { It("falls back to the album when an eligible track's embedded art will not extract", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) // HasCoverArt is set, but the file is not audio, so nothing extracts. - mfRepo.SetData(model.MediaFiles{{ - ID: "mfbad", AlbumID: "albad", LibraryID: 0, HasCoverArt: true, - Path: "tests/fixtures/artist/an-album/front.png", - }}) - albumRepo.SetData(model.Albums{{ID: "albad", Name: "Album"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ + ID: "mfbad", AlbumID: "albad", HasCoverArt: true, Path: fixtureAlbumDir + "/front.png", + }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "albad", Name: "Album"}) seedFoundStore("al", "albad", coverBytes) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mfbad"), 0, false) @@ -376,10 +374,10 @@ var _ = Describe("Artwork", func() { It("routes a single-disc track through disc resolution too", func() { // DiscArtPriority applies to single-disc albums too, over the album's own found art. - folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{{ID: "alsd", Name: "Album", FolderIDs: []string{"f1"}, Discs: model.Discs{1: ""}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alsd", Name: "Album", FolderIDs: []string{fid}, Discs: model.Discs{1: ""}}) seedFoundStore("al", "alsd", []byte("album-art-distinct")) - mfRepo.SetData(model.MediaFiles{{ID: "mf6", AlbumID: "alsd", DiscNumber: 1, HasCoverArt: false}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf6", AlbumID: "alsd", DiscNumber: 1, FolderID: fid, Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: false}) img, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf6"), 0, false) Expect(err).ToNot(HaveOccurred()) @@ -389,8 +387,8 @@ var _ = Describe("Artwork", func() { Describe("disc", func() { It("serves a local disc-folder image", func() { - folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{{ID: "aldc", Name: "Album", FolderIDs: []string{"f1"}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc", Name: "Album", FolderIDs: []string{fid}}) img, err := svc.Get(ctx, model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc", 1), nil), 0, false) Expect(err).ToNot(HaveOccurred()) @@ -400,8 +398,8 @@ var _ = Describe("Artwork", func() { // The resize cache keys on id + album mtime, not on the bytes, so dropping the source // between the two requests is what shows a warm hit never touches the filesystem. It("serves a sized disc image from cache without re-reading the source", func() { - folderRepo.result = []model.Folder{{Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{{ID: "aldc3", Name: "Album", FolderIDs: []string{"f1"}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc3", Name: "Album", FolderIDs: []string{fid}}) discID := model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc3", 1), nil) first, err := svc.Get(ctx, discID, 64, false) @@ -409,7 +407,9 @@ var _ = Describe("Artwork", func() { warmed := readAll(first) Expect(warmed).ToNot(BeEmpty()) - folderRepo.result = nil + // Unlisting the images leaves the cache key alone, so only a cache hit can still serve. + _, err = db.Db().Exec("UPDATE folder SET image_files = '[]' WHERE id = ?", fid) + Expect(err).ToNot(HaveOccurred()) second, err := svc.Get(ctx, discID, 64, false) Expect(err).ToNot(HaveOccurred()) @@ -418,11 +418,9 @@ var _ = Describe("Artwork", func() { // A disc image can change without the album row changing, so the key folds in ImagesUpdatedAt. It("invalidates the cached image when the folder's images change", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}, - ImagesUpdatedAt: time.Now().Add(-time.Hour), - }} - albumRepo.SetData(model.Albums{{ID: "aldc4", Name: "Album", FolderIDs: []string{"f1"}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + setImagesUpdatedAt(fid, time.Now().Add(-time.Hour)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc4", Name: "Album", FolderIDs: []string{fid}}) discID := model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc4", 1), nil) first, err := svc.Get(ctx, discID, 64, false) @@ -430,7 +428,7 @@ var _ = Describe("Artwork", func() { firstKey := first.ETag readAll(first) - folderRepo.result[0].ImagesUpdatedAt = time.Now() + setImagesUpdatedAt(fid, time.Now()) second, err := svc.Get(ctx, discID, 64, false) Expect(err).ToNot(HaveOccurred()) readAll(second) @@ -439,11 +437,9 @@ var _ = Describe("Artwork", func() { // Disc art has no content hash, so without an explicit validator every ETag would be empty. It("gives a full-size disc image a validator that tracks the source", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", ImageFiles: []string{"cover.jpg"}, - ImagesUpdatedAt: time.Now().Add(-time.Hour), - }} - albumRepo.SetData(model.Albums{{ID: "aldc5", Name: "Album", FolderIDs: []string{"f1"}}}) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + setImagesUpdatedAt(fid, time.Now().Add(-time.Hour)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc5", Name: "Album", FolderIDs: []string{fid}}) discID := model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc5", 1), nil) first, err := svc.Get(ctx, discID, 0, false) @@ -451,7 +447,7 @@ var _ = Describe("Artwork", func() { readAll(first) Expect(first.ETag).ToNot(BeEmpty()) - folderRepo.result[0].ImagesUpdatedAt = time.Now() + setImagesUpdatedAt(fid, time.Now()) second, err := svc.Get(ctx, discID, 0, false) Expect(err).ToNot(HaveOccurred()) readAll(second) @@ -459,8 +455,7 @@ var _ = Describe("Artwork", func() { }) It("falls back to album art when no disc image matches", func() { - folderRepo.result = nil - albumRepo.SetData(model.Albums{{ID: "aldc2", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "aldc2", Name: "Album"}) seedFoundStore("al", "aldc2", coverBytes) img, err := svc.Get(ctx, model.NewArtworkID(model.KindDiscArtwork, model.DiscArtworkID("aldc2", 1), nil), 0, false) @@ -471,7 +466,7 @@ var _ = Describe("Artwork", func() { Describe("GetOrPlaceholder", func() { It("accepts a raw entity id and serves its cover art", func() { - albumRepo.SetData(model.Albums{{ID: "rawal", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "rawal", Name: "Album"}) seedFoundStore("al", "rawal", coverBytes) img, err := svc.GetOrPlaceholder(ctx, "rawal", 0, false) @@ -526,17 +521,14 @@ func fileMtime(path string) int64 { var _ = Describe("EntityExists", func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() - albumRepo := tests.CreateMockAlbumRepo() - albumRepo.SetData(model.Albums{{ID: "al1"}}) - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{{ID: "ar1"}}) - radioRepo := tests.CreateMockedRadioRepo() - Expect(radioRepo.Put(ctx, &model.Radio{ID: "ra1", Name: "R"})).To(Succeed()) - ds = &tests.MockDataStore{MockedAlbum: albumRepo, MockedArtist: artistRepo, MockedRadio: radioRepo} + ds = newTestDS(ctx) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album"}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist"}) + putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "R"}) }) DescribeTable("reports whether the owning entity is still there", diff --git a/core/artwork/e2e/acquire_serve_test.go b/core/artwork/e2e/acquire_serve_test.go index 2adbc14c0..045fe2646 100644 --- a/core/artwork/e2e/acquire_serve_test.go +++ b/core/artwork/e2e/acquire_serve_test.go @@ -13,9 +13,14 @@ import ( "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/artwork" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/tests/harness" "github.com/navidrome/navidrome/utils/cache" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -25,22 +30,31 @@ import ( var _ = Describe("Acquisition → serve loop", func() { var ( ctx context.Context - ds *tests.MockDataStore - artRepo *tests.MockArtworkRepo - queueRepo *tests.MockArtworkQueueRepo - albumRepo *tests.MockAlbumRepo - artistRepo *tests.MockArtistRepo - mfRepo *tests.MockMediaFileRepo - plRepo *tests.MockPlaylistRepo - radioRepo *tests.MockedRadioRepo - folderRepo *fakeFolderRepo - libRepo *tests.MockLibraryRepo + ds model.DataStore + artRepo model.ArtworkRepository store *artwork.ImageStore svc artwork.Artwork worker *artwork.Worker coverBytes []byte ) + // Requests carry a user, the worker resolves as the first admin, and only admins may store + // radios and playlists, so every call runs as this admin. + admin := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true} + putFolder := func(rel string, images ...string) string { + GinkgoHelper() + lib, err := ds.Library().Get(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + f := model.NewFolder(*lib, rel) + f.ImageFiles = images + Expect(ds.Folder().Put(ctx, f)).To(Succeed()) + return f.ID + } + putRadio := func(rd model.Radio) { + GinkgoHelper() + Expect(ds.Radio().Put(ctx, &rd)).To(Succeed()) + } + itemFound := func(kind model.Kind, id string) func() bool { return func() bool { ia, err := artRepo.GetItemArtwork(ctx, kind, id, model.ImageTypePrimary) @@ -63,7 +77,7 @@ var _ = Describe("Acquisition → serve loop", func() { } BeforeEach(func() { - ctx = GinkgoT().Context() + ctx = request.WithUser(GinkgoT().Context(), admin) repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) coverBytes = readFixture(coverFixture) @@ -77,28 +91,12 @@ var _ = Describe("Acquisition → serve loop", func() { c.DevArtworkWorkerConcurrency = 1 }) - folderRepo = &fakeFolderRepo{} - libRepo = &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: repoRoot}}) - artRepo = tests.CreateMockArtworkRepo() - queueRepo = tests.CreateMockArtworkQueueRepo() - albumRepo = tests.CreateMockAlbumRepo() - artistRepo = tests.CreateMockArtistRepo() - mfRepo = tests.CreateMockMediaFileRepo() - plRepo = tests.CreateMockPlaylistRepo() - radioRepo = tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{} - ds = &tests.MockDataStore{ - MockedArtwork: artRepo, - MockedArtworkQueue: queueRepo, - MockedAlbum: albumRepo, - MockedArtist: artistRepo, - MockedMediaFile: mfRepo, - MockedPlaylist: plRepo, - MockedRadio: radioRepo, - MockedFolder: folderRepo, - MockedLibrary: libRepo, - } + harness.TruncateDB(userTables) + ds = persistence.New(db.Db()) + artRepo = ds.Artwork() + u := admin + Expect(ds.User().Put(ctx, &u)).To(Succeed()) + Expect(ds.Library().Put(ctx, &model.Library{ID: model.DefaultLibraryID, Name: "Music", Path: repoRoot})).To(Succeed()) ffm := tests.NewMockFFmpeg("") store = artwork.NewImageStore(GinkgoT().TempDir()) // size=0 requests stream originals, so this reader is never called (serving_test covers resizing). @@ -113,8 +111,8 @@ var _ = Describe("Acquisition → serve loop", func() { }) seedFolderAlbum := func(albumID string) { - folderRepo.result = []model.Folder{{Path: albumFolderPath, ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{{ID: albumID, Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0}}) + GinkgoHelper() + persistencetest.PutAlbums(ctx, ds, model.Album{ID: albumID, Name: "Album", FolderIDs: []string{putFolder(albumFolderPath, "cover.jpg")}}) } It("acquires and serves a cover whose format has no registered decoder (#5950)", func() { @@ -123,9 +121,8 @@ var _ = Describe("Acquisition → serve loop", func() { Expect(os.WriteFile(filepath.Join(libDir, "an-album", "cover.jxl"), jxlFixture, 0600)).To(Succeed()) conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" }) - libRepo.SetData(model.Libraries{{ID: 0, Path: libDir}}) - folderRepo.result = []model.Folder{{Path: "an-album", ImageFiles: []string{"cover.jxl"}}} - albumRepo.SetData(model.Albums{{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0}}) + persistencetest.SetLibraries(ctx, ds, libDir) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{putFolder("an-album", "cover.jxl")}}) bump("al", "al1") runWorkerUntil(ctx, worker, itemFound(model.KindAlbumArtwork, "al1")) @@ -154,7 +151,7 @@ var _ = Describe("Acquisition → serve loop", func() { It("acquires an artist's uploaded image and serves it", func() { name := writeUpload(consts.EntityArtist, "artist-e2e.png", artistPngFixture) - artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist", UploadedImage: name}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist", UploadedImage: name}) bump("ar", "ar1") runWorkerUntil(ctx, worker, itemFound(model.KindArtistArtwork, "ar1")) @@ -170,8 +167,10 @@ var _ = Describe("Acquisition → serve loop", func() { It("generates a playlist grid from its tracks' album art and serves it from the store", func() { seedFolderAlbum("al1") - plRepo.SetData(model.Playlists{{ID: "pl1", Name: "Playlist"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"al1"}} + track := model.MediaFile{ID: "mfpl", AlbumID: "al1", LibraryID: model.DefaultLibraryID, Path: "pl/track.mp3"} + Expect(ds.MediaFile().Put(ctx, &track)).To(Succeed()) + Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: "pl1", Name: "Playlist", OwnerID: admin.ID, + Tracks: model.PlaylistTracks{{MediaFileID: track.ID, MediaFile: track}}})).To(Succeed()) bump("pl", "pl1") runWorkerUntil(ctx, worker, itemFound(model.KindPlaylistArtwork, "pl1")) @@ -190,7 +189,7 @@ var _ = Describe("Acquisition → serve loop", func() { It("acquires a radio station's uploaded image and serves it", func() { name := writeUpload(consts.EntityRadio, "radio-e2e.jpg", coverFixture) - radioRepo.Data["ra1"] = &model.Radio{ID: "ra1", Name: "Station", UploadedImage: name} + putRadio(model.Radio{ID: "ra1", Name: "Station", UploadedImage: name}) bump("ra", "ra1") runWorkerUntil(ctx, worker, itemFound(model.KindRadioArtwork, "ra1")) @@ -205,9 +204,9 @@ var _ = Describe("Acquisition → serve loop", func() { }) It("serves an unresolved track provisionally, then upgrades to the worker's state row", func() { - mfRepo.SetData(model.MediaFiles{{ - ID: "mf1", AlbumID: "al1", HasCoverArt: true, LibraryID: 0, Path: mp3Fixture, - }}) + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ + ID: "mf1", AlbumID: "al1", HasCoverArt: true, LibraryID: model.DefaultLibraryID, Path: mp3Fixture, + })).To(Succeed()) provisional, err := svc.Get(ctx, tests.MustParseArtworkID("mf-mf1"), 0, false) Expect(err).ToNot(HaveOccurred()) @@ -255,7 +254,7 @@ var _ = Describe("Acquisition → serve loop", func() { It("acquires GIF artwork, whose decoder only core/artwork's blank import registers", func() { writeUploadedImage(consts.EntityRadio, "station.gif", gifFixture) - radioRepo.Data["ra1"] = &model.Radio{ID: "ra1", Name: "Station", UploadedImage: "station.gif"} + putRadio(model.Radio{ID: "ra1", Name: "Station", UploadedImage: "station.gif"}) bump("ra", "ra1") runWorkerUntil(ctx, worker, itemFound(model.KindRadioArtwork, "ra1")) @@ -268,11 +267,11 @@ var _ = Describe("Acquisition → serve loop", func() { }) It("deduplicates byte-identical art across entities onto one image row", func() { - folderRepo.result = []model.Folder{{Path: albumFolderPath, ImageFiles: []string{"cover.jpg"}}} - albumRepo.SetData(model.Albums{ - {ID: "al1", Name: "Album", FolderIDs: []string{"f1"}, LibraryID: 0}, - {ID: "al2", Name: "Same Cover", FolderIDs: []string{"f1"}, LibraryID: 0}, - }) + fid := putFolder(albumFolderPath, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}}, + model.Album{ID: "al2", Name: "Same Cover", FolderIDs: []string{fid}}, + ) bump("al", "al1") bump("al", "al2") runWorkerUntil(ctx, worker, func() bool { @@ -289,7 +288,7 @@ var _ = Describe("Acquisition → serve loop", func() { It("stops serving a file-backed image once its source file changes underneath", func() { name := writeUpload(consts.EntityRadio, "radio-stale.jpg", coverFixture) - radioRepo.Data["ra1"] = &model.Radio{ID: "ra1", Name: "Station", UploadedImage: name} + putRadio(model.Radio{ID: "ra1", Name: "Station", UploadedImage: name}) bump("ra", "ra1") runWorkerUntil(ctx, worker, itemFound(model.KindRadioArtwork, "ra1")) @@ -317,7 +316,7 @@ var _ = Describe("Acquisition → serve loop", func() { }) It("records an absent state for an entity with no art and reports it unavailable", func() { - albumRepo.SetData(model.Albums{{ID: "alx", Name: "Artless", LibraryID: 0}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Artless"}) bump("al", "alx") runWorkerUntil(ctx, worker, itemAbsent(model.KindAlbumArtwork, "alx")) diff --git a/core/artwork/e2e/e2e_suite_test.go b/core/artwork/e2e/e2e_suite_test.go index fdeba3000..1ab911bdf 100644 --- a/core/artwork/e2e/e2e_suite_test.go +++ b/core/artwork/e2e/e2e_suite_test.go @@ -65,23 +65,6 @@ func runWorkerUntil(ctx context.Context, worker *artwork.Worker, until func() bo Eventually(done, 2*time.Second).Should(Receive(BeNil())) } -type fakeFolderRepo struct { - model.FolderRepository - result []model.Folder -} - -func (f *fakeFolderRepo) GetAll(context.Context, ...model.QueryOptions) ([]model.Folder, error) { - return f.result, nil -} - -func (f *fakeFolderRepo) HasAudioOutsideFolders(context.Context, model.Folder, []string) (bool, error) { - return false, nil -} - -func (f *fakeFolderRepo) Get(context.Context, string) (*model.Folder, error) { - return nil, model.ErrNotFound -} - func writeUpload(entityType, name, srcFixture string) string { GinkgoHelper() dst := model.UploadedImagePath(entityType, name) diff --git a/core/artwork/e2e/resolution_harness_test.go b/core/artwork/e2e/resolution_harness_test.go index d6ca38473..9b679fd21 100644 --- a/core/artwork/e2e/resolution_harness_test.go +++ b/core/artwork/e2e/resolution_harness_test.go @@ -30,6 +30,7 @@ import ( "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" @@ -50,7 +51,7 @@ const ( var ( rctx context.Context - rds *tests.MockDataStore + rds model.DataStore rstore *artwork.ImageStore rsvc artwork.Artwork rworker *artwork.Worker @@ -74,7 +75,9 @@ var _ = BeforeSuite(func() { db.Db().SetMaxOpenConns(1) db.Init(request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", IsAdmin: true})) - userTables = harness.ResettableTables() + var err error + userTables, err = persistencetest.Tables() + Expect(err).ToNot(HaveOccurred()) }) var _ = AfterSuite(func() { @@ -99,7 +102,7 @@ func setupResolutionHarness() { rctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", UserName: "admin", IsAdmin: true}) harness.TruncateDB(userTables) - rds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + rds = persistence.New(db.Db()) adminUser := model.User{ID: "admin-1", UserName: "admin", Name: "Admin", IsAdmin: true, NewPassword: "password"} Expect(rds.User().Put(rctx, &adminUser)).To(Succeed()) diff --git a/core/artwork/folders_album_test.go b/core/artwork/folders_album_test.go index 7d18cc4ab..89a2576db 100644 --- a/core/artwork/folders_album_test.go +++ b/core/artwork/folders_album_test.go @@ -6,27 +6,59 @@ import ( "time" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) +// spyFolderRepo counts parent lookups and can fail them or the album-root check. +type spyFolderRepo struct { + model.FolderRepository + getCalls int + getErr error + otherAudioErr error +} + +func (f *spyFolderRepo) Get(ctx context.Context, id string) (*model.Folder, error) { + f.getCalls++ + if f.getErr != nil { + return nil, f.getErr + } + return f.FolderRepository.Get(ctx, id) +} + +func (f *spyFolderRepo) HasAudioOutsideFolders(ctx context.Context, parent model.Folder, excludeIDs []string) (bool, error) { + if f.otherAudioErr != nil { + return false, f.otherAudioErr + } + return f.FolderRepository.HasAudioOutsideFolders(ctx, parent, excludeIDs) +} + // The e2e specs cover which image wins for a layout; these pin what a layout cannot reach: that // the album-root parent is only fetched when it could qualify, and what happens when that fails. var _ = Describe("loadAlbumFoldersPaths", func() { var ( ctx context.Context - ds *tests.MockDataStore - repo *fakeFolderRepo + ds model.DataStore + repo *spyFolderRepo album model.Album now time.Time ) + putFolders := func(folders ...model.Folder) { + GinkgoHelper() + for _, f := range folders { + f.LibraryID = model.DefaultLibraryID + Expect(ds.Folder().Put(ctx, &f)).To(Succeed()) + } + } + BeforeEach(func() { ctx = GinkgoT().Context() now = time.Now().Truncate(time.Second) - repo = &fakeFolderRepo{} - ds = &tests.MockDataStore{MockedFolder: repo} + real := newTestDS(ctx) + repo = &spyFolderRepo{FolderRepository: real.Folder()} + ds = persistencetest.Stub(real, persistencetest.Repos{Folder: func(model.FolderRepository) model.FolderRepository { return repo }}) album = model.Album{ ID: "album1", Name: "Album", @@ -35,73 +67,72 @@ var _ = Describe("loadAlbumFoldersPaths", func() { }) It("does not query the parent when it is already one of the album's folders", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist", Name: "Album", ParentID: "folder2", + putFolders( + model.Folder{ID: "folder1", Path: "Artist", Name: "Album", ParentID: "folder2", ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - {ID: "folder2", Path: "", Name: "Artist", ImagesUpdatedAt: now}, - } + model.Folder{ID: "folder2", Path: "", Name: "Artist", ImagesUpdatedAt: now}, + ) _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) Expect(err).ToNot(HaveOccurred()) Expect(imgFiles).To(ConsistOf("Artist/Album/cover.jpg")) - Expect(repo.getCallCount).To(BeZero()) + Expect(repo.getCalls).To(BeZero()) }) It("does not query the parent when the album's folders have different parents", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist1/Album", Name: "part1", ParentID: "parentA", + putFolders( + model.Folder{ID: "folder1", Path: "Artist1/Album", Name: "part1", ParentID: "parentA", ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - {ID: "folder2", Path: "Artist2/Album", Name: "part2", ParentID: "parentB", + model.Folder{ID: "folder2", Path: "Artist2/Album", Name: "part2", ParentID: "parentB", ImagesUpdatedAt: now}, - } + ) _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) Expect(err).ToNot(HaveOccurred()) Expect(imgFiles).To(ConsistOf("Artist1/Album/part1/cover.jpg")) - Expect(repo.getCallCount).To(BeZero()) + Expect(repo.getCalls).To(BeZero()) }) It("does not query the parent for a single-folder album that has images of its own", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist", Name: "Album", ParentID: "artistFolder", - ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - } + putFolders(model.Folder{ID: "folder1", Path: "Artist", Name: "Album", ParentID: "artistFolder", + ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}) _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) Expect(err).ToNot(HaveOccurred()) Expect(imgFiles).To(ConsistOf("Artist/Album/cover.jpg")) - Expect(repo.getCallCount).To(BeZero()) + Expect(repo.getCalls).To(BeZero()) }) It("does not promote the library root, so its images never become album art", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: ".", Name: "AlbumPart1", ParentID: "rootFolder", + putFolders( + model.Folder{ID: "folder1", Path: ".", Name: "AlbumPart1", ParentID: "rootFolder", ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - {ID: "folder2", Path: ".", Name: "AlbumPart2", ParentID: "rootFolder", + model.Folder{ID: "folder2", Path: ".", Name: "AlbumPart2", ParentID: "rootFolder", ImagesUpdatedAt: now}, - } - repo.parentResult = &model.Folder{ID: "rootFolder", Name: ".", ImageFiles: []string{"unrelated.jpg"}} + model.Folder{ID: "rootFolder", Name: ".", ImageFiles: []string{"unrelated.jpg"}}, + ) _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) Expect(err).ToNot(HaveOccurred()) Expect(imgFiles).To(ConsistOf("AlbumPart1/cover.jpg")) - Expect(repo.getCallCount).To(Equal(1)) + Expect(repo.getCalls).To(Equal(1)) }) It("does not promote a parent that holds another album's audio", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder", + putFolders( + model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder", ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - {ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder", + model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder", ImagesUpdatedAt: now}, - } - repo.parentResult = &model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album", - ParentID: "artistFolder", ImageFiles: []string{"artist.jpg"}} - repo.hasOtherAudio = true + model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album", + ParentID: "artistFolder", ImageFiles: []string{"artist.jpg"}}, + model.Folder{ID: "otherAlbum", Path: "Artist/Album", Name: "Bonus", ParentID: "albumFolder", + NumAudioFiles: 3}, + ) _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) @@ -110,14 +141,14 @@ var _ = Describe("loadAlbumFoldersPaths", func() { }) It("promotes the album root parent into the returned paths", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder", - ImagesUpdatedAt: now}, - {ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder", - ImagesUpdatedAt: now}, - } - repo.parentResult = &model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album", - ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}} + putFolders( + model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "albumFolder", + ImagesUpdatedAt: now, NumAudioFiles: 5}, + model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "albumFolder", + ImagesUpdatedAt: now, NumAudioFiles: 5}, + model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album", + ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}}, + ) paths, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) @@ -127,12 +158,12 @@ var _ = Describe("loadAlbumFoldersPaths", func() { }) It("propagates errors from the album-root check", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist/Album", Name: "disc1", ParentID: "albumFolder", + putFolders( + model.Folder{ID: "folder1", Path: "Artist/Album", Name: "disc1", ParentID: "albumFolder", ImagesUpdatedAt: now}, - } - repo.parentResult = &model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album", - ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}} + model.Folder{ID: "albumFolder", Path: "Artist", Name: "Album", + ParentID: "artistFolder", ImageFiles: []string{"cover.jpg"}}, + ) repo.otherAudioErr = errors.New("db connection failed") _, _, _, err := loadAlbumFoldersPaths(ctx, ds, album) @@ -141,33 +172,33 @@ var _ = Describe("loadAlbumFoldersPaths", func() { }) It("propagates non-ErrNotFound errors from the parent folder lookup", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "parentFolder", + putFolders( + model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "parentFolder", ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - {ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "parentFolder", + model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "parentFolder", ImagesUpdatedAt: now}, - } + ) repo.getErr = errors.New("db connection failed") _, _, _, err := loadAlbumFoldersPaths(ctx, ds, album) Expect(err).To(MatchError("db connection failed")) - Expect(repo.getCallCount).To(Equal(1)) + Expect(repo.getCalls).To(Equal(1)) }) It("continues when the parent folder has been deleted", func() { - repo.result = []model.Folder{ - {ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "missingParent", + putFolders( + model.Folder{ID: "folder1", Path: "Artist/Album", Name: "CD1", ParentID: "missingParent", ImagesUpdatedAt: now, ImageFiles: []string{"cover.jpg"}}, - {ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "missingParent", + model.Folder{ID: "folder2", Path: "Artist/Album", Name: "CD2", ParentID: "missingParent", ImagesUpdatedAt: now}, - } + ) _, imgFiles, _, err := loadAlbumFoldersPaths(ctx, ds, album) Expect(err).ToNot(HaveOccurred()) Expect(imgFiles).To(ConsistOf("Artist/Album/CD1/cover.jpg")) - Expect(repo.getCallCount).To(Equal(1)) + Expect(repo.getCalls).To(Equal(1)) }) }) diff --git a/core/artwork/folders_artist_paths_test.go b/core/artwork/folders_artist_paths_test.go index 723bd36b7..c04be1af4 100644 --- a/core/artwork/folders_artist_paths_test.go +++ b/core/artwork/folders_artist_paths_test.go @@ -7,7 +7,7 @@ import ( "time" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -38,8 +38,7 @@ var _ = Describe("commonDir", func() { var _ = Describe("loadArtistFolder", func() { var ( ctx context.Context - ds *tests.MockDataStore - repo *fakeFolderRepo + ds model.DataStore albums model.Albums updatedAt time.Time ) @@ -47,10 +46,13 @@ var _ = Describe("loadArtistFolder", func() { BeforeEach(func() { ctx = GinkgoT().Context() updatedAt = time.Now().Truncate(time.Second).Add(5 * time.Minute) - repo = &fakeFolderRepo{result: []model.Folder{{ImagesUpdatedAt: updatedAt}}} - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 1, Path: filepath.FromSlash("/music")}}) - ds = &tests.MockDataStore{MockedFolder: repo, MockedLibrary: libRepo} + ds = newTestDS(ctx) + persistencetest.SetLibraries(ctx, ds, filepath.FromSlash("/music")) + lib, err := ds.Library().Get(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + artistFolder := model.NewFolder(*lib, "artist") + artistFolder.ImagesUpdatedAt = updatedAt + Expect(ds.Folder().Put(ctx, artistFolder)).To(Succeed()) albums = model.Albums{{LibraryID: 1, ID: "album1", Name: "Album 1"}} }) @@ -68,7 +70,7 @@ var _ = Describe("loadArtistFolder", func() { Expect(err).ToNot(HaveOccurred()) Expect(folder).To(Equal(filepath.FromSlash("/music/artist"))) - Expect(upd).To(Equal(updatedAt)) + Expect(upd).To(BeTemporally("==", updatedAt)) }) It("climbs above the shared folder when two albums live in the same one", func() { @@ -79,7 +81,7 @@ var _ = Describe("loadArtistFolder", func() { Expect(err).ToNot(HaveOccurred()) Expect(folder).To(Equal(filepath.FromSlash("/music/artist"))) - Expect(upd).To(Equal(updatedAt)) + Expect(upd).To(BeTemporally("==", updatedAt)) }) It("stops at the folder where distinct album roots already meet", func() { @@ -90,11 +92,13 @@ var _ = Describe("loadArtistFolder", func() { Expect(err).ToNot(HaveOccurred()) Expect(folder).To(Equal(filepath.FromSlash("/music/artist"))) - Expect(upd).To(Equal(updatedAt)) + Expect(upd).To(BeTemporally("==", updatedAt)) }) It("returns the error when the folder lookup fails", func() { - repo.err = errors.New("fake error") + ds = persistencetest.Stub(ds, persistencetest.Repos{Folder: func(r model.FolderRepository) model.FolderRepository { + return &failingFolderRepo{FolderRepository: r, err: errors.New("fake error")} + }}) folder, upd, err := loadArtistFolder(ctx, ds, albums, []string{ filepath.FromSlash("/music/artist/album1"), @@ -106,3 +110,12 @@ var _ = Describe("loadArtistFolder", func() { Expect(upd).To(BeZero()) }) }) + +type failingFolderRepo struct { + model.FolderRepository + err error +} + +func (f *failingFolderRepo) GetAll(context.Context, ...model.QueryOptions) ([]model.Folder, error) { + return nil, f.err +} diff --git a/core/artwork/housekeeping_test.go b/core/artwork/housekeeping_test.go index d18b06178..a39b23982 100644 --- a/core/artwork/housekeeping_test.go +++ b/core/artwork/housekeeping_test.go @@ -7,7 +7,7 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -27,10 +27,8 @@ var _ = Describe("RefreshableKinds", func() { var _ = Describe("Housekeeping", func() { var ( - ctx context.Context - ds *tests.MockDataStore - queueRepo *tests.MockArtworkQueueRepo - propRepo *tests.MockedPropertyRepo + ctx context.Context + ds model.DataStore ) BeforeEach(func() { @@ -42,9 +40,7 @@ var _ = Describe("Housekeeping", func() { c.EnableExternalServices = true }) - queueRepo = tests.CreateMockArtworkQueueRepo() - propRepo = &tests.MockedPropertyRepo{} - ds = &tests.MockDataStore{MockedArtworkQueue: queueRepo, MockedProperty: propRepo} + ds = newTestDS(ctx) }) Describe("Fingerprint", func() { @@ -99,65 +95,60 @@ var _ = Describe("Housekeeping", func() { It("records the current fingerprint when none was ever stored", func() { Expect(ReconcileConfigFingerprint(ctx, ds)).To(Succeed()) - Expect(propRepo.Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal(ConfigFingerprint())) + Expect(ds.Property().Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal(ConfigFingerprint())) }) It("leaves a stale fingerprint stored, so the warning survives a restart", func() { - Expect(propRepo.Put(ctx, consts.ArtConfFingerprintPropertyKey, "stale-fingerprint")).To(Succeed()) + Expect(ds.Property().Put(ctx, consts.ArtConfFingerprintPropertyKey, "stale-fingerprint")).To(Succeed()) Expect(ReconcileConfigFingerprint(ctx, ds)).To(Succeed()) - Expect(propRepo.Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal("stale-fingerprint")) + Expect(ds.Property().Get(ctx, consts.ArtConfFingerprintPropertyKey)).To(Equal("stale-fingerprint")) }) }) Describe("EnqueueMissingAll", func() { - var artRepo *tests.MockArtworkRepo - BeforeEach(func() { - artRepo = tests.CreateMockArtworkRepo() - ds.MockedArtwork = artRepo - queueRepo.ItemArtworkSource = artRepo - queueRepo.ExistingIDs = map[string]map[string]bool{ - "al": {"al1": true, "al2": true}, - "ar": {"ar1": true}, - "pl": {"pl1": true}, - "ra": {"ra1": true}, - } + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album 1"}, model.Album{ID: "al2", Name: "Album 2"}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist"}) + putPlaylist(ctx, ds, model.Playlist{ID: "pl1", Name: "Playlist"}) + putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "Radio"}) }) It("enqueues only entities that have no item_artwork row, across all kinds", func() { - artRepo.ItemData["al-resolved"] = model.ItemArtwork{ItemKind: "al", ItemID: "al1", ImageType: model.ImageTypePrimary, Hash: "somehash"} - artRepo.ItemData["ar-absent"] = model.ItemArtwork{ItemKind: "ar", ItemID: "ar1", ImageType: model.ImageTypePrimary, Hash: ""} + Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "al", ItemID: "al1", ImageType: model.ImageTypePrimary, Hash: "somehash"})).To(Succeed()) + Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "ar1", ImageType: model.ImageTypePrimary, Hash: ""})).To(Succeed()) err := enqueueMissingAll(ctx, ds) Expect(err).ToNot(HaveOccurred()) - for _, it := range queueRepo.Data { - Expect(it.Priority).To(Equal(model.ArtworkPriorityRecheck)) + stats, err := ds.ArtworkQueue().CountQueued(ctx, nil, nil) + Expect(err).ToNot(HaveOccurred()) + Expect(stats).ToNot(BeEmpty()) + for _, st := range stats { + Expect(st.Priority).To(Equal(model.ArtworkPriorityRecheck)) } - Expect(findQueued(queueRepo, "al", "al2")).ToNot(BeNil()) - Expect(findQueued(queueRepo, "pl", "pl1")).ToNot(BeNil()) - Expect(findQueued(queueRepo, "ra", "ra1")).ToNot(BeNil()) - Expect(findQueued(queueRepo, "al", "al1")).To(BeNil()) - Expect(findQueued(queueRepo, "ar", "ar1")).To(BeNil()) + Expect(queued(ctx, ds, "al", "al2")).ToNot(BeNil()) + Expect(queued(ctx, ds, "pl", "pl1")).ToNot(BeNil()) + Expect(queued(ctx, ds, "ra", "ra1")).ToNot(BeNil()) + Expect(queued(ctx, ds, "al", "al1")).To(BeNil()) + Expect(queued(ctx, ds, "ar", "ar1")).To(BeNil()) }) }) }) var _ = Describe("ItemName", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ctx context.Context BeforeEach(func() { ctx = GinkgoT().Context() - albumRepo := tests.CreateMockAlbumRepo() - albumRepo.SetData(model.Albums{ - {ID: "al-1", Name: "Kid A"}, - {ID: "al-2", Name: "Sandinista!", Discs: model.Discs{2: "Side Three"}}, - }) - ds = &tests.MockDataStore{MockedAlbum: albumRepo} - Expect(ds.Artist().(*tests.MockArtistRepo).Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed()) + ds = newTestDS(ctx) + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "al-1", Name: "Kid A"}, + model.Album{ID: "al-2", Name: "Sandinista!", Discs: model.Discs{2: "Side Three"}}, + ) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Radiohead"}) }) It("returns the album name", func() { diff --git a/core/artwork/library_fs_test.go b/core/artwork/library_fs_test.go index 868c5e45a..53c4ac886 100644 --- a/core/artwork/library_fs_test.go +++ b/core/artwork/library_fs_test.go @@ -3,28 +3,30 @@ package artwork import ( "context" + "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/storage/storagetest" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("loadLibraryView", Ordered, func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore BeforeAll(func() { + DeferCleanup(conf.SnapshotConfig()) storagetest.Register("fake", &storagetest.FakeFS{}) }) BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{MockedLibrary: &tests.MockLibraryRepo{}} + ds = newTestDS(ctx) }) It("returns a view for a library backed by registered storage", func() { - Expect(ds.Library().Put(ctx, &model.Library{ID: 1, Path: "fake:///music"})).To(Succeed()) + persistencetest.SetLibraries(ctx, ds, "fake:///music") lib, err := loadLibraryView(ctx, ds, 1) Expect(err).ToNot(HaveOccurred()) @@ -45,7 +47,7 @@ var _ = Describe("loadLibraryView", Ordered, func() { }) It("returns an error when the library path uses an unregistered scheme", func() { - Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Path: "unsupported:///music"})).To(Succeed()) + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Unsupported", Path: "unsupported:///music"})).To(Succeed()) _, err := loadLibraryView(ctx, ds, 2) Expect(err).To(HaveOccurred()) }) diff --git a/core/artwork/processor_test.go b/core/artwork/processor_test.go index a1b07ebb7..906a5d0fa 100644 --- a/core/artwork/processor_test.go +++ b/core/artwork/processor_test.go @@ -18,7 +18,9 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -43,36 +45,34 @@ func pngHeaderWithDims(w, h uint32) []byte { var _ = Describe("processor.acquire", func() { var ( - ctx context.Context - ds *tests.MockDataStore - folderRepo *fakeFolderRepo - libRepo *tests.MockLibraryRepo - ffm *tests.MockFFmpeg - ag *agents.Agents - store *ImageStore - artRepo *tests.MockArtworkRepo - repoRoot string - proc *processor + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + ag *agents.Agents + store *ImageStore + artRepo model.ArtworkRepository + repoRoot string + proc *processor ) + // poisonBlurHash overwrites a stored image's blurhash, so a later re-decode would show. + poisonBlurHash := func(hash string) { + GinkgoHelper() + _, err := db.Db().Exec("UPDATE artwork SET blur_hash = 'SENTINEL' WHERE hash = ?", hash) + Expect(err).ToNot(HaveOccurred()) + } + BeforeEach(func() { ctx = GinkgoT().Context() var err error repoRoot, err = os.Getwd() Expect(err).ToNot(HaveOccurred()) - folderRepo = &fakeFolderRepo{} - libRepo = &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) ffm = tests.NewMockFFmpeg("") - ag = agents.GetAgents(&tests.MockDataStore{}, nil) - artRepo = tests.CreateMockArtworkRepo() - ds = &tests.MockDataStore{ - MockedFolder: folderRepo, - MockedLibrary: libRepo, - MockedArtwork: artRepo, - } - ds.MockedAlbum = tests.CreateMockAlbumRepo() + ag = agents.GetAgents(ds, nil) + artRepo = ds.Artwork() store = NewImageStore(GinkgoT().TempDir()) proc = &processor{ds: ds, store: store, resolver: newResolver(ds, ag, ffm, nil)} @@ -80,13 +80,8 @@ var _ = Describe("processor.acquire", func() { }) It("found-folder: persists state from a folder image, writes no store file, keeps sourcePath/refMtime", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1"}) Expect(out).To(Equal(outcomeFound)) @@ -117,13 +112,8 @@ var _ = Describe("processor.acquire", func() { }) It("holds it once across the write window", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "alL1", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alL1", Name: "Album", FolderIDs: []string{fid}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alL1"}) Expect(out).To(Equal(outcomeFound)) @@ -134,10 +124,7 @@ var _ = Describe("processor.acquire", func() { // Resolution can reach the network, so holding the lock across it would let one slow // provider block prune, and every drain queued behind prune's writer. It("never takes it while only resolving", func() { - folderRepo.result = nil - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "alL2", Name: "Album", FolderIDs: []string{"f1"}}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alL2", Name: "Album", FolderIDs: []string{"f1"}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alL2"}) Expect(out).To(Equal(outcomeAbsent)) @@ -146,10 +133,7 @@ var _ = Describe("processor.acquire", func() { }) It("found-embedded: writes a store file and computes a non-empty blurhash from a real fixture", func() { - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}, - }) - folderRepo.result = nil + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al2", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{"f1"}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"}) Expect(out).To(Equal(outcomeFound)) @@ -169,10 +153,7 @@ var _ = Describe("processor.acquire", func() { }) It("absent: no local source and no external error persists a known-absent state", func() { - folderRepo.result = nil - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al3", Name: "Album"}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Album"}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3"}) Expect(out).To(Equal(outcomeAbsent)) @@ -189,11 +170,9 @@ var _ = Describe("processor.acquire", func() { // A folder listing that names a cover the FS will not hand over: a stale mount. libRoot := GinkgoT().TempDir() Expect(os.MkdirAll(filepath.Join(libRoot, "an-album"), 0o755)).To(Succeed()) - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}}) - folderRepo.result = []model.Folder{{Path: "an-album", ImageFiles: []string{"cover.jpg"}}} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al-io", Name: "Album", FolderIDs: []string{"f1"}}, - }) + useLibrary(ctx, ds, libRoot) + fid := putFolder(ctx, ds, "an-album", "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-io", Name: "Album", FolderIDs: []string{fid}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al-io"}) Expect(out).To(Equal(outcomeFailed)) @@ -208,9 +187,6 @@ var _ = Describe("processor.acquire", func() { // The file would still open, so the spec would pass on the decode error instead. Skip("chmod does not restrict read access on Windows") } - radioRepo := tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{} - ds.MockedRadio = radioRepo dir := GinkgoT().TempDir() conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(dir) }) upload := model.UploadedImagePath(consts.EntityRadio, "ra-io.jpg") @@ -218,7 +194,7 @@ var _ = Describe("processor.acquire", func() { Expect(os.WriteFile(upload, []byte("x"), 0o600)).To(Succeed()) Expect(os.Chmod(upload, 0o000)).To(Succeed()) // present, but unreadable DeferCleanup(func() { _ = os.Chmod(upload, 0o600) }) - radioRepo.Data["ra-io"] = &model.Radio{ID: "ra-io", Name: "Station", UploadedImage: "ra-io.jpg"} + putRadio(ctx, ds, model.Radio{ID: "ra-io", Name: "Station", UploadedImage: "ra-io.jpg"}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra-io"}) Expect(out).To(Equal(outcomeFailed)) @@ -234,9 +210,6 @@ var _ = Describe("processor.acquire", func() { // os.Open under a non-directory maps to a not-exist error on Windows, so no localError. Skip("cannot provoke an open fault via a non-directory parent on Windows") } - radioRepo := tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{} - ds.MockedRadio = radioRepo dir := GinkgoT().TempDir() conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(dir) }) upload := model.UploadedImagePath(consts.EntityRadio, "ra-tr.jpg") @@ -244,7 +217,7 @@ var _ = Describe("processor.acquire", func() { // deterministically and regardless of the test user's privileges. Expect(os.MkdirAll(filepath.Dir(filepath.Dir(upload)), 0o755)).To(Succeed()) Expect(os.WriteFile(filepath.Dir(upload), []byte("x"), 0o600)).To(Succeed()) - radioRepo.Data["ra-tr"] = &model.Radio{ID: "ra-tr", Name: "Station", UploadedImage: "ra-tr.jpg"} + putRadio(ctx, ds, model.Radio{ID: "ra-tr", Name: "Station", UploadedImage: "ra-tr.jpg"}) trace := &ChainTrace{} out, _, _ := proc.acquire(withTrace(ctx, trace), model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra-tr"}) @@ -258,9 +231,7 @@ var _ = Describe("processor.acquire", func() { It("failed-on-extError: leaves the item's state untouched", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al4", Name: "Album"}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) out, _, retryIn := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"}) @@ -273,9 +244,7 @@ var _ = Describe("processor.acquire", func() { It("failed-on-extError: reports the delay a throttled provider asked for", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al4r", Name: "Album"}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4r", Name: "Album"}) imageAgents(&fakeImageAgent{name: "throttled", err: &agents.RetryLaterError{RetryIn: 42 * time.Second}}) out, _, retryIn := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4r"}) @@ -285,13 +254,8 @@ var _ = Describe("processor.acquire", func() { It("found-stale: a fallback hit after a transient external failure persists state and returns outcomeFoundStale", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "alstale", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alstale", Name: "Album", FolderIDs: []string{fid}}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alstale"}) @@ -307,9 +271,9 @@ var _ = Describe("processor.acquire", func() { libRoot := GinkgoT().TempDir() Expect(os.MkdirAll(filepath.Join(libRoot, "album"), 0755)).To(Succeed()) Expect(os.WriteFile(filepath.Join(libRoot, "album", "cover.jpg"), jxlCodestream, 0600)).To(Succeed()) - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}}) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alU", Name: "Album", FolderIDs: []string{"f1"}}}) - folderRepo.result = []model.Folder{{Path: "album", ImageFiles: []string{"cover.jpg"}}} + useLibrary(ctx, ds, libRoot) + fid := putFolder(ctx, ds, "album", "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alU", Name: "Album", FolderIDs: []string{fid}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alU"}) Expect(out).To(Equal(outcomeFound)) @@ -327,9 +291,9 @@ var _ = Describe("processor.acquire", func() { libRoot := GinkgoT().TempDir() Expect(os.MkdirAll(filepath.Join(libRoot, "album"), 0755)).To(Succeed()) Expect(os.WriteFile(filepath.Join(libRoot, "album", "cover.jpg"), nil, 0600)).To(Succeed()) - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}}) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alE", Name: "Album", FolderIDs: []string{"f1"}}}) - folderRepo.result = []model.Folder{{Path: "album", ImageFiles: []string{"cover.jpg"}}} + useLibrary(ctx, ds, libRoot) + fid := putFolder(ctx, ds, "album", "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alE", Name: "Album", FolderIDs: []string{fid}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alE"}) Expect(out).To(Equal(outcomeFailed)) @@ -346,7 +310,7 @@ var _ = Describe("processor.acquire", func() { })) DeferCleanup(srv.Close) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alX", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alX", Name: "Album"}) imageAgents(&fakeImageAgent{name: "deezerFake", imgs: []agents.ExternalImage{{URL: srv.URL, Size: 500}}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alX"}) @@ -365,7 +329,7 @@ var _ = Describe("processor.acquire", func() { })) DeferCleanup(srv.Close) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alext", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alext", Name: "Album"}) imageAgents(&fakeImageAgent{name: "deezerFake", imgs: []agents.ExternalImage{{URL: srv.URL, Size: 500}}}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alext"}) @@ -384,14 +348,8 @@ var _ = Describe("processor.acquire", func() { }) It("dedup: a second item with identical bytes skips decode and reuses the artwork row", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al5", Name: "Album A", FolderIDs: []string{"f1"}}, - {ID: "al6", Name: "Album B", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al5", Name: "Album A", FolderIDs: []string{fid}}, model.Album{ID: "al6", Name: "Album B", FolderIDs: []string{fid}}) out1, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al5"}) Expect(out1).To(Equal(outcomeFound)) @@ -399,9 +357,7 @@ var _ = Describe("processor.acquire", func() { Expect(err).ToNot(HaveOccurred()) // A re-decode instead of a hash dedup would overwrite this sentinel. - poisoned := artRepo.Data[ia1.Hash] - poisoned.BlurHash = "SENTINEL" - artRepo.Data[ia1.Hash] = poisoned + poisonBlurHash(ia1.Hash) out2, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al6"}) Expect(out2).To(Equal(outcomeFound)) @@ -426,13 +382,12 @@ var _ = Describe("processor.acquire", func() { Expect(os.WriteFile(img, imgBytes, 0600)).To(Succeed()) Expect(os.Chtimes(img, time.Unix(mtime, 0), time.Unix(mtime, 0))).To(Succeed()) } - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}}) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "alA", Name: "Album A", FolderIDs: []string{"fa"}}, - {ID: "alB", Name: "Album B", FolderIDs: []string{"fb"}}, - }) + useLibrary(ctx, ds, libRoot) + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "alA", Name: "Album A", FolderIDs: []string{putFolder(ctx, ds, "album-a", "cover.jpg")}}, + model.Album{ID: "alB", Name: "Album B", FolderIDs: []string{putFolder(ctx, ds, "album-b", "cover.jpg")}}, + ) - folderRepo.result = []model.Folder{{Path: "album-a", ImageFiles: []string{"cover.jpg"}}} outN, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alA"}) Expect(outN).To(Equal(outcomeFound)) iaA, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alA", model.ImageTypePrimary) @@ -442,11 +397,8 @@ var _ = Describe("processor.acquire", func() { Expect(iaA.RefMtime).To(Equal(time.Unix(1000, 0).UnixNano())) // A re-decode instead of a hash dedup would overwrite this sentinel. - poisoned := artRepo.Data[iaA.Hash] - poisoned.BlurHash = "SENTINEL" - artRepo.Data[iaA.Hash] = poisoned + poisonBlurHash(iaA.Hash) - folderRepo.result = []model.Folder{{Path: "album-b", ImageFiles: []string{"cover.jpg"}}} outN, _, _ = proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alB"}) Expect(outN).To(Equal(outcomeFound)) iaB, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alB", model.ImageTypePrimary) @@ -460,7 +412,7 @@ var _ = Describe("processor.acquire", func() { Expect(filepath.ToSlash(iaAafter.SourcePath)).To(HaveSuffix("album-a/cover.jpg")) Expect(iaAafter.RefMtime).To(Equal(time.Unix(1000, 0).UnixNano())) - Expect(artRepo.Data).To(HaveLen(1)) + Expect(artRepo.GetMimeByHash(ctx)).To(HaveLen(1)) reused, err := artRepo.GetImage(ctx, iaA.Hash) Expect(err).ToNot(HaveOccurred()) Expect(reused.BlurHash).To(Equal("SENTINEL")) @@ -474,9 +426,7 @@ var _ = Describe("processor.acquire", func() { // Truncated PNG: a known format, so this is a real decode failure, not a missing decoder. Expect(os.WriteFile(imgPath, pngHeaderWithDims(100, 100), 0600)).To(Succeed()) - radioRepo := tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{"ra1": {ID: "ra1", Name: "Radio", UploadedImage: "ra1_test.jpg"}} - ds.MockedRadio = radioRepo + putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "Radio", UploadedImage: "ra1_test.jpg"}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra1"}) Expect(out).To(Equal(outcomeFailed)) @@ -495,9 +445,7 @@ var _ = Describe("processor.acquire", func() { Expect(f.Truncate(maxImageBytes() + 1)).To(Succeed()) Expect(f.Close()).To(Succeed()) - radioRepo := tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{"big": {ID: "big", Name: "Radio", UploadedImage: "big_test.jpg"}} - ds.MockedRadio = radioRepo + putRadio(ctx, ds, model.Radio{ID: "big", Name: "Radio", UploadedImage: "big_test.jpg"}) out, _, _ := proc.acquire(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "big"}) Expect(out).To(Equal(outcomeFailed)) @@ -557,9 +505,9 @@ var _ = Describe("processor.acquire", func() { Expect(err).ToNot(HaveOccurred()) Expect(os.MkdirAll(filepath.Join(libRoot, "album"), 0755)).To(Succeed()) Expect(os.WriteFile(filepath.Join(libRoot, "album", "cover.jpg"), imgBytes, 0600)).To(Succeed()) - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}}) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alM", Name: "Album", FolderIDs: []string{"f1"}}}) - folderRepo.result = []model.Folder{{Path: "album", ImageFiles: []string{"cover.jpg"}}} + useLibrary(ctx, ds, libRoot) + fid := putFolder(ctx, ds, "album", "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alM", Name: "Album", FolderIDs: []string{fid}}) hash, err := hashImage(bytes.NewReader(imgBytes)) Expect(err).ToNot(HaveOccurred()) @@ -575,10 +523,7 @@ var _ = Describe("processor.acquire", func() { }) It("store write failure: fails without writing state", func() { - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al7", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}, - }) - folderRepo.result = nil + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al7", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{"f1"}}) // A store root that is a plain file makes every MkdirAll under it fail. blockedRoot := filepath.Join(GinkgoT().TempDir(), "not-a-dir") diff --git a/core/artwork/prune_test.go b/core/artwork/prune_test.go index 206e67b06..09a61dee0 100644 --- a/core/artwork/prune_test.go +++ b/core/artwork/prune_test.go @@ -8,14 +8,16 @@ import ( "path/filepath" "time" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) type flakyGetArtworkRepo struct { - *tests.MockArtworkRepo + model.ArtworkRepository } func (f *flakyGetArtworkRepo) GetMimeByHash(context.Context) (map[string]string, error) { @@ -24,32 +26,29 @@ func (f *flakyGetArtworkRepo) GetMimeByHash(context.Context) (map[string]string, var _ = Describe("Prune", func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore var store *ImageStore - var awRepo *tests.MockArtworkRepo + var awRepo model.ArtworkRepository BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - awRepo = ds.Artwork().(*tests.MockArtworkRepo) + ds = newTestDS(ctx) + awRepo = ds.Artwork() store = NewImageStore(GinkgoT().TempDir()) }) - // PutImage refreshes created_at like the SQL repo, so fixtures are aged directly. + // PutImage refreshes created_at, so fixtures are aged directly. ageArtwork := func(h string, t time.Time) { - a := awRepo.Data[h] - a.CreatedAt = t - awRepo.Data[h] = a + GinkgoHelper() + _, err := db.Db().Exec("UPDATE artwork SET created_at = ? WHERE hash = ?", t, h) + Expect(err).ToNot(HaveOccurred()) } It("purges dangling item_artwork state for gone entities, summed across kinds", func() { + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "live-artist", Name: "Live"}) Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "al", ItemID: "gone-album", ImageType: model.ImageTypePrimary})).To(Succeed()) Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "gone-artist", ImageType: model.ImageTypePrimary})).To(Succeed()) Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "ar", ItemID: "live-artist", ImageType: model.ImageTypePrimary})).To(Succeed()) - awRepo.ExistingIDs = map[string]map[string]bool{ - "al": {}, - "ar": {"live-artist": true}, - } Expect(prune(ctx, ds, store)).To(Succeed()) @@ -62,18 +61,16 @@ var _ = Describe("Prune", func() { }) It("purges dangling artwork_queue rows for gone entities", func() { - queueRepo := tests.CreateMockArtworkQueueRepo() - Expect(queueRepo.Enqueue(ctx, + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "live-album", Name: "Live"}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "gone-album", ImageType: model.ImageTypePrimary}, model.ArtworkQueueItem{ItemKind: "al", ItemID: "live-album", ImageType: model.ImageTypePrimary}, )).To(Succeed()) - queueRepo.ExistingIDs = map[string]map[string]bool{"al": {"live-album": true}} - ds.MockedArtworkQueue = queueRepo Expect(prune(ctx, ds, store)).To(Succeed()) - Expect(findQueued(queueRepo, "al", "gone-album")).To(BeNil()) - Expect(findQueued(queueRepo, "al", "live-album")).ToNot(BeNil()) + Expect(queued(ctx, ds, "al", "gone-album")).To(BeNil()) + Expect(queued(ctx, ds, "al", "live-album")).ToNot(BeNil()) }) It("deletes orphan rows and their store files, keeps referenced ones", func() { @@ -107,6 +104,7 @@ var _ = Describe("Prune", func() { Expect(store.Write(h, "image/jpeg", bytes.NewReader(data))).To(Succeed()) Expect(awRepo.PutImage(ctx, &model.Artwork{Hash: h, Mime: "image/jpeg"})).To(Succeed()) ageArtwork(h, time.Now().Add(-2*time.Hour)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "a1", Name: "Album"}) Expect(awRepo.PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: "al", ItemID: "a1", ImageType: model.ImageTypePrimary, Hash: h, Source: "folder"})).To(Succeed()) @@ -226,7 +224,9 @@ var _ = Describe("Prune", func() { }) It("never sweeps files on a transient DB error", func() { - ds.MockedArtwork = &flakyGetArtworkRepo{MockArtworkRepo: tests.CreateMockArtworkRepo()} + ds = persistencetest.Stub(ds, persistencetest.Repos{Artwork: func(r model.ArtworkRepository) model.ArtworkRepository { + return &flakyGetArtworkRepo{ArtworkRepository: r} + }}) data := []byte("live-bytes") h, _ := hashImage(bytes.NewReader(data)) diff --git a/core/artwork/resolve_test.go b/core/artwork/resolve_test.go index bea2611dc..8358b1ae7 100644 --- a/core/artwork/resolve_test.go +++ b/core/artwork/resolve_test.go @@ -15,6 +15,7 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -44,30 +45,24 @@ var _ = Describe("IsArtistImageFile", func() { var _ = Describe("resolveItem", func() { var ( - ctx context.Context - ds *tests.MockDataStore - folderRepo *fakeFolderRepo - libRepo *tests.MockLibraryRepo - ffm *tests.MockFFmpeg - ag *agents.Agents - repoRoot string + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + ag *agents.Agents + repoRoot string ) BeforeEach(func() { - ctx = GinkgoT().Context() + // The worker resolves as an admin, which is what lets it see private playlists. + ctx = asAdmin(GinkgoT().Context()) var err error repoRoot, err = os.Getwd() Expect(err).ToNot(HaveOccurred()) - folderRepo = &fakeFolderRepo{} - libRepo = &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) ffm = tests.NewMockFFmpeg("") - ag = agents.GetAgents(&tests.MockDataStore{}, nil) - ds = &tests.MockDataStore{ - MockedFolder: folderRepo, - MockedLibrary: libRepo, - } + ag = agents.GetAgents(ds, nil) }) Describe("kind dispatch", func() { @@ -80,13 +75,10 @@ var _ = Describe("resolveItem", func() { Describe("media file", func() { BeforeEach(func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) - ds.MockedMediaFile = tests.CreateMockMediaFileRepo() }) It("resolves embedded art from the track file", func() { - ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: "mf1", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true}, - }) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: true}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mf1"}) Expect(err).ToNot(HaveOccurred()) @@ -99,9 +91,7 @@ var _ = Describe("resolveItem", func() { }) It("resolves absent when the track has no cover art", func() { - ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: "mf2", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: false}, - }) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf2", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: false}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mf2"}) Expect(err).ToNot(HaveOccurred()) @@ -111,9 +101,7 @@ var _ = Describe("resolveItem", func() { It("resolves absent when media file cover art is disabled", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = false }) - ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: "mf3", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true}, - }) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf3", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: true}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mf3"}) Expect(err).ToNot(HaveOccurred()) @@ -130,17 +118,11 @@ var _ = Describe("resolveItem", func() { Describe("album", func() { BeforeEach(func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" }) - ds.MockedAlbum = tests.CreateMockAlbumRepo() }) It("resolves folder art from the library FS", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1"}) Expect(err).ToNot(HaveOccurred()) @@ -153,10 +135,7 @@ var _ = Describe("resolveItem", func() { }) It("falls back to embedded art when no folder image matches", func() { - folderRepo.result = nil - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al2", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{"f1"}}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"}) Expect(err).ToNot(HaveOccurred()) @@ -169,9 +148,7 @@ var _ = Describe("resolveItem", func() { It("sets extErr when the external source errors without being not-found", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al3", Name: "Album"}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3"}) @@ -182,9 +159,7 @@ var _ = Describe("resolveItem", func() { It("does not set extErr when the external source reports not-found", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al4", Name: "Album"}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4", Name: "Album"}) // no image agents enabled -> the external step is a definitive not-found res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"}) @@ -195,13 +170,8 @@ var _ = Describe("resolveItem", func() { It("carries extErr onto a fallback folder hit after a transient external failure", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al6", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al6", Name: "Album", FolderIDs: []string{fid}}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al6"}) @@ -214,13 +184,8 @@ var _ = Describe("resolveItem", func() { It("does not carry extErr onto a fallback folder hit after a definitive external not-found", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al7", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al7", Name: "Album", FolderIDs: []string{fid}}) // no image agents enabled -> the external step is a definitive not-found res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al7"}) @@ -233,9 +198,7 @@ var _ = Describe("resolveItem", func() { It("routes the external step through the injected gate, keyed by agent name", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al5", Name: "Album"}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al5", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("boom")}) var gatedNames []string gate := func(name string, f func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) { @@ -258,9 +221,7 @@ var _ = Describe("resolveItem", func() { imgPath := filepath.Join(tmpDir, "artwork", "artist", "ar1_test.jpg") Expect(os.WriteFile(imgPath, []byte("uploaded artist image"), 0600)).To(Succeed()) - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"}}) - ds.MockedArtist = artistRepo + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1"}) Expect(err).ToNot(HaveOccurred()) @@ -272,18 +233,9 @@ var _ = Describe("resolveItem", func() { It("falls through to the ArtistArtPriority chain when there is no upload", func() { conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "album/artist.*" }) - folderRepo.result = []model.Folder{{ - LibraryPath: testFileLibPath(repoRoot), - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"artist.png"}, - }} - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{{ID: "ar2", Name: "Artist"}}) - ds.MockedArtist = artistRepo - ds.MockedAlbum = tests.CreateMockAlbumRepo() - ds.MockedAlbum.(*tests.MockAlbumRepo).All = model.Albums{ - {ID: "al9", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}}, - } + fid := putFolder(ctx, ds, fixtureAlbumDir, "artist.png") + putArtistAlbums(ctx, ds, model.Artist{ID: "ar2", Name: "Artist"}, + model.Album{ID: "al9", Name: "Album", FolderIDs: []string{fid}}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar2"}) Expect(err).ToNot(HaveOccurred()) @@ -295,9 +247,7 @@ var _ = Describe("resolveItem", func() { It("sets extErr when the external source errors without being not-found", func() { conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" }) - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{{ID: "ar3", Name: "Artist"}}) - ds.MockedArtist = artistRepo + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar3", Name: "Artist"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar3"}) @@ -308,9 +258,7 @@ var _ = Describe("resolveItem", func() { It("does not set extErr when the external source reports not-found", func() { conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" }) - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{{ID: "ar4", Name: "Artist"}}) - ds.MockedArtist = artistRepo + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar4", Name: "Artist"}) // no image agents enabled -> the external step is a definitive not-found res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar4"}) @@ -321,9 +269,7 @@ var _ = Describe("resolveItem", func() { It("routes the external step through the injected gate, keyed by agent name", func() { conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "external" }) - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{{ID: "ar5", Name: "Artist"}}) - ds.MockedArtist = artistRepo + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar5", Name: "Artist"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("boom")}) var gatedNames []string gate := func(name string, f func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) { @@ -343,9 +289,7 @@ var _ = Describe("resolveItem", func() { tmpDir := GinkgoT().TempDir() conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) - radioRepo := tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{"ra1": {ID: "ra1", Name: "Radio"}} - ds.MockedRadio = radioRepo + putRadio(ctx, ds, model.Radio{ID: "ra1", Name: "Radio"}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra1"}) Expect(err).ToNot(HaveOccurred()) @@ -359,9 +303,7 @@ var _ = Describe("resolveItem", func() { imgPath := filepath.Join(tmpDir, "artwork", "radio", "ra2_test.jpg") Expect(os.WriteFile(imgPath, []byte("uploaded radio image"), 0600)).To(Succeed()) - radioRepo := tests.CreateMockedRadioRepo() - radioRepo.Data = map[string]*model.Radio{"ra2": {ID: "ra2", Name: "Radio", UploadedImage: "ra2_test.jpg"}} - ds.MockedRadio = radioRepo + putRadio(ctx, ds, model.Radio{ID: "ra2", Name: "Radio", UploadedImage: "ra2_test.jpg"}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ra", ItemID: "ra2"}) Expect(err).ToNot(HaveOccurred()) @@ -373,27 +315,28 @@ var _ = Describe("resolveItem", func() { }) Describe("playlist", func() { + // artless re-stores the albums with no folder, so they yield no grid tile. + artless := func(ids ...string) { + GinkgoHelper() + for _, id := range ids { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: id, Name: id}) + } + } + BeforeEach(func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum = tests.CreateMockAlbumRepo() - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "t1", Name: "T1", FolderIDs: []string{"f1"}}, - {ID: "t2", Name: "T2", FolderIDs: []string{"f1"}}, - {ID: "t3", Name: "T3", FolderIDs: []string{"f1"}}, - {ID: "t4", Name: "T4", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "t1", Name: "T1", FolderIDs: []string{fid}}, + model.Album{ID: "t2", Name: "T2", FolderIDs: []string{fid}}, + model.Album{ID: "t3", Name: "T3", FolderIDs: []string{fid}}, + model.Album{ID: "t4", Name: "T4", FolderIDs: []string{fid}}, + ) }) DescribeTable("yields a generated grid from up to 4 album tiles", func(albumIDs []string, expectedSize int) { - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl1", Name: "Playlist"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: albumIDs} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pl1", Name: "Playlist"}, albumIDs...) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl1"}) Expect(err).ToNot(HaveOccurred()) @@ -421,11 +364,8 @@ var _ = Describe("resolveItem", func() { c.EnableM3UExternalAlbumArt = false c.CoverArtPriority = "external" }) - folderRepo.result = nil - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "plgrid", Name: "Playlist"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1", "t2"}} - ds.MockedPlaylist = plRepo + artless("t1", "t2") + putPlaylist(ctx, ds, model.Playlist{ID: "plgrid", Name: "Playlist"}, "t1", "t2") imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("boom")}) var gatedNames []string gate := func(name string, f func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) { @@ -445,10 +385,7 @@ var _ = Describe("resolveItem", func() { imgPath := filepath.Join(tmpDir, "artwork", "playlist", "plu_test.jpg") Expect(os.WriteFile(imgPath, []byte("uploaded playlist image"), 0600)).To(Succeed()) - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "plu", Name: "Playlist", UploadedImage: "plu_test.jpg"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1", "t2"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "plu", Name: "Playlist", UploadedImage: "plu_test.jpg"}, "t1", "t2") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plu"}) Expect(err).ToNot(HaveOccurred()) @@ -463,10 +400,7 @@ var _ = Describe("resolveItem", func() { Expect(os.WriteFile(filepath.Join(plDir, "list.m3u"), []byte("#EXTM3U"), 0600)).To(Succeed()) Expect(os.WriteFile(filepath.Join(plDir, "list.jpg"), []byte("sidecar image"), 0600)).To(Succeed()) - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pls", Name: "Playlist", Path: filepath.Join(plDir, "list.m3u")}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1", "t2"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pls", Name: "Playlist", Path: filepath.Join(plDir, "list.m3u")}, "t1", "t2") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pls"}) Expect(err).ToNot(HaveOccurred()) @@ -481,10 +415,7 @@ var _ = Describe("resolveItem", func() { imgPath := filepath.Join(dir, "cover.png") Expect(os.WriteFile(imgPath, []byte("local external image"), 0600)).To(Succeed()) - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pll", Name: "Playlist", ExternalImageURL: imgPath}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pll", Name: "Playlist", ExternalImageURL: imgPath}, "t1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pll"}) Expect(err).ToNot(HaveOccurred()) @@ -496,15 +427,12 @@ var _ = Describe("resolveItem", func() { }) It("never opens a local ExternalImageURL that is not an image file", func() { - folderRepo.result = nil // no grid tiles, so only the local file could produce a reader + artless("t1") // no grid tiles, so only the local file could produce a reader dir := GinkgoT().TempDir() secretPath := filepath.Join(dir, "config.ini") Expect(os.WriteFile(secretPath, []byte("password=secret"), 0600)).To(Succeed()) - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "plni", Name: "Playlist", ExternalImageURL: secretPath}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "plni", Name: "Playlist", ExternalImageURL: secretPath}, "t1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plni"}) Expect(err).ToNot(HaveOccurred()) @@ -514,12 +442,9 @@ var _ = Describe("resolveItem", func() { It("routes ExternalImageURL through extGate and sets extError on transient failure", func() { conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) - folderRepo.result = nil // no grid tiles, so the external failure is what surfaces + artless("t1") // no grid tiles, so the external failure is what surfaces - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "ple", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "ple", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}, "t1") var gatedNames []string gate := func(name string, _ func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) { @@ -536,12 +461,9 @@ var _ = Describe("resolveItem", func() { It("records the m3u failure in the trace even when album sampling adds its own steps", func() { conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) - folderRepo.result = nil // the sampled album yields no tile, so the m3u failure is what forced the retry + artless("t1") // the sampled album yields no tile, so the m3u failure is what forced the retry - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "plm3u", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "plm3u", Name: "Playlist", ExternalImageURL: "http://example.com/cover.jpg"}, "t1") gate := func(string, func() (io.ReadCloser, string, error)) (io.ReadCloser, string, error) { return nil, "", errors.New("network down") @@ -566,12 +488,9 @@ var _ = Describe("resolveItem", func() { }) It("treats a missing local ExternalImageURL as a definitive miss, not extError", func() { - folderRepo.result = nil // no grid tiles, so the local-file miss is what surfaces + artless("t1") // no grid tiles, so the local-file miss is what surfaces - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "plm", Name: "Playlist", ExternalImageURL: "/nonexistent/path/cover.jpg"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "plm", Name: "Playlist", ExternalImageURL: "/nonexistent/path/cover.jpg"}, "t1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plm"}) Expect(err).ToNot(HaveOccurred()) @@ -586,10 +505,7 @@ var _ = Describe("resolveItem", func() { })) defer srv.Close() - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl404", Name: "Playlist", ExternalImageURL: srv.URL}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pl404", Name: "Playlist", ExternalImageURL: srv.URL}, "t1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl404"}) Expect(err).ToNot(HaveOccurred()) @@ -602,8 +518,7 @@ var _ = Describe("resolveItem", func() { // A local resolver holds no agents: reaching the external branch would panic, not degrade. It("skips the external step instead of dereferencing absent agents", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum = tests.CreateMockAlbumRepo() - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Album"}) res, err := newLocalResolver(ds, ffm).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"}) Expect(err).ToNot(HaveOccurred()) @@ -621,10 +536,7 @@ var _ = Describe("resolveItem", func() { })) defer srv.Close() - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pllocal", Name: "Playlist", ExternalImageURL: srv.URL}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pllocal", Name: "Playlist", ExternalImageURL: srv.URL}, "t1") item := model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pllocal"} res, err := newLocalResolver(ds, ffm).resolve(ctx, item) @@ -642,16 +554,13 @@ var _ = Describe("resolveItem", func() { It("treats an ExternalImageURL 500 as a transient failure and sets extError", func() { conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) - folderRepo.result = nil // no grid tiles, so the external failure is what surfaces + artless("t1") // no grid tiles, so the external failure is what surfaces srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) })) defer srv.Close() - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl500", Name: "Playlist", ExternalImageURL: srv.URL}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pl500", Name: "Playlist", ExternalImageURL: srv.URL}, "t1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl500"}) Expect(err).ToNot(HaveOccurred()) @@ -660,14 +569,8 @@ var _ = Describe("resolveItem", func() { }) It("yields an empty resolution when no album has art", func() { - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "empty1", Name: "Empty"}, - }) - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl2", Name: "Playlist"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"empty1"}} - ds.MockedPlaylist = plRepo - folderRepo.result = nil + artless("empty1") + putPlaylist(ctx, ds, model.Playlist{ID: "pl2", Name: "Playlist"}, "empty1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl2"}) Expect(err).ToNot(HaveOccurred()) @@ -679,13 +582,10 @@ var _ = Describe("resolveItem", func() { libRoot := GinkgoT().TempDir() Expect(os.MkdirAll(filepath.Join(libRoot, "bomb"), 0755)).To(Succeed()) Expect(os.WriteFile(filepath.Join(libRoot, "bomb", "cover.jpg"), pngHeaderWithDims(50000, 50000), 0600)).To(Succeed()) - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(libRoot)}}) - folderRepo.result = []model.Folder{{Path: "bomb", ImageFiles: []string{"cover.jpg"}}} + useLibrary(ctx, ds, libRoot) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "t1", Name: "T1", FolderIDs: []string{putFolder(ctx, ds, "bomb", "cover.jpg")}}) - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "plbomb", Name: "Playlist"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"t1"}} - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "plbomb", Name: "Playlist"}, "t1") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plbomb"}) Expect(err).ToNot(HaveOccurred()) @@ -694,11 +594,8 @@ var _ = Describe("resolveItem", func() { }) It("does not resolve as absent when every sampled album fails to resolve", func() { - // The album ids are absent from MockAlbumRepo, so every tile fails non-externally. - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl3", Name: "Playlist"}}) - plRepo.TracksRepo = &tests.MockPlaylistTrackRepo{AlbumIDs: []string{"missing1", "missing2"}} - ds.MockedPlaylist = plRepo + // The tracks point at albums that are not stored, so every tile fails non-externally. + putPlaylist(ctx, ds, model.Playlist{ID: "pl3", Name: "Playlist"}, "missing1", "missing2") res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl3"}) Expect(err).To(HaveOccurred()) @@ -706,17 +603,25 @@ var _ = Describe("resolveItem", func() { }) It("returns an error when the playlist tracks cannot be loaded", func() { - plRepo := tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl4", Name: "Playlist"}}) - ds.MockedPlaylist = plRepo + putPlaylist(ctx, ds, model.Playlist{ID: "pl4", Name: "Playlist"}) + noTracks := persistencetest.Stub(ds, persistencetest.Repos{Playlist: func(r model.PlaylistRepository) model.PlaylistRepository { + return &noTracksPlaylistRepo{PlaylistRepository: r} + }}) - res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl4"}) + res, err := newResolver(noTracks, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "pl4"}) Expect(err).To(HaveOccurred()) Expect(res).To(Equal(resolution{})) }) }) }) +// noTracksPlaylistRepo stands in for a playlist whose track repository cannot be built. +type noTracksPlaylistRepo struct{ model.PlaylistRepository } + +func (noTracksPlaylistRepo) Tracks(context.Context, string, bool) model.PlaylistTrackRepository { + return nil +} + // decodeTile runs before the processor's own guards, so it must enforce the caps itself. var _ = Describe("decodeTile", func() { It("rejects a decompression bomb before the full decode", func() { diff --git a/core/artwork/trace_test.go b/core/artwork/trace_test.go index 821e21e7b..bac86ed33 100644 --- a/core/artwork/trace_test.go +++ b/core/artwork/trace_test.go @@ -12,7 +12,9 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -207,38 +209,28 @@ var _ = Describe("external agent tracing", func() { var _ = Describe("resolveAlbum tracing", func() { var ( - ctx context.Context - ds *tests.MockDataStore - albumRepo *tests.MockAlbumRepo - folderRepo *fakeFolderRepo - ffm *tests.MockFFmpeg - ag *agents.Agents - t *ChainTrace + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + ag *agents.Agents + t *ChainTrace ) BeforeEach(func() { + t = &ChainTrace{} + ctx = withTrace(GinkgoT().Context(), t) conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" }) repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - albumRepo = tests.CreateMockAlbumRepo() - folderRepo = &fakeFolderRepo{} - ds = &tests.MockDataStore{ - MockedAlbum: albumRepo, - MockedFolder: folderRepo, - MockedLibrary: libRepo, - } + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) ffm = tests.NewMockFFmpeg("") - ag = agents.GetAgents(&tests.MockDataStore{}, nil) - t = &ChainTrace{} - ctx = withTrace(GinkgoT().Context(), t) + ag = agents.GetAgents(ds, nil) }) It("records a pattern skipped because the album folder holds no images", func() { - albumRepo.SetData(model.Albums{ - {ID: "al1", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{fid}}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1"}) Expect(err).ToNot(HaveOccurred()) @@ -253,13 +245,8 @@ var _ = Describe("resolveAlbum tracing", func() { }) It("records an evaluated pattern that matched nothing as a miss, not a skip", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"artist.png"}, - }} - albumRepo.SetData(model.Albums{ - {ID: "al3", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "artist.png") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{fid}}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3"}) Expect(err).ToNot(HaveOccurred()) @@ -271,7 +258,7 @@ var _ = Describe("resolveAlbum tracing", func() { It("ignores an empty priority token", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg," }) - albumRepo.SetData(model.Albums{{ID: "al2", Name: "Album", FolderIDs: []string{"f1"}}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al2", Name: "Album", FolderIDs: []string{putFolder(ctx, ds, fixtureAlbumDir)}}) _, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2"}) Expect(err).ToNot(HaveOccurred()) @@ -283,15 +270,11 @@ var _ = Describe("resolveAlbum tracing", func() { var _ = Describe("resolveArtist tracing", func() { var ( - ctx context.Context - ds *tests.MockDataStore - artistRepo *tests.MockArtistRepo - albumRepo *tests.MockAlbumRepo - folderRepo *fakeFolderRepo - ffm *tests.MockFFmpeg - ag *agents.Agents - t *ChainTrace - repoRoot string + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + ag *agents.Agents + t *ChainTrace ) uploadPath := func(file string) string { @@ -302,33 +285,23 @@ var _ = Describe("resolveArtist tracing", func() { } BeforeEach(func() { + t = &ChainTrace{} + ctx = withTrace(GinkgoT().Context(), t) conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(GinkgoT().TempDir()) c.ArtistArtPriority = "album/artist.*" }) - var err error - repoRoot, err = os.Getwd() + repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - artistRepo = tests.CreateMockArtistRepo() - albumRepo = tests.CreateMockAlbumRepo() - folderRepo = &fakeFolderRepo{} - ds = &tests.MockDataStore{ - MockedArtist: artistRepo, - MockedAlbum: albumRepo, - MockedFolder: folderRepo, - MockedLibrary: libRepo, - } + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) ffm = tests.NewMockFFmpeg("") - ag = agents.GetAgents(&tests.MockDataStore{}, nil) - t = &ChainTrace{} - ctx = withTrace(GinkgoT().Context(), t) + ag = agents.GetAgents(ds, nil) }) It("records the upload short-circuit as a hit", func() { path := uploadPath("ar1_test.jpg") - artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist", UploadedImage: "ar1_test.jpg"}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1"}) Expect(err).ToNot(HaveOccurred()) @@ -338,7 +311,7 @@ var _ = Describe("resolveArtist tracing", func() { }) It("records an upload miss before walking the chain", func() { - artistRepo.SetData(model.Artists{{ID: "ar2", Name: "Artist"}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar2", Name: "Artist"}) _, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar2"}) Expect(err).ToNot(HaveOccurred()) @@ -346,13 +319,9 @@ var _ = Describe("resolveArtist tracing", func() { }) It("labels each step with the configured priority token", func() { - folderRepo.result = []model.Folder{{ - LibraryPath: testFileLibPath(repoRoot), - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"artist.png"}, - }} - artistRepo.SetData(model.Artists{{ID: "ar4", Name: "Artist"}}) - albumRepo.All = model.Albums{{ID: "al9", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}}} + fid := putFolder(ctx, ds, fixtureAlbumDir, "artist.png") + putArtistAlbums(ctx, ds, model.Artist{ID: "ar4", Name: "Artist"}, + model.Album{ID: "al9", Name: "Album", FolderIDs: []string{fid}}) res, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar4"}) Expect(err).ToNot(HaveOccurred()) @@ -366,7 +335,7 @@ var _ = Describe("resolveArtist tracing", func() { }) It("records a configured pattern that could not be evaluated", func() { - artistRepo.SetData(model.Artists{{ID: "ar5", Name: "Artist"}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar5", Name: "Artist"}) _, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar5"}) Expect(err).ToNot(HaveOccurred()) @@ -378,8 +347,8 @@ var _ = Describe("resolveArtist tracing", func() { It("records why an artist folder pattern was skipped", func() { conf.Update(func(c *conf.Options) { c.ArtistArtPriority = "artist.*" }) - artistRepo.SetData(model.Artists{{ID: "ar6", Name: "Artist"}}) - albumRepo.All = model.Albums{{ID: "al10", Name: "Album", LibraryID: 0, FolderIDs: []string{"f1"}}} + putArtistAlbums(ctx, ds, model.Artist{ID: "ar6", Name: "Artist"}, + model.Album{ID: "al10", Name: "Album", FolderIDs: []string{"f1"}}) _, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar6"}) Expect(err).ToNot(HaveOccurred()) @@ -396,7 +365,7 @@ var _ = Describe("resolveArtist tracing", func() { path := uploadPath("ar3_test.jpg") Expect(os.Chmod(path, 0o000)).To(Succeed()) DeferCleanup(func() { _ = os.Chmod(path, 0o600) }) - artistRepo.SetData(model.Artists{{ID: "ar3", Name: "Artist", UploadedImage: "ar3_test.jpg"}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar3", Name: "Artist", UploadedImage: "ar3_test.jpg"}) _, err := newResolver(ds, ag, ffm, nil).resolve(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar3"}) Expect(err).ToNot(HaveOccurred()) @@ -408,16 +377,21 @@ var _ = Describe("resolveArtist tracing", func() { var _ = Describe("NewTracingResolver", func() { var ( - ctx context.Context - ds *tests.MockDataStore - albumRepo *tests.MockAlbumRepo - artistRepo *tests.MockArtistRepo - artworkRepo *tests.MockArtworkRepo - queueRepo *tests.MockArtworkQueueRepo - ffm *tests.MockFFmpeg - t *ChainTrace + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + t *ChainTrace ) + // Explain must leave both tables as it found them. + expectNothingPersisted := func() { + GinkgoHelper() + var rows int + Expect(db.Db().QueryRow("SELECT count(*) FROM item_artwork").Scan(&rows)).To(Succeed()) + Expect(rows).To(BeZero(), "explain is read-only; a diagnostic walk must never become the stored answer") + Expect(queueCount(ctx, ds)).To(BeZero()) + } + BeforeEach(func() { ctx = GinkgoT().Context() conf.Update(func(c *conf.Options) { @@ -427,20 +401,8 @@ var _ = Describe("NewTracingResolver", func() { }) repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - albumRepo = tests.CreateMockAlbumRepo() - artistRepo = tests.CreateMockArtistRepo() - artworkRepo = tests.CreateMockArtworkRepo() - queueRepo = tests.CreateMockArtworkQueueRepo() - ds = &tests.MockDataStore{ - MockedAlbum: albumRepo, - MockedArtist: artistRepo, - MockedFolder: &fakeFolderRepo{}, - MockedLibrary: libRepo, - MockedArtwork: artworkRepo, - MockedArtworkQueue: queueRepo, - } + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) ffm = tests.NewMockFFmpeg("") t = &ChainTrace{} }) @@ -451,10 +413,10 @@ var _ = Describe("NewTracingResolver", func() { BeforeEach(func() { // Misses, so the chain falls through to the local tier and both are traced. fake = &fakeImageAgent{name: "probe", err: agents.ErrNotFound} - albumRepo.SetData(model.Albums{{ - ID: "al1", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}, - }}) - artistRepo.SetData(model.Artists{{ID: "ar1", Name: "Artist"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ + ID: "al1", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3", FolderIDs: []string{putFolder(ctx, ds, fixtureAlbumDir)}, + }) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar1", Name: "Artist"}) }) It("asks the agents and records what each answered", func() { @@ -479,9 +441,7 @@ var _ = Describe("NewTracingResolver", func() { _, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "al1") Expect(err).ToNot(HaveOccurred()) - Expect(artworkRepo.ItemData).To(BeEmpty(), - "explain is read-only; a diagnostic walk must never become the stored answer") - Expect(queueRepo.Data).To(BeEmpty()) + expectNothingPersisted() }) It("resolves an artist without persisting anything", func() { @@ -490,16 +450,15 @@ var _ = Describe("NewTracingResolver", func() { Expect(err).ToNot(HaveOccurred()) Expect(source).To(BeEmpty()) Expect(fake.artistCalls).To(Equal(1)) - Expect(artworkRepo.ItemData).To(BeEmpty()) - Expect(queueRepo.Data).To(BeEmpty()) + expectNothingPersisted() }) It("closes the reader it does not hand back", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "embedded" }) ffm = tests.NewMockFFmpeg("fake image bytes") - albumRepo.SetData(model.Albums{{ - ID: "al2", Name: "Album", EmbedArtPath: "tests/fixtures/artist/an-album/no-such-file.mp3", FolderIDs: []string{"f1"}, - }}) + persistencetest.PutAlbums(ctx, ds, model.Album{ + ID: "al2", Name: "Album", EmbedArtPath: fixtureAlbumDir + "/no-such-file.mp3", FolderIDs: []string{putFolder(ctx, ds, fixtureAlbumDir)}, + }) source, err := NewTracingResolver(ds, imageAgents(fake), ffm, t, true).Resolve(ctx, model.KindAlbumArtwork, "al2") @@ -516,10 +475,7 @@ var _ = Describe("NewTracingResolver", func() { c.CoverArtPriority = "external, cover.*" c.EnableMediaFileCoverArt = true }) - mfRepo := tests.CreateMockMediaFileRepo() - mfRepo.SetData(model.MediaFiles{{ID: "mf1", LibraryID: 0, HasCoverArt: true, - Path: "tests/fixtures/artist/an-album/test.mp3"}}) - ds.MockedMediaFile = mfRepo + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", HasCoverArt: true, Path: fixtureAlbumDir + "/test.mp3"}) offline := NewTracingResolver(ds, imageAgents(fake), ffm, t, false) _, err := offline.Resolve(ctx, model.KindDiscArtwork, "al1:1") @@ -540,37 +496,33 @@ var _ = Describe("NewTracingResolver", func() { var _ = Describe("resolveDisc tracing", func() { var ( - ctx context.Context - ds *tests.MockDataStore - albumRepo *tests.MockAlbumRepo - folderRepo *fakeFolderRepo - ffm *tests.MockFFmpeg - t *ChainTrace + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + t *ChainTrace ) + // putDiscAlbum stores al1 with its disc-2 track in the fixture folder, listing images there. + putDiscAlbum := func(images ...string) { + GinkgoHelper() + fid := putFolder(ctx, ds, fixtureAlbumDir, images...) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", AlbumID: "al1", DiscNumber: 2, FolderID: fid, Path: fixtureAlbumDir + "/test.mp3"}) + } + BeforeEach(func() { - repoRoot, err := os.Getwd() - Expect(err).ToNot(HaveOccurred()) - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - albumRepo = tests.CreateMockAlbumRepo() - albumRepo.SetData(model.Albums{{ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}}) - folderRepo = &fakeFolderRepo{} - mfRepo := tests.CreateMockMediaFileRepo() - mfRepo.SetData(model.MediaFiles{{ID: "mf1", AlbumID: "al1", DiscNumber: 2, Path: "tests/fixtures/artist/an-album/test.mp3"}}) - ds = &tests.MockDataStore{ - MockedAlbum: albumRepo, - MockedMediaFile: mfRepo, - MockedFolder: folderRepo, - MockedLibrary: libRepo, - } - ffm = tests.NewMockFFmpeg("") t = &ChainTrace{} ctx = withTrace(GinkgoT().Context(), t) + repoRoot, err := os.Getwd() + Expect(err).ToNot(HaveOccurred()) + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) + ffm = tests.NewMockFFmpeg("") }) It("accounts for every configured entry, including the ones that map to no source", func() { conf.Update(func(c *conf.Options) { c.DiscArtPriority = "external, discsubtitle, cover.jpg" }) + putDiscAlbum() res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2)) @@ -585,10 +537,7 @@ var _ = Describe("resolveDisc tracing", func() { It("records the entry that won and stops there", func() { conf.Update(func(c *conf.Options) { c.DiscArtPriority = "disc*.*, cover.jpg, embedded" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} + putDiscAlbum("cover.jpg") res, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, model.DiscArtworkID("al1", 2)) @@ -607,6 +556,7 @@ var _ = Describe("resolveDisc tracing", func() { It("reports an unparseable disc id rather than explaining another disc", func() { conf.Update(func(c *conf.Options) { c.DiscArtPriority = "cover.jpg" }) + putDiscAlbum() _, err := newResolver(ds, nil, ffm, nil).resolveDisc(ctx, "al1") Expect(err).To(HaveOccurred()) }) @@ -614,27 +564,22 @@ var _ = Describe("resolveDisc tracing", func() { var _ = Describe("resolveMediaFile tracing", func() { var ( - ctx context.Context - ds *tests.MockDataStore - mfRepo *tests.MockMediaFileRepo - ffm *tests.MockFFmpeg - t *ChainTrace + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + t *ChainTrace ) BeforeEach(func() { + t = &ChainTrace{} + ctx = withTrace(GinkgoT().Context(), t) conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - mfRepo = tests.CreateMockMediaFileRepo() - mfRepo.SetData(model.MediaFiles{{ - ID: "mf1", Title: "Song", HasCoverArt: true, Path: "tests/fixtures/artist/an-album/test.mp3", - }}) - ds = &tests.MockDataStore{MockedMediaFile: mfRepo, MockedLibrary: libRepo} + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Title: "Song", HasCoverArt: true, Path: fixtureAlbumDir + "/test.mp3"}) ffm = tests.NewMockFFmpeg("") - t = &ChainTrace{} - ctx = withTrace(GinkgoT().Context(), t) }) It("separates a disabled setting from a track with nothing embedded", func() { @@ -649,7 +594,7 @@ var _ = Describe("resolveMediaFile tracing", func() { }) It("records a track with no embedded art as a miss", func() { - mfRepo.SetData(model.MediaFiles{{ID: "mf2", Title: "Song", HasCoverArt: false}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf2", Title: "Song", Path: "song.mp3", HasCoverArt: false}) _, err := newResolver(ds, nil, ffm, nil).resolveMediaFile(ctx, "mf2") diff --git a/core/artwork/uploader_test.go b/core/artwork/uploader_test.go index 5f705a5ff..a4e7e4996 100644 --- a/core/artwork/uploader_test.go +++ b/core/artwork/uploader_test.go @@ -9,7 +9,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -18,16 +17,16 @@ var _ = Describe("Uploader", func() { var ctx context.Context var svc Uploader var tmpDir string - var artRepo *tests.MockArtworkRepo - var queueRepo *tests.MockArtworkQueueRepo + var artRepo model.ArtworkRepository + var queueRepo model.ArtworkQueueRepository BeforeEach(func() { ctx = GinkgoT().Context() tmpDir = GinkgoT().TempDir() conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) - artRepo = tests.CreateMockArtworkRepo() - queueRepo = tests.CreateMockArtworkQueueRepo() - ds := &tests.MockDataStore{MockedArtwork: artRepo, MockedArtworkQueue: queueRepo} + ds := newTestDS(ctx) + artRepo = ds.Artwork() + queueRepo = ds.ArtworkQueue() svc = NewUploader(ds) }) diff --git a/core/artwork/worker_soak_test.go b/core/artwork/worker_soak_test.go index eb1c2ee24..c75f90f41 100644 --- a/core/artwork/worker_soak_test.go +++ b/core/artwork/worker_soak_test.go @@ -11,6 +11,7 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -34,26 +35,16 @@ var _ = Describe("Worker soak", func() { repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) - libRepo := &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) - folderRepo := &fakeFolderRepo{result: []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }}} + ds := newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") ffm := tests.NewMockFFmpeg("") - ag := agents.GetAgents(&tests.MockDataStore{}, nil) - artRepo := tests.CreateMockArtworkRepo() - albumRepo := tests.CreateMockAlbumRepo() - albumRepo.SetData(model.Albums{ - {ID: "al-folder", Name: "Folder Album", FolderIDs: []string{"f1"}}, - {ID: "al-embed", Name: "Embedded Album", EmbedArtPath: "tests/fixtures/artist/an-album/test.mp3", FolderIDs: []string{"f1"}}, - }) - ds := &tests.MockDataStore{ - MockedFolder: folderRepo, - MockedLibrary: libRepo, - MockedArtwork: artRepo, - MockedAlbum: albumRepo, - } + ag := agents.GetAgents(ds, nil) + artRepo := ds.Artwork() + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "al-folder", Name: "Folder Album", FolderIDs: []string{fid}}, + model.Album{ID: "al-embed", Name: "Embedded Album", EmbedArtPath: fixtureAlbumDir + "/test.mp3"}, + ) store := NewImageStore(GinkgoT().TempDir()) proc := &processor{ds: ds, store: store, resolver: newResolver(ds, ag, ffm, nil)} conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" }) diff --git a/core/artwork/worker_test.go b/core/artwork/worker_test.go index e37faa865..1af5101f7 100644 --- a/core/artwork/worker_test.go +++ b/core/artwork/worker_test.go @@ -13,8 +13,9 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/cache" @@ -51,24 +52,42 @@ func (c *recordingCache) getKeys() []string { // Simulates a concurrent Enqueue between DequeueBatch and the worker's delete, so // DeleteIfUnchanged on the dequeued value no-ops. type reenqueueOnDequeue struct { - *tests.MockArtworkQueueRepo + model.ArtworkQueueRepository done bool } func (r *reenqueueOnDequeue) DequeueBatch(ctx context.Context, n int, kinds ...string) ([]model.ArtworkQueueItem, error) { - items, err := r.MockArtworkQueueRepo.DequeueBatch(ctx, n, kinds...) - if !r.done && len(items) > 0 { - r.done = true - for k, it := range r.Data { - if it.ItemKind == items[0].ItemKind && it.ItemID == items[0].ItemID { - it.RetryAt = items[0].RetryAt.Add(time.Minute) - r.Data[k] = it - } - } + items, err := r.ArtworkQueueRepository.DequeueBatch(ctx, n, kinds...) + if err != nil || r.done || len(items) == 0 { + return items, err } + r.done = true + _, err = db.Db().ExecContext(ctx, "UPDATE artwork_queue SET retry_at = ? WHERE item_kind = ? AND item_id = ?", + items[0].RetryAt.Add(time.Minute), items[0].ItemKind, items[0].ItemID) return items, err } +func withQueue(ds model.DataStore, queue model.ArtworkQueueRepository) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{ + ArtworkQueue: func(model.ArtworkQueueRepository) model.ArtworkQueueRepository { return queue }, + }) +} + +func withRacingQueue(ds model.DataStore) model.DataStore { + return withQueue(ds, &reenqueueOnDequeue{ArtworkQueueRepository: ds.ArtworkQueue()}) +} + +// cancelOnDequeue cancels the drain right after its batch is read, so nothing is dispatched. +type cancelOnDequeue struct { + model.ArtworkQueueRepository + cancel context.CancelFunc +} + +func (c *cancelOnDequeue) DequeueBatch(ctx context.Context, n int, kinds ...string) ([]model.ArtworkQueueItem, error) { + defer c.cancel() + return c.ArtworkQueueRepository.DequeueBatch(ctx, n, kinds...) +} + type fakeEventBroker struct { http.Handler mu sync.Mutex @@ -95,54 +114,8 @@ func (f *fakeEventBroker) getEvents() []events.Event { var _ events.Broker = (*fakeEventBroker)(nil) -// expireQueued ages a row past the retry budget, so the next drain settles it instead of retrying. -func expireQueued(q *tests.MockArtworkQueueRepo, id string) { - GinkgoHelper() - for k, v := range q.Data { - if v.ItemID == id { - v.EnqueuedAt = time.Now().Add(-(giveUpAfter + time.Hour)) - q.Data[k] = v - } - } -} - -func findQueued(q *tests.MockArtworkQueueRepo, kind, id string) *model.ArtworkQueueItem { - for _, it := range q.Data { - if it.ItemKind == kind && it.ItemID == id { - return &it - } - } - return nil -} - -// visibilityPlaylistDS models playlist_repository's userFilter: a private playlist is only -// visible when the ctx carries an admin, so headless work must wrap ctx with one first. -type visibilityPlaylistDS struct { - *tests.MockDataStore - private model.Playlist - tracks model.PlaylistTrackRepository -} - -func (v *visibilityPlaylistDS) Playlist() model.PlaylistRepository { - repo := tests.CreateMockPlaylistRepo() - repo.TracksRepo = v.tracks - repo.SetData(model.Playlists{v.private}) - return &visibilityPlaylistRepo{MockPlaylistRepo: repo} -} - -type visibilityPlaylistRepo struct { - *tests.MockPlaylistRepo -} - -func (v *visibilityPlaylistRepo) Get(ctx context.Context, id string) (*model.Playlist, error) { - if u, ok := request.UserFrom(ctx); !ok || !u.IsAdmin { - return nil, model.ErrNotFound - } - return v.MockPlaylistRepo.Get(ctx, id) -} - type panickingAlbumRepo struct { - *tests.MockAlbumRepo + model.AlbumRepository panicID string } @@ -150,53 +123,31 @@ func (r *panickingAlbumRepo) Get(ctx context.Context, id string) (*model.Album, if id == r.panicID { panic("boom") //nolint:forbidigo } - return r.MockAlbumRepo.Get(ctx, id) -} - -func adminUserRepo() *tests.MockedUserRepo { - repo := tests.CreateMockUserRepo() - Expect(repo.Put(GinkgoT().Context(), &model.User{ID: "admin", UserName: "admin", IsAdmin: true})).To(Succeed()) - return repo + return r.AlbumRepository.Get(ctx, id) } var _ = Describe("Worker", func() { var ( - ctx context.Context - ds *tests.MockDataStore - folderRepo *fakeFolderRepo - libRepo *tests.MockLibraryRepo - ffm *tests.MockFFmpeg - ag *agents.Agents - store *ImageStore - artRepo *tests.MockArtworkRepo - queueRepo *tests.MockArtworkQueueRepo - broker *fakeEventBroker - imgCache *recordingCache - repoRoot string - w *Worker + ctx context.Context + ds model.DataStore + ffm *tests.MockFFmpeg + ag *agents.Agents + store *ImageStore + broker *fakeEventBroker + imgCache *recordingCache + w *Worker ) BeforeEach(func() { ctx = GinkgoT().Context() - var err error - repoRoot, err = os.Getwd() + repoRoot, err := os.Getwd() Expect(err).ToNot(HaveOccurred()) conf.Update(func(c *conf.Options) { c.CacheFolder = conf.NewDir(GinkgoT().TempDir()) }) - folderRepo = &fakeFolderRepo{} - libRepo = &tests.MockLibraryRepo{} - libRepo.SetData(model.Libraries{{ID: 0, Path: testFileLibPath(repoRoot)}}) + ds = newTestDS(ctx) + useLibrary(ctx, ds, repoRoot) ffm = tests.NewMockFFmpeg("") - ag = agents.GetAgents(&tests.MockDataStore{}, nil) - artRepo = tests.CreateMockArtworkRepo() - queueRepo = tests.CreateMockArtworkQueueRepo() - ds = &tests.MockDataStore{ - MockedFolder: folderRepo, - MockedLibrary: libRepo, - MockedArtwork: artRepo, - MockedArtworkQueue: queueRepo, - } - ds.MockedAlbum = tests.CreateMockAlbumRepo() + ag = agents.GetAgents(ds, nil) store = NewImageStore(GinkgoT().TempDir()) conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.jpg, embedded" @@ -214,14 +165,9 @@ var _ = Describe("Worker", func() { Describe("drain", func() { It("processes a seeded queue item and removes it from the queue", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}, - }) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan, })).To(Succeed()) @@ -229,22 +175,17 @@ var _ = Describe("Worker", func() { Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al1", model.ImageTypePrimary) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al1", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Source).To(Equal("folder")) - count, err := queueRepo.Count(ctx) - Expect(err).ToNot(HaveOccurred()) - Expect(count).To(BeZero(), "a found item must be deleted from the queue") + Expect(queueCount(ctx, ds)).To(BeZero(), "a found item must be deleted from the queue") }) It("processes an mf queue item, writing state and storing embedded bytes", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) - ds.MockedMediaFile = tests.CreateMockMediaFileRepo() - ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: "mf1", LibraryID: 0, Path: "tests/fixtures/artist/an-album/test.mp3", HasCoverArt: true}, - }) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Path: fixtureAlbumDir + "/test.mp3", HasCoverArt: true}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "mf", ItemID: "mf1", Priority: model.ArtworkPriorityBump, })).To(Succeed()) @@ -252,12 +193,12 @@ var _ = Describe("Worker", func() { Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - ia, err := artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindMediaFileArtwork, "mf1", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Source).To(Equal("embedded")) Expect(ia.Hash).ToNot(BeEmpty()) - art, err := artRepo.GetImage(ctx, ia.Hash) + art, err := ds.Artwork().GetImage(ctx, ia.Hash) Expect(err).ToNot(HaveOccurred()) r, err := store.Open(ia.Hash, art.Mime) Expect(err).ToNot(HaveOccurred()) @@ -266,99 +207,91 @@ var _ = Describe("Worker", func() { Expect(err).ToNot(HaveOccurred()) Expect(data).ToNot(BeEmpty(), "embedded bytes must be written to the store") - count, err := queueRepo.Count(ctx) - Expect(err).ToNot(HaveOccurred()) - Expect(count).To(BeZero()) + Expect(queueCount(ctx, ds)).To(BeZero()) }) It("reschedules a failed item via MarkFailed with a backed-off retry_at", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al4", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al4", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al4"})).To(Succeed()) n, err := w.drain(ctx, 2) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - it := findQueued(queueRepo, "al", "al4") + it := queued(ctx, ds, "al", "al4") Expect(it).ToNot(BeNil()) Expect(it.Attempts).To(Equal(1)) Expect(it.RetryAt).To(BeTemporally(">", time.Now())) - _, err = artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al4", model.ImageTypePrimary) + _, err = ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al4", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound), "a timeout must never settle on absent") }) It("fails an item that panics, without stopping the rest of the batch", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - albums := tests.CreateMockAlbumRepo() - albums.SetData(model.Albums{ - {ID: "alboom", Name: "Album", FolderIDs: []string{"f1"}}, - {ID: "alok", Name: "Album", FolderIDs: []string{"f1"}}, - }) - ds.MockedAlbum = &panickingAlbumRepo{MockAlbumRepo: albums, panicID: "alboom"} - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alboom"})).To(Succeed()) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alok"})).To(Succeed()) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "alboom", Name: "Album", FolderIDs: []string{fid}}, + model.Album{ID: "alok", Name: "Album", FolderIDs: []string{fid}}, + ) + panicky := persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return &panickingAlbumRepo{AlbumRepository: r, panicID: "alboom"} + }}) + w = NewWorker(panicky, store, ag, ffm, broker, imgCache) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alboom"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alok"})).To(Succeed()) n, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(2)) - it := findQueued(queueRepo, "al", "alboom") + it := queued(ctx, ds, "al", "alboom") Expect(it).ToNot(BeNil(), "a panicking item must be rescheduled, not dropped") Expect(it.Attempts).To(Equal(1)) Expect(it.RetryAt).To(BeTemporally(">", time.Now())) Expect(it.Trace).To(ContainSubstring("boom")) - Expect(findQueued(queueRepo, "al", "alok")).To(BeNil()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alok", model.ImageTypePrimary) + Expect(queued(ctx, ds, "al", "alok")).To(BeNil()) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "alok", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Source).To(Equal("folder")) }) It("reschedules past the provider's requested delay when it exceeds the backoff", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al9", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al9", Name: "Album"}) // Well above backoff(0)'s jittered ceiling, so only the hint can produce this retry_at. const askedFor = 90 * time.Minute imageAgents(&fakeImageAgent{name: "throttledAgent", err: &agents.RetryLaterError{RetryIn: askedFor}}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed()) n, err := w.drain(ctx, 2) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - it := findQueued(queueRepo, "al", "al9") + it := queued(ctx, ds, "al", "al9") Expect(it).ToNot(BeNil()) Expect(it.RetryAt).To(BeTemporally("~", time.Now().Add(askedFor), time.Minute)) }) It("reschedules a found-stale item via MarkFailed while keeping its served state", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external, cover.jpg" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "alstale", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alstale", Name: "Album", FolderIDs: []string{fid}}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alstale"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alstale"})).To(Succeed()) n, err := w.drain(ctx, 2) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - it := findQueued(queueRepo, "al", "alstale") + it := queued(ctx, ds, "al", "alstale") Expect(it).ToNot(BeNil(), "a found-stale row must survive for a higher-priority retry") Expect(it.Attempts).To(Equal(1)) Expect(it.RetryAt).To(BeTemporally(">", time.Now())) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alstale", model.ImageTypePrimary) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "alstale", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Source).To(Equal("folder"), "the fallback art is served meanwhile") @@ -368,17 +301,10 @@ var _ = Describe("Worker", func() { }) It("keeps a row re-enqueued between dequeue and delete", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al7", Name: "Album", FolderIDs: []string{"f1"}}, - }) - racing := &reenqueueOnDequeue{MockArtworkQueueRepo: queueRepo} - ds.MockedArtworkQueue = racing - w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al7", Name: "Album", FolderIDs: []string{fid}}) + w = NewWorker(withRacingQueue(ds), store, ag, ffm, broker, imgCache) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: "al7", Priority: model.ArtworkPriorityScan, })).To(Succeed()) @@ -387,28 +313,26 @@ var _ = Describe("Worker", func() { Expect(n).To(Equal(1)) // The concurrent re-enqueue changed retry_at, so the found-path delete was a no-op. - Expect(findQueued(queueRepo, "al", "al7")).ToNot(BeNil()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al7", model.ImageTypePrimary) + Expect(queued(ctx, ds, "al", "al7")).ToNot(BeNil()) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al7", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Source).To(Equal("folder")) }) It("keeps a fresh re-enqueue ahead of a stale failure backoff", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al8", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al8", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) - racing := &reenqueueOnDequeue{MockArtworkQueueRepo: queueRepo} - ds.MockedArtworkQueue = racing - w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al8"})).To(Succeed()) - dequeued := findQueued(queueRepo, "al", "al8").RetryAt + w = NewWorker(withRacingQueue(ds), store, ag, ffm, broker, imgCache) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al8"})).To(Succeed()) + dequeued := queued(ctx, ds, "al", "al8").RetryAt n, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) // The re-enqueue reset retry_at; the failure path must not stomp it nor bump attempts. - it := findQueued(queueRepo, "al", "al8") + it := queued(ctx, ds, "al", "al8") Expect(it).ToNot(BeNil()) Expect(it.Attempts).To(BeZero()) Expect(it.RetryAt).To(BeTemporally("==", dequeued.Add(time.Minute))) @@ -416,56 +340,56 @@ var _ = Describe("Worker", func() { It("gives up and settles absent once the retry budget is exhausted", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al9", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al9", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al9"})).To(Succeed()) // Age the row past the retry budget. - expireQueued(queueRepo, "al9") + expireQueued("al", "al9") n, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - Expect(findQueued(queueRepo, "al", "al9")).To(BeNil()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al9", model.ImageTypePrimary) + Expect(queued(ctx, ds, "al", "al9")).To(BeNil()) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al9", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Hash).To(BeEmpty()) }) It("keeps already-served art when the retry budget is exhausted", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al10", Name: "Album"}}) - Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{ + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al10", Name: "Album"}) + Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ ItemKind: "al", ItemID: "al10", ImageType: model.ImageTypePrimary, Hash: "cafebabe", Source: "external:lastfm", })).To(Succeed()) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al10"})).To(Succeed()) - expireQueued(queueRepo, "al10") + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al10"})).To(Succeed()) + expireQueued("al", "al10") n, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - Expect(findQueued(queueRepo, "al", "al10")).To(BeNil()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al10", model.ImageTypePrimary) + Expect(queued(ctx, ds, "al", "al10")).To(BeNil()) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al10", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Hash).To(Equal("cafebabe"), "a persistent outage must not discard served art") }) It("records on the queue row why the last attempt failed", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al11", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al11", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al11"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al11"})).To(Succeed()) _, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) - it := findQueued(queueRepo, "al", "al11") + it := queued(ctx, ds, "al", "al11") Expect(it).ToNot(BeNil()) Expect(DecodeTrace(it.Trace, "")).To(ContainElement(SatisfyAll( HaveField("Candidate", "external:failAgent"), @@ -478,16 +402,16 @@ var _ = Describe("Worker", func() { // failure is written. Recording first would silently lose it for every unresolved item. It("keeps the failure for an item that never resolved at all", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al13", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al13", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al13"})).To(Succeed()) - expireQueued(queueRepo, "al13") + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al13"})).To(Succeed()) + expireQueued("al", "al13") _, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al13", model.ImageTypePrimary) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al13", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred(), "settling absent must create the row the failure is written to") Expect(ia.Hash).To(BeEmpty()) Expect(DecodeTrace(ia.LastFailure, "")).ToNot(BeEmpty()) @@ -495,21 +419,21 @@ var _ = Describe("Worker", func() { It("keeps the failure on the state row after the queue row is deleted", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al12", Name: "Album"}}) - Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{ + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al12", Name: "Album"}) + Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ ItemKind: "al", ItemID: "al12", ImageType: model.ImageTypePrimary, Hash: "cafebabe", Source: "external:lastfm", })).To(Succeed()) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) w = NewWorker(ds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al12"})).To(Succeed()) - expireQueued(queueRepo, "al12") + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al12"})).To(Succeed()) + expireQueued("al", "al12") _, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) - Expect(findQueued(queueRepo, "al", "al12")).To(BeNil()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al12", model.ImageTypePrimary) + Expect(queued(ctx, ds, "al", "al12")).To(BeNil()) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al12", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(DecodeTrace(ia.LastFailure, "")).ToNot(BeEmpty(), "the queue row is gone, so this is the only remaining record of the failure") @@ -520,19 +444,16 @@ var _ = Describe("Worker", func() { // doing so: a transient read error would look permanent. It("does not settle absent on exhaustion for a media file", func() { conf.Update(func(c *conf.Options) { c.EnableMediaFileCoverArt = true }) - ds.MockedMediaFile = tests.CreateMockMediaFileRepo() - ds.MockedMediaFile.(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: "mfX", LibraryID: 0, Path: "tests/fixtures/artist/an-album/gone.mp3", HasCoverArt: true}, - }) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mfX"})).To(Succeed()) - expireQueued(queueRepo, "mfX") + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mfX", Path: fixtureAlbumDir + "/gone.mp3", HasCoverArt: true}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "mf", ItemID: "mfX"})).To(Succeed()) + expireQueued("mf", "mfX") n, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - Expect(findQueued(queueRepo, "mf", "mfX")).To(BeNil(), "the row must stop retrying") - _, err = artRepo.GetItemArtwork(ctx, model.KindMediaFileArtwork, "mfX", model.ImageTypePrimary) + Expect(queued(ctx, ds, "mf", "mfX")).To(BeNil(), "the row must stop retrying") + _, err = ds.Artwork().GetItemArtwork(ctx, model.KindMediaFileArtwork, "mfX", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound), "no row leaves the track unresolved, so a later view can still recover it") // Known gap: with no row and no absent settle, there is nowhere to keep the failure. @@ -540,21 +461,15 @@ var _ = Describe("Worker", func() { }) It("resolves a private playlist under an admin context instead of failing forever", func() { - ds.MockedUser = adminUserRepo() - vds := &visibilityPlaylistDS{ - MockDataStore: ds, - private: model.Playlist{ID: "plPriv", OwnerID: "admin"}, - tracks: &tests.MockPlaylistTrackRepo{}, - } - w = NewWorker(vds, store, ag, ffm, broker, imgCache) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plPriv"})).To(Succeed()) + putPlaylist(ctx, ds, model.Playlist{ID: "plPriv", Name: "Private", Public: false}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "pl", ItemID: "plPriv"})).To(Succeed()) n, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) Expect(n).To(Equal(1)) - Expect(findQueued(queueRepo, "pl", "plPriv")).To(BeNil()) - ia, err := artRepo.GetItemArtwork(ctx, model.KindPlaylistArtwork, "plPriv", model.ImageTypePrimary) + Expect(queued(ctx, ds, "pl", "plPriv")).To(BeNil()) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindPlaylistArtwork, "plPriv", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Hash).To(BeEmpty()) }) @@ -566,17 +481,14 @@ var _ = Describe("Worker", func() { }) It("broadcasts a single refresh event for the found items in a batch", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al1", Name: "Album 1", FolderIDs: []string{"f1"}}, - {ID: "al2", Name: "Album 2", FolderIDs: []string{"f1"}}, - }) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan})).To(Succeed()) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2", Priority: model.ArtworkPriorityScan})).To(Succeed()) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1", Priority: model.ArtworkPriorityScan})).To(Succeed()) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "al1", Name: "Album 1", FolderIDs: []string{fid}}, + model.Album{ID: "al2", Name: "Album 2", FolderIDs: []string{fid}}, + ) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al2", Priority: model.ArtworkPriorityScan})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "ar", ItemID: "ar1", Priority: model.ArtworkPriorityScan})).To(Succeed()) n, err := w.drain(ctx, 3) Expect(err).ToNot(HaveOccurred()) @@ -621,9 +533,8 @@ var _ = Describe("Worker", func() { It("broadcasts a refresh when an item resolves to absent (removed cover)", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "cover.*" }) // local-only; no folder image → absent - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "al3", Name: "Artless"}}) - folderRepo.result = nil - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3", Priority: model.ArtworkPriorityScan})).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al3", Name: "Artless"}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "al3", Priority: model.ArtworkPriorityScan})).To(Succeed()) n, err := w.drain(ctx, 2) Expect(err).ToNot(HaveOccurred()) @@ -633,16 +544,16 @@ var _ = Describe("Worker", func() { Expect(evts).To(HaveLen(1), "a removed cover must live-refresh clients so they drop it") Expect(evts[0].(*events.RefreshResource).Data(evts[0])).To(ContainSubstring("al3")) - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al3", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) Expect(ia.Hash).To(BeEmpty(), "the outcome was absent, not found") }) It("does not broadcast when no item is found", func() { conf.Update(func(c *conf.Options) { c.CoverArtPriority = "external" }) - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Album"}) imageAgents(&fakeImageAgent{name: "failAgent", err: errors.New("agent timed out")}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"})).To(Succeed()) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ItemKind: "al", ItemID: "alx"})).To(Succeed()) n, err := w.drain(ctx, 2) Expect(err).ToNot(HaveOccurred()) @@ -768,15 +679,10 @@ var _ = Describe("Worker", func() { Describe("precache", func() { BeforeEach(func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "alpc", Name: "Album", FolderIDs: []string{"f1"}}, - }) + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alpc", Name: "Album", FolderIDs: []string{fid}}) conf.Update(func(c *conf.Options) { c.UICoverArtSize = 300 }) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: "alpc", Priority: model.ArtworkPriorityScan, })).To(Succeed()) }) @@ -848,12 +754,8 @@ var _ = Describe("Worker", func() { c.CoverArtPriority = "cover.jpg" c.ArtistArtPriority = "external" }) - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "alx", Name: "Album", FolderIDs: []string{"f1"}}}) - ds.MockedArtist = tests.CreateMockArtistRepo() + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "alx", Name: "Album", FolderIDs: []string{fid}}) // Every artist lookup blocks until released, standing in for the rate limiter. block := make(chan struct{}) @@ -861,16 +763,16 @@ var _ = Describe("Worker", func() { for i := range 8 { artists = append(artists, model.Artist{ID: fmt.Sprintf("arx%d", i), Name: "A"}) } - ds.MockedArtist.(*tests.MockArtistRepo).SetData(artists) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artists...) imageAgents(&fakeImageAgent{name: "slowAgent", block: block}) // Artists first, exactly as Backfill orders them. for _, a := range artists { - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "ar", ItemID: a.ID, Priority: model.ArtworkPriorityBackfill, })).To(Succeed()) } - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: "alx", Priority: model.ArtworkPriorityBackfill, })).To(Succeed()) @@ -885,12 +787,12 @@ var _ = Describe("Worker", func() { }) Eventually(func() bool { - ia, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "alx", model.ImageTypePrimary) + ia, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "alx", model.ImageTypePrimary) return err == nil && ia.Hash != "" }, 5*time.Second, 50*time.Millisecond).Should(BeTrue(), "a blocked external pool must not hold up local artwork") - _, err := artRepo.GetItemArtwork(ctx, model.KindArtistArtwork, "arx0", model.ImageTypePrimary) + _, err := ds.Artwork().GetItemArtwork(ctx, model.KindArtistArtwork, "arx0", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound), "artists are still blocked, as intended") }) }) @@ -902,55 +804,52 @@ var _ = Describe("Worker", func() { for i := range 8 { id := fmt.Sprintf("alc%d", i) albums = append(albums, model.Album{ID: id, Name: "Album"}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: id, Priority: model.ArtworkPriorityScan, })).To(Succeed()) } - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(albums) - cancelledCtx, cancel := context.WithCancel(ctx) - cancel() + persistencetest.PutAlbums(ctx, ds, albums...) + drainCtx, cancel := context.WithCancel(ctx) + w = NewWorker(withQueue(ds, &cancelOnDequeue{ArtworkQueueRepository: ds.ArtworkQueue(), cancel: cancel}), + store, ag, ffm, broker, imgCache) - _, err := w.drain(cancelledCtx, 1) + n, err := w.drain(drainCtx, 1) Expect(err).ToNot(HaveOccurred()) + Expect(n).To(Equal(8), "the whole batch was read before the cancellation") for i := range 8 { id := fmt.Sprintf("alc%d", i) - Expect(findQueued(queueRepo, "al", id)).ToNot(BeNil(), "row "+id+" must survive a cancelled drain") + Expect(queued(ctx, ds, "al", id)).ToNot(BeNil(), "row "+id+" must survive a cancelled drain") } }) It("stops dispatching and leaves the rest queued when paused mid-batch", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") albums := model.Albums{} for i := range 8 { id := fmt.Sprintf("alp%d", i) - albums = append(albums, model.Album{ID: id, Name: "Album", FolderIDs: []string{"f1"}}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + albums = append(albums, model.Album{ID: id, Name: "Album", FolderIDs: []string{fid}}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: id, Priority: model.ArtworkPriorityScan, })).To(Succeed()) } - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(albums) + persistencetest.PutAlbums(ctx, ds, albums...) // Pauses as soon as the first item has left the queue. w.PauseWhile(func() bool { - n, _ := queueRepo.Count(ctx) + n, _ := ds.ArtworkQueue().Count(ctx) return n < 8 }) _, err := w.drain(ctx, 1) Expect(err).ToNot(HaveOccurred()) - count, err := queueRepo.Count(ctx) - Expect(err).ToNot(HaveOccurred()) - Expect(count).To(Equal(int64(7)), "only the item dispatched before the pause may leave the queue") + Expect(queueCount(ctx, ds)).To(Equal(int64(7)), "only the item dispatched before the pause may leave the queue") }) It("dequeues past the worker pool so one drain covers many items", func() { for i := range 16 { - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{{ID: fmt.Sprintf("alb%d", i), Name: "Album"}}) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + persistencetest.PutAlbums(ctx, ds, model.Album{ID: fmt.Sprintf("alb%d", i), Name: "Album"}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: fmt.Sprintf("alb%d", i), Priority: model.ArtworkPriorityScan, })).To(Succeed()) } @@ -978,14 +877,9 @@ var _ = Describe("Worker", func() { }) It("does not drain the queue while paused", func() { - folderRepo.result = []model.Folder{{ - Path: "tests/fixtures/artist/an-album", - ImageFiles: []string{"cover.jpg"}, - }} - ds.MockedAlbum.(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: "al1", Name: "Album", FolderIDs: []string{"f1"}}, - }) - Expect(queueRepo.Enqueue(ctx, model.ArtworkQueueItem{ + fid := putFolder(ctx, ds, fixtureAlbumDir, "cover.jpg") + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al1", Name: "Album", FolderIDs: []string{fid}}) + Expect(ds.ArtworkQueue().Enqueue(ctx, model.ArtworkQueueItem{ ItemKind: "al", ItemID: "al1", Priority: model.ArtworkPriorityScan, })).To(Succeed()) w.PauseWhile(func() bool { return true }) @@ -998,7 +892,7 @@ var _ = Describe("Worker", func() { Eventually(done, 2*time.Second).Should(Receive(BeNil())) }) - Consistently(func() any { return findQueued(queueRepo, "al", "al1") }, 300*time.Millisecond).ShouldNot(BeNil()) + Consistently(func() any { return queued(ctx, ds, "al", "al1") }, 300*time.Millisecond).ShouldNot(BeNil()) }) It("does not leak goroutines after Run exits", func() { @@ -1006,8 +900,7 @@ var _ = Describe("Worker", func() { ignore := goleak.IgnoreCurrent() DeferCleanup(func() { goleak.VerifyNone(GinkgoT(), ignore) }) - localDS := &tests.MockDataStore{MockedArtworkQueue: tests.CreateMockArtworkQueueRepo()} - lw := NewWorker(localDS, NewImageStore(GinkgoT().TempDir()), agents.GetAgents(localDS, nil), tests.NewMockFFmpeg(""), &fakeEventBroker{}, imgCache) + lw := NewWorker(ds, NewImageStore(GinkgoT().TempDir()), ag, tests.NewMockFFmpeg(""), &fakeEventBroker{}, imgCache) runCtx, cancel := context.WithCancel(ctx) done := make(chan error, 1) diff --git a/core/artwork/worker_timing_test.go b/core/artwork/worker_timing_test.go index 63f12d03c..5694ab584 100644 --- a/core/artwork/worker_timing_test.go +++ b/core/artwork/worker_timing_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/tests" . "github.com/onsi/gomega" ) @@ -83,8 +84,9 @@ func TestArtworkBreakerDoesNotCloseOnAnIsolatedAnswer(t *testing.T) { func TestArtworkGatePerAgentBreakerIsolation(t *testing.T) { synctest.Test(t, func(t *testing.T) { g := NewWithT(t) - w := NewWorker(&tests.MockDataStore{}, NewImageStore(t.TempDir()), - agents.GetAgents(&tests.MockDataStore{}, nil), tests.NewMockFFmpeg(""), &fakeEventBroker{}, nil) + noDS := struct{ model.DataStore }{} + w := NewWorker(noDS, NewImageStore(t.TempDir()), + agents.GetAgents(noDS, nil), tests.NewMockFFmpeg(""), &fakeEventBroker{}, nil) fail := func() (io.ReadCloser, string, error) { return nil, "", errors.New("boom") } for range breakerThreshold { diff --git a/core/auth/auth_test.go b/core/auth/auth_test.go index 4b63e668c..e8500f7d1 100644 --- a/core/auth/auth_test.go +++ b/core/auth/auth_test.go @@ -8,20 +8,24 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) func TestAuth(t *testing.T) { log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Auth Test Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() const ( oneDay = 24 * time.Hour @@ -34,10 +38,7 @@ var _ = BeforeSuite(func() { var _ = Describe("Auth", func() { BeforeEach(func() { - ds := &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - } - auth.Init(ds) + auth.Init(persistence.New(db.Db())) }) Describe("Validate", func() { diff --git a/core/common_test.go b/core/common_test.go index cb8d5b981..edb440a64 100644 --- a/core/common_test.go +++ b/core/common_test.go @@ -7,9 +7,11 @@ import ( . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" ) var _ = Describe("common.go", func() { @@ -31,18 +33,15 @@ var _ = Describe("common.go", func() { Describe("AbsolutePath", func() { var ( - ds *tests.MockDataStore + ds model.DataStore libId int path string ) BeforeEach(func() { - ds = &tests.MockDataStore{} - libId = 1 + ds = persistence.New(db.Db()) path = "music/file.mp3" - mockLib := &tests.MockLibraryRepo{} - mockLib.SetData(model.Libraries{{ID: libId, Path: "/library/root"}}) - ds.MockedLibrary = mockLib + libId = persistencetest.SetLibraries(ctx, ds, "/other", "/library/root")[1] }) It("returns the absolute path when library exists", func() { diff --git a/core/core_suite_test.go b/core/core_suite_test.go index 2ecf2cace..0f51eee1c 100644 --- a/core/core_suite_test.go +++ b/core/core_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestCore(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Core Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/core/external/extdata_helper_test.go b/core/external/extdata_helper_test.go index 73d88e5b4..538c908c7 100644 --- a/core/external/extdata_helper_test.go +++ b/core/external/extdata_helper_test.go @@ -6,175 +6,40 @@ import ( "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/utils/slice" "github.com/stretchr/testify/mock" ) -// --- Shared Mock Implementations --- +var adminUser = model.User{ID: "admin-1", UserName: "admin-1", IsAdmin: true} -// mockArtistRepo mocks model.ArtistRepository -type mockArtistRepo struct { - mock.Mock +// credited returns participants crediting the artists in the main artist role. +func credited(artists ...model.Artist) model.Participants { + p := model.Participants{} + p.Add(model.RoleArtist, artists...) + return p +} + +var errDBDown = errors.New("db down") + +// failingArtists serves an artist repository whose lookups fail with err. +func failingArtists(ds model.DataStore, err error) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{Artist: func(r model.ArtistRepository) model.ArtistRepository { + return failingArtistRepo{r, err} + }}) +} + +type failingArtistRepo struct { model.ArtistRepository + err error } -func newMockArtistRepo() *mockArtistRepo { - return &mockArtistRepo{} +func (r failingArtistRepo) Get(context.Context, string) (*model.Artist, error) { + return nil, r.err } -// SetData sets up basic Get expectations. -func (m *mockArtistRepo) SetData(artists model.Artists) { - for _, a := range artists { - artistCopy := a - m.On("Get", artistCopy.ID).Return(&artistCopy, nil) - } -} - -// Get implements model.ArtistRepository. -func (m *mockArtistRepo) Get(_ context.Context, id string) (*model.Artist, error) { - args := m.Called(id) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(*model.Artist), args.Error(1) -} - -// GetAll implements model.ArtistRepository. -func (m *mockArtistRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Artists, error) { - argsSlice := make([]any, len(options)) - for i, v := range options { - argsSlice[i] = v - } - args := m.Called(argsSlice...) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(model.Artists), args.Error(1) -} - -// SetError is a helper to set up a generic error for GetAll. -func (m *mockArtistRepo) SetError(hasError bool) { - if hasError { - m.On("GetAll", mock.Anything).Return(nil, errors.New("mock repo error")) - } -} - -// FindByName is a helper to set up a GetAll expectation for finding by name. -func (m *mockArtistRepo) FindByName(name string, artist model.Artist) { - m.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Filters != nil - })).Return(model.Artists{artist}, nil).Once() -} - -// mockMediaFileRepo mocks model.MediaFileRepository -type mockMediaFileRepo struct { - mock.Mock - model.MediaFileRepository -} - -func newMockMediaFileRepo() *mockMediaFileRepo { - return &mockMediaFileRepo{} -} - -// SetData sets up basic Get expectations. -func (m *mockMediaFileRepo) SetData(mediaFiles model.MediaFiles) { - for _, mf := range mediaFiles { - mfCopy := mf - m.On("Get", mfCopy.ID).Return(&mfCopy, nil) - } -} - -// Get implements model.MediaFileRepository. -func (m *mockMediaFileRepo) Get(ctx context.Context, id string) (*model.MediaFile, error) { - args := m.Called(id) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(*model.MediaFile), args.Error(1) -} - -// GetAllByTags implements model.MediaFileRepository. -func (m *mockMediaFileRepo) GetAllByTags(ctx context.Context, _ model.TagName, _ []string, options ...model.QueryOptions) (model.MediaFiles, error) { - return m.GetAll(ctx, options...) -} - -// GetAll implements model.MediaFileRepository. -func (m *mockMediaFileRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { - argsSlice := make([]any, len(options)) - for i, v := range options { - argsSlice[i] = v - } - args := m.Called(argsSlice...) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(model.MediaFiles), args.Error(1) -} - -// GetRandom implements model.MediaFileRepository. -func (m *mockMediaFileRepo) GetRandom(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { - argsSlice := make([]any, len(options)) - for i, v := range options { - argsSlice[i] = v - } - args := m.Called(argsSlice...) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(model.MediaFiles), args.Error(1) -} - -// SetError is a helper to set up a generic error for GetAll. -func (m *mockMediaFileRepo) SetError(hasError bool) { - if hasError { - m.On("GetAll", mock.Anything).Return(nil, errors.New("mock repo error")) - } -} - -// FindByMBID is a helper to set up a GetAll expectation for finding by MBID. -func (m *mockMediaFileRepo) FindByMBID(mbid string, mediaFile model.MediaFile) { - m.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Filters != nil - })).Return(model.MediaFiles{mediaFile}, nil).Once() -} - -// FindByArtistAndTitle is a helper to set up a GetAll expectation for finding by artist/title. -func (m *mockMediaFileRepo) FindByArtistAndTitle(artistID string, title string, mediaFile model.MediaFile) { - m.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Filters != nil - })).Return(model.MediaFiles{mediaFile}, nil).Once() -} - -// mockAlbumRepo mocks model.AlbumRepository -type mockAlbumRepo struct { - mock.Mock - model.AlbumRepository -} - -func newMockAlbumRepo() *mockAlbumRepo { - return &mockAlbumRepo{} -} - -// Get implements model.AlbumRepository. -func (m *mockAlbumRepo) Get(_ context.Context, id string) (*model.Album, error) { - args := m.Called(id) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(*model.Album), args.Error(1) -} - -// GetAll implements model.AlbumRepository. -func (m *mockAlbumRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Albums, error) { - argsSlice := make([]any, len(options)) - for i, v := range options { - argsSlice[i] = v - } - args := m.Called(argsSlice...) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(model.Albums), args.Error(1) +func (r failingArtistRepo) GetAll(context.Context, ...model.QueryOptions) (model.Artists, error) { + return nil, r.err } // mockSimilarArtistAgent mocks agents implementing ArtistTopSongsRetriever and ArtistSimilarRetriever diff --git a/core/external/extdata_suite_test.go b/core/external/extdata_suite_test.go index 21d5745ba..6aa301686 100644 --- a/core/external/extdata_suite_test.go +++ b/core/external/extdata_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestExternal(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "External Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/core/external/provider_refreshinfo_test.go b/core/external/provider_refreshinfo_test.go index a1216dd94..571cdef13 100644 --- a/core/external/provider_refreshinfo_test.go +++ b/core/external/provider_refreshinfo_test.go @@ -9,9 +9,11 @@ import ( "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/matcher" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/events" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" @@ -37,13 +39,11 @@ func (f *fakeBroker) sent() []events.Event { var _ = Describe("Provider - RefreshInfo", func() { var ( - ctx context.Context - p external.Provider - ds *tests.MockDataStore - ag *mockAgents - broker *fakeBroker - mockArtistRepo *tests.MockArtistRepo - mockAlbumRepo *tests.MockAlbumRepo + ctx context.Context + p external.Provider + ds model.DataStore + ag *mockAgents + broker *fakeBroker ) expectArtistAgents := func() { @@ -67,39 +67,37 @@ var _ = Describe("Provider - RefreshInfo", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = new(tests.MockDataStore) + ds = persistence.New(db.Db()) ag = new(mockAgents) broker = &fakeBroker{} p = external.NewProvider(ds, ag, matcher.New(ds), broker) - mockArtistRepo = ds.Artist().(*tests.MockArtistRepo) - mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo) }) It("repopulates an artist even when its info is fresh", func() { fresh := time.Now() - mockArtistRepo.SetData(model.Artists{{ + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ ID: "ar-1", Name: "Test Artist", Biography: "stale", ExternalInfoUpdatedAt: &fresh, - }}) + }) expectArtistAgents() Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(Succeed()) - saved, err := mockArtistRepo.Get(ctx, "ar-1") + saved, err := ds.Artist().Get(ctx, "ar-1") Expect(err).ToNot(HaveOccurred()) Expect(saved.Biography).To(Equal("Fresh Bio")) }) It("repopulates an album even when its info is fresh", func() { fresh := time.Now() - mockAlbumRepo.SetData(model.Albums{{ + persistencetest.PutAlbums(ctx, ds, model.Album{ ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist", Description: "stale", ExternalInfoUpdatedAt: &fresh, - }}) + }) expectAlbumAgents() Expect(p.RefreshInfo(ctx, model.KindAlbumArtwork, "al-1")).To(Succeed()) - saved, err := mockAlbumRepo.Get(ctx, "al-1") + saved, err := ds.Album().Get(ctx, "al-1") Expect(err).ToNot(HaveOccurred()) Expect(saved.Description).To(Equal("Fresh Notes")) }) @@ -113,7 +111,7 @@ var _ = Describe("Provider - RefreshInfo", func() { }) It("broadcasts a RefreshResource naming the artist", func() { - mockArtistRepo.SetData(model.Artists{{ID: "ar-1", Name: "Test Artist"}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Test Artist"}) expectArtistAgents() Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(Succeed()) @@ -127,7 +125,7 @@ var _ = Describe("Provider - RefreshInfo", func() { }) It("broadcasts a RefreshResource naming the album", func() { - mockAlbumRepo.SetData(model.Albums{{ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-1", Name: "Test Album", AlbumArtist: "Test Artist"}) expectAlbumAgents() Expect(p.RefreshInfo(ctx, model.KindAlbumArtwork, "al-1")).To(Succeed()) @@ -139,11 +137,12 @@ var _ = Describe("Provider - RefreshInfo", func() { }) It("does not broadcast when the artist cannot be loaded", func() { - mockArtistRepo.SetData(model.Artists{{ID: "ar-1", Name: "Test Artist"}}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Test Artist"}) expectArtistAgents() - mockArtistRepo.SetError(true) + failing := failingArtists(ds, errDBDown) + p = external.NewProvider(failing, ag, matcher.New(failing), broker) - _ = p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1") + Expect(p.RefreshInfo(ctx, model.KindArtistArtwork, "ar-1")).To(MatchError(errDBDown)) Expect(broker.sent()).To(BeEmpty()) }) diff --git a/core/external/provider_similarsongs_test.go b/core/external/provider_similarsongs_test.go index 3944edb68..d540a8e54 100644 --- a/core/external/provider_similarsongs_test.go +++ b/core/external/provider_similarsongs_test.go @@ -7,202 +7,134 @@ import ( "slices" "strings" - "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/core/agents" . "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/matcher" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model/criteria" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" ) +// nilTracksRepo is a playlist repository whose Tracks lookup fails, as the real one does when it +// cannot load the playlist. +type nilTracksRepo struct{ model.PlaylistRepository } + +func (nilTracksRepo) Tracks(context.Context, string, bool) model.PlaylistTrackRepository { return nil } + +// unboundedRandomRepo is a media file repository whose GetRandom ignores Max. +type unboundedRandomRepo struct{ model.MediaFileRepository } + +func (r unboundedRandomRepo) GetRandom(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { + for i := range options { + options[i].Max = 0 + } + return r.MediaFileRepository.GetRandom(ctx, options...) +} + var _ = Describe("Provider - SimilarSongs", func() { var ds model.DataStore var provider Provider var mockAgent *mockSimilarArtistAgent - var mockTopAgent agents.ArtistTopSongsRetriever - var mockSimilarAgent agents.ArtistSimilarRetriever var agentsCombined *mockAgents - var artistRepo *mockArtistRepo - var mediaFileRepo *mockMediaFileRepo - var albumRepo *mockAlbumRepo - var playlistRepo *tests.MockPlaylistRepo - var playlistTrackRepo *tests.MockPlaylistTrackRepo - var genreRepo *tests.MockedGenreRepo var ctx context.Context BeforeEach(func() { - ctx = GinkgoT().Context() - - artistRepo = newMockArtistRepo() - mediaFileRepo = newMockMediaFileRepo() - albumRepo = newMockAlbumRepo() - playlistTrackRepo = &tests.MockPlaylistTrackRepo{} - playlistRepo = tests.CreateMockPlaylistRepo() - playlistRepo.TracksRepo = playlistTrackRepo - genreRepo = &tests.MockedGenreRepo{} - - ds = &tests.MockDataStore{ - MockedArtist: artistRepo, - MockedMediaFile: mediaFileRepo, - MockedAlbum: albumRepo, - MockedPlaylist: playlistRepo, - MockedGenre: genreRepo, - } + ctx = request.WithUser(GinkgoT().Context(), adminUser) + ds = persistence.New(db.Db()) + admin := adminUser + Expect(ds.User().Put(ctx, &admin)).To(Succeed()) mockAgent = &mockSimilarArtistAgent{} - mockTopAgent = mockAgent - mockSimilarAgent = mockAgent - agentsCombined = &mockAgents{ - topSongsAgent: mockTopAgent, - similarAgent: mockSimilarAgent, + topSongsAgent: mockAgent, + similarAgent: mockAgent, } provider = NewProvider(ds, agentsCombined, matcher.New(ds), &fakeBroker{}) }) - // Resolves track-1 through the GetEntityByID probe order and on to its artist. Left permissive: - // no spec here asserts how many times the entity is looked up. - stubTrackEntity := func() { - track := model.MediaFile{ID: "track-1", Title: "Track", Artist: "Artist", ArtistID: "artist-1"} - artist := model.Artist{ID: "artist-1", Name: "Artist"} - artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Maybe() - albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Maybe() - mediaFileRepo.On("Get", "track-1").Return(&track, nil).Maybe() - artistRepo.On("Get", "artist-1").Return(&artist, nil).Maybe() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist}, nil).Maybe() + useStore := func(store model.DataStore) { + provider = NewProvider(store, agentsCombined, matcher.New(store), &fakeBroker{}) + } + + putPlaylist := func(pls model.Playlist, trackIDs ...string) { + GinkgoHelper() + pls.OwnerID = adminUser.ID + Expect(ds.Playlist().Put(ctx, &pls)).To(Succeed()) + if len(trackIDs) > 0 { + _, err := ds.Playlist().Tracks(ctx, pls.ID, false).Add(ctx, trackIDs) + Expect(err).ToNot(HaveOccurred()) + } + } + + anySimilarByTrack := func() *mock.Call { + return agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) + } + + putTrackEntity := func() { + GinkgoHelper() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist-1", Name: "Artist"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "track-1", Title: "Track", Artist: "Artist", ArtistID: "artist-1"}) } Describe("dispatch by entity type", func() { Context("when ID is a MediaFile (track)", func() { It("calls GetSimilarSongsByTrack and returns matched songs", func() { - track := model.MediaFile{ID: "track-1", Title: "Just Can't Get Enough", Artist: "Depeche Mode", MbzRecordingID: "track-mbid"} - - // Depeche Mode artist row used by matcher artist resolution and track-fetch back-mapping. dmArtist := model.Artist{ID: "dm-1", Name: "Depeche Mode", OrderArtistName: "depeche mode", MbzArtistID: "artist-mbid"} - dmParticipant := model.Participant{Artist: dmArtist} - matchedSong := model.MediaFile{ - ID: "matched-1", Title: "Dreaming of Me", Artist: "Depeche Mode", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{dmParticipant}}, - } - - // GetEntityByID tries Artist, Album, Playlist, then MediaFile - artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once() - mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, dmArtist) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "track-1", Title: "Just Can't Get Enough", Artist: "Depeche Mode", MbzRecordingID: "track-mbid"}, + model.MediaFile{ID: "matched-1", Title: "Dreaming of Me", Artist: "Depeche Mode", Participants: credited(dmArtist)}, + ) agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Just Can't Get Enough", "Depeche Mode", "track-mbid", 1). Return([]agents.Song{ {Name: "Dreaming of Me", MBID: "", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "artist-mbid"}}}, }, nil).Once() - // Matcher artist resolution: resolve Depeche Mode in the artist table. - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{dmArtist}, nil).Maybe() - - // ID phase: no IDs → squirrel.And with media_file.id; won't be called but guard it. - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Eq) - return ok - })).Return(model.MediaFiles{}, nil).Maybe() - - // MBID phase: won't fire (empty MBID). - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - and, ok := opt.Filters.(squirrel.And) - if !ok || len(and) < 1 { - return false - } - eq, hasEq := and[0].(squirrel.Eq) - if !hasEq { - return false - } - _, hasMBID := eq["mbz_recording_id"] - return hasMBID - })).Return(model.MediaFiles{}, nil).Maybe() - - // Matcher track-fetch: subquery returns the matched song with participants. - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - and, ok := opt.Filters.(squirrel.And) - if !ok { - return false - } - for _, f := range and { - sql, _, err := f.ToSql() - if err == nil && strings.Contains(sql, "media_file_artists") { - return true - } - } - return false - })).Return(model.MediaFiles{matchedSong}, nil).Maybe() - songs, err := provider.SimilarSongs(ctx, "track-1", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("matched-1")) + Expect(ids(songs)).To(Equal([]string{"matched-1"})) }) It("falls back to artist-based algorithm when GetSimilarSongsByTrack returns empty", func() { - track := model.MediaFile{ID: "track-1", Title: "Track", Artist: "Artist", ArtistID: "artist-1"} - artist := model.Artist{ID: "artist-1", Name: "Artist"} - song := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"} - - // GetEntityByID for the initial call tries Artist, Album, Playlist, then MediaFile - artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once() - mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once() + putTrackEntity() + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}) agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Track", "Artist", "", mock.Anything). Return([]agents.Song{}, nil).Once() - - // Fallback calls getArtist(id) which calls GetEntityByID again - this time it finds the mediafile - // and recursively calls getArtist(v.ArtistID) - artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Once() - mediaFileRepo.On("Get", "track-1").Return(&track, nil).Once() - - // Then it recurses with the artist-1 ID - artistRepo.On("Get", "artist-1").Return(&artist, nil).Maybe() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{artist}, nil).Maybe() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist", "", 15). Return([]agents.Artist{}, nil).Once() - - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 0 && opt.Filters != nil - })).Return(model.Artists{}, nil).Once() - mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist", "", mock.Anything). Return([]agents.Song{{Name: "Song One", MBID: "mbid-1"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song}, nil).Once() - songs, err := provider.SimilarSongs(ctx, "track-1", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) + Expect(ids(songs)).To(Equal([]string{"song-1"})) }) It("tops the mix up with the fallback when the agent's picks alone are too few", func() { - stubTrackEntity() + putTrackEntity() + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "agent-1", Title: "Agent Pick", MbzRecordingID: "mbid-agent"}, + model.MediaFile{ID: "song-1", Title: "Song One", MbzRecordingID: "mbid-1"}, + ) // The agent knows one track of the three asked for. agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Track", "Artist", "", 3). Return([]agents.Song{{Name: "Agent Pick", MBID: "mbid-agent"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything). - Return(model.MediaFiles{{ID: "agent-1", Title: "Agent Pick", MbzRecordingID: "mbid-agent"}}, nil).Once() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist", "", 15). Return([]agents.Artist{}, nil).Once() mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist", "", mock.Anything). Return([]agents.Song{{Name: "Song One", MBID: "mbid-1"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything). - Return(model.MediaFiles{{ID: "song-1", Title: "Song One", MbzRecordingID: "mbid-1"}}, nil).Once() songs, err := provider.SimilarSongs(ctx, "track-1", 3) @@ -211,7 +143,11 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("reaches a unique pick that sits past the count-th repeat", func() { - stubTrackEntity() + putTrackEntity() + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "t-a", Title: "Song A", MbzRecordingID: "mbid-a"}, + model.MediaFile{ID: "t-b", Title: "Song B", MbzRecordingID: "mbid-b"}, + ) mockAgent.On("GetSimilarArtists", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return([]agents.Artist{}, nil).Maybe() mockAgent.On("GetArtistTopSongs", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). @@ -221,10 +157,6 @@ var _ = Describe("Provider - SimilarSongs", func() { repeated := agents.Song{Name: "Song A", MBID: "mbid-a"} agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Track", "Artist", "", 2). Return([]agents.Song{repeated, repeated, {Name: "Song B", MBID: "mbid-b"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{ - {ID: "t-a", Title: "Song A", MbzRecordingID: "mbid-a"}, - {ID: "t-b", Title: "Song B", MbzRecordingID: "mbid-b"}, - }, nil).Once() songs, err := provider.SimilarSongs(ctx, "track-1", 2) @@ -233,24 +165,22 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("keeps topping up when the agent's picks repeat a track", func() { - stubTrackEntity() + putTrackEntity() + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "t-a", Title: "Song A", MbzRecordingID: "mbid-a"}, + model.MediaFile{ID: "t-b", Title: "Song B", MbzRecordingID: "mbid-b"}, + model.MediaFile{ID: "t-c", Title: "Song C", MbzRecordingID: "mbid-c"}, + ) // The matcher re-emits a track when the same input song repeats, so these three // picks resolve to only two distinct library tracks. repeated := agents.Song{Name: "Song A", MBID: "mbid-a"} agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Track", "Artist", "", 3). Return([]agents.Song{repeated, repeated, {Name: "Song B", MBID: "mbid-b"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{ - {ID: "t-a", Title: "Song A", MbzRecordingID: "mbid-a"}, - {ID: "t-b", Title: "Song B", MbzRecordingID: "mbid-b"}, - }, nil).Once() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist", "", 15). Return([]agents.Artist{}, nil).Once() mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist", "", mock.Anything). Return([]agents.Song{{Name: "Song C", MBID: "mbid-c"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything). - Return(model.MediaFiles{{ID: "t-c", Title: "Song C", MbzRecordingID: "mbid-c"}}, nil).Once() songs, err := provider.SimilarSongs(ctx, "track-1", 3) @@ -261,181 +191,122 @@ var _ = Describe("Provider - SimilarSongs", func() { Context("when ID is an Album", func() { It("calls GetSimilarSongsByAlbum and returns matched songs", func() { - album := model.Album{ID: "album-1", Name: "Speak & Spell", AlbumArtist: "Depeche Mode", MbzAlbumID: "album-mbid"} - matchedSong := model.MediaFile{ID: "matched-1", Title: "New Life", Artist: "Depeche Mode", MbzRecordingID: "song-mbid"} - - // GetEntityByID tries Artist, Album, Playlist, then MediaFile - artistRepo.On("Get", "album-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "album-1").Return(&album, nil).Once() + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album-1", Name: "Speak & Spell", AlbumArtist: "Depeche Mode", MbzAlbumID: "album-mbid"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "matched-1", Title: "New Life", Artist: "Depeche Mode", MbzRecordingID: "song-mbid"}) agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "album-1", "Speak & Spell", "Depeche Mode", "album-mbid", 1). Return([]agents.Song{ {Name: "New Life", MBID: "song-mbid", Artists: []agents.Artist{{Name: "Depeche Mode"}}}, }, nil).Once() - // Mock loadTracksByID - no ID matches - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Eq) - return ok - })).Return(model.MediaFiles{}, nil).Once() - - // Mock loadTracksByMBID - MBID match - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - and, ok := opt.Filters.(squirrel.And) - if !ok || len(and) < 1 { - return false - } - _, hasEq := and[0].(squirrel.Eq) - return hasEq - })).Return(model.MediaFiles{matchedSong}, nil).Once() - songs, err := provider.SimilarSongs(ctx, "album-1", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("matched-1")) + Expect(ids(songs)).To(Equal([]string{"matched-1"})) }) It("falls back to sampled album tracks when GetSimilarSongsByAlbum returns ErrNotFound", func() { - album := model.Album{ID: "album-1", Name: "Album", AlbumArtist: "Artist", AlbumArtistID: "artist-1"} - seed := model.MediaFile{ID: "seed-1", Title: "Seed", Artist: "Artist"} - - artistRepo.On("Get", "album-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "album-1").Return(&album, nil).Once() + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "album-1", Name: "Album", AlbumArtist: "Artist", AlbumArtistID: "artist-1"}, + model.Album{ID: "album-2", Name: "Other"}, + ) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "seed-1", Title: "Seed", Artist: "Artist", AlbumID: "album-1"}, + model.MediaFile{ID: "gone", Title: "Gone", AlbumID: "album-1", Missing: true}, + model.MediaFile{ID: "other", Title: "Other", AlbumID: "album-2"}, + ) agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "album-1", "Album", "Artist", "", mock.Anything). Return(nil, agents.ErrNotFound).Once() - - mediaFileRepo.On("GetRandom", mock.MatchedBy(func(opt model.QueryOptions) bool { - sql, args, err := opt.Filters.ToSql() - return err == nil && strings.Contains(sql, "album_id") && - strings.Contains(sql, "missing") && slices.Contains(args, any(false)) && slices.Contains(args, any("album-1")) - })).Return(model.MediaFiles{seed}, nil).Once() - // seedMix falls back to the seed itself when the agent finds nothing. - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "seed-1", "Seed", "Artist", "", mock.Anything). - Return([]agents.Song{}, nil).Once() + anySimilarByTrack().Return([]agents.Song{}, nil) songs, err := provider.SimilarSongs(ctx, "album-1", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("seed-1")) + Expect(ids(songs)).To(Equal([]string{"seed-1"})) }) }) Context("when ID is an Album and the album agent returns nothing (AudioMuse-only)", func() { It("samples the album's tracks and returns their track-similars", func() { - album := model.Album{ID: "al-1", Name: "The Album", AlbumArtist: "A"} - artistRepo.On("Get", "al-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "al-1").Return(&album, nil).Once() + aArtist := model.Artist{ID: "a1", Name: "A", OrderArtistName: "a"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, aArtist) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-1", Name: "The Album", AlbumArtist: "A"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed", Artist: "A", AlbumID: "al-1"}, + model.MediaFile{ID: "m1", Title: "AudioMuseResult", Artist: "A", Participants: credited(aArtist)}, + ) // AudioMuse doesn't implement album similarity -> empty. agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "al-1", "The Album", "A", "", 5). Return([]agents.Song{}, nil).Once() - - // sampleAlbumTracks -> GetRandom(album_id) -> one seed track - mediaFileRepo.On("GetRandom", mock.MatchedBy(func(opt model.QueryOptions) bool { - sql, args, err := opt.Filters.ToSql() - return err == nil && strings.Contains(sql, "album_id") && - strings.Contains(sql, "missing") && slices.Contains(args, any(false)) && slices.Contains(args, any("al-1")) - })).Return(model.MediaFiles{{ID: "s1", Title: "Seed", Artist: "A"}}, nil).Once() - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed", "A", "", 5). Return([]agents.Song{{Name: "AudioMuseResult", Artists: []agents.Artist{{Name: "A"}}}}, nil).Once() - // Matcher resolves "AudioMuseResult" -> a real MediaFile credited to artist "A". - aArtist := model.Artist{ID: "a1", Name: "A", OrderArtistName: "a"} - matchedTrack := model.MediaFile{ - ID: "m1", Title: "AudioMuseResult", Artist: "A", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{{Artist: aArtist}}}, - } - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{aArtist}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{matchedTrack}, nil).Maybe() - songs, err := provider.SimilarSongs(ctx, "al-1", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).ToNot(BeEmpty()) - Expect(songs[0].ID).To(Equal("m1")) + Expect(ids(songs)).To(Equal([]string{"m1"})) }) }) Context("when ID is an Artist", func() { It("calls GetSimilarSongsByArtist and returns matched songs", func() { - artist := model.Artist{ID: "artist-1", Name: "Depeche Mode", MbzArtistID: "artist-mbid"} - matchedSong := model.MediaFile{ID: "matched-1", Title: "Enjoy the Silence", Artist: "Depeche Mode", MbzRecordingID: "song-mbid"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist-1", Name: "Depeche Mode", MbzArtistID: "artist-mbid"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "matched-1", Title: "Enjoy the Silence", Artist: "Depeche Mode", MbzRecordingID: "song-mbid"}) - artistRepo.On("Get", "artist-1").Return(&artist, nil).Once() agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Depeche Mode", "artist-mbid", 1). Return([]agents.Song{ {Name: "Enjoy the Silence", MBID: "song-mbid", Artists: []agents.Artist{{Name: "Depeche Mode"}}}, }, nil).Once() - // Mock loadTracksByID - no ID matches - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Eq) - return ok - })).Return(model.MediaFiles{}, nil).Once() - - // Mock loadTracksByMBID - MBID match - mediaFileRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - and, ok := opt.Filters.(squirrel.And) - if !ok || len(and) < 1 { - return false - } - _, hasEq := and[0].(squirrel.Eq) - return hasEq - })).Return(model.MediaFiles{matchedSong}, nil).Once() - songs, err := provider.SimilarSongs(ctx, "artist-1", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("matched-1")) + Expect(ids(songs)).To(Equal([]string{"matched-1"})) }) }) Context("when ID is an Artist and both the artist agent and the similar-artists fallback are empty", func() { It("samples the artist's tracks and returns their track-similars", func() { artist := model.Artist{ID: "ar-1", Name: "The Artist"} - // Get is called twice: once to resolve the entity, once inside similarSongsFallback. - artistRepo.On("Get", "ar-1").Return(&artist, nil).Maybe() + other := model.Artist{ID: "ar-2", Name: "Someone Else"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist, other) + albumCredit := model.Participants{} + albumCredit.Add(model.RoleAlbumArtist, artist) + // An artist credited only on the album (compilations, classical) still yields seeds. + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed", Participants: albumCredit}, + model.MediaFile{ID: "s2", Title: "Seed Two", Participants: credited(artist)}, + model.MediaFile{ID: "gone", Title: "Gone", Participants: credited(artist), Missing: true}, + model.MediaFile{ID: "theirs", Title: "Theirs", Participants: credited(other)}, + ) agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "ar-1", "The Artist", "", 5). Return([]agents.Song{}, nil).Once() - // similarSongsFallback: no similar artists, no top songs -> empty (allow its lookups). mockAgent.On("GetSimilarArtists", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return([]agents.Artist{}, nil).Maybe() mockAgent.On("GetArtistTopSongs", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). Return([]agents.Song{}, nil).Maybe() - - // Seeds come from the participant join covering both roles, so an artist credited - // only on the album (compilations, classical) still yields seeds. - mediaFileRepo.On("GetRandom", mock.MatchedBy(func(opt model.QueryOptions) bool { - sql, args, err := opt.Filters.ToSql() - return err == nil && strings.Contains(sql, "media_file_artists") && - strings.Contains(sql, "missing") && slices.Contains(args, any(false)) && slices.Contains(args, any("ar-1")) && - slices.Contains(args, any(model.RoleAlbumArtist.String())) && slices.Contains(args, any(model.RoleArtist.String())) - })).Return(model.MediaFiles{{ID: "s1", Title: "Seed"}}, nil).Once() - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed", "", "", 5). - Return([]agents.Song{{Name: "Result"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{ID: "m1", Title: "Result"}}, nil).Maybe() + anySimilarByTrack().Return([]agents.Song{{Name: "Result"}}, nil) songs, err := provider.SimilarSongs(ctx, "ar-1", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).ToNot(BeEmpty()) + Expect(ids(songs)).To(ConsistOf("s1", "s2")) }) }) Context("when ID is an Artist and the similar-artists fallback can't fill the mix", func() { It("tops the mix up with the artist's own track-similars", func() { artist := model.Artist{ID: "ar-1", Name: "Thin Artist"} - topSong := model.MediaFile{ID: "top-1", Title: "Top Song", ArtistID: "ar-1", MbzRecordingID: "mbid-top"} - - artistRepo.On("Get", "ar-1").Return(&artist, nil).Maybe() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist}, nil).Maybe() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "top-1", Title: "Top Song", ArtistID: "ar-1", MbzRecordingID: "mbid-top"}, + model.MediaFile{ID: "s1", Title: "Seed", Artist: "Thin Artist", Participants: credited(artist)}, + model.MediaFile{ID: "mix-1", Title: "Mix Song", MbzRecordingID: "mbid-mix"}, + ) agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "ar-1", "Thin Artist", "", 5). Return([]agents.Song{}, nil).Once() @@ -446,14 +317,9 @@ var _ = Describe("Provider - SimilarSongs", func() { Return([]agents.Artist{}, nil).Once() mockAgent.On("GetArtistTopSongs", mock.Anything, "ar-1", "Thin Artist", "", mock.Anything). Return([]agents.Song{{Name: "Top Song", MBID: "mbid-top"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{topSong}, nil).Once() - mediaFileRepo.On("GetRandom", mock.Anything). - Return(model.MediaFiles{{ID: "s1", Title: "Seed", Artist: "Thin Artist"}}, nil).Once() agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed", "Thin Artist", "", mock.Anything). Return([]agents.Song{{Name: "Mix Song", MBID: "mbid-mix"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything). - Return(model.MediaFiles{{ID: "mix-1", Title: "Mix Song", MbzRecordingID: "mbid-mix"}}, nil).Once() songs, err := provider.SimilarSongs(ctx, "ar-1", 5) @@ -465,92 +331,71 @@ var _ = Describe("Provider - SimilarSongs", func() { Context("when ID is an Artist and the agent plus the similar-artists fallback already fill the mix", func() { It("does not pay for seed-track sampling", func() { artist := model.Artist{ID: "ar-1", Name: "The Artist"} - artistRepo.On("Get", "ar-1").Return(&artist, nil).Maybe() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist}, nil).Maybe() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "t-a", Title: "A", MbzRecordingID: "mbid-a", Participants: credited(artist)}, + model.MediaFile{ID: "t-b", Title: "B", MbzRecordingID: "mbid-b", Participants: credited(artist)}, + model.MediaFile{ID: "t-c", Title: "C", MbzRecordingID: "mbid-c", Participants: credited(artist)}, + ) agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "ar-1", "The Artist", "", 3). Return([]agents.Song{{Name: "A", MBID: "mbid-a"}, {Name: "B", MBID: "mbid-b"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{ - {ID: "t-a", Title: "A", MbzRecordingID: "mbid-a"}, - {ID: "t-b", Title: "B", MbzRecordingID: "mbid-b"}, - }, nil).Once() // The similar-artists fallback supplies the third track, so the mix is full. mockAgent.On("GetSimilarArtists", mock.Anything, "ar-1", "The Artist", "", 15). Return([]agents.Artist{}, nil).Once() mockAgent.On("GetArtistTopSongs", mock.Anything, "ar-1", "The Artist", "", mock.Anything). Return([]agents.Song{{Name: "C", MBID: "mbid-c"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything). - Return(model.MediaFiles{{ID: "t-c", Title: "C", MbzRecordingID: "mbid-c"}}, nil).Once() - mediaFileRepo.On("GetRandom", mock.Anything).Return(model.MediaFiles{{ID: "seed"}}, nil).Maybe() - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). - Return([]agents.Song{}, nil).Maybe() + anySimilarByTrack().Return([]agents.Song{}, nil).Maybe() songs, err := provider.SimilarSongs(ctx, "ar-1", 3) Expect(err).ToNot(HaveOccurred()) Expect(ids(songs)).To(ConsistOf("t-a", "t-b", "t-c")) - mediaFileRepo.AssertNotCalled(GinkgoT(), "GetRandom", mock.Anything) + agentsCombined.AssertNotCalled(GinkgoT(), "GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) }) }) Context("when ID is a Playlist", func() { It("samples playlist tracks and returns their track-similars", func() { - pls := model.Playlist{ID: "pl-1", Name: "My List"} - seedTrack := model.MediaFile{ID: "s1", Title: "Seed One", Artist: "A"} + aArtist := model.Artist{ID: "a1", Name: "A", OrderArtistName: "a"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, aArtist) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed One", Artist: "A"}, + model.MediaFile{ID: "m1", Title: "Similar", Artist: "A", Participants: credited(aArtist)}, + ) + putPlaylist(model.Playlist{ID: "pl-1", Name: "My List"}, "s1") - // GetEntityByID order: Artist, Album, Playlist(hit) - artistRepo.On("Get", "pl-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-1").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - - // samplePlaylistTracks -> Tracks(...).GetAll -> one seed track, bounded+randomized in SQL - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: seedTrack}, - }) - - // seedMix -> GetSimilarSongsByTrack for the seed agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed One", "A", "", 5). Return([]agents.Song{{Name: "Similar", Artists: []agents.Artist{{Name: "A"}}}}, nil).Once() - // Matcher resolves "Similar" -> a real MediaFile (allow the matcher's lookups). - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{{ID: "a1", Name: "A"}}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{ID: "m1", Title: "Similar"}}, nil).Maybe() - songs, err := provider.SimilarSongs(ctx, "pl-1", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).ToNot(BeEmpty()) + Expect(ids(songs)).To(Equal([]string{"m1"})) }) It("asks for a smart-playlist refresh so an unevaluated one still yields seeds", func() { // A smart playlist materializes no playlist_tracks until it is evaluated, so sampling // without the refresh would mix an empty seed set. - pls := model.Playlist{ID: "pl-smart", Name: "Smart"} - artistRepo.On("Get", "pl-smart").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-smart").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: model.MediaFile{ID: "s1", Title: "Seed One"}}, - }) - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). - Return([]agents.Song{}, nil).Maybe() + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "s1", Title: "Seed One"}) + putPlaylist(model.Playlist{ID: "pl-smart", Name: "Smart", Rules: &criteria.Criteria{ + Expression: criteria.All{criteria.Contains{"title": "seed"}}, + }}) + anySimilarByTrack().Return([]agents.Song{}, nil) songs, err := provider.SimilarSongs(ctx, "pl-smart", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).ToNot(BeEmpty()) - Expect(playlistRepo.TracksRefreshed).To(BeTrue()) + Expect(ids(songs)).To(Equal([]string{"s1"})) }) It("returns an error instead of panicking when the track repository is unavailable", func() { - // Tracks() logs and returns a nil repository when its own lookup fails. - pls := model.Playlist{ID: "pl-nil", Name: "Gone"} - artistRepo.On("Get", "pl-nil").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-nil").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistRepo.TracksRepo = nil + putPlaylist(model.Playlist{ID: "pl-nil", Name: "Gone"}) + useStore(persistencetest.Stub(ds, persistencetest.Repos{Playlist: func(r model.PlaylistRepository) model.PlaylistRepository { + return nilTracksRepo{r} + }})) _, err := provider.SimilarSongs(ctx, "pl-nil", 5) @@ -558,103 +403,81 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("does not seed a mix with missing tracks", func() { - pls := model.Playlist{ID: "pl-missing", Name: "Missing"} - artistRepo.On("Get", "pl-missing").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-missing").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: model.MediaFile{ID: "s1", Title: "Seed One"}}, - }) - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything). - Return([]agents.Song{}, nil).Maybe() + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed One"}, + model.MediaFile{ID: "gone", Title: "Gone", Missing: true}, + ) + putPlaylist(model.Playlist{ID: "pl-missing", Name: "Missing"}, "s1", "gone") + anySimilarByTrack().Return([]agents.Song{}, nil) - _, err := provider.SimilarSongs(ctx, "pl-missing", 5) + songs, err := provider.SimilarSongs(ctx, "pl-missing", 5) Expect(err).ToNot(HaveOccurred()) - sql, args, sqlErr := playlistTrackRepo.Options.Filters.ToSql() - Expect(sqlErr).ToNot(HaveOccurred()) - Expect(sql).To(ContainSubstring("missing")) - Expect(args).To(ContainElement(false), "must exclude missing files, not select them") + Expect(ids(songs)).To(Equal([]string{"s1"}), "must exclude missing files, not select them") }) It("keeps a later seed's picks when an earlier seed overlaps it", func() { // The matcher stops once it has count matches, and it re-emits the shared track, so // matching only count of the merged set would spend slots on the duplicate. - pls := model.Playlist{ID: "pl-overlap2", Name: "Overlap2"} - artistRepo.On("Get", "pl-overlap2").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-overlap2").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: model.MediaFile{ID: "s1", Title: "Seed One"}}, - {MediaFile: model.MediaFile{ID: "s2", Title: "Seed Two"}}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed One"}, + model.MediaFile{ID: "s2", Title: "Seed Two"}, + model.MediaFile{ID: "x", Title: "X"}, + model.MediaFile{ID: "y", Title: "Y"}, + model.MediaFile{ID: "z", Title: "Z"}, + ) + putPlaylist(model.Playlist{ID: "pl-overlap2", Name: "Overlap2"}, "s1", "s2") shared := agents.Song{ID: "x", Name: "X"} agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed One", "", "", 3). Return([]agents.Song{shared}, nil).Once() agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s2", "Seed Two", "", "", 3). Return([]agents.Song{shared, {ID: "y", Name: "Y"}, {ID: "z", Name: "Z"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{ - {ID: "x", Title: "X"}, {ID: "y", Title: "Y"}, {ID: "z", Title: "Z"}, - }, nil).Maybe() songs, err := provider.SimilarSongs(ctx, "pl-overlap2", 3) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(3), "the duplicate must not cost a slot") + Expect(ids(songs)).To(ConsistOf("x", "y", "z"), "the duplicate must not cost a slot") }) It("returns a track once when two seeds recommend it", func() { // The matcher re-emits a track when two inputs are identical, so overlapping // recommendations would otherwise take two slots in the mix. - pls := model.Playlist{ID: "pl-overlap", Name: "Overlap"} - artistRepo.On("Get", "pl-overlap").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-overlap").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: model.MediaFile{ID: "s1", Title: "Seed One"}}, - {MediaFile: model.MediaFile{ID: "s2", Title: "Seed Two"}}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed One"}, + model.MediaFile{ID: "s2", Title: "Seed Two"}, + model.MediaFile{ID: "m1", Title: "Shared"}, + ) + putPlaylist(model.Playlist{ID: "pl-overlap", Name: "Overlap"}, "s1", "s2") shared := agents.Song{ID: "m1", Name: "Shared"} agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed One", "", "", 5). Return([]agents.Song{shared}, nil).Once() agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s2", "Seed Two", "", "", 5). Return([]agents.Song{shared}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{ID: "m1", Title: "Shared"}}, nil).Maybe() songs, err := provider.SimilarSongs(ctx, "pl-overlap", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1), "the shared recommendation must appear once") + Expect(ids(songs)).To(Equal([]string{"m1"}), "the shared recommendation must appear once") }) It("does not seed a mix twice with a track the playlist repeats", func() { - pls := model.Playlist{ID: "pl-dup", Name: "Dupes"} - artistRepo.On("Get", "pl-dup").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-dup").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - // The same file at two positions, which playlists allow. - dup := model.MediaFile{ID: "s1", Title: "Seed One"} - playlistTrackRepo.SetData(model.PlaylistTracks{{MediaFile: dup}, {MediaFile: dup}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "s1", Title: "Seed One"}) + putPlaylist(model.Playlist{ID: "pl-dup", Name: "Dupes"}, "s1", "s1") agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed One", "", "", 5). Return([]agents.Song{}, nil).Once() songs, err := provider.SimilarSongs(ctx, "pl-dup", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1), "the repeated track must appear once") + Expect(ids(songs)).To(Equal([]string{"s1"}), "the repeated track must appear once") agentsCombined.AssertNumberOfCalls(GinkgoT(), "GetSimilarSongsByTrack", 1) }) It("clamps an enormous count before it reaches the queries", func() { // count+1 in the local agent overflows on MaxInt64, and GetRandom omits the SQL // limit unless Max is positive, so the query would hydrate the whole library. - pls := model.Playlist{ID: "pl-huge", Name: "Huge"} - artistRepo.On("Get", "pl-huge").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-huge").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: model.MediaFile{ID: "s1", Title: "Seed One"}}, - }) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "s1", Title: "Seed One"}) + putPlaylist(model.Playlist{ID: "pl-huge", Name: "Huge"}, "s1") agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed One", "", "", 500). Return([]agents.Song{}, nil).Once() @@ -666,7 +489,6 @@ var _ = Describe("Provider - SimilarSongs", func() { It("does not panic when the caller asks for a non-positive count", func() { // Subsonic passes count straight through, so a negative one reaches the provider. - // The guard returns before any lookup, so no repository setup is needed. songs, err := provider.SimilarSongs(ctx, "pl-neg", -1) Expect(err).ToNot(HaveOccurred()) @@ -674,14 +496,15 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("blends results from every seed, not just the first", func() { - pls := model.Playlist{ID: "pl-blend", Name: "Blend"} - artistRepo.On("Get", "pl-blend").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-blend").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: model.MediaFile{ID: "s1", Title: "Seed One"}}, - {MediaFile: model.MediaFile{ID: "s2", Title: "Seed Two"}}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed One"}, + model.MediaFile{ID: "s2", Title: "Seed Two"}, + model.MediaFile{ID: "a1", Title: "A1"}, + model.MediaFile{ID: "a2", Title: "A2"}, + model.MediaFile{ID: "b1", Title: "B1"}, + model.MediaFile{ID: "b2", Title: "B2"}, + ) + putPlaylist(model.Playlist{ID: "pl-blend", Name: "Blend"}, "s1", "s2") // Each seed returns a full count's worth, as a real similarity agent does. Asking for // one more than seed one can supply makes this independent of the final shuffle: @@ -691,34 +514,20 @@ var _ = Describe("Provider - SimilarSongs", func() { agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s2", "Seed Two", "", "", 3). Return([]agents.Song{{ID: "b1", Name: "B1"}, {ID: "b2", Name: "B2"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{ - {ID: "a1", Title: "A1"}, {ID: "a2", Title: "A2"}, - {ID: "b1", Title: "B1"}, {ID: "b2", Title: "B2"}, - }, nil).Maybe() - songs, err := provider.SimilarSongs(ctx, "pl-blend", 3) Expect(err).ToNot(HaveOccurred()) Expect(songs).To(HaveLen(3)) - ids := ids(songs) - Expect(ids).To(ContainElement(BeElementOf("b1", "b2")), "seed two must be represented in the mix") + Expect(ids(songs)).To(ContainElement(BeElementOf("b1", "b2")), "seed two must be represented in the mix") }) It("falls back to the seed tracks themselves when no similar songs are found", func() { - pls := model.Playlist{ID: "pl-2", Name: "Fallback List"} - seed1 := model.MediaFile{ID: "s1", Title: "Seed One", Artist: "A"} - seed2 := model.MediaFile{ID: "s2", Title: "Seed Two", Artist: "B"} + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed One", Artist: "A"}, + model.MediaFile{ID: "s2", Title: "Seed Two", Artist: "B"}, + ) + putPlaylist(model.Playlist{ID: "pl-2", Name: "Fallback List"}, "s1", "s2") - artistRepo.On("Get", "pl-2").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-2").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - - playlistTrackRepo.SetData(model.PlaylistTracks{ - {MediaFile: seed1}, - {MediaFile: seed2}, - }) - - // Both seeds come back empty, so the mix must fall back to the seeds themselves. agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed One", "A", "", 5). Return([]agents.Song{}, nil).Once() agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s2", "Seed Two", "B", "", 5). @@ -727,48 +536,37 @@ var _ = Describe("Provider - SimilarSongs", func() { songs, err := provider.SimilarSongs(ctx, "pl-2", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(2)) - Expect([]string{songs[0].ID, songs[1].ID}).To(ConsistOf("s1", "s2")) + Expect(ids(songs)).To(ConsistOf("s1", "s2")) }) It("samples the album when the agent's picks are not in this library", func() { // Last.fm answers from its own catalogue, so a small library can match none of it. // An unmatched non-empty answer must not shortcut the sampling fallback. - album := model.Album{ID: "al-nm", Name: "NoMatch", AlbumArtist: "A"} - artistRepo.On("Get", "al-nm").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "al-nm").Return(&album, nil).Once() + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-nm", Name: "NoMatch", AlbumArtist: "A"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "s1", Title: "Album Track", AlbumID: "al-nm"}) agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "al-nm", "NoMatch", "A", "", 5). Return([]agents.Song{{Name: "Not In Library"}}, nil).Once() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{}, nil).Maybe() - - // The matcher resolves nothing; the sampled seed is what reaches the mix. - mediaFileRepo.On("GetRandom", mock.Anything). - Return(model.MediaFiles{{ID: "s1", Title: "Album Track"}}, nil).Once() agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Album Track", "", "", 5). Return([]agents.Song{}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{}, nil).Maybe() songs, err := provider.SimilarSongs(ctx, "al-nm", 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("s1")) + Expect(ids(songs)).To(Equal([]string{"s1"})) }) It("caps agent calls at maxSeeds when the repository ignores the bound", func() { // Isolates seedMix's own cap: the album sampler bounds the query with Max, so this // exercises the guard by having the repo hand back more rows than were asked for. - album := model.Album{ID: "al-cap", Name: "Cap", AlbumArtist: "A"} - artistRepo.On("Get", "al-cap").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "al-cap").Return(&album, nil).Once() + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-cap", Name: "Cap", AlbumArtist: "A"}) + for _, id := range []string{"t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"} { + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: id, Title: id, AlbumID: "al-cap"}) + } + useStore(persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return unboundedRandomRepo{r} + }})) agentsCombined.On("GetSimilarSongsByAlbum", mock.Anything, "al-cap", "Cap", "A", "", 5). Return([]agents.Song{}, nil).Once() - - var overflow model.MediaFiles - for _, id := range []string{"t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8"} { - overflow = append(overflow, model.MediaFile{ID: id, Title: id}) - } - mediaFileRepo.On("GetRandom", mock.Anything).Return(overflow, nil).Once() agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, 5). Return([]agents.Song{}, nil) @@ -781,21 +579,13 @@ var _ = Describe("Provider - SimilarSongs", func() { It("still finds maxSeeds distinct seeds when the leading positions repeat", func() { // The sampler over-fetches for exactly this case: a page bounded at maxSeeds could // be entirely one repeated file and collapse to a single seed. - pls := model.Playlist{ID: "pl-3", Name: "Big List"} - dup := model.MediaFile{ID: "dup", Title: "Dup", Artist: "A"} - tracks := model.PlaylistTracks{ - {MediaFile: dup}, {MediaFile: dup}, {MediaFile: dup}, {MediaFile: dup}, {MediaFile: dup}, - } + trackIDs := []string{"dup", "dup", "dup", "dup", "dup"} + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "dup", Title: "Dup", Artist: "A"}) for _, id := range []string{"seed-1", "seed-2", "seed-3", "seed-4", "seed-5"} { - tracks = append(tracks, model.PlaylistTrack{ - MediaFile: model.MediaFile{ID: id, Title: id, Artist: "A"}, - }) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: id, Title: id, Artist: "A"}) + trackIDs = append(trackIDs, id) } - - artistRepo.On("Get", "pl-3").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "pl-3").Return(nil, model.ErrNotFound).Once() - playlistRepo.SetData(model.Playlists{pls}) - playlistTrackRepo.SetData(tracks) + putPlaylist(model.Playlist{ID: "pl-3", Name: "Big List"}, trackIDs...) agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything, 5). Return([]agents.Song{}, nil) @@ -804,146 +594,108 @@ var _ = Describe("Provider - SimilarSongs", func() { Expect(err).ToNot(HaveOccurred()) Expect(songs).To(HaveLen(5)) - Expect(playlistTrackRepo.Options.Sort).To(Equal("random")) agentsCombined.AssertNumberOfCalls(GinkgoT(), "GetSimilarSongsByTrack", 5) }) + + It("samples a different set of seeds across calls", func() { + var trackIDs []string + for _, id := range []string{"t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7", "t8", "t9"} { + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: id, Title: id}) + trackIDs = append(trackIDs, id) + } + putPlaylist(model.Playlist{ID: "pl-random", Name: "Random"}, trackIDs...) + anySimilarByTrack().Return([]agents.Song{}, nil) + + seen := map[string]struct{}{} + for range 10 { + songs, err := provider.SimilarSongs(ctx, "pl-random", 5) + Expect(err).ToNot(HaveOccurred()) + seeds := ids(songs) + slices.Sort(seeds) + seen[strings.Join(seeds, ",")] = struct{}{} + } + + Expect(len(seen)).To(BeNumerically(">", 1)) + }) }) Context("when ID is a Genre (not resolved by GetEntityByID)", func() { It("samples genre songs and returns their track-similars", func() { - // GetEntityByID misses everywhere; the empty/auto-created mocks need no setup. - artistRepo.On("Get", "g-1").Return(nil, model.ErrNotFound).Once() - albumRepo.On("Get", "g-1").Return(nil, model.ErrNotFound).Once() - mediaFileRepo.On("Get", "g-1").Return(nil, model.ErrNotFound).Once() - genreRepo.Data = map[string]model.Genre{"g-1": {ID: "g-1", Name: "Jazz"}} + jazz := model.NewTag(model.TagGenre, "Jazz") + rock := model.NewTag(model.TagGenre, "Rock") + Expect(ds.Tag().Add(ctx, 1, jazz, rock)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "s1", Title: "Seed", Tags: model.Tags{model.TagGenre: {"Jazz"}}}, + model.MediaFile{ID: "gone", Title: "Gone", Tags: model.Tags{model.TagGenre: {"Jazz"}}, Missing: true}, + model.MediaFile{ID: "rock", Title: "Rock", Tags: model.Tags{model.TagGenre: {"Rock"}}}, + ) + anySimilarByTrack().Return([]agents.Song{{Name: "Similar"}}, nil) - // sampleGenreTracks -> GetRandom with the indexed media_file_tags semi-join (not a json_tree scan) - mediaFileRepo.On("GetRandom", mock.MatchedBy(func(opt model.QueryOptions) bool { - if opt.Filters == nil { - return false - } - sql, args, err := opt.Filters.ToSql() - return err == nil && strings.Contains(sql, "media_file_tags") && - !strings.Contains(sql, "json_tree") && strings.Contains(sql, "missing") && slices.Contains(args, any(false)) - })).Return(model.MediaFiles{{ID: "s1", Title: "Seed"}}, nil).Once() - agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "s1", "Seed", "", "", 5). - Return([]agents.Song{{Name: "Similar"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.Anything).Return(model.MediaFiles{{ID: "m1", Title: "Similar"}}, nil).Maybe() - - songs, err := provider.SimilarSongs(ctx, "g-1", 5) + songs, err := provider.SimilarSongs(ctx, jazz.ID, 5) Expect(err).ToNot(HaveOccurred()) - Expect(songs).ToNot(BeEmpty()) + Expect(ids(songs)).To(Equal([]string{"s1"})) }) }) }) It("returns similar songs from main artist and similar artists", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One"} - similarArtist := model.Artist{ID: "artist-3", Name: "Similar Artist"} - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"} - song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"} - song3 := model.MediaFile{ID: "song-3", Title: "Song Three", ArtistID: "artist-3", MbzRecordingID: "mbid-3"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, + model.Artist{ID: "artist-1", Name: "Artist One"}, + model.Artist{ID: "artist-3", Name: "Similar Artist"}, + ) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}, + model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"}, + model.MediaFile{ID: "song-3", Title: "Song Three", ArtistID: "artist-3", MbzRecordingID: "mbid-3"}, + ) - artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe() - artistRepo.On("Get", "artist-3").Return(&similarArtist, nil).Maybe() - - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{artist1}, nil).Once() - - // New similar songs by artist returns ErrNotFound to trigger fallback agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return(nil, agents.ErrNotFound).Once() - - similarAgentsResp := []agents.Artist{ - {Name: "Similar Artist", MBID: "similar-mbid"}, - } mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15). - Return(similarAgentsResp, nil).Once() - - // Mock the three-phase artist lookup: ID (skipped - no IDs), MBID, then Name - // MBID lookup returns empty (no match) - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Eq) - return opt.Max == 0 && ok - })).Return(model.Artists{}, nil).Once() - // Name lookup returns the similar artist - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Or) - return opt.Max == 0 && ok - })).Return(model.Artists{similarArtist}, nil).Once() - + Return([]agents.Artist{{Name: "Similar Artist", MBID: "similar-mbid"}}, nil).Once() mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return([]agents.Song{ {Name: "Song One", MBID: "mbid-1"}, {Name: "Song Two", MBID: "mbid-2"}, }, nil).Once() - mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-3", "Similar Artist", "", mock.Anything). Return([]agents.Song{ {Name: "Song Three", MBID: "mbid-3"}, }, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song3}, nil).Once() - songs, err := provider.SimilarSongs(ctx, "artist-1", 3) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(3)) - for _, song := range songs { - Expect(song.ID).To(BeElementOf("song-1", "song-2", "song-3")) - } + Expect(ids(songs)).To(ConsistOf("song-1", "song-2", "song-3")) }) It("keeps picking until the fallback holds count distinct tracks", func() { // A collaboration in two artists' top songs lands in the chooser twice. Picking a fixed // count of entries lets those duplicates eat the budget and strand unique candidates. - track := model.MediaFile{ID: "track-1", Title: "Track", Artist: "Artist One", ArtistID: "artist-1"} - artist1 := model.Artist{ID: "artist-1", Name: "Artist One"} - similarArtist := model.Artist{ID: "artist-3", Name: "Similar Artist"} - - artistRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Twice() - albumRepo.On("Get", "track-1").Return(nil, model.ErrNotFound).Twice() - mediaFileRepo.On("Get", "track-1").Return(&track, nil).Twice() - artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe() - artistRepo.On("Get", "artist-3").Return(&similarArtist, nil).Maybe() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{artist1}, nil).Maybe() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, + model.Artist{ID: "artist-1", Name: "Artist One"}, + model.Artist{ID: "artist-3", Name: "Similar Artist"}, + ) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "track-1", Title: "Track", Artist: "Artist One", ArtistID: "artist-1"}, + model.MediaFile{ID: "t-a", Title: "Shared", MbzRecordingID: "mbid-a"}, + model.MediaFile{ID: "t-b", Title: "B", MbzRecordingID: "mbid-b"}, + model.MediaFile{ID: "t-c", Title: "C", MbzRecordingID: "mbid-c"}, + ) agentsCombined.On("GetSimilarSongsByTrack", mock.Anything, "track-1", "Track", "Artist One", "", 3). Return([]agents.Song{}, nil).Once() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15). Return([]agents.Artist{{Name: "Similar Artist"}}, nil).Once() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Eq) - return opt.Max == 0 && ok - })).Return(model.Artists{}, nil).Once() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - _, ok := opt.Filters.(squirrel.Or) - return opt.Max == 0 && ok - })).Return(model.Artists{similarArtist}, nil).Once() - - shared := model.MediaFile{ID: "t-a", Title: "Shared", MbzRecordingID: "mbid-a"} mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return([]agents.Song{{Name: "Shared", MBID: "mbid-a"}}, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")). - Return(model.MediaFiles{shared}, nil).Once() - mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-3", "Similar Artist", "", mock.Anything). Return([]agents.Song{ {Name: "Shared", MBID: "mbid-a"}, {Name: "B", MBID: "mbid-b"}, {Name: "C", MBID: "mbid-c"}, }, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{ - shared, - {ID: "t-b", Title: "B", MbzRecordingID: "mbid-b"}, - {ID: "t-c", Title: "C", MbzRecordingID: "mbid-c"}, - }, nil).Once() songs, err := provider.SimilarSongs(ctx, "track-1", 3) @@ -952,14 +704,6 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("returns ErrNotFound when artist is not found", func() { - artistRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound) - mediaFileRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound) - albumRepo.On("Get", "artist-unknown-artist").Return(nil, model.ErrNotFound) - - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{}, nil).Maybe() - songs, err := provider.SimilarSongs(ctx, "artist-unknown-artist", 5) Expect(err).To(Equal(model.ErrNotFound)) @@ -967,67 +711,37 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("returns songs from main artist when GetSimilarArtists returns error", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One"} - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist-1", Name: "Artist One"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}) - artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{artist1}, nil).Maybe() - - // New similar songs by artist returns ErrNotFound to trigger fallback agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return(nil, agents.ErrNotFound).Once() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15). Return(nil, errors.New("error getting similar artists")).Once() - - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 0 && opt.Filters != nil - })).Return(model.Artists{}, nil).Once() - mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return([]agents.Song{ {Name: "Song One", MBID: "mbid-1"}, }, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() - songs, err := provider.SimilarSongs(ctx, "artist-1", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) + Expect(ids(songs)).To(Equal([]string{"song-1"})) }) It("returns empty list when GetArtistTopSongs returns error", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One"} + artist := model.Artist{ID: "artist-1", Name: "Artist One"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "gone", Title: "Gone", Participants: credited(artist), Missing: true}) - artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{artist1}, nil).Maybe() - - // New similar songs by artist returns ErrNotFound to trigger fallback agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return(nil, agents.ErrNotFound).Once() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15). Return([]agents.Artist{}, nil).Once() - - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 0 && opt.Filters != nil - })).Return(model.Artists{}, nil).Once() - mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return(nil, errors.New("error getting top songs")).Once() - - // Fallback yields nothing, so the sampling path is tried and also finds no tracks. - mediaFileRepo.On("GetRandom", mock.MatchedBy(func(opt model.QueryOptions) bool { - sql, args, err := opt.Filters.ToSql() - return err == nil && strings.Contains(sql, "artist_id") && - strings.Contains(sql, "missing") && slices.Contains(args, any(false)) && slices.Contains(args, any("artist-1")) - })).Return(model.MediaFiles{}, nil).Once() + // The fallback yields nothing, so the sampling path is tried and finds only a missing track. + anySimilarByTrack().Return([]agents.Song{}, nil).Maybe() songs, err := provider.SimilarSongs(ctx, "artist-1", 5) @@ -1036,38 +750,25 @@ var _ = Describe("Provider - SimilarSongs", func() { }) It("respects count parameter", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One"} - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"} - song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"} + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "artist-1", Name: "Artist One"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-1"}, + model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-2"}, + ) - artistRepo.On("Get", "artist-1").Return(&artist1, nil).Maybe() - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 1 && opt.Filters != nil - })).Return(model.Artists{artist1}, nil).Maybe() - - // New similar songs by artist returns ErrNotFound to trigger fallback agentsCombined.On("GetSimilarSongsByArtist", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return(nil, agents.ErrNotFound).Once() - mockAgent.On("GetSimilarArtists", mock.Anything, "artist-1", "Artist One", "", 15). Return([]agents.Artist{}, nil).Once() - - artistRepo.On("GetAll", mock.MatchedBy(func(opt model.QueryOptions) bool { - return opt.Max == 0 && opt.Filters != nil - })).Return(model.Artists{}, nil).Once() - mockAgent.On("GetArtistTopSongs", mock.Anything, "artist-1", "Artist One", "", mock.Anything). Return([]agents.Song{ {Name: "Song One", MBID: "mbid-1"}, {Name: "Song Two", MBID: "mbid-2"}, }, nil).Once() - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once() - songs, err := provider.SimilarSongs(ctx, "artist-1", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(BeElementOf("song-1", "song-2")) + Expect(ids(songs)).To(ConsistOf(BeElementOf("song-1", "song-2"))) }) }) diff --git a/core/external/provider_topsongs_test.go b/core/external/provider_topsongs_test.go index 072725ba7..4a16f69df 100644 --- a/core/external/provider_topsongs_test.go +++ b/core/external/provider_topsongs_test.go @@ -10,8 +10,11 @@ import ( "github.com/navidrome/navidrome/core/agents" . "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/matcher" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" @@ -19,190 +22,133 @@ import ( var _ = Describe("Provider - TopSongs", func() { var ( - p Provider - artistRepo *mockArtistRepo // From provider_helper_test.go - mediaFileRepo *mockMediaFileRepo // From provider_helper_test.go - ag *mockAgents // Consolidated mock from export_test.go - ctx context.Context + p Provider + ds model.DataStore + ag *mockAgents + ctx context.Context ) + artist1 := model.Artist{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"} + BeforeEach(func() { - // Disable fuzzy matching for these tests to avoid unexpected GetAll calls + ctx = request.WithUser(GinkgoT().Context(), adminUser) conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 }) - - ctx = GinkgoT().Context() - - artistRepo = newMockArtistRepo() // Use helper mock - mediaFileRepo = newMockMediaFileRepo() // Use helper mock - - // Configure tests.MockDataStore to use the testify/mock-based repos - ds := &tests.MockDataStore{ - MockedArtist: artistRepo, - MockedMediaFile: mediaFileRepo, - } - + ds = persistence.New(db.Db()) ag = new(mockAgents) - p = NewProvider(ds, ag, matcher.New(ds), &fakeBroker{}) }) - It("returns top songs for a known artist", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() + withFailingArtists := func(err error) { + failing := failingArtists(ds, err) + p = NewProvider(failing, ag, matcher.New(failing), &fakeBroker{}) + } - // Mock agent response + It("returns top songs for a known artist", func() { + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}, + model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"}, + ) agentSongs := []agents.Song{ {Name: "Song One", MBID: "mbid-song-1"}, {Name: "Song Two", MBID: "mbid-song-2"}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() - // Mock finding matching tracks (both returned in a single query) - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"} - song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(2)) - Expect(songs[0].ID).To(Equal("song-1")) - Expect(songs[1].ID).To(Equal("song-2")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) Context("artist id and/or name", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - BeforeEach(func() { + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}) agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}} ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() - - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() }) It("returns top songs for a known artist by id only", func() { - artistRepo.On("Get", "artist-1").Return(&artist1, nil).Once() - songs, err := p.TopSongs(ctx, "", "artist-1", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("returns top songs for a known artist by id, falling back to name", func() { - artistRepo.On("Get", "fake-id").Return(nil, model.ErrNotFound).Once() - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "fake-id", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) }) It("bails if lookup by id returns a fatal error", func() { - artistRepo.On("Get", "artist-1").Return(nil, model.ErrInvalidAuth).Once() + withFailingArtists(model.ErrInvalidAuth) + songs, err := p.TopSongs(ctx, "Artist One", "artist-1", 2) + Expect(songs).To(BeEmpty()) - Expect(err).To(HaveOccurred()) + Expect(err).To(MatchError(model.ErrInvalidAuth)) }) It("bails if lookup by name returns a fatal error", func() { - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(nil, model.ErrInvalidAuth).Once() + withFailingArtists(model.ErrInvalidAuth) + songs, err := p.TopSongs(ctx, "Artist One", "", 2) + Expect(songs).To(BeEmpty()) - Expect(err).To(HaveOccurred()) + Expect(err).To(MatchError(model.ErrInvalidAuth)) }) It("backfills name and MBID onto an unnamed primary credit (the queried artist) and matches", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", Participants: credited(artist1)}) - // Agent leaves the first credit unnamed (e.g. an MBID-less collaborator slot). That blank - // credit IS the queried artist, so enrichment fills both name and MBID; the song then matches - // the queried artist's track via the backfilled identity. + // The blank first credit IS the queried artist, so enrichment fills both name and MBID and + // the song matches the queried artist's track via the backfilled identity. agentSongs := []agents.Song{ {Name: "Song One", Artists: []agents.Artist{{}}}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() - track := model.MediaFile{ - ID: "song-1", Title: "Song One", ArtistID: "artist-1", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{ - {ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}, - }}, - } - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil) - songs, err := p.TopSongs(ctx, "Artist One", "", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) + Expect(ids(songs)).To(Equal([]string{"song-1"})) }) It("does not stamp the queried MBID onto an already-named different first credit", func() { - // The queried artist (One) appears only as a featured collaborator; the displayed first credit - // is a DIFFERENT artist (Two) returned without an MBID. Enrichment must NOT assign One's MBID - // to Two — only Two's name match (which fails here) or One's own credit may resolve the track. - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil) + // The first credit is a different artist (Two) without an MBID. Stamping One's MBID onto it + // would resolve it to One, matching One's same-titled track. + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "one-track", Title: "Collab Song", ArtistID: "artist-1", Participants: credited(artist1)}) agentSongs := []agents.Song{ {Name: "Collab Song", Artists: []agents.Artist{{Name: "Artist Two"}}}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() - // Library track is credited to Artist One (the queried artist) under a same title. If the - // queried MBID were wrongly stamped onto the "Artist Two" credit, that mismatched name+MBID artistRepo.On("Get", "fake-id").Return(nil, model.ErrNotFound).Once() - - // could mis-resolve. With the guard, "Artist Two" stays MBID-less and does not match One's track. - track := model.MediaFile{ - ID: "one-track", Title: "Collab Song", ArtistID: "artist-1", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{ - {ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: "mbid-artist-1"}, - }}, - } - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{track}, nil) - songs, err := p.TopSongs(ctx, "Artist One", "", 1) Expect(err).ToNot(HaveOccurred()) - // "Artist Two" (named, MBID-less, not in the library) does not resolve to One's track. Expect(songs).To(BeEmpty()) }) It("returns nil for an unknown artist", func() { - // Mock artist not found - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{}, nil).Once() - songs, err := p.TopSongs(ctx, "Unknown Artist", "", 5) Expect(err).ToNot(HaveOccurred()) // TopSongs returns nil error if artist not found Expect(songs).To(BeNil()) - artistRepo.AssertExpectations(GinkgoT()) ag.AssertNotCalled(GinkgoT(), "GetArtistTopSongs", mock.Anything, mock.Anything, mock.Anything, mock.Anything, mock.Anything) }) It("returns error when the agent returns an error", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Mock agent error + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) agentErr := errors.New("agent error") ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agentErr).Once() @@ -210,30 +156,23 @@ var _ = Describe("Provider - TopSongs", func() { Expect(err).To(MatchError(agentErr)) Expect(songs).To(BeNil()) - artistRepo.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT()) }) It("returns ErrNotFound when the agent returns ErrNotFound", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Mock agent ErrNotFound + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, agents.ErrNotFound).Once() songs, err := p.TopSongs(ctx, "Artist One", "", 5) Expect(err).To(MatchError(model.ErrNotFound)) Expect(songs).To(BeNil()) - artistRepo.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT()) }) // This endpoint answered with an empty list before retry-later existed; it must keep doing so. It("returns an empty list, not a client error, when the agents are throttled", func() { - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 5). Return(nil, agents.ErrRetryLater).Once() @@ -246,231 +185,136 @@ var _ = Describe("Provider - TopSongs", func() { }) It("returns fewer songs if count is less than available top songs", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Mock agent response (only need 1 for the test) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}) agentSongs := []agents.Song{{Name: "Song One", MBID: "mbid-song-1"}} ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() - // Mock finding matching track - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("returns fewer songs if fewer matching tracks are found", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - // Matcher artist resolution for the title-match path (song2 falls through). - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe() - - // Mock agent response + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}) agentSongs := []agents.Song{ {Name: "Song One", MBID: "mbid-song-1"}, {Name: "Song Two", MBID: "mbid-song-2"}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() - // Mock finding matching tracks (only find song 1 on bulk query) - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() // bulk MBID query - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once() // title track-fetch for song2: no match - songs, err := p.TopSongs(ctx, "Artist One", "", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("returns error when context is canceled during agent call", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Setup context that will be canceled + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) canceledCtx, cancel := context.WithCancel(ctx) + ag.On("GetArtistTopSongs", canceledCtx, "artist-1", "Artist One", "mbid-artist-1", 5). + Run(func(mock.Arguments) { cancel() }). + Return(nil, context.Canceled).Once() - // Mock agent call to return context canceled error - ag.On("GetArtistTopSongs", canceledCtx, "artist-1", "Artist One", "mbid-artist-1", 5).Return(nil, context.Canceled).Once() - - cancel() // Cancel the context before calling songs, err := p.TopSongs(canceledCtx, "Artist One", "", 5) Expect(err).To(MatchError(context.Canceled)) Expect(songs).To(BeNil()) - artistRepo.AssertExpectations(GinkgoT()) ag.AssertExpectations(GinkgoT()) }) It("falls back to title matching when MbzRecordingID is missing", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - // Matcher artist resolution for both title-fallback songs. - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe() - - // Mock agent response with songs that have NO MBID (empty string) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1", Participants: credited(artist1)}, + model.MediaFile{ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", Participants: credited(artist1)}, + ) agentSongs := []agents.Song{ - {Name: "Song One", MBID: ""}, // No MBID, should fall back to title matching - {Name: "Song Two", MBID: ""}, // No MBID, should fall back to title matching + {Name: "Song One", MBID: ""}, + {Name: "Song Two", MBID: ""}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() - // Title track-fetch: tracks must carry RoleArtist participants so back-mapping routes them. - participant1 := model.Participant{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"} - song1 := model.MediaFile{ - ID: "song-1", Title: "Song One", Artist: "Artist One", ArtistID: "artist-1", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}}, - } - song2 := model.MediaFile{ - ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}}, - } - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(2)) - Expect(songs[0].ID).To(Equal("song-1")) - Expect(songs[1].ID).To(Equal("song-2")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("combines MBID and title matching when some songs have missing MbzRecordingID", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - // Matcher artist resolution for song2's title-fallback path. - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{artist1}, nil).Maybe() - - // Mock agent response with mixed MBID availability + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}, + model.MediaFile{ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", Participants: credited(artist1)}, + ) agentSongs := []agents.Song{ - {Name: "Song One", MBID: "mbid-song-1"}, // Has MBID, should match by MBID - {Name: "Song Two", MBID: ""}, // No MBID, should fall back to title matching + {Name: "Song One", MBID: "mbid-song-1"}, + {Name: "Song Two", MBID: ""}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() - // Mock the MBID query (finds song1 by MBID) - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1", OrderTitle: "song one"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() - - // Title track-fetch: song2 must carry RoleArtist participants for back-mapping. - participant1 := model.Participant{ID: "artist-1", Name: "Artist One", OrderArtistName: "artist one"} - song2 := model.MediaFile{ - ID: "song-2", Title: "Song Two", Artist: "Artist One", ArtistID: "artist-1", - Participants: model.Participants{model.RoleArtist: model.ParticipantList{participant1}}, - } - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song2}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(2)) - Expect(songs[0].ID).To(Equal("song-1")) // Found by MBID - Expect(songs[1].ID).To(Equal("song-2")) // Found by title - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("only returns requested count when provider returns additional items", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Mock agent response + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}, + model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"}, + ) agentSongs := []agents.Song{ {Name: "Song One", MBID: "mbid-song-1"}, {Name: "Song Two", MBID: "mbid-song-2"}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() - // Mock finding matching tracks (both returned in a single query) - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"} - song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1", MbzRecordingID: "mbid-song-2"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("matches songs by ID first when agent provides IDs", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Mock agent response with IDs provided (highest priority matching) - // Note: Songs have no MBID to ensure only ID matching is used + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1"}, + model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1"}, + ) agentSongs := []agents.Song{ {ID: "song-1", Name: "Song One"}, {ID: "song-2", Name: "Song Two"}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 2).Return(agentSongs, nil).Once() - // Mock ID lookup (first query - should match both songs directly) - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1"} - song2 := model.MediaFile{ID: "song-2", Title: "Song Two", ArtistID: "artist-1"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1, song2}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 2) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(2)) - Expect(songs[0].ID).To(Equal("song-1")) - Expect(songs[1].ID).To(Equal("song-2")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1", "song-2"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) It("falls back to MBID when ID is not found", func() { - // Mock finding the artist - artist1 := model.Artist{ID: "artist-1", Name: "Artist One", MbzArtistID: "mbid-artist-1"} - artistRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.Artists{artist1}, nil).Once() - - // Mock agent response with ID that won't be found, but MBID that will + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, artist1) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"}) agentSongs := []agents.Song{ {ID: "non-existent-id", Name: "Song One", MBID: "mbid-song-1"}, } ag.On("GetArtistTopSongs", ctx, "artist-1", "Artist One", "mbid-artist-1", 1).Return(agentSongs, nil).Once() - // Mock ID lookup - returns empty (ID not found) - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{}, nil).Once() - // Mock MBID lookup - finds the song - song1 := model.MediaFile{ID: "song-1", Title: "Song One", ArtistID: "artist-1", MbzRecordingID: "mbid-song-1"} - mediaFileRepo.On("GetAll", mock.AnythingOfType("model.QueryOptions")).Return(model.MediaFiles{song1}, nil).Once() - songs, err := p.TopSongs(ctx, "Artist One", "", 1) Expect(err).ToNot(HaveOccurred()) - Expect(songs).To(HaveLen(1)) - Expect(songs[0].ID).To(Equal("song-1")) - artistRepo.AssertExpectations(GinkgoT()) + Expect(ids(songs)).To(Equal([]string{"song-1"})) ag.AssertExpectations(GinkgoT()) - mediaFileRepo.AssertExpectations(GinkgoT()) }) }) diff --git a/core/external/provider_updatealbuminfo_test.go b/core/external/provider_updatealbuminfo_test.go index 87243ad23..705f46078 100644 --- a/core/external/provider_updatealbuminfo_test.go +++ b/core/external/provider_updatealbuminfo_test.go @@ -9,9 +9,11 @@ import ( "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/matcher" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" @@ -23,19 +25,31 @@ func init() { var _ = Describe("Provider - UpdateAlbumInfo", func() { var ( - ctx context.Context - p external.Provider - ds *tests.MockDataStore - ag *mockAgents - mockAlbumRepo *tests.MockAlbumRepo + ctx context.Context + p external.Provider + ds model.DataStore + ag *mockAgents ) + expectCached := func(got, want *model.Album) { + GinkgoHelper() + Expect(got.ID).To(Equal(want.ID)) + Expect(got.Name).To(Equal(want.Name)) + Expect(got.ExternalUrl).To(Equal(want.ExternalUrl)) + Expect(got.Description).To(Equal(want.Description)) + Expect(got.LargeImageUrl).To(Equal(want.LargeImageUrl)) + if want.ExternalInfoUpdatedAt == nil { + Expect(got.ExternalInfoUpdatedAt).To(BeNil()) + } else { + Expect(*got.ExternalInfoUpdatedAt).To(BeTemporally("==", *want.ExternalInfoUpdatedAt)) + } + } + BeforeEach(func() { ctx = GinkgoT().Context() - ds = new(tests.MockDataStore) + ds = persistence.New(db.Db()) ag = new(mockAgents) p = external.NewProvider(ds, ag, matcher.New(ds), &fakeBroker{}) - mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo) conf.Update(func(c *conf.Options) { c.DevAlbumInfoTimeToLive = 1 * time.Hour }) }) @@ -54,7 +68,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { AlbumArtist: "Test Artist", MbzAlbumID: "mbid-album", } - mockAlbumRepo.SetData(model.Albums{*originalAlbum}) + persistencetest.PutAlbums(ctx, ds, *originalAlbum) expectedInfo := &agents.AlbumInfo{ URL: "http://example.com/album", @@ -77,6 +91,12 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { Expect(updatedAlbum.ExternalInfoUpdatedAt).NotTo(BeNil()) Expect(*updatedAlbum.ExternalInfoUpdatedAt).To(BeTemporally("~", time.Now(), time.Second)) + stored, err := ds.Album().Get(ctx, "al-existing") + Expect(err).NotTo(HaveOccurred()) + Expect(stored.Description).To(Equal("Album Description")) + Expect(stored.LargeImageUrl).To(Equal("http://example.com/large.jpg")) + Expect(stored.SmallImageUrl).To(Equal("http://example.com/small.jpg")) + ag.AssertExpectations(GinkgoT()) }) @@ -91,13 +111,13 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { LargeImageUrl: "http://cached.com/large.jpg", ExternalInfoUpdatedAt: new(now.Add(-conf.Server().DevAlbumInfoTimeToLive / 2)), } - mockAlbumRepo.SetData(model.Albums{*originalAlbum}) + persistencetest.PutAlbums(ctx, ds, *originalAlbum) updatedAlbum, err := p.UpdateAlbumInfo(ctx, "al-cached") Expect(err).NotTo(HaveOccurred()) Expect(updatedAlbum).NotTo(BeNil()) - Expect(*updatedAlbum).To(Equal(*originalAlbum)) + expectCached(updatedAlbum, originalAlbum) ag.AssertNotCalled(GinkgoT(), "GetAlbumInfo", mock.Anything, mock.Anything, mock.Anything, mock.Anything) }) @@ -114,13 +134,13 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { LargeImageUrl: "http://expired.com/large.jpg", ExternalInfoUpdatedAt: new(expiredTime), } - mockAlbumRepo.SetData(model.Albums{*originalAlbum}) + persistencetest.PutAlbums(ctx, ds, *originalAlbum) updatedAlbum, err := p.UpdateAlbumInfo(ctx, "al-expired") Expect(err).NotTo(HaveOccurred()) Expect(updatedAlbum).NotTo(BeNil()) - Expect(*updatedAlbum).To(Equal(*originalAlbum)) + expectCached(updatedAlbum, originalAlbum) ag.AssertNotCalled(GinkgoT(), "GetAlbumInfo", mock.Anything, mock.Anything, mock.Anything, mock.Anything) }) @@ -132,7 +152,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { AlbumArtist: "Agent Error Artist", MbzAlbumID: "mbid-agent-error", } - mockAlbumRepo.SetData(model.Albums{*originalAlbum}) + persistencetest.PutAlbums(ctx, ds, *originalAlbum) expectedErr := errors.New("agent communication failed") ag.On("GetAlbumInfo", ctx, "Agent Error Album", "Agent Error Artist", "mbid-agent-error").Return(nil, expectedErr) @@ -151,7 +171,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { AlbumArtist: "Agent NotFound Artist", MbzAlbumID: "mbid-agent-notfound", } - mockAlbumRepo.SetData(model.Albums{*originalAlbum}) + persistencetest.PutAlbums(ctx, ds, *originalAlbum) ag.On("GetAlbumInfo", ctx, "Agent NotFound Album", "Agent NotFound Artist", "mbid-agent-notfound").Return(nil, agents.ErrNotFound) @@ -159,7 +179,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { Expect(err).NotTo(HaveOccurred()) Expect(updatedAlbum).NotTo(BeNil()) - Expect(*updatedAlbum).To(Equal(*originalAlbum)) + expectCached(updatedAlbum, originalAlbum) Expect(updatedAlbum.ExternalInfoUpdatedAt).To(BeNil()) ag.AssertExpectations(GinkgoT()) @@ -172,7 +192,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { AlbumArtist: "Throttled Artist", MbzAlbumID: "mbid-throttled", } - mockAlbumRepo.SetData(model.Albums{*originalAlbum}) + persistencetest.PutAlbums(ctx, ds, *originalAlbum) ag.On("GetAlbumInfo", ctx, "Throttled Album", "Throttled Artist", "mbid-throttled"). Return(nil, agents.ErrRetryLater) @@ -181,7 +201,7 @@ var _ = Describe("Provider - UpdateAlbumInfo", func() { Expect(err).NotTo(HaveOccurred()) Expect(updatedAlbum).NotTo(BeNil()) - Expect(*updatedAlbum).To(Equal(*originalAlbum)) + expectCached(updatedAlbum, originalAlbum) Expect(updatedAlbum.ExternalInfoUpdatedAt).To(BeNil()) ag.AssertExpectations(GinkgoT()) diff --git a/core/external/provider_updateartistinfo_test.go b/core/external/provider_updateartistinfo_test.go index b85e9862e..e6411cf70 100644 --- a/core/external/provider_updateartistinfo_test.go +++ b/core/external/provider_updateartistinfo_test.go @@ -9,9 +9,11 @@ import ( "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/core/matcher" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/stretchr/testify/mock" @@ -23,20 +25,18 @@ func init() { var _ = Describe("Provider - UpdateArtistInfo", func() { var ( - ctx context.Context - p external.Provider - ds *tests.MockDataStore - ag *mockAgents - mockArtistRepo *tests.MockArtistRepo + ctx context.Context + p external.Provider + ds model.DataStore + ag *mockAgents ) BeforeEach(func() { - conf.Update(func(c *conf.Options) { c.DevArtistInfoTimeToLive = 1 * time.Hour }) ctx = GinkgoT().Context() - ds = new(tests.MockDataStore) + conf.Update(func(c *conf.Options) { c.DevArtistInfoTimeToLive = 1 * time.Hour }) + ds = persistence.New(db.Db()) ag = new(mockAgents) p = external.NewProvider(ds, ag, matcher.New(ds), &fakeBroker{}) - mockArtistRepo = ds.Artist().(*tests.MockArtistRepo) }) It("returns error when artist is not found", func() { @@ -56,7 +56,6 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { ID: "ar-existing", Name: "Test Artist", } - mockArtistRepo.SetData(model.Artists{*originalArtist}) expectedMBID := "mbid-artist-123" expectedBio := "Artist Bio" @@ -79,7 +78,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { ag.On("GetArtistURL", ctx, "ar-existing", "Test Artist", expectedMBID).Return(expectedURL, nil).Once() ag.On("GetSimilarArtists", ctx, "ar-existing", "Test Artist", expectedMBID, 100).Return(rawSimilar, nil).Once() - mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-existing", 10, false) @@ -99,13 +98,21 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { Expect(updatedArtist.SimilarArtists[0].ID).To(Equal("ar-similar-2")) Expect(updatedArtist.SimilarArtists[0].Name).To(Equal("Similar Artist 2")) + stored, err := ds.Artist().Get(ctx, "ar-existing") + Expect(err).NotTo(HaveOccurred()) + Expect(stored.Biography).To(Equal("Artist Bio")) + Expect(stored.LargeImageUrl).To(Equal("http://large.jpg")) + Expect(stored.ExternalInfoUpdatedAt).NotTo(BeNil()) + Expect(stored.SimilarArtists).To(HaveLen(3), "the stored list keeps similar artists missing from the library") + Expect(stored.SimilarArtists[0].ID).To(Equal("ar-similar-2")) + ag.AssertExpectations(GinkgoT()) }) // Stamping a throttled round would cache the empty result for the whole TTL. It("does not stamp ExternalInfoUpdatedAt when the agents are throttled", func() { originalArtist := &model.Artist{ID: "ar-throttled", Name: "Throttled Artist"} - mockArtistRepo.SetData(model.Artists{*originalArtist}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist) ag.On("GetArtistMBID", ctx, "ar-throttled", "Throttled Artist").Return("", agents.ErrRetryLater).Once() ag.On("GetArtistImages", ctx, "ar-throttled", "Throttled Artist", "").Return(nil, agents.ErrRetryLater).Once() @@ -126,7 +133,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { ID: "ar-encoded-bio", Name: "Encoded Bio Artist", } - mockArtistRepo.SetData(model.Artists{*originalArtist}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist) expectedMBID := "mbid-encoded-bio" expectedBio := "R&B" @@ -160,7 +167,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { }, } similarInDS := model.Artist{ID: "ar-similar-present", Name: "Similar Present Updated"} - mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-cached", 5, false) @@ -172,7 +179,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { Expect(updatedArtist.ExternalUrl).To(Equal(originalArtist.ExternalUrl)) Expect(updatedArtist.Biography).To(Equal(originalArtist.Biography)) Expect(updatedArtist.LargeImageUrl).To(Equal(originalArtist.LargeImageUrl)) - Expect(updatedArtist.ExternalInfoUpdatedAt).To(Equal(originalArtist.ExternalInfoUpdatedAt)) + Expect(*updatedArtist.ExternalInfoUpdatedAt).To(BeTemporally("==", *originalArtist.ExternalInfoUpdatedAt)) Expect(updatedArtist.SimilarArtists).To(HaveLen(1)) Expect(updatedArtist.SimilarArtists[0].ID).To(Equal(similarInDS.ID)) @@ -196,7 +203,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { }, } similarInDS := model.Artist{ID: "ar-exp-similar", Name: "Expired Similar Updated"} - mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-expired", 5, false) @@ -204,7 +211,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { Expect(updatedArtist).NotTo(BeNil()) Expect(updatedArtist.ID).To(Equal(originalArtist.ID)) Expect(updatedArtist.Name).To(Equal(originalArtist.Name)) - Expect(updatedArtist.ExternalInfoUpdatedAt).To(Equal(originalArtist.ExternalInfoUpdatedAt)) + Expect(*updatedArtist.ExternalInfoUpdatedAt).To(BeTemporally("==", *originalArtist.ExternalInfoUpdatedAt)) Expect(updatedArtist.SimilarArtists).To(HaveLen(1)) Expect(updatedArtist.SimilarArtists[0].ID).To(Equal(similarInDS.ID)) @@ -229,7 +236,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { }, } similarInDS := model.Artist{ID: "ar-sim-present", Name: "Similar Present Updated"} - mockArtistRepo.SetData(model.Artists{*originalArtist, similarInDS}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarInDS) updatedArtist, err := p.UpdateArtistInfo(ctx, "ar-similar-test", 5, true) @@ -250,7 +257,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { ID: "ar-agent-fail", Name: "Agent Fail Artist", } - mockArtistRepo.SetData(model.Artists{*originalArtist}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist) expectedErr := errors.New("agent MBID failed") ag.On("GetArtistMBID", ctx, "ar-agent-fail", "Agent Fail Artist").Return("", expectedErr).Once() @@ -273,7 +280,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { Name: "ID Match Artist", } similarByID := model.Artist{ID: "ar-similar-by-id", Name: "Similar By ID", MbzArtistID: "mbid-similar"} - mockArtistRepo.SetData(model.Artists{*originalArtist, similarByID}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarByID) // Agent returns similar artist with ID (highest priority matching) rawSimilar := []agents.Artist{ @@ -301,7 +308,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { Name: "MBID Match Artist", } similarByMBID := model.Artist{ID: "ar-similar-by-mbid", Name: "Similar By MBID", MbzArtistID: "mbid-similar"} - mockArtistRepo.SetData(model.Artists{*originalArtist, similarByMBID}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarByMBID) // Agent returns similar artist with only MBID (no ID) rawSimilar := []agents.Artist{ @@ -329,7 +336,7 @@ var _ = Describe("Provider - UpdateArtistInfo", func() { Name: "Name Match Artist", } similarByName := model.Artist{ID: "ar-similar-by-name", Name: "Similar By Name"} - mockArtistRepo.SetData(model.Artists{*originalArtist, similarByName}) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, *originalArtist, similarByName) // Agent returns similar artist with non-matching ID and MBID rawSimilar := []agents.Artist{ diff --git a/core/library_test.go b/core/library_test.go index e1000d969..2e8c0710d 100644 --- a/core/library_test.go +++ b/core/library_test.go @@ -13,8 +13,10 @@ import ( _ "github.com/navidrome/navidrome/adapters/gotaglib" // Register taglib extractor "github.com/navidrome/navidrome/core" _ "github.com/navidrome/navidrome/core/storage/local" // Register local storage + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" @@ -24,9 +26,7 @@ import ( // These tests require the local storage adapter and the taglib extractor to be registered. var _ = Describe("Library Service", func() { var service core.Library - var ds *tests.MockDataStore - var libraryRepo *tests.MockLibraryRepo - var userRepo *tests.MockedUserRepo + var ds model.DataStore var ctx context.Context var tempDir string var scanner *tests.MockScanner @@ -34,13 +34,21 @@ var _ = Describe("Library Service", func() { var broker *mockEventBroker var pluginManager *mockPluginUnloader + putLibrary := func(lib model.Library) { + GinkgoHelper() + Expect(ds.Library().Put(ctx, &lib)).To(Succeed()) + } + + storedLibrary := func(id int) *model.Library { + GinkgoHelper() + lib, err := ds.Library().Get(ctx, id) + Expect(err).NotTo(HaveOccurred()) + return lib + } + BeforeEach(func() { - ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - libraryRepo = &tests.MockLibraryRepo{} - userRepo = tests.CreateMockUserRepo() - ds.MockedLibrary = libraryRepo - ds.MockedUser = userRepo + ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin1", UserName: "admin", IsAdmin: true}) + ds = persistence.New(db.Db()) // Create a mock scanner that tracks calls scanner = tests.NewMockScanner() @@ -73,13 +81,13 @@ var _ = Describe("Library Service", func() { Describe("Create", func() { It("creates a new library successfully", func() { - library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "New Library", Path: tempDir} _, err := repo.Save(ctx, library) Expect(err).NotTo(HaveOccurred()) - Expect(libraryRepo.Data[1].Name).To(Equal("New Library")) - Expect(libraryRepo.Data[1].Path).To(Equal(tempDir)) + Expect(storedLibrary(2).Name).To(Equal("New Library")) + Expect(storedLibrary(2).Path).To(Equal(tempDir)) }) It("fails when library name is empty", func() { @@ -114,14 +122,7 @@ var _ = Describe("Library Service", func() { Context("Database constraint violations", func() { BeforeEach(func() { // Set up an existing library that will cause constraint violations - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Existing Library", Path: tempDir}, - }) - }) - - AfterEach(func() { - // Reset custom PutFn after each test - libraryRepo.PutFn = nil + putLibrary(model.Library{ID: 2, Name: "Existing Library", Path: tempDir}) }) It("handles name uniqueness constraint violation from database", func() { @@ -130,13 +131,7 @@ var _ = Describe("Library Service", func() { Expect(err).NotTo(HaveOccurred()) DeferCleanup(func() { os.RemoveAll(otherTempDir) }) - // Try to create another library with the same name - library := &model.Library{ID: 2, Name: "Existing Library", Path: otherTempDir} - - // Mock the repository to return a UNIQUE constraint error - libraryRepo.PutFn = func(library *model.Library) error { - return errors.New("UNIQUE constraint failed: library.name") - } + library := &model.Library{ID: 3, Name: "Existing Library", Path: otherTempDir} _, err = repo.Save(ctx, library) @@ -147,13 +142,7 @@ var _ = Describe("Library Service", func() { }) It("handles path uniqueness constraint violation from database", func() { - // Try to create another library with the same path - library := &model.Library{ID: 2, Name: "Different Library", Path: tempDir} - - // Mock the repository to return a UNIQUE constraint error - libraryRepo.PutFn = func(library *model.Library) error { - return errors.New("UNIQUE constraint failed: library.path") - } + library := &model.Library{ID: 3, Name: "Different Library", Path: tempDir} _, err := repo.Save(ctx, library) @@ -167,9 +156,7 @@ var _ = Describe("Library Service", func() { Describe("Update", func() { BeforeEach(func() { - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) }) It("updates an existing library successfully", func() { @@ -177,22 +164,24 @@ var _ = Describe("Library Service", func() { Expect(err).NotTo(HaveOccurred()) DeferCleanup(func() { os.RemoveAll(newTempDir) }) - library := &model.Library{ID: 1, Name: "Updated Library", Path: newTempDir} + library := &model.Library{ID: 2, Name: "Updated Library", Path: newTempDir} - err = repo.Update(ctx, "1", *library) + err = repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) - Expect(libraryRepo.Data[1].Name).To(Equal("Updated Library")) - Expect(libraryRepo.Data[1].Path).To(Equal(newTempDir)) + Expect(storedLibrary(2).Name).To(Equal("Updated Library")) + Expect(storedLibrary(2).Path).To(Equal(newTempDir)) }) It("forwards the columns sent by the client to the repository", func() { - library := &model.Library{ID: 1, Name: "Updated Library", Path: tempDir} + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir, PIDAlbum: "folder"}) + library := &model.Library{ID: 2, Name: "Updated Library", Path: tempDir} - err := repo.Update(ctx, "1", *library, "name", "path") + err := repo.Update(ctx, "2", *library, "name", "path") Expect(err).NotTo(HaveOccurred()) - Expect(libraryRepo.PutCols).To(Equal([]string{"name", "path"})) + Expect(storedLibrary(2).Name).To(Equal("Updated Library")) + Expect(storedLibrary(2).PIDAlbum).To(Equal("folder")) }) It("fails when library doesn't exist", func() { @@ -210,9 +199,9 @@ var _ = Describe("Library Service", func() { }) It("fails when library name is empty", func() { - library := &model.Library{ID: 1, Path: tempDir} + library := &model.Library{ID: 2, Path: tempDir} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("ra.validation.required")) @@ -220,48 +209,39 @@ var _ = Describe("Library Service", func() { It("cleans and normalizes the path on update", func() { unnormalizedPath := tempDir + "//../" + filepath.Base(tempDir) - library := &model.Library{ID: 1, Name: "Updated Library", Path: unnormalizedPath} + library := &model.Library{ID: 2, Name: "Updated Library", Path: unnormalizedPath} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) - Expect(libraryRepo.Data[1].Path).To(Equal(filepath.Clean(unnormalizedPath))) + Expect(storedLibrary(2).Path).To(Equal(filepath.Clean(unnormalizedPath))) }) It("allows updating library with same name (no change)", func() { // Set up a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir}) // Update the library keeping the same name (should be allowed) - library := &model.Library{ID: 1, Name: "Test Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "Test Library", Path: tempDir} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) }) It("allows updating library with same path (no change)", func() { // Set up a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir}) // Update the library keeping the same path (should be allowed) - library := &model.Library{ID: 1, Name: "Test Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "Test Library", Path: tempDir} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) }) Context("Database constraint violations during update", func() { - BeforeEach(func() { - // Reset any custom PutFn from previous tests - libraryRepo.PutFn = nil - }) - It("handles name uniqueness constraint violation during update", func() { // Create additional temp directory for the test otherTempDir, err := os.MkdirTemp("", "navidrome-other-") @@ -269,20 +249,12 @@ var _ = Describe("Library Service", func() { DeferCleanup(func() { os.RemoveAll(otherTempDir) }) // Set up two libraries - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Library One", Path: tempDir}, - {ID: 2, Name: "Library Two", Path: otherTempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Library One", Path: tempDir}) + putLibrary(model.Library{ID: 3, Name: "Library Two", Path: otherTempDir}) - // Mock database constraint violation - libraryRepo.PutFn = func(library *model.Library) error { - return errors.New("UNIQUE constraint failed: library.name") - } + library := &model.Library{ID: 3, Name: "Library One", Path: otherTempDir} - // Try to update library 2 to have the same name as library 1 - library := &model.Library{ID: 2, Name: "Library One", Path: otherTempDir} - - err = repo.Update(ctx, "2", *library) + err = repo.Update(ctx, "3", *library) Expect(err).To(HaveOccurred()) var validationErr *rest.ValidationError @@ -297,20 +269,12 @@ var _ = Describe("Library Service", func() { DeferCleanup(func() { os.RemoveAll(otherTempDir) }) // Set up two libraries - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Library One", Path: tempDir}, - {ID: 2, Name: "Library Two", Path: otherTempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Library One", Path: tempDir}) + putLibrary(model.Library{ID: 3, Name: "Library Two", Path: otherTempDir}) - // Mock database constraint violation - libraryRepo.PutFn = func(library *model.Library) error { - return errors.New("UNIQUE constraint failed: library.path") - } + library := &model.Library{ID: 3, Name: "Library Two", Path: tempDir} - // Try to update library 2 to have the same path as library 1 - library := &model.Library{ID: 2, Name: "Library Two", Path: tempDir} - - err = repo.Update(ctx, "2", *library) + err = repo.Update(ctx, "3", *library) Expect(err).To(HaveOccurred()) var validationErr *rest.ValidationError @@ -414,15 +378,13 @@ var _ = Describe("Library Service", func() { Context("Update operation", func() { BeforeEach(func() { - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir}) }) It("fails when updated path is not absolute", func() { - library := &model.Library{ID: 1, Name: "Test", Path: "relative/path"} + library := &model.Library{ID: 2, Name: "Test", Path: "relative/path"} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).To(HaveOccurred()) var validationErr *rest.ValidationError @@ -432,23 +394,21 @@ var _ = Describe("Library Service", func() { It("allows updating library with same name (no change)", func() { // Set up a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir}) // Update the library keeping the same name (should be allowed) - library := &model.Library{ID: 1, Name: "Test Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "Test Library", Path: tempDir} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) }) It("fails when updated path does not exist", func() { nonExistentPath := filepath.Join(tempDir, "nonexistent") - library := &model.Library{ID: 1, Name: "Test", Path: nonExistentPath} + library := &model.Library{ID: 2, Name: "Test", Path: nonExistentPath} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).To(HaveOccurred()) var validationErr *rest.ValidationError @@ -461,9 +421,9 @@ var _ = Describe("Library Service", func() { err := os.WriteFile(testFile, []byte("test"), 0600) Expect(err).NotTo(HaveOccurred()) - library := &model.Library{ID: 1, Name: "Test", Path: testFile} + library := &model.Library{ID: 2, Name: "Test", Path: testFile} - err = repo.Update(ctx, "1", *library) + err = repo.Update(ctx, "2", *library) Expect(err).To(HaveOccurred()) var validationErr *rest.ValidationError @@ -473,9 +433,9 @@ var _ = Describe("Library Service", func() { It("handles multiple validation errors on update", func() { // Try to update with empty name and invalid path - library := &model.Library{ID: 1, Name: "", Path: "relative/path"} + library := &model.Library{ID: 2, Name: "", Path: "relative/path"} - err := repo.Update(ctx, "1", *library) + err := repo.Update(ctx, "2", *library) Expect(err).To(HaveOccurred()) var validationErr *rest.ValidationError @@ -490,16 +450,15 @@ var _ = Describe("Library Service", func() { Describe("Delete", func() { BeforeEach(func() { - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Library to Delete", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir}) }) It("deletes an existing library successfully", func() { - err := repo.Delete(ctx, "1") + err := repo.Delete(ctx, "2") Expect(err).NotTo(HaveOccurred()) - Expect(libraryRepo.Data).To(BeEmpty()) + _, err = ds.Library().Get(ctx, 2) + Expect(err).To(MatchError(model.ErrNotFound)) }) It("fails when library doesn't exist", func() { @@ -518,22 +477,15 @@ var _ = Describe("Library Service", func() { regularUser = &model.User{ID: "user1", UserName: "regular", IsAdmin: false} adminUser = &model.User{ID: "admin1", UserName: "admin", IsAdmin: true} - userRepo.Data = map[string]*model.User{ - "regular": regularUser, - "admin": adminUser, - } - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Library 1", Path: "/music1"}, - {ID: 2, Name: "Library 2", Path: "/music2"}, - {ID: 3, Name: "Library 3", Path: "/music3"}, - }) + Expect(ds.User().Put(ctx, regularUser)).To(Succeed()) + Expect(ds.User().Put(ctx, adminUser)).To(Succeed()) + putLibrary(model.Library{ID: 2, Name: "Library 2", Path: "/music2"}) + putLibrary(model.Library{ID: 3, Name: "Library 3", Path: "/music3"}) }) Describe("GetUserLibraries", func() { It("returns user's libraries", func() { - userRepo.UserLibraries = map[string][]int{ - "user1": {1}, - } + Expect(ds.User().SetUserLibraries(ctx, "user1", []int{1})).To(Succeed()) result, err := service.GetUserLibraries(ctx, "user1") @@ -555,7 +507,8 @@ var _ = Describe("Library Service", func() { err := service.SetUserLibraries(ctx, "user1", []int{1, 2}) Expect(err).NotTo(HaveOccurred()) - libraries := userRepo.UserLibraries["user1"] + libraries, err := ds.User().GetUserLibraries(ctx, "user1") + Expect(err).NotTo(HaveOccurred()) Expect(libraries).To(HaveLen(2)) }) @@ -610,10 +563,8 @@ var _ = Describe("Library Service", func() { Context("regular user", func() { BeforeEach(func() { + Expect(ds.User().SetUserLibraries(ctx, "user1", []int{1})).To(Succeed()) ctx = request.WithUser(ctx, *regularUser) - userRepo.UserLibraries = map[string][]int{ - "user1": {1}, - } }) It("allows access to user's libraries", func() { @@ -632,7 +583,7 @@ var _ = Describe("Library Service", func() { Context("no user in context", func() { It("fails with user not found error", func() { - err := service.ValidateLibraryAccess(ctx, "user1", 1) + err := service.ValidateLibraryAccess(GinkgoT().Context(), "user1", 1) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("user not found in context")) @@ -650,7 +601,7 @@ var _ = Describe("Library Service", func() { }) It("triggers scan when creating a new library", func() { - library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "New Library", Path: tempDir} _, err := repo.Save(ctx, library) Expect(err).NotTo(HaveOccurred()) @@ -667,9 +618,7 @@ var _ = Describe("Library Service", func() { It("triggers scan when updating library path", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) // Create a new temporary directory for the update newTempDir, err := os.MkdirTemp("", "navidrome-library-update-") @@ -677,8 +626,8 @@ var _ = Describe("Library Service", func() { DeferCleanup(func() { os.RemoveAll(newTempDir) }) // Update the library with a new path - library := &model.Library{ID: 1, Name: "Updated Library", Path: newTempDir} - err = repo.Update(ctx, "1", *library) + library := &model.Library{ID: 2, Name: "Updated Library", Path: newTempDir} + err = repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) // Wait briefly for the goroutine to complete @@ -693,13 +642,11 @@ var _ = Describe("Library Service", func() { It("does not trigger scan when updating library without path change", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) // Update the library name only (same path) - library := &model.Library{ID: 1, Name: "Updated Name", Path: tempDir} - err := repo.Update(ctx, "1", *library) + library := &model.Library{ID: 2, Name: "Updated Name", Path: tempDir} + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) // Wait a bit to ensure no scan was triggered @@ -709,10 +656,10 @@ var _ = Describe("Library Service", func() { }) It("triggers scan when updating the library PID config", func() { - libraryRepo.SetData(model.Libraries{{ID: 1, Name: "Library", Path: tempDir}}) + putLibrary(model.Library{ID: 2, Name: "Library", Path: tempDir}) - library := model.Library{ID: 1, Name: "Library", Path: tempDir, PIDAlbum: "folder"} - Expect(repo.Update(ctx, "1", library)).To(Succeed()) + library := model.Library{ID: 2, Name: "Library", Path: tempDir, PIDAlbum: "folder"} + Expect(repo.Update(ctx, "2", library)).To(Succeed()) Eventually(func() int { return scanner.GetScanAllCallCount() @@ -722,11 +669,11 @@ var _ = Describe("Library Service", func() { }) It("does not trigger scan when the PID fields were not sent", func() { - libraryRepo.SetData(model.Libraries{{ID: 1, Name: "Library", Path: tempDir, PIDAlbum: "folder"}}) + putLibrary(model.Library{ID: 2, Name: "Library", Path: tempDir, PIDAlbum: "folder"}) // The REST layer decodes a missing pidAlbum as "". Only the sent fields count. - library := model.Library{ID: 1, Name: "Renamed", Path: tempDir} - Expect(repo.Update(ctx, "1", library, "name", "path")).To(Succeed()) + library := model.Library{ID: 2, Name: "Renamed", Path: tempDir} + Expect(repo.Update(ctx, "2", library, "name", "path")).To(Succeed()) Consistently(func() int { return scanner.GetScanAllCallCount() @@ -734,11 +681,11 @@ var _ = Describe("Library Service", func() { }) It("waits for a running scan before triggering a new one", func() { - libraryRepo.SetData(model.Libraries{{ID: 1, Name: "Library", Path: tempDir}}) + putLibrary(model.Library{ID: 2, Name: "Library", Path: tempDir}) scanner.SetScanning(true) - library := model.Library{ID: 1, Name: "Library", Path: tempDir, PIDAlbum: "folder"} - Expect(repo.Update(ctx, "1", library)).To(Succeed()) + library := model.Library{ID: 2, Name: "Library", Path: tempDir, PIDAlbum: "folder"} + Expect(repo.Update(ctx, "2", library)).To(Succeed()) Consistently(func() int { return scanner.GetScanAllCallCount() @@ -765,13 +712,11 @@ var _ = Describe("Library Service", func() { It("does not trigger scan when library update fails", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) // Try to update with invalid data (empty name) - library := &model.Library{ID: 1, Name: "", Path: tempDir} - err := repo.Update(ctx, "1", *library) + library := &model.Library{ID: 2, Name: "", Path: tempDir} + err := repo.Update(ctx, "2", *library) Expect(err).To(HaveOccurred()) // Ensure no scan was triggered since update failed @@ -782,12 +727,10 @@ var _ = Describe("Library Service", func() { It("triggers scan when deleting a library", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Library to Delete", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir}) // Delete the library - err := repo.Delete(ctx, "1") + err := repo.Delete(ctx, "2") Expect(err).NotTo(HaveOccurred()) // Wait briefly for the goroutine to complete @@ -813,7 +756,7 @@ var _ = Describe("Library Service", func() { Context("Watcher Integration", func() { It("starts watcher when creating a new library", func() { - library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "New Library", Path: tempDir} _, err := repo.Save(ctx, library) Expect(err).NotTo(HaveOccurred()) @@ -823,19 +766,17 @@ var _ = Describe("Library Service", func() { return watcherManager.lenStarted() }, time.Second, 10*time.Millisecond).Should(Equal(1)) - Expect(watcherManager.StartedWatchers[0].ID).To(Equal(1)) + Expect(watcherManager.StartedWatchers[0].ID).To(Equal(2)) Expect(watcherManager.StartedWatchers[0].Name).To(Equal("New Library")) Expect(watcherManager.StartedWatchers[0].Path).To(Equal(tempDir)) }) It("restarts watcher when library path is updated", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) // Simulate that this library already has a watcher - watcherManager.simulateExistingLibrary(model.Library{ID: 1, Name: "Original Library", Path: tempDir}) + watcherManager.simulateExistingLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) // Create a new temp directory for the update newTempDir, err := os.MkdirTemp("", "navidrome-library-update-") @@ -843,8 +784,8 @@ var _ = Describe("Library Service", func() { DeferCleanup(func() { os.RemoveAll(newTempDir) }) // Update library with new path - library := &model.Library{ID: 1, Name: "Updated Library", Path: newTempDir} - err = repo.Update(ctx, "1", *library) + library := &model.Library{ID: 2, Name: "Updated Library", Path: newTempDir} + err = repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) // Verify watcher was restarted @@ -852,19 +793,17 @@ var _ = Describe("Library Service", func() { return watcherManager.lenRestarted() }, time.Second, 10*time.Millisecond).Should(Equal(1)) - Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(1)) + Expect(watcherManager.RestartedWatchers[0].ID).To(Equal(2)) Expect(watcherManager.RestartedWatchers[0].Path).To(Equal(newTempDir)) }) It("does not restart watcher when only library name is updated", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) // Update library with same path but different name - library := &model.Library{ID: 1, Name: "Updated Name", Path: tempDir} - err := repo.Update(ctx, "1", *library) + library := &model.Library{ID: 2, Name: "Updated Name", Path: tempDir} + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) // Verify watcher was NOT restarted (since path didn't change) @@ -875,11 +814,9 @@ var _ = Describe("Library Service", func() { It("stops watcher when library is deleted", func() { // Set up a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir}) - err := repo.Delete(ctx, "1") + err := repo.Delete(ctx, "2") Expect(err).NotTo(HaveOccurred()) // Verify watcher was stopped @@ -887,14 +824,12 @@ var _ = Describe("Library Service", func() { return watcherManager.lenStopped() }, time.Second, 10*time.Millisecond).Should(Equal(1)) - Expect(watcherManager.StoppedWatchers[0]).To(Equal(1)) + Expect(watcherManager.StoppedWatchers[0]).To(Equal(2)) }) It("does not stop watcher when library deletion fails", func() { // Set up a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Test Library", Path: tempDir}) // Mock deletion to fail by trying to delete non-existent library err := repo.Delete(ctx, "999") @@ -919,7 +854,7 @@ var _ = Describe("Library Service", func() { }) It("sends refresh event when creating a library", func() { - library := &model.Library{ID: 1, Name: "New Library", Path: tempDir} + library := &model.Library{ID: 2, Name: "New Library", Path: tempDir} _, err := repo.Save(ctx, library) @@ -929,12 +864,10 @@ var _ = Describe("Library Service", func() { It("sends refresh event when updating a library", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Original Library", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Original Library", Path: tempDir}) - library := &model.Library{ID: 1, Name: "Updated Library", Path: tempDir} - err := repo.Update(ctx, "1", *library) + library := &model.Library{ID: 2, Name: "Updated Library", Path: tempDir} + err := repo.Update(ctx, "2", *library) Expect(err).NotTo(HaveOccurred()) Expect(broker.Events).To(HaveLen(1)) @@ -942,9 +875,7 @@ var _ = Describe("Library Service", func() { It("sends refresh event when deleting a library", func() { // First create a library - libraryRepo.SetData(model.Libraries{ - {ID: 2, Name: "Library to Delete", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir}) err := repo.Delete(ctx, "2") @@ -964,9 +895,7 @@ var _ = Describe("Library Service", func() { }) It("calls UnloadDisabledPlugins after successful library deletion", func() { - libraryRepo.SetData(model.Libraries{ - {ID: 2, Name: "Library to Delete", Path: tempDir}, - }) + putLibrary(model.Library{ID: 2, Name: "Library to Delete", Path: tempDir}) err := repo.Delete(ctx, "2") Expect(err).NotTo(HaveOccurred()) diff --git a/core/lyrics/lyrics_suite_test.go b/core/lyrics/lyrics_suite_test.go index baf961ad1..818415572 100644 --- a/core/lyrics/lyrics_suite_test.go +++ b/core/lyrics/lyrics_suite_test.go @@ -9,6 +9,7 @@ import ( "github.com/navidrome/navidrome/core/storage/local" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model/metadata" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -17,11 +18,13 @@ import ( func TestLyrics(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Lyrics Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() // core/storage/local calls log.Fatal if the default scanner extractor is unregistered // when constructing any localStorage. Register a no-op so storage.For("file://...") works diff --git a/core/lyrics/lyrics_test.go b/core/lyrics/lyrics_test.go index 9bdd82688..52ec486d2 100644 --- a/core/lyrics/lyrics_test.go +++ b/core/lyrics/lyrics_test.go @@ -4,12 +4,17 @@ import ( "context" "encoding/json" "errors" + "fmt" "os" "path/filepath" + "time" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/lyrics" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils" . "github.com/onsi/ginkgo/v2" @@ -179,18 +184,11 @@ var _ = Describe("Lyrics", func() { embeddedJSON, err := json.Marshal(embeddedLyrics) Expect(err).ToNot(HaveOccurred()) - repo := &tests.MockMediaFileRepo{} - repo.SetData(model.MediaFiles{ - { - Lyrics: string(embeddedJSON), - Path: "tests/fixtures/01 Invisible (RED) Edit Version.mp3", - }, - { - Lyrics: "[]", - Path: "tests/fixtures/test.mp3", - }, - }) - svc := lyrics.NewLyrics(&tests.MockDataStore{MockedMediaFile: repo}, nil) + ds := persistence.New(db.Db()) + useRepoRootAsLibrary(ctx, ds) + putRickAstleySong(ctx, ds, "tests/fixtures/01 Invisible (RED) Edit Version.mp3", string(embeddedJSON)) + putRickAstleySong(ctx, ds, "tests/fixtures/test.mp3", "[]") + svc := lyrics.NewLyrics(ds, nil) list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") Expect(err).ToNot(HaveOccurred()) @@ -438,26 +436,45 @@ var _ = Describe("Lyrics", func() { var _ = Describe("GetLyricsByArtistTitle", func() { var svc lyrics.Lyrics - var repo *tests.MockMediaFileRepo - var ds *tests.MockDataStore + var ds model.DataStore BeforeEach(func() { conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded" }) - repo = &tests.MockMediaFileRepo{} - ds = &tests.MockDataStore{MockedMediaFile: repo} + ds = persistence.New(db.Db()) svc = lyrics.NewLyrics(ds, nil) }) It("bounds the query to a duplicate window", func() { - repo.SetData(model.MediaFiles{}) - _, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") + conf.Update(func(c *conf.Options) { c.LyricsPriority = ".lrc" }) + useRepoRootAsLibrary(ctx, ds) + var decoys []string + for i := range 10 { + decoys = append(decoys, putRickAstleySong(ctx, ds, fmt.Sprintf("missing/%02d.mp3", i), "")) + } + withSidecar := putRickAstleySong(ctx, ds, "tests/fixtures/test.mp3", "") + _, err := db.Db().Exec("UPDATE media_file SET updated_at = ? WHERE id = ?", time.Now().Add(-time.Hour), withSidecar) Expect(err).ToNot(HaveOccurred()) - Expect(repo.Options.Max).To(Equal(10)) + + list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(BeNil()) + + Expect(ds.MediaFile().Delete(ctx, decoys[0])).To(Succeed()) + list, err = svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(Equal(syncedLyrics)) }) It("returns nil when no media file matches", func() { - repo.SetData(model.MediaFiles{}) - list, err := svc.GetLyricsByArtistTitle(ctx, "Nobody", "No Song") + lyricsJSON, err := json.Marshal(embeddedLyrics) + Expect(err).ToNot(HaveOccurred()) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON)) + + list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "No Song") + Expect(err).ToNot(HaveOccurred()) + Expect(list).To(BeNil()) + + list, err = svc.GetLyricsByArtistTitle(ctx, "Nobody", "Never Gonna Give You Up") Expect(err).ToNot(HaveOccurred()) Expect(list).To(BeNil()) }) @@ -468,9 +485,7 @@ var _ = Describe("Lyrics", func() { embedded, _ := embeddedList.Main() embeddedJSON, err := json.Marshal(model.LyricList{embedded}) Expect(err).ToNot(HaveOccurred()) - repo.SetData(model.MediaFiles{ - {ID: "1", Title: "Never Gonna Give You Up", Lyrics: string(embeddedJSON)}, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(embeddedJSON)) list, err := svc.GetLyricsByArtistTitle(ctx, "Rick Astley", "Never Gonna Give You Up") Expect(err).ToNot(HaveOccurred()) @@ -480,6 +495,30 @@ var _ = Describe("Lyrics", func() { }) }) +func useRepoRootAsLibrary(ctx context.Context, ds model.DataStore) { + GinkgoHelper() + root, err := os.Getwd() + Expect(err).ToNot(HaveOccurred()) + persistencetest.SetLibraries(ctx, ds, root) +} + +// putRickAstleySong stores "Never Gonna Give You Up" by Rick Astley at path and returns its ID. +func putRickAstleySong(ctx context.Context, ds model.DataStore, path, lyrics string) string { + GinkgoHelper() + artist := model.Artist{ID: "ar-rick", Name: "Rick Astley"} + Expect(ds.Artist().Put(ctx, &artist)).To(Succeed()) + mf := &model.MediaFile{ + LibraryID: model.DefaultLibraryID, + Path: path, + Title: "Never Gonna Give You Up", + Lyrics: lyrics, + UpdatedAt: time.Now(), + Participants: model.Participants{model.RoleArtist: {{Artist: artist}}}, + } + Expect(ds.MediaFile().Put(ctx, mf)).To(Succeed()) + return mf.ID +} + type mockPluginLoader struct { lyrics model.LyricList err error diff --git a/core/maintenance_test.go b/core/maintenance_test.go index 5e821b644..1a5fddacd 100644 --- a/core/maintenance_test.go +++ b/core/maintenance_test.go @@ -4,10 +4,14 @@ import ( "context" "errors" "sync" + "sync/atomic" "time" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -15,90 +19,126 @@ import ( ) var _ = Describe("Maintenance", func() { - var ds *tests.MockDataStore - var mfRepo *extendedMediaFileRepo + var ds model.DataStore var service Maintenance var ctx context.Context + fileExists := func(id string) bool { + GinkgoHelper() + exists, err := ds.MediaFile().Exists(ctx, id) + Expect(err).ToNot(HaveOccurred()) + return exists + } + + albumExists := func(id string) bool { + GinkgoHelper() + exists, err := ds.Album().Exists(ctx, id) + Expect(err).ToNot(HaveOccurred()) + return exists + } + + getAlbum := func(id string) *model.Album { + GinkgoHelper() + al, err := ds.Album().Get(ctx, id) + Expect(err).ToNot(HaveOccurred()) + return al + } + + starred := func(id string) bool { + GinkgoHelper() + return getAlbum(id).Starred + } + + putArtist := func(id string) model.Participant { + GinkgoHelper() + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: id, Name: "Artist " + id}) + return model.Participant{ID: id, Name: "Artist " + id} + } + + artistSongCount := func(id string) int { + GinkgoHelper() + a, err := ds.Artist().Get(ctx, id) + Expect(err).ToNot(HaveOccurred()) + return a.SongCount + } + BeforeEach(func() { ctx = GinkgoT().Context() - ctx = request.WithUser(ctx, model.User{ID: "user1", IsAdmin: true}) - - ds = createTestDataStore() - mfRepo = ds.MockedMediaFile.(*extendedMediaFileRepo) + ds = persistence.New(db.Db()) + admin := model.User{ID: "user1", UserName: "user1", IsAdmin: true} + Expect(ds.User().Put(ctx, &admin)).To(Succeed()) + ctx = request.WithUser(ctx, admin) service = NewMaintenance(ds) + DeferCleanup(func() { service.(*maintenanceService).wait() }) }) Describe("DeleteMissingFiles", func() { Context("with specific IDs", func() { It("deletes specific missing files and runs GC", func() { - // Setup: mock missing files with album IDs - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - {ID: "mf2", AlbumID: "album2", Missing: true}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1"}, model.Album{ID: "album2"}, model.Album{ID: "album3"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "mf1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "mf2", AlbumID: "album2", Missing: true}, + model.MediaFile{ID: "mf3", AlbumID: "album3", Missing: true}, + ) err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf2"}) Expect(err).ToNot(HaveOccurred()) - Expect(mfRepo.deleteMissingCalled).To(BeTrue()) - Expect(mfRepo.deletedIDs).To(Equal([]string{"mf1", "mf2"})) - Expect(ds.GCCalled).To(BeTrue(), "GC should be called after deletion") + Expect(fileExists("mf1")).To(BeFalse()) + Expect(fileExists("mf2")).To(BeFalse()) + Expect(fileExists("mf3")).To(BeTrue()) + Expect(albumExists("album1")).To(BeFalse(), "GC should purge albums left empty by the deletion") + Expect(albumExists("album2")).To(BeFalse(), "GC should purge albums left empty by the deletion") + Expect(albumExists("album3")).To(BeTrue()) }) It("triggers artist stats refresh and album refresh after deletion", func() { - artistRepo := ds.MockedArtist.(*extendedArtistRepo) - // Setup: mock missing files with albums - albumRepo := ds.MockedAlbum.(*extendedAlbumRepo) - albumRepo.SetData(model.Albums{ - {ID: "album1", Name: "Test Album", SongCount: 5}, - }) - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - {ID: "mf2", AlbumID: "album1", Missing: false, Size: 1000, Duration: 180}, - {ID: "mf3", AlbumID: "album1", Missing: false, Size: 2000, Duration: 200}, - }) + artist := model.Participants{model.RoleArtist: {putArtist("ar1")}} + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1", Name: "Test Album", SongCount: 5, Participants: artist}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "mf1", AlbumID: "album1", Album: "Test Album", Missing: true, Participants: artist}, + model.MediaFile{ID: "mf2", AlbumID: "album1", Album: "Test Album", Size: 1000, Duration: 180, Participants: artist}, + model.MediaFile{ID: "mf3", AlbumID: "album1", Album: "Test Album", Size: 2000, Duration: 200, Participants: artist}, + ) + Expect(artistSongCount("ar1")).To(BeZero()) err := service.DeleteMissingFiles(ctx, []string{"mf1"}) Expect(err).ToNot(HaveOccurred()) - - // Wait for background goroutines to complete service.(*maintenanceService).wait() - // RefreshStats should be called - Expect(artistRepo.IsRefreshStatsCalled()).To(BeTrue(), "Artist stats should be refreshed") - - // Album should be updated with new calculated values - Expect(albumRepo.GetPutCallCount()).To(BeNumerically(">", 0), "Album.Put() should be called to refresh album data") + Expect(artistSongCount("ar1")).To(Equal(2), "Artist stats should be refreshed") + al := getAlbum("album1") + Expect(al.SongCount).To(Equal(2)) + Expect(al.Size).To(Equal(int64(3000))) + Expect(al.Duration).To(BeNumerically("==", 380)) }) It("returns error if deletion fails", func() { - mfRepo.deleteMissingError = errors.New("delete failed") + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Missing: true}) + service = NewMaintenance(withMediaFileErrors(ds, mediaFileErrors{deleteMissing: errors.New("delete failed")})) err := service.DeleteMissingFiles(ctx, []string{"mf1"}) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("delete failed")) + Expect(fileExists("mf1")).To(BeTrue()) }) It("continues even if album tracking fails", func() { - mfRepo.SetError(true) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Missing: true}) + service = NewMaintenance(withMediaFileErrors(ds, mediaFileErrors{getAll: errors.New("get failed")})) err := service.DeleteMissingFiles(ctx, []string{"mf1"}) - // Should not fail, just log warning Expect(err).ToNot(HaveOccurred()) - Expect(mfRepo.deleteMissingCalled).To(BeTrue()) + Expect(fileExists("mf1")).To(BeFalse()) }) It("returns error if GC fails", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - }) - - // Set GC to return error - ds.GCError = errors.New("gc failed") + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", AlbumID: "album1", Missing: true}) + service = NewMaintenance(withGCError(ds, errors.New("gc failed"))) err := service.DeleteMissingFiles(ctx, []string{"mf1"}) @@ -109,418 +149,411 @@ var _ = Describe("Maintenance", func() { Context("album ID extraction", func() { It("extracts unique album IDs from missing files", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - {ID: "mf2", AlbumID: "album1", Missing: true}, - {ID: "mf3", AlbumID: "album2", Missing: true}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "mf1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "mf2", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "mf3", AlbumID: "album2", Missing: true}, + model.MediaFile{ID: "mf4", AlbumID: "album3", Missing: true}, + ) - err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf2", "mf3"}) + ids, err := service.(*maintenanceService).getAffectedAlbumIDs(ctx, []string{"mf1", "mf2", "mf3"}) Expect(err).ToNot(HaveOccurred()) + Expect(ids).To(ConsistOf("album1", "album2")) }) It("skips files without album IDs", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "", Missing: true}, - {ID: "mf2", AlbumID: "album1", Missing: true}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "mf1", AlbumID: "", Missing: true}, + model.MediaFile{ID: "mf2", AlbumID: "album1", Missing: true}, + ) - err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf2"}) + ids, err := service.(*maintenanceService).getAffectedAlbumIDs(ctx, []string{"mf1", "mf2"}) Expect(err).ToNot(HaveOccurred()) + Expect(ids).To(ConsistOf("album1")) }) }) }) Describe("DeleteAllMissingFiles", func() { It("deletes all missing files and runs GC", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - {ID: "mf2", AlbumID: "album2", Missing: true}, - {ID: "mf3", AlbumID: "album3", Missing: true}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1"}, model.Album{ID: "album2"}, model.Album{ID: "album3"}, model.Album{ID: "album4"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "mf1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "mf2", AlbumID: "album2", Missing: true}, + model.MediaFile{ID: "mf3", AlbumID: "album3", Missing: true}, + model.MediaFile{ID: "mf4", AlbumID: "album4"}, + ) err := service.DeleteAllMissingFiles(ctx) Expect(err).ToNot(HaveOccurred()) - Expect(ds.GCCalled).To(BeTrue(), "GC should be called after deletion") + for _, id := range []string{"mf1", "mf2", "mf3"} { + Expect(fileExists(id)).To(BeFalse()) + } + Expect(fileExists("mf4")).To(BeTrue()) + Expect(albumExists("album1")).To(BeFalse(), "GC should purge albums left empty by the deletion") + Expect(albumExists("album4")).To(BeTrue()) }) It("returns error if deletion fails", func() { - mfRepo.SetError(true) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", Missing: true}) + service = NewMaintenance(withMediaFileErrors(ds, mediaFileErrors{deleteAllMissing: errors.New("delete failed")})) err := service.DeleteAllMissingFiles(ctx) - Expect(err).To(HaveOccurred()) + Expect(err).To(MatchError(ContainSubstring("delete failed"))) + Expect(fileExists("mf1")).To(BeTrue()) }) It("handles empty result gracefully", func() { - mfRepo.SetData(model.MediaFiles{}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1"}) err := service.DeleteAllMissingFiles(ctx) Expect(err).ToNot(HaveOccurred()) + Expect(fileExists("mf1")).To(BeTrue()) }) }) Describe("Album refresh logic", func() { - var albumRepo *extendedAlbumRepo - - BeforeEach(func() { - albumRepo = ds.MockedAlbum.(*extendedAlbumRepo) - }) - Context("when album has no tracks after deletion", func() { It("skips the album without updating it", func() { - // Setup album with no remaining tracks - albumRepo.SetData(model.Albums{ - {ID: "album1", Name: "Empty Album", SongCount: 1}, - }) - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - }) - - err := service.DeleteMissingFiles(ctx, []string{"mf1"}) - + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1", Name: "Empty Album", SongCount: 1}) + lastUpdate := time.Now().Add(-time.Hour).Truncate(time.Second) + _, err := db.Db().Exec("UPDATE album SET updated_at = ? WHERE id = ?", lastUpdate, "album1") Expect(err).ToNot(HaveOccurred()) - // Wait for background goroutines to complete - service.(*maintenanceService).wait() + Expect(service.(*maintenanceService).refreshAlbums(ctx, []string{"album1"})).To(Succeed()) - // Album should NOT be updated because it has no tracks left - Expect(albumRepo.GetPutCallCount()).To(Equal(0), "Album with no tracks should not be updated") + al := getAlbum("album1") + Expect(al.SongCount).To(Equal(1), "Album with no tracks should not be updated") + Expect(al.UpdatedAt).To(BeTemporally("==", lastUpdate)) }) }) Context("when Put fails for one album", func() { It("continues processing other albums", func() { - albumRepo.SetData(model.Albums{ - {ID: "album1", Name: "Album 1"}, - {ID: "album2", Name: "Album 2"}, - }) - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - {ID: "mf2", AlbumID: "album1", Missing: false, Size: 1000, Duration: 180}, - {ID: "mf3", AlbumID: "album2", Missing: true}, - {ID: "mf4", AlbumID: "album2", Missing: false, Size: 2000, Duration: 200}, - }) - - // Make Put fail on first call but succeed on subsequent calls - albumRepo.putError = errors.New("put failed") - albumRepo.failOnce = true + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1", Name: "Album 1"}, model.Album{ID: "album2", Name: "Album 2"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "mf1", AlbumID: "album1", Album: "Album 1", Missing: true}, + model.MediaFile{ID: "mf2", AlbumID: "album1", Album: "Album 1", Size: 1000, Duration: 180}, + model.MediaFile{ID: "mf3", AlbumID: "album2", Album: "Album 2", Missing: true}, + model.MediaFile{ID: "mf4", AlbumID: "album2", Album: "Album 2", Size: 2000, Duration: 200}, + ) + service = NewMaintenance(withAlbumPutFailures(ds, 1)) err := service.DeleteMissingFiles(ctx, []string{"mf1", "mf3"}) - // Should not fail even if one album's Put fails Expect(err).ToNot(HaveOccurred()) - - // Wait for background goroutines to complete service.(*maintenanceService).wait() - // Put should have been called multiple times - Expect(albumRepo.GetPutCallCount()).To(BeNumerically(">", 0), "Put should be attempted") + refreshed := 0 + for _, id := range []string{"album1", "album2"} { + if getAlbum(id).SongCount == 1 { + refreshed++ + } + } + Expect(refreshed).To(Equal(1), "the album whose Put did not fail should still be refreshed") }) }) Context("when media file loading fails", func() { It("logs warning but continues when tracking affected albums fails", func() { - // Set up log capturing hook, cleanup := tests.LogHook() defer cleanup() - albumRepo.SetData(model.Albums{ - {ID: "album1", Name: "Album 1"}, - }) - mfRepo.SetData(model.MediaFiles{ - {ID: "mf1", AlbumID: "album1", Missing: true}, - }) - // Make GetAll fail when loading media files - mfRepo.SetError(true) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1", Name: "Album 1"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf1", AlbumID: "album1", Missing: true}) + service = NewMaintenance(withMediaFileErrors(ds, mediaFileErrors{getAll: errors.New("get failed")})) err := service.DeleteMissingFiles(ctx, []string{"mf1"}) - // Deletion should succeed despite the tracking error Expect(err).ToNot(HaveOccurred()) - Expect(mfRepo.deleteMissingCalled).To(BeTrue()) + service.(*maintenanceService).wait() + Expect(fileExists("mf1")).To(BeFalse()) - // Verify the warning was logged - Expect(hook.LastEntry()).ToNot(BeNil()) - Expect(hook.LastEntry().Level).To(Equal(logrus.WarnLevel)) - Expect(hook.LastEntry().Message).To(Equal("Error tracking affected albums for refresh")) + Expect(hook.AllEntries()).To(ContainElement(SatisfyAll( + HaveField("Level", logrus.WarnLevel), + HaveField("Message", "Error tracking affected albums for refresh"), + ))) }) }) }) Describe("RemapMissingFile", func() { It("relocates the missing file's identity onto the target and runs GC", func() { - created := time.Now().Add(-30 * 24 * time.Hour) - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", Path: "old/song.mp3", AlbumID: "album1", CreatedAt: created, Missing: true}, - {ID: "t1", Path: "new/song.mp3", AlbumID: "album1", Missing: false}, - }) + created := time.Now().Add(-30 * 24 * time.Hour).Truncate(time.Second) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1"}, model.Album{ID: "orphan"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", Path: "old/song.mp3", AlbumID: "album1", CreatedAt: created, Missing: true}, + model.MediaFile{ID: "t1", Path: "new/song.mp3", AlbumID: "album1", Missing: false}, + ) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - got, err := mfRepo.Get(ctx, "m1") + got, err := ds.MediaFile().Get(ctx, "m1") Expect(err).ToNot(HaveOccurred()) - Expect(got.Path).To(Equal("new/song.mp3")) // moved to target's location + Expect(got.Path).To(Equal("new/song.mp3")) Expect(got.Missing).To(BeFalse()) - Expect(got.CreatedAt).To(BeTemporally("==", created)) // created_at preserved - exists, _ := mfRepo.Exists(ctx, "t1") - Expect(exists).To(BeFalse()) // discarded row removed - Expect(ds.GCCalled).To(BeTrue()) + Expect(got.CreatedAt).To(BeTemporally("==", created)) + Expect(fileExists("t1")).To(BeFalse()) + Expect(albumExists("orphan")).To(BeFalse(), "GC should purge empty albums") }) It("moves the target's annotations, bookmarks and playlist entries onto the surviving id", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", AlbumID: "album1", Missing: true}, - {ID: "t1", AlbumID: "album1", Missing: false}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "t1", AlbumID: "album1", Missing: false}, + ) + Expect(ds.MediaFile().SetStar(ctx, true, "t1")).To(Succeed()) + Expect(ds.MediaFile().AddBookmark(ctx, "t1", "here", 42)).To(Succeed()) + pls := &model.Playlist{Name: "pls", OwnerID: "user1"} + Expect(ds.Playlist().Put(ctx, pls)).To(Succeed()) + _, err := ds.Playlist().Tracks(ctx, pls.ID, false).Add(ctx, []string{"t1"}) + Expect(err).ToNot(HaveOccurred()) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - Expect(mfRepo.ReassignReferencesCalls).To(HaveKeyWithValue("t1", "m1")) + got, err := ds.MediaFile().Get(ctx, "m1") + Expect(err).ToNot(HaveOccurred()) + Expect(got.Starred).To(BeTrue()) + bookmarks, err := ds.MediaFile().GetBookmarks(ctx) + Expect(err).ToNot(HaveOccurred()) + Expect(bookmarks).To(HaveLen(1)) + Expect(bookmarks[0].Item.ID).To(Equal("m1")) + Expect(bookmarks[0].Position).To(Equal(int64(42))) + ids, err := ds.Playlist().Tracks(ctx, pls.ID, false).GetMediaFileIDs(ctx) + Expect(err).ToNot(HaveOccurred()) + Expect(ids).To(Equal([]string{"m1"})) }) It("reassigns album annotations when the old album is emptied", func() { - albumRepo := ds.MockedAlbum.(*extendedAlbumRepo) - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", AlbumID: "album1", Missing: true}, - {ID: "t1", AlbumID: "album2", Missing: false}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1"}, model.Album{ID: "album2"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "t1", AlbumID: "album2", Missing: false}, + ) + Expect(ds.Album().SetStar(ctx, true, "album1")).To(Succeed()) - mfRepo.SetCountAll(0) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - Expect(albumRepo.ReassignAnnotationCalls).To(HaveKeyWithValue("album1", "album2")) + Expect(starred("album2")).To(BeTrue()) }) It("does not reassign album annotations when the old album is not emptied", func() { - albumRepo := ds.MockedAlbum.(*extendedAlbumRepo) - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", AlbumID: "album1", Missing: true}, - {ID: "m2", AlbumID: "album1", Missing: false}, - {ID: "t1", AlbumID: "album2", Missing: false}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "album1"}, model.Album{ID: "album2"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "m2", AlbumID: "album1", Missing: false}, + model.MediaFile{ID: "t1", AlbumID: "album2", Missing: false}, + ) + Expect(ds.Album().SetStar(ctx, true, "album1")).To(Succeed()) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - Expect(albumRepo.ReassignAnnotationCalls).To(BeEmpty()) + Expect(starred("album1")).To(BeTrue()) + Expect(starred("album2")).To(BeFalse()) }) It("does not reassign annotations when the album is unchanged", func() { - albumRepo := ds.MockedAlbum.(*extendedAlbumRepo) - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", AlbumID: "album1", Missing: true}, - {ID: "t1", AlbumID: "album1", Missing: false}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "t1", AlbumID: "album1", Missing: false}, + ) + spy := &reassignSpy{} + service = NewMaintenance(withReassignSpy(ds, spy)) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - Expect(albumRepo.ReassignAnnotationCalls).To(BeEmpty()) + Expect(spy.calls()).To(BeEmpty()) }) It("returns ErrNotFound when the missing file does not exist", func() { - mfRepo.SetData(model.MediaFiles{{ID: "t1", Missing: false}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "t1", Missing: false}) Expect(service.RemapMissingFile(ctx, "nope", "t1")).To(MatchError(model.ErrNotFound)) }) It("refuses to remap from a file that is not missing", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", Missing: false}, - {ID: "t1", Missing: false}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", Missing: false}, + model.MediaFile{ID: "t1", Missing: false}, + ) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(MatchError(ErrNotMissing)) }) It("refuses to remap a file onto itself", func() { - mfRepo.SetData(model.MediaFiles{{ID: "m1", Missing: true}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "m1", Missing: true}) Expect(service.RemapMissingFile(ctx, "m1", "m1")).To(MatchError(ErrSameFile)) }) It("refuses to remap onto a target that is itself missing", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", Missing: true}, - {ID: "t1", Missing: true}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", Missing: true}, + model.MediaFile{ID: "t1", Missing: true}, + ) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(MatchError(ErrTargetMissing)) }) It("refreshes artist and album stats right after the remap", func() { - artistRepo := ds.MockedArtist.(*extendedArtistRepo) - albumRepo := ds.MockedAlbum.(*extendedAlbumRepo) - albumRepo.SetData(model.Albums{ - {ID: "album1", Name: "Old Album", SongCount: 2, Size: 1100, Duration: 110}, - {ID: "album2", Name: "New Album", SongCount: 1, Size: 2000, Duration: 200}, - }) - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", Path: "old/1.mp3", Album: "Old Album", AlbumID: "album1", Missing: true, Size: 100, Duration: 10}, - {ID: "k1", Path: "old/2.mp3", Album: "Old Album", AlbumID: "album1", Missing: false, Size: 1000, Duration: 100}, - {ID: "t1", Path: "new/1.mp3", Album: "New Album", AlbumID: "album2", Missing: false, Size: 2000, Duration: 200}, - }) + artist := model.Participants{model.RoleArtist: {putArtist("ar1")}} + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: "album1", Name: "Old Album", SongCount: 2, Size: 1100, Duration: 110}, + model.Album{ID: "album2", Name: "New Album", SongCount: 1, Size: 2000, Duration: 200, Participants: artist}, + ) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", Path: "old/1.mp3", Album: "Old Album", AlbumID: "album1", Missing: true, Size: 100, Duration: 10}, + model.MediaFile{ID: "k1", Path: "old/2.mp3", Album: "Old Album", AlbumID: "album1", Missing: false, Size: 1000, Duration: 100}, + model.MediaFile{ID: "t1", Path: "new/1.mp3", Album: "New Album", AlbumID: "album2", Missing: false, Size: 2000, Duration: 200, Participants: artist}, + ) + Expect(artistSongCount("ar1")).To(BeZero()) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - Expect(artistRepo.IsRefreshStatsCalled()).To(BeTrue(), "Artist stats should be refreshed") + Expect(artistSongCount("ar1")).To(Equal(1), "Artist stats should be refreshed") - // The old album lost the remapped track, so its stats are recalculated from the remaining one - oldAlbum, err := albumRepo.Get(ctx, "album1") - Expect(err).ToNot(HaveOccurred()) + oldAlbum := getAlbum("album1") Expect(oldAlbum.SongCount).To(Equal(1)) Expect(oldAlbum.Size).To(Equal(int64(1000))) Expect(oldAlbum.Duration).To(BeNumerically("==", 100)) - // The target album keeps the track, now under the missing file's ID - newAlbum, err := albumRepo.Get(ctx, "album2") - Expect(err).ToNot(HaveOccurred()) + newAlbum := getAlbum("album2") Expect(newAlbum.SongCount).To(Equal(1)) Expect(newAlbum.Size).To(Equal(int64(2000))) Expect(newAlbum.Duration).To(BeNumerically("==", 200)) }) It("returns an error if GC fails", func() { - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", AlbumID: "album1", Missing: true}, - {ID: "t1", AlbumID: "album1", Missing: false}, - }) - ds.GCError = errors.New("gc failed") + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "t1", AlbumID: "album1", Missing: false}, + ) + service = NewMaintenance(withGCError(ds, errors.New("gc failed"))) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(MatchError(ContainSubstring("gc failed"))) }) It("preserves the target's participants on the remapped track", func() { - participant := model.Participant{ - ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist", - } - mfRepo.SetData(model.MediaFiles{ - {ID: "m1", AlbumID: "album1", Missing: true}, - {ID: "t1", AlbumID: "album2", Missing: false, Participants: model.Participants{ + Expect(ds.Artist().Put(ctx, &model.Artist{ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist"})).To(Succeed()) + participant := model.Participant{ID: "a1", Name: "Artist", OrderArtistName: "artist", MbzArtistID: "mbz-artist"} + stored := model.Participant{ID: "a1", Name: "Artist"} + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "m1", AlbumID: "album1", Missing: true}, + model.MediaFile{ID: "t1", AlbumID: "album2", Missing: false, Participants: model.Participants{ model.RoleArtist: model.ParticipantList{participant}, }}, - }) + ) Expect(service.RemapMissingFile(ctx, "m1", "t1")).To(Succeed()) - // The surviving row is the missing file's ID, holding the target's data - got, err := mfRepo.GetWithParticipants(ctx, "m1") + got, err := ds.MediaFile().GetWithParticipants(ctx, "m1") Expect(err).ToNot(HaveOccurred()) - Expect(got.Participants).To(HaveKeyWithValue(model.RoleArtist, model.ParticipantList{participant})) + Expect(got.Participants).To(HaveKeyWithValue(model.RoleArtist, model.ParticipantList{stored})) }) }) }) -// Test helper to create a mock DataStore with controllable behavior -func createTestDataStore() *tests.MockDataStore { - ds := &tests.MockDataStore{} +type mediaFileErrors struct { + getAll, deleteMissing, deleteAllMissing error +} - // Create extended album repo with Put tracking - albumRepo := &extendedAlbumRepo{ - MockAlbumRepo: tests.CreateMockAlbumRepo(), +func withMediaFileErrors(ds model.DataStore, errs mediaFileErrors) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return &mediaFileErrorsRepo{MediaFileRepository: r, errs: errs} + }}) +} + +type mediaFileErrorsRepo struct { + model.MediaFileRepository + errs mediaFileErrors +} + +func (r *mediaFileErrorsRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { + if r.errs.getAll != nil { + return nil, r.errs.getAll } - ds.MockedAlbum = albumRepo + return r.MediaFileRepository.GetAll(ctx, options...) +} - // Create extended artist repo with RefreshStats tracking - artistRepo := &extendedArtistRepo{ - MockArtistRepo: tests.CreateMockArtistRepo(), +func (r *mediaFileErrorsRepo) DeleteMissing(ctx context.Context, ids []string) error { + if r.errs.deleteMissing != nil { + return r.errs.deleteMissing } - ds.MockedArtist = artistRepo + return r.MediaFileRepository.DeleteMissing(ctx, ids) +} - // Create extended media file repo with DeleteMissing support - mfRepo := &extendedMediaFileRepo{ - MockMediaFileRepo: tests.CreateMockMediaFileRepo(), +func (r *mediaFileErrorsRepo) DeleteAllMissing(ctx context.Context) (int64, error) { + if r.errs.deleteAllMissing != nil { + return 0, r.errs.deleteAllMissing } - ds.MockedMediaFile = mfRepo - - return ds + return r.MediaFileRepository.DeleteAllMissing(ctx) } -// Extension of MockMediaFileRepo to add DeleteMissing method -type extendedMediaFileRepo struct { - *tests.MockMediaFileRepo - deleteMissingCalled bool - deletedIDs []string - deleteMissingError error +func withGCError(ds model.DataStore, err error) model.DataStore { + return persistencetest.Overlay(ds, func(ds model.DataStore) model.DataStore { + return &gcErrorDS{DataStore: ds, err: err} + }) } -func (m *extendedMediaFileRepo) DeleteMissing(ctx context.Context, ids []string) error { - m.deleteMissingCalled = true - m.deletedIDs = ids - if m.deleteMissingError != nil { - return m.deleteMissingError +type gcErrorDS struct { + model.DataStore + err error +} + +func (d *gcErrorDS) GC(context.Context, ...int) error { return d.err } + +// withAlbumPutFailures makes the first n album Puts fail, across every Album() call and transaction. +func withAlbumPutFailures(ds model.DataStore, n int32) model.DataStore { + remaining := &atomic.Int32{} + remaining.Store(n) + return persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return &albumPutFailuresRepo{AlbumRepository: r, remaining: remaining} + }}) +} + +type albumPutFailuresRepo struct { + model.AlbumRepository + remaining *atomic.Int32 +} + +func (r *albumPutFailuresRepo) Put(ctx context.Context, al *model.Album) error { + if r.remaining.Add(-1) >= 0 { + return errors.New("put failed") } - // Actually delete from the mock data - for _, id := range ids { - delete(m.Data, id) - } - return nil + return r.AlbumRepository.Put(ctx, al) } -// Extension of MockAlbumRepo to track Put calls -type extendedAlbumRepo struct { - *tests.MockAlbumRepo - mu sync.RWMutex - putCallCount int - lastPutData *model.Album - putError error - failOnce bool +// reassignSpy records album annotation reassignments, which are no-ops in the DB when both IDs are equal. +type reassignSpy struct { + mu sync.Mutex + got []string } -func (m *extendedAlbumRepo) Put(ctx context.Context, album *model.Album) error { - m.mu.Lock() - m.putCallCount++ - m.lastPutData = album - - // Handle failOnce behavior - var err error - if m.putError != nil { - if m.failOnce { - err = m.putError - m.putError = nil // Clear error after first failure - m.mu.Unlock() - return err - } - err = m.putError - m.mu.Unlock() - return err - } - m.mu.Unlock() - - return m.MockAlbumRepo.Put(ctx, album) +func (s *reassignSpy) calls() []string { + s.mu.Lock() + defer s.mu.Unlock() + return s.got } -func (m *extendedAlbumRepo) GetPutCallCount() int { - m.mu.RLock() - defer m.mu.RUnlock() - return m.putCallCount +func withReassignSpy(ds model.DataStore, spy *reassignSpy) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return &reassignSpyRepo{AlbumRepository: r, spy: spy} + }}) } -// Extension of MockArtistRepo to track RefreshStats calls -type extendedArtistRepo struct { - *tests.MockArtistRepo - mu sync.RWMutex - refreshStatsCalled bool - refreshStatsError error +type reassignSpyRepo struct { + model.AlbumRepository + spy *reassignSpy } -func (m *extendedArtistRepo) RefreshStats(ctx context.Context, allArtists bool) (int64, error) { - m.mu.Lock() - m.refreshStatsCalled = true - err := m.refreshStatsError - m.mu.Unlock() - - if err != nil { - return 0, err - } - return m.MockArtistRepo.RefreshStats(ctx, allArtists) -} - -func (m *extendedArtistRepo) IsRefreshStatsCalled() bool { - m.mu.RLock() - defer m.mu.RUnlock() - return m.refreshStatsCalled +func (r *reassignSpyRepo) ReassignAnnotation(ctx context.Context, prevID, newID string) error { + r.spy.mu.Lock() + r.spy.got = append(r.spy.got, prevID+"->"+newID) + r.spy.mu.Unlock() + return r.AlbumRepository.ReassignAnnotation(ctx, prevID, newID) } diff --git a/core/matcher/matcher_internal_test.go b/core/matcher/matcher_internal_test.go index 5b987d937..07657c3c0 100644 --- a/core/matcher/matcher_internal_test.go +++ b/core/matcher/matcher_internal_test.go @@ -2,8 +2,10 @@ package matcher import ( "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -230,11 +232,9 @@ var _ = Describe("bucketTracks", func() { var _ = Describe("resolveArtists ID fast-path", func() { It("owns an artist supplied by ID without a name match", func() { ctx := GinkgoT().Context() - artistRepo := tests.CreateMockArtistRepo() - artistRepo.SetData(model.Artists{ - {ID: "ar-x", Name: "Some Artist", OrderArtistName: "some artist", MbzArtistID: "mbz-x"}, - }) - ds := &tests.MockDataStore{MockedArtist: artistRepo} + ds := persistence.New(db.Db()) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, + model.Artist{ID: "ar-x", Name: "Some Artist", OrderArtistName: "some artist", MbzArtistID: "mbz-x"}) m := New(ds) queries := []indexedQuery{ diff --git a/core/matcher/matcher_suite_test.go b/core/matcher/matcher_suite_test.go index ff50557ad..377543891 100644 --- a/core/matcher/matcher_suite_test.go +++ b/core/matcher/matcher_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestMatcher(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Matcher Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/core/matcher/matcher_test.go b/core/matcher/matcher_test.go index 48e53f2ee..7b732ea14 100644 --- a/core/matcher/matcher_test.go +++ b/core/matcher/matcher_test.go @@ -9,97 +9,29 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/matcher" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" - "github.com/stretchr/testify/mock" ) var _ = Describe("Matcher", func() { var ds model.DataStore - var mediaFileRepo *mockMediaFileRepo - var artistRepo *mockArtistRepo var ctx context.Context var m *matcher.Matcher BeforeEach(func() { ctx = GinkgoT().Context() - mediaFileRepo = newMockMediaFileRepo() - artistRepo = newMockArtistRepo() - DeferCleanup(func() { - mediaFileRepo.AssertExpectations(GinkgoT()) - }) - ds = &tests.MockDataStore{ - MockedMediaFile: mediaFileRepo, - MockedArtist: artistRepo, - } + user := model.User{ID: "user-1", UserName: "user-1"} + ds = persistence.New(db.Db()) + Expect(ds.User().Put(ctx, &user)).To(Succeed()) + ctx = request.WithUser(ctx, user) m = matcher.New(ds) }) - // Per-phase expectation helpers. Each `expect*Phase` registers a .Once() expectation - // that will fail the suite via AssertExpectations if the phase is NOT called. Tests - // use these to deterministically verify which matching phases fire. Phases that may - // or may not fire should use the `allow*Phase` variants instead, which register - // .Maybe() fallbacks. - expectIDPhase := func(matches model.MediaFiles) { - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInAnd("media_file.id"))). - Return(matches, nil).Once() - } - expectMBIDPhase := func(matches model.MediaFiles) { - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInAnd("mbz_recording_id"))). - Return(matches, nil).Once() - } - expectISRCPhase := func(matches model.MediaFiles) { - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInEq("missing"))). - Return(matches, nil).Once() - } - - // allowIdentifierPhases installs .Maybe() catch-alls for the ID/MBID/ISRC phases so - // tests that only care about the title phase don't fail on those unexpected calls. - allowIdentifierPhases := func() { - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInAnd("media_file.id"))). - Return(model.MediaFiles{}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInAnd("mbz_recording_id"))). - Return(model.MediaFiles{}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInEq("missing"))). - Return(model.MediaFiles{}, nil).Maybe() - } - - // allowOtherPhases installs .Maybe() catch-alls so phases that short-circuit (return - // early without hitting the DB) don't cause test failures for unexpected calls. Call - // this after expect*Phase for the phases the test actually wants to verify. - allowOtherPhases := func() { - allowIdentifierPhases() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(model.MediaFiles{}, nil).Maybe() - } - - // allowTitlePhase wires title matching from a list of library tracks. Each track must carry - // Participants[RoleArtist] with the artist IDs that credit it; the helper derives the artist - // rows the artist resolution returns from those participants, then returns the tracks from - // the track-fetch query. - allowTitlePhase := func(tracks model.MediaFiles) { - // Artist resolution: build artist rows from the tracks' participants. - seen := map[string]model.Artist{} - for _, t := range tracks { - for _, p := range t.Participants[model.RoleArtist] { - if _, ok := seen[p.ID]; !ok { - seen[p.ID] = p.Artist - } - } - } - artists := make(model.Artists, 0, len(seen)) - for _, a := range seen { - artists = append(artists, a) - } - artistRepo.On("GetAll", mock.Anything).Return(artists, nil).Maybe() - // Track fetch (media_file_artists subquery). - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(tracks, nil).Maybe() - } - Describe("MatchSongs", func() { Context("matching by direct ID", func() { It("matches songs with an ID field to MediaFiles by ID", func() { @@ -110,8 +42,7 @@ var _ = Describe("Matcher", func() { idMatch := model.MediaFile{ ID: "track-1", Title: "Some Song", Artist: "Some Artist", } - expectIDPhase(model.MediaFiles{idMatch}) - allowOtherPhases() + putTracks(ctx, ds, model.MediaFiles{idMatch}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -129,8 +60,7 @@ var _ = Describe("Matcher", func() { ID: "track-mbid", Title: "Paranoid Android", Artist: "Radiohead", MbzRecordingID: "abc-123", } - expectMBIDPhase(model.MediaFiles{mbidMatch}) - allowOtherPhases() + putTracks(ctx, ds, model.MediaFiles{mbidMatch}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -148,8 +78,7 @@ var _ = Describe("Matcher", func() { ID: "track-isrc", Title: "Paranoid Android", Artist: "Radiohead", Tags: model.Tags{model.TagISRC: []string{"GBAYE0000351"}}, } - expectISRCPhase(model.MediaFiles{isrcMatch}) - allowOtherPhases() + putTracks(ctx, ds, model.MediaFiles{isrcMatch}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -167,7 +96,7 @@ var _ = Describe("Matcher", func() { ID: "track-title", Title: "Enjoy the Silence", Artist: "Depeche Mode", Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), } - allowTitlePhase(model.MediaFiles{titleMatch}) + putTracks(ctx, ds, model.MediaFiles{titleMatch}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -183,7 +112,7 @@ var _ = Describe("Matcher", func() { ID: "track-fuzzy", Title: "Bohemian Rhapsody (Live)", Artist: "Queen", Participants: artistParticipants(model.Artist{ID: "queen", Name: "Queen", OrderArtistName: "queen"}), } - allowTitlePhase(model.MediaFiles{fuzzyMatch}) + putTracks(ctx, ds, model.MediaFiles{fuzzyMatch}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -200,7 +129,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "beatles", Name: "The Beatles", OrderArtistName: "beatles"}), }, } - allowTitlePhase(differentTracks) + putTracks(ctx, ds, differentTracks) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(BeEmpty()) @@ -218,7 +147,7 @@ var _ = Describe("Matcher", func() { ID: "br-live", Title: "Bohemian Rhapsody (Live)", Artist: "Queen", Participants: artistParticipants(model.Artist{ID: "queen", Name: "Queen", OrderArtistName: "queen"}), } - allowTitlePhase(model.MediaFiles{libraryTrack}) + putTracks(ctx, ds, model.MediaFiles{libraryTrack}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -235,7 +164,7 @@ var _ = Describe("Matcher", func() { ID: "br", Title: "Bohemian Rhapsody", Artist: "Queen", Album: "A Night at the Opera", Participants: artistParticipants(model.Artist{ID: "queen", Name: "Queen", OrderArtistName: "queen"}), } - allowTitlePhase(model.MediaFiles{libraryTrack}) + putTracks(ctx, ds, model.MediaFiles{libraryTrack}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(2)) @@ -247,17 +176,13 @@ var _ = Describe("Matcher", func() { Context("priority ordering", func() { It("prefers ID match over MBID match", func() { conf.Update(func(c *conf.Options) { c.Matcher.FuzzyThreshold = 100 }) - // Song has both ID and MBID set. The matcher should resolve via ID - // and short-circuit the MBID phase entirely, so no MBID fetch should - // occur even though an mbz_recording_id exists in the input. songs := []agents.Song{ {ID: "track-id", Name: "Song", MBID: "mbid-1", Artists: []agents.Artist{{Name: "Artist"}}}, } - idMatch := model.MediaFile{ - ID: "track-id", Title: "Song", Artist: "Artist", - } - expectIDPhase(model.MediaFiles{idMatch}) - allowOtherPhases() + putTracks(ctx, ds, model.MediaFiles{ + {ID: "track-mbid", Title: "Song", Artist: "Artist", MbzRecordingID: "mbid-1"}, + {ID: "track-id", Title: "Song", Artist: "Artist"}, + }) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -284,7 +209,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "art", Name: "Artist", OrderArtistName: "artist"}), }, } - allowTitlePhase(tracks) + putTracks(ctx, ds, tracks) result, err := m.MatchSongs(ctx, songs, 2) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(2)) @@ -314,7 +239,7 @@ var _ = Describe("Matcher", func() { model.Artist{ID: "ph", Name: "Pharrell", OrderArtistName: "pharrell"}, ), } - allowTitlePhase(model.MediaFiles{track}) + putTracks(ctx, ds, model.MediaFiles{track}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -335,7 +260,7 @@ var _ = Describe("Matcher", func() { model.Artist{ID: "a-inxs", Name: "INXS", OrderArtistName: "inxs"}, ), } - allowTitlePhase(model.MediaFiles{track}) + putTracks(ctx, ds, model.MediaFiles{track}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -346,6 +271,7 @@ var _ = Describe("Matcher", func() { It("does not match a track where the searched artist is only the album artist", func() { songs := []agents.Song{ {Name: "Qmart", Artists: []agents.Artist{{Name: "808 State"}}}, + {Name: "Hyperballad", Artists: []agents.Artist{{Name: "Björk"}}}, } // Track performed by Björk on an "808 State" compilation: 808 State is the // albumartist, Björk is the performer. Searching 808 State must NOT match it. @@ -360,15 +286,8 @@ var _ = Describe("Matcher", func() { }, }, } - // Artist resolution returns "808 state" only if some artist row matches; here the - // album-artist participant exists but is NOT role='artist', so the track-fetch query's - // EXISTS (role='artist') would not return the track in production. The mock - // returns it anyway; back-mapping must drop it because no role='artist' - // participant is a resolved artist for the query "808 state". - artistRepo.On("GetAll", mock.Anything). - Return(model.Artists{{ID: "a-808", Name: "808 State", OrderArtistName: "808 state"}}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(model.MediaFiles{track}, nil).Maybe() + // The Björk query fetches the track, so only the back-mapping keeps it away from 808 State. + putTracks(ctx, ds, model.MediaFiles{track}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -383,13 +302,7 @@ var _ = Describe("Matcher", func() { ID: "by-mbid", Title: "Song A", Artist: "Correct Artist", Participants: artistParticipants(model.Artist{ID: "a9", Name: "Correct Artist", OrderArtistName: "correct artist", MbzArtistID: "mbid-9"}), } - // Artist resolution returns the artist matched by mbz_artist_id; its order name - // ("correct artist") differs from the query name ("typo artist"), so - // resolution must come from the MBID branch. - artistRepo.On("GetAll", mock.Anything). - Return(model.Artists{{ID: "a9", Name: "Correct Artist", OrderArtistName: "correct artist", MbzArtistID: "mbid-9"}}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(model.MediaFiles{track}, nil).Maybe() + putTracks(ctx, ds, model.MediaFiles{track}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -407,10 +320,7 @@ var _ = Describe("Matcher", func() { artist := model.Artist{ID: "a-shared", Name: "Canonical", OrderArtistName: "canonical", MbzArtistID: "mbid-shared"} trackA := model.MediaFile{ID: "ta", Title: "Song A", Artist: "Canonical", Participants: artistParticipants(artist)} trackB := model.MediaFile{ID: "tb", Title: "Song B", Artist: "Canonical", Participants: artistParticipants(artist)} - artistRepo.On("GetAll", mock.Anything). - Return(model.Artists{{ID: "a-shared", Name: "Canonical", OrderArtistName: "canonical", MbzArtistID: "mbid-shared"}}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(model.MediaFiles{trackA, trackB}, nil).Maybe() + putTracks(ctx, ds, model.MediaFiles{trackA, trackB}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -419,26 +329,26 @@ var _ = Describe("Matcher", func() { }) }) - // These tests register their own track-fetch expectations per-test (to inject - // an error), so they use allowIdentifierPhases — NOT allowOtherPhases, which would - // add a .Maybe() title-phase catch-all that masks the injected error. Context("title phase DB errors", func() { + BeforeEach(func() { + ds = persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return failingTitleFetchRepo{r} + }}) + m = matcher.New(ds) + }) + It("returns an error when the title query fails and nothing else matched", func() { songs := []agents.Song{ {Name: "Song A", Artists: []agents.Artist{{Name: "Artist One"}}}, {Name: "Song B", Artists: []agents.Artist{{Name: "Artist Two"}}}, } - allowIdentifierPhases() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{ - {ID: "a1", Name: "Artist One", OrderArtistName: "artist one"}, - {ID: "a2", Name: "Artist Two", OrderArtistName: "artist two"}, - }, nil) - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(nil, errors.New("db down")) + putTracks(ctx, ds, model.MediaFiles{ + {ID: "a", Title: "Song A", Participants: artistParticipants(model.Artist{ID: "a1", Name: "Artist One", OrderArtistName: "artist one"})}, + {ID: "b", Title: "Song B", Participants: artistParticipants(model.Artist{ID: "a2", Name: "Artist Two", OrderArtistName: "artist two"})}, + }) _, err := m.MatchSongs(ctx, songs, 5) - Expect(err).To(HaveOccurred()) - Expect(err.Error()).To(ContainSubstring("db down")) + Expect(err).To(MatchError(errTitleFetch)) }) It("keeps exact-phase matches when the title query fails", func() { @@ -446,17 +356,10 @@ var _ = Describe("Matcher", func() { {ID: "track-1", Name: "Exact Song", Artists: []agents.Artist{{Name: "Exact Artist"}}}, {Name: "Fuzzy Song", Artists: []agents.Artist{{Name: "Fuzzy Artist"}}}, } - idMatch := model.MediaFile{ID: "track-1", Title: "Exact Song", Artist: "Exact Artist"} - expectIDPhase(model.MediaFiles{idMatch}) - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInAnd("mbz_recording_id"))). - Return(model.MediaFiles{}, nil).Maybe() - mediaFileRepo.On("GetAll", mock.MatchedBy(matchFieldInEq("missing"))). - Return(model.MediaFiles{}, nil).Maybe() - artistRepo.On("GetAll", mock.Anything).Return(model.Artists{ - {ID: "fa", Name: "Fuzzy Artist", OrderArtistName: "fuzzy artist"}, - }, nil) - mediaFileRepo.On("GetAll", mock.MatchedBy(matchTracksByArtistQuery())). - Return(nil, errors.New("db down")) + putTracks(ctx, ds, model.MediaFiles{ + {ID: "track-1", Title: "Exact Song", Artist: "Exact Artist"}, + {ID: "fuzzy", Title: "Fuzzy Song", Participants: artistParticipants(model.Artist{ID: "fa", Name: "Fuzzy Artist", OrderArtistName: "fuzzy artist"})}, + }) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -487,7 +390,7 @@ var _ = Describe("Matcher", func() { model.Artist{ID: "drake", Name: "Drake", OrderArtistName: "drake"}, ), } - allowTitlePhase(model.MediaFiles{oneArtist, bothArtists}) + putTracks(ctx, ds, model.MediaFiles{oneArtist, bothArtists}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -507,7 +410,7 @@ var _ = Describe("Matcher", func() { model.Artist{ID: "drake", Name: "Drake", OrderArtistName: "drake"}, ), } - allowTitlePhase(model.MediaFiles{track}) + putTracks(ctx, ds, model.MediaFiles{track}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -526,7 +429,7 @@ var _ = Describe("Matcher", func() { model.Artist{ID: "ar-x", Name: "Some Artist", OrderArtistName: "some artist"}, ), } - allowTitlePhase(model.MediaFiles{track}) + putTracks(ctx, ds, model.MediaFiles{track}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -556,7 +459,7 @@ var _ = Describe("Matcher", func() { model.Artist{ID: "id-future", Name: "Future", OrderArtistName: "future"}, ), } - allowTitlePhase(model.MediaFiles{starredOne, shareTwo}) + putTracks(ctx, ds, model.MediaFiles{starredOne, shareTwo}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -575,8 +478,7 @@ var _ = Describe("Matcher", func() { mf1 := model.MediaFile{ID: "track-1", Title: "Song One", Artist: "Artist A"} mf2 := model.MediaFile{ID: "track-2", Title: "Song Two", Artist: "Artist B"} - expectIDPhase(model.MediaFiles{mf1, mf2}) - allowOtherPhases() + putTracks(ctx, ds, model.MediaFiles{mf1, mf2}) result, err := m.MatchSongsIndexed(ctx, songs) Expect(err).ToNot(HaveOccurred()) @@ -594,8 +496,7 @@ var _ = Describe("Matcher", func() { } mf1 := model.MediaFile{ID: "track-1", Title: "Known Song", Artist: "Known Artist"} - expectIDPhase(model.MediaFiles{mf1}) - allowOtherPhases() + putTracks(ctx, ds, model.MediaFiles{mf1}) result, err := m.MatchSongsIndexed(ctx, songs) Expect(err).ToNot(HaveOccurred()) @@ -632,7 +533,7 @@ var _ = Describe("Matcher", func() { {Name: "Similar Song", Artists: []agents.Artist{{Name: "Depeche Mode", MBID: "artist-mbid-123"}}, Album: "Violator", AlbumMBID: "album-mbid-456"}, } - allowTitlePhase(model.MediaFiles{wrongMatch, correctMatch}) + putTracks(ctx, ds, model.MediaFiles{wrongMatch, correctMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -654,7 +555,7 @@ var _ = Describe("Matcher", func() { {Name: "Similar Song", Artists: []agents.Artist{{Name: "Depeche Mode"}}, Album: "Violator"}, } - allowTitlePhase(model.MediaFiles{wrongMatch, correctMatch}) + putTracks(ctx, ds, model.MediaFiles{wrongMatch, correctMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -676,7 +577,7 @@ var _ = Describe("Matcher", func() { {Name: "Similar Song", Artists: []agents.Artist{{Name: "Depeche Mode"}}}, } - allowTitlePhase(model.MediaFiles{wrongMatch, correctMatch}) + putTracks(ctx, ds, model.MediaFiles{wrongMatch, correctMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -689,8 +590,9 @@ var _ = Describe("Matcher", func() { songs := []agents.Song{ {Name: "Similar Song"}, } - - allowTitlePhase(model.MediaFiles{}) + putTracks(ctx, ds, model.MediaFiles{{ID: "t", Title: "Similar Song", Artist: "Depeche Mode", + Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), + }}) result, err := m.MatchSongs(ctx, songs, 5) @@ -715,7 +617,7 @@ var _ = Describe("Matcher", func() { {Name: "Yesterday", Artists: []agents.Artist{{Name: "Frank Sinatra"}}, Album: "My Way"}, } - allowTitlePhase(model.MediaFiles{cover1, cover2, cover3}) + putTracks(ctx, ds, model.MediaFiles{cover1, cover2, cover3}) result, err := m.MatchSongs(ctx, songs, 5) @@ -746,7 +648,7 @@ var _ = Describe("Matcher", func() { {Name: "Song B", Artists: []agents.Artist{{Name: "Artist Two"}}}, } - allowTitlePhase(model.MediaFiles{lessAccurateMatch, preciseMatch, artistTwoMatch}) + putTracks(ctx, ds, model.MediaFiles{lessAccurateMatch, preciseMatch, artistTwoMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -773,7 +675,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "a1b", Name: "Artist One", OrderArtistName: "artist one", MbzArtistID: ""}), } // Artist resolution returns both a1 (by name+mbid) and a1b (by name). - allowTitlePhase(model.MediaFiles{other, precise}) + putTracks(ctx, ds, model.MediaFiles{other, precise}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) @@ -796,7 +698,7 @@ var _ = Describe("Matcher", func() { }, } - allowTitlePhase(artistTracks) + putTracks(ctx, ds, artistTracks) result, err := m.MatchSongs(ctx, songs, 5) @@ -817,7 +719,7 @@ var _ = Describe("Matcher", func() { }, } - allowTitlePhase(artistTracks) + putTracks(ctx, ds, artistTracks) result, err := m.MatchSongs(ctx, songs, 5) @@ -840,7 +742,7 @@ var _ = Describe("Matcher", func() { }, } - allowTitlePhase(artistTracks) + putTracks(ctx, ds, artistTracks) result, err := m.MatchSongs(ctx, songs, 5) @@ -862,7 +764,7 @@ var _ = Describe("Matcher", func() { }, } - allowTitlePhase(artistTracks) + putTracks(ctx, ds, artistTracks) result, err := m.MatchSongs(ctx, songs, 5) @@ -894,7 +796,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "queen", Name: "Queen", OrderArtistName: "queen"}), } - allowTitlePhase(model.MediaFiles{wrongMatch, correctMatch}) + putTracks(ctx, ds, model.MediaFiles{wrongMatch, correctMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -916,7 +818,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), } - allowTitlePhase(model.MediaFiles{wrongMatch, correctMatch}) + putTracks(ctx, ds, model.MediaFiles{wrongMatch, correctMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -938,7 +840,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), } - allowTitlePhase(model.MediaFiles{fuzzyMatch, exactMatch}) + putTracks(ctx, ds, model.MediaFiles{fuzzyMatch, exactMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -961,7 +863,7 @@ var _ = Describe("Matcher", func() { Starred: true, Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), } - allowTitlePhase(model.MediaFiles{albumMatch, starredTrack}) + putTracks(ctx, ds, model.MediaFiles{albumMatch, starredTrack}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -982,7 +884,7 @@ var _ = Describe("Matcher", func() { Rating: 4, Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), } - allowTitlePhase(model.MediaFiles{albumMatch, ratedTrack}) + putTracks(ctx, ds, model.MediaFiles{albumMatch, ratedTrack}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -1004,7 +906,7 @@ var _ = Describe("Matcher", func() { Starred: true, Participants: artistParticipants(model.Artist{ID: "dm", Name: "Depeche Mode", OrderArtistName: "depeche mode"}), } - allowTitlePhase(model.MediaFiles{plain, starred}) + putTracks(ctx, ds, model.MediaFiles{plain, starred}) result, err := m.MatchSongs(ctx, songs, 5) Expect(err).ToNot(HaveOccurred()) Expect(result).To(HaveLen(1)) @@ -1030,7 +932,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{wrongDuration, correctMatch}) + putTracks(ctx, ds, model.MediaFiles{wrongDuration, correctMatch}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1048,7 +950,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{closeDuration}) + putTracks(ctx, ds, model.MediaFiles{closeDuration}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1070,7 +972,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{farDuration, closeDuration}) + putTracks(ctx, ds, model.MediaFiles{farDuration, closeDuration}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1088,7 +990,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{differentDuration}) + putTracks(ctx, ds, model.MediaFiles{differentDuration}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1110,7 +1012,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{differentTitle, correctTitle}) + putTracks(ctx, ds, model.MediaFiles{differentTitle, correctTitle}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1128,7 +1030,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{anyTrack}) + putTracks(ctx, ds, model.MediaFiles{anyTrack}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1146,7 +1048,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "ta", Name: "Test Artist", OrderArtistName: "test artist"}), } - allowTitlePhase(model.MediaFiles{shortTrack}) + putTracks(ctx, ds, model.MediaFiles{shortTrack}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1169,7 +1071,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "sa", Name: "Same Artist", OrderArtistName: "same artist"}), } - allowTitlePhase(model.MediaFiles{shortTrack, longTrack}) + putTracks(ctx, ds, model.MediaFiles{shortTrack, longTrack}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1197,7 +1099,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "beatles", Name: "The Beatles", OrderArtistName: "beatles"}), } - allowTitlePhase(model.MediaFiles{libraryTrack}) + putTracks(ctx, ds, model.MediaFiles{libraryTrack}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1223,7 +1125,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "art", Name: "Artist", OrderArtistName: "artist"}), } - allowTitlePhase(model.MediaFiles{trackA, trackB, trackC}) + putTracks(ctx, ds, model.MediaFiles{trackA, trackB, trackC}) result, err := m.MatchSongs(ctx, songs, 5) @@ -1248,7 +1150,7 @@ var _ = Describe("Matcher", func() { Participants: artistParticipants(model.Artist{ID: "art", Name: "Artist", OrderArtistName: "artist"}), } - allowTitlePhase(model.MediaFiles{trackA, trackB}) + putTracks(ctx, ds, model.MediaFiles{trackA, trackB}) result, err := m.MatchSongs(ctx, songs, 2) @@ -1260,85 +1162,49 @@ var _ = Describe("Matcher", func() { }) }) -type mockMediaFileRepo struct { - mock.Mock - model.MediaFileRepository -} +var errTitleFetch = errors.New("db down") -func newMockMediaFileRepo() *mockMediaFileRepo { - return &mockMediaFileRepo{} -} +type failingTitleFetchRepo struct{ model.MediaFileRepository } -func (m *mockMediaFileRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { - argsSlice := make([]any, len(options)) - for i, v := range options { - argsSlice[i] = v +func (r failingTitleFetchRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { + if len(options) > 0 && isTitleFetch(options[0]) { + return nil, errTitleFetch } - args := m.Called(argsSlice...) - if args.Get(0) == nil { - return nil, args.Error(1) + return r.MediaFileRepository.GetAll(ctx, options...) +} + +// isTitleFetch reports whether opt is the title phase's track fetch, the only query that reads media_file_artists. +func isTitleFetch(opt model.QueryOptions) bool { + and, ok := opt.Filters.(squirrel.And) + if !ok { + return false } - return args.Get(0).(model.MediaFiles), args.Error(1) -} - -func (m *mockMediaFileRepo) GetAllByTags(ctx context.Context, _ model.TagName, _ []string, options ...model.QueryOptions) (model.MediaFiles, error) { - return m.GetAll(ctx, options...) -} - -func (m *mockMediaFileRepo) SetError(hasError bool) { - if hasError { - m.On("GetAll", mock.Anything).Return(nil, errors.New("mock repo error")) - } -} - -type mockArtistRepo struct { - mock.Mock - model.ArtistRepository -} - -func newMockArtistRepo() *mockArtistRepo { - return &mockArtistRepo{} -} - -func (m *mockArtistRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Artists, error) { - argsSlice := make([]any, len(options)) - for i, v := range options { - argsSlice[i] = v - } - args := m.Called(argsSlice...) - if args.Get(0) == nil { - return nil, args.Error(1) - } - return args.Get(0).(model.Artists), args.Error(1) -} - -// matchFieldInAnd returns a matcher that checks whether QueryOptions.Filters is a -// squirrel.And whose first element is a squirrel.Eq containing the given field name. -func matchFieldInAnd(fieldName string) func(opt model.QueryOptions) bool { - return func(opt model.QueryOptions) bool { - and, ok := opt.Filters.(squirrel.And) - if !ok || len(and) < 2 { - return false + for _, f := range and { + sql, _, err := f.ToSql() + if err == nil && strings.Contains(sql, "media_file_artists") { + return true } - eq, hasEq := and[0].(squirrel.Eq) - if !hasEq { - return false - } - _, hasField := eq[fieldName] - return hasField } + return false } -// matchFieldInEq returns a matcher that checks whether QueryOptions.Filters is a -// squirrel.Eq containing the given field name. -func matchFieldInEq(fieldName string) func(opt model.QueryOptions) bool { - return func(opt model.QueryOptions) bool { - eq, ok := opt.Filters.(squirrel.Eq) - if !ok { - return false +// putTracks stores the tracks in library 1 with the artists credited in their participants. +// Starred and Rating are saved as the logged user's annotations. +func putTracks(ctx context.Context, ds model.DataStore, tracks model.MediaFiles) { + GinkgoHelper() + for _, t := range tracks { + for _, list := range t.Participants { + for _, p := range list { + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, p.Artist) + } + } + persistencetest.PutMediaFiles(ctx, ds, t) + if t.Starred { + Expect(ds.MediaFile().SetStar(ctx, true, t.ID)).To(Succeed()) + } + if t.Rating > 0 { + Expect(ds.MediaFile().SetRating(ctx, t.Rating, t.ID)).To(Succeed()) } - _, hasField := eq[fieldName] - return hasField } } @@ -1350,21 +1216,3 @@ func artistParticipants(artists ...model.Artist) model.Participants { } return model.Participants{model.RoleArtist: list} } - -// matchTracksByArtistQuery matches the title phase's track-fetch query, identified by its -// squirrel.And containing a squirrel.Expr whose SQL references media_file_artists. -func matchTracksByArtistQuery() func(opt model.QueryOptions) bool { - return func(opt model.QueryOptions) bool { - and, ok := opt.Filters.(squirrel.And) - if !ok { - return false - } - for _, f := range and { - sql, _, err := f.ToSql() - if err == nil && strings.Contains(sql, "media_file_artists") { - return true - } - } - return false - } -} diff --git a/core/players_test.go b/core/players_test.go index 991312418..174c99710 100644 --- a/core/players_test.go +++ b/core/players_test.go @@ -4,26 +4,54 @@ import ( "context" "time" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Players", func() { var players Players - var repo *mockPlayerRepository + var ds model.DataStore var ctx context.Context var beforeRegister time.Time + var trcID string + + add := func(p *model.Player) { + GinkgoHelper() + Expect(ds.Player().Put(ctx, p)).To(Succeed()) + if p.HasAPIKey { + _, err := db.Db().Exec("UPDATE player SET api_key_hash = 'hash' WHERE id = ?", p.ID) + Expect(err).ToNot(HaveOccurred()) + } + } + + expectStored := func(p *model.Player) { + GinkgoHelper() + stored, err := ds.Player().Get(ctx, p.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(stored.UserId).To(Equal(p.UserId)) + Expect(stored.Client).To(Equal(p.Client)) + Expect(stored.Name).To(Equal(p.Name)) + Expect(stored.UserAgent).To(Equal(p.UserAgent)) + Expect(stored.IP).To(Equal(p.IP)) + Expect(stored.LastSeen).To(BeTemporally("~", p.LastSeen, time.Millisecond)) + } BeforeEach(func() { ctx = log.NewContext(GinkgoT().Context()) + ds = persistence.New(db.Db()) + for _, u := range []model.User{{ID: "userid", UserName: "johndoe"}, {ID: "otheruser", UserName: "other"}} { + Expect(ds.User().Put(ctx, &u)).To(Succeed()) + } ctx = request.WithUser(ctx, model.User{ID: "userid", UserName: "johndoe"}) ctx = request.WithUsername(ctx, "johndoe") - repo = &mockPlayerRepository{} - ds := &tests.MockDataStore{MockedPlayer: repo, MockedTranscoding: &tests.MockTranscodingRepo{}} + trc, err := ds.Transcoding().FindByFormat(ctx, "mp3") + Expect(err).ToNot(HaveOccurred()) + trcID = trc.ID players = NewPlayers(ds) beforeRegister = time.Now() }) @@ -37,7 +65,7 @@ var _ = Describe("Players", func() { Expect(p.Client).To(Equal("client")) Expect(p.UserId).To(Equal("userid")) Expect(p.UserAgent).To(Equal("chrome")) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) Expect(trc).To(BeNil()) }) @@ -46,13 +74,13 @@ var _ = Describe("Players", func() { Expect(err).ToNot(HaveOccurred()) Expect(p.ID).ToNot(BeEmpty()) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) Expect(trc).To(BeNil()) }) It("creates a new player if client does not match the one in DB", func() { - plr := &model.Player{ID: "123", Name: "A Player", Client: "client1111", LastSeen: time.Time{}} - repo.add(plr) + plr := &model.Player{ID: "123", Name: "A Player", Client: "client1111", UserId: "userid", LastSeen: time.Time{}} + add(plr) p, trc, err := players.Register(ctx, "123", "client2222", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).ToNot(BeEmpty()) @@ -63,61 +91,61 @@ var _ = Describe("Players", func() { }) It("does not reuse another user's player by ID", func() { - plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "otheruser", UserAgent: "Pixel", TranscodingId: "1"} - repo.add(plr) + plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "otheruser", UserAgent: "Pixel", TranscodingId: trcID} + add(plr) p, trc, err := players.Register(ctx, "123", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).ToNot(Equal("123")) Expect(p.UserId).To(Equal("userid")) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) Expect(trc).To(BeNil()) }) It("finds players by ID", func() { plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", LastSeen: time.Time{}} - repo.add(plr) + add(plr) p, trc, err := players.Register(ctx, "123", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) Expect(trc).To(BeNil()) }) It("finds player by client and user names when ID is not found", func() { plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", UserAgent: "chrome", LastSeen: time.Time{}} - repo.add(plr) + add(plr) p, _, err := players.Register(ctx, "999", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) }) It("finds player by client and user names when not ID is provided", func() { plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", UserAgent: "chrome", LastSeen: time.Time{}} - repo.add(plr) + add(plr) p, _, err := players.Register(ctx, "", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) }) It("finds player by ID and return its transcoding", func() { - plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", LastSeen: time.Time{}, TranscodingId: "1"} - repo.add(plr) + plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", LastSeen: time.Time{}, TranscodingId: trcID} + add(plr) p, trc, err := players.Register(ctx, "123", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) - Expect(trc.ID).To(Equal("1")) + expectStored(p) + Expect(trc.ID).To(Equal(trcID)) }) It("does not rename a player that has an API key", func() { plr := &model.Player{ID: "123", Name: "My Phone", Client: "client", UserId: "userid", HasAPIKey: true} - repo.add(plr) + add(plr) p, _, err := players.Register(ctx, "123", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) @@ -132,12 +160,12 @@ var _ = Describe("Players", func() { It("finds player by client and user names when not ID is provided", func() { plr := &model.Player{ID: "123", Name: "A Player", Client: "client", UserId: "userid", UserAgent: "chrome", LastSeen: time.Time{}} - repo.add(plr) + add(plr) p, _, err := players.Register(ctx, "", "client", "chrome", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) }) }) }) @@ -152,7 +180,7 @@ var _ = Describe("Players", func() { Expect(p.UserAgent).To(Equal("android")) Expect(p.IP).To(Equal("1.2.3.4")) Expect(p.LastSeen).To(BeTemporally(">=", beforeRegister)) - Expect(repo.lastSaved).To(Equal(p)) + expectStored(p) Expect(trc).To(BeNil()) }) @@ -163,44 +191,10 @@ var _ = Describe("Players", func() { }) It("returns the player's transcoding", func() { - p, trc, err := players.Touch(ctx, model.Player{ID: "123", UserId: "userid", TranscodingId: "1"}, "c", "ua", "1.2.3.4") + p, trc, err := players.Touch(ctx, model.Player{ID: "123", UserId: "userid", TranscodingId: trcID}, "c", "ua", "1.2.3.4") Expect(err).ToNot(HaveOccurred()) Expect(p.ID).To(Equal("123")) - Expect(trc.ID).To(Equal("1")) + Expect(trc.ID).To(Equal(trcID)) }) }) }) - -type mockPlayerRepository struct { - model.PlayerRepository - lastSaved *model.Player - data map[string]model.Player -} - -func (m *mockPlayerRepository) add(p *model.Player) { - if m.data == nil { - m.data = make(map[string]model.Player) - } - m.data[p.ID] = *p -} - -func (m *mockPlayerRepository) Get(_ context.Context, id string) (*model.Player, error) { - if p, ok := m.data[id]; ok { - return &p, nil - } - return nil, model.ErrNotFound -} - -func (m *mockPlayerRepository) FindMatch(_ context.Context, userId, client, userAgent string) (*model.Player, error) { - for _, p := range m.data { - if p.Client == client && p.UserId == userId && p.UserAgent == userAgent { - return &p, nil - } - } - return nil, model.ErrNotFound -} - -func (m *mockPlayerRepository) Put(_ context.Context, p *model.Player) error { - m.lastSaved = p - return nil -} diff --git a/core/playlists/import_test.go b/core/playlists/import_test.go index b4052ddde..e82a535a0 100644 --- a/core/playlists/import_test.go +++ b/core/playlists/import_test.go @@ -7,7 +7,6 @@ import ( "io" "os" "path/filepath" - "strconv" "strings" "testing/iotest" "time" @@ -15,10 +14,13 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/id" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -27,31 +29,37 @@ import ( ) var _ = Describe("Playlists - Import", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ps playlists.Playlists - var mockPlsRepo *tests.MockPlaylistRepo - var mockLibRepo *tests.MockLibraryRepo var ctx context.Context + useLibrary := func(dir string, tracks ...string) { + GinkgoHelper() + persistencetest.SetLibraries(ctx, ds, dir) + putTracks(ctx, ds, model.DefaultLibraryID, tracks...) + } + savedPlaylists := func() model.Playlists { + GinkgoHelper() + all, err := ds.Playlist().GetAll(asAdmin(ctx)) + Expect(err).ToNot(HaveOccurred()) + return all + } + BeforeEach(func() { ctx = GinkgoT().Context() - mockPlsRepo = tests.CreateMockPlaylistRepo() - mockLibRepo = &tests.MockLibraryRepo{} - ds = &tests.MockDataStore{ - MockedPlaylist: mockPlsRepo, - MockedLibrary: mockLibRepo, - } + ds = persistence.New(db.Db()) + putUsers(ctx, ds, "123") + ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) ctx = request.WithUser(ctx, model.User{ID: "123"}) }) Describe("ImportFromFolder", func() { var folder *model.Folder BeforeEach(func() { - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) - ds.MockedMediaFile = &mockedMediaFileRepo{} libPath, _ := os.Getwd() // Set up library with the actual library path that matches the folder - mockLibRepo.SetData([]model.Library{{ID: 1, Path: libPath}}) + useLibrary(libPath, "tests/fixtures/playlists/test.mp3", "tests/fixtures/playlists/test.ogg", + "tests/fixtures/playlists/abc.mp3", "tests/fixtures/playlists/def.mp3") folder = &model.Folder{ ID: "1", LibraryID: 1, @@ -69,7 +77,9 @@ var _ = Describe("Playlists - Import", func() { Expect(pls.Tracks).To(HaveLen(2)) Expect(pls.Tracks[0].Path).To(Equal("tests/fixtures/playlists/test.mp3")) Expect(pls.Tracks[1].Path).To(Equal("tests/fixtures/playlists/test.ogg")) - Expect(mockPlsRepo.Last).To(Equal(pls)) + stored := storedPlaylist(ctx, ds, pls.ID) + Expect(stored.OwnerID).To(Equal("123")) + Expect(trackIDs(stored)).To(Equal(trackIDs(pls))) }) It("parses playlists using LF ending", func() { @@ -120,9 +130,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3", "test.ogg"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3", "test.ogg") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -138,9 +146,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -157,9 +163,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -176,9 +180,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -194,9 +196,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -211,9 +211,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -228,9 +226,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -246,9 +242,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -264,9 +258,7 @@ var _ = Describe("Playlists - Import", func() { plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte(m3u), 0600)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -278,9 +270,7 @@ var _ = Describe("Playlists - Import", func() { conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") m3u := "#EXTALBUMARTURL:https://example.com/new-cover.jpg\ntest.mp3\n" plsFile := filepath.Join(tmpDir, "test.m3u") @@ -291,23 +281,25 @@ var _ = Describe("Playlists - Import", func() { Name: "Existing Playlist", Path: plsFile, Sync: true, + OwnerID: "123", UploadedImage: "existing-id.jpg", ExternalImageURL: "https://example.com/old-cover.jpg", } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") Expect(err).ToNot(HaveOccurred()) Expect(pls.UploadedImage).To(Equal("existing-id.jpg")) Expect(pls.ExternalImageURL).To(Equal("https://example.com/new-cover.jpg")) + stored := storedPlaylist(ctx, ds, "existing-id") + Expect(stored.UploadedImage).To(Equal("existing-id.jpg")) + Expect(stored.ExternalImageURL).To(Equal("https://example.com/new-cover.jpg")) }) It("skips non-synced playlist on re-import (respects user's choice)", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte("test.mp3\n"), 0600)).To(Succeed()) @@ -319,7 +311,7 @@ var _ = Describe("Playlists - Import", func() { Sync: false, OwnerID: "123", } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") @@ -327,13 +319,12 @@ var _ = Describe("Playlists - Import", func() { // updatePlaylist skips the non-synced playlist, so the returned // playlist has no ID (was never persisted/updated). Expect(pls.ID).To(BeEmpty()) + Expect(storedPlaylist(ctx, ds, "existing-id").Tracks).To(BeEmpty()) }) It("stores a content hash but re-imports unchanged M3U playlists", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir) plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte("test.mp3\n"), 0600)).To(Succeed()) @@ -342,25 +333,18 @@ var _ = Describe("Playlists - Import", func() { first, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") Expect(err).ToNot(HaveOccurred()) Expect(first.ImportedHash).ToNot(BeEmpty()) + Expect(storedPlaylist(ctx, ds, first.ID).ImportedHash).To(Equal(first.ImportedHash)) - // Re-import with a matching stored hash: M3U must still be re-imported, not skipped. - existingPls := &model.Playlist{ - ID: "m3u-id", Name: "Test", Path: plsFile, Sync: true, - OwnerID: "123", ImportedHash: first.ImportedHash, - } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} - mockPlsRepo.Last = nil - + // Re-import with a matching stored hash: M3U must still be re-imported, so a track added since resolves. + putTracks(ctx, ds, model.DefaultLibraryID, "test.mp3") _, err = ps.ImportFromFolder(ctx, plsFolder, "test.m3u") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).ToNot(BeNil()) + Expect(storedPlaylist(ctx, ds, first.ID).Tracks).To(HaveLen(1)) }) It("clears ExternalImageURL on re-scan when directive is removed", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3"}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir, "test.mp3") m3u := "test.mp3\n" plsFile := filepath.Join(tmpDir, "test.m3u") @@ -371,14 +355,16 @@ var _ = Describe("Playlists - Import", func() { Name: "Existing Playlist", Path: plsFile, Sync: true, + OwnerID: "123", ExternalImageURL: "https://example.com/old-cover.jpg", } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} pls, err := ps.ImportFromFolder(ctx, plsFolder, "test.m3u") Expect(err).ToNot(HaveOccurred()) Expect(pls.ExternalImageURL).To(BeEmpty()) + Expect(storedPlaylist(ctx, ds, "existing-id").ExternalImageURL).To(BeEmpty()) }) }) @@ -386,7 +372,9 @@ var _ = Describe("Playlists - Import", func() { It("parses well-formed playlists", func() { pls, err := ps.ImportFromFolder(ctx, folder, "recently_played.nsp") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).To(Equal(pls)) + stored := storedPlaylist(ctx, ds, pls.ID) + Expect(stored.Name).To(Equal(pls.Name)) + Expect(stored.Rules).To(Equal(pls.Rules)) Expect(pls.OwnerID).To(Equal("123")) Expect(pls.Name).To(Equal("Recently Played")) Expect(pls.Comment).To(Equal("Recently played tracks")) @@ -423,40 +411,39 @@ var _ = Describe("Playlists - Import", func() { It("preserves counters when re-importing an existing smart playlist", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir) nsp := `{"name":"My Smart","all":[{"is":{"loved":true}}],"sort":"title","order":"asc"}` plsFile := filepath.Join(tmpDir, "smart.nsp") Expect(os.WriteFile(plsFile, []byte(nsp), 0600)).To(Succeed()) existingPls := &model.Playlist{ - ID: "smart-id", - Name: "My Smart", - Path: plsFile, - Sync: true, - OwnerID: "123", - SongCount: 42, - Duration: 123.4, - Size: 5000, + ID: "smart-id", + Name: "My Smart", + Path: plsFile, + Sync: true, + OwnerID: "123", + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"loved": true}}}, } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) + // Put leaves a smart playlist's counters to its evaluation, so set them directly. + _, err := db.Db().Exec("UPDATE playlist SET song_count = 42, duration = 123.4, size = 5000 WHERE id = 'smart-id'") + Expect(err).ToNot(HaveOccurred()) plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} - _, err := ps.ImportFromFolder(ctx, plsFolder, "smart.nsp") + pls, err := ps.ImportFromFolder(ctx, plsFolder, "smart.nsp") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).ToNot(BeNil()) - Expect(mockPlsRepo.Last.IsSmartPlaylist()).To(BeTrue()) - Expect(mockPlsRepo.Last.SongCount).To(Equal(42)) - Expect(mockPlsRepo.Last.Duration).To(Equal(float32(123.4))) - Expect(mockPlsRepo.Last.Size).To(Equal(int64(5000))) + Expect(pls.IsSmartPlaylist()).To(BeTrue()) + Expect(pls.SongCount).To(Equal(42)) + Expect(pls.Duration).To(Equal(float32(123.4))) + Expect(pls.Size).To(Equal(int64(5000))) + Expect(storedPlaylist(ctx, ds, "smart-id").Rules.Sort).To(Equal("title")) }) It("skips re-import when the smart playlist file content is unchanged", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir) nsp := `{"name":"My Smart","all":[{"is":{"loved":true}}]}` plsFile := filepath.Join(tmpDir, "smart.nsp") @@ -467,19 +454,22 @@ var _ = Describe("Playlists - Import", func() { OwnerID: "123", SongCount: 42, ImportedHash: hashOf(nsp), } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) + originalTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + backdate("smart-id", originalTime) plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} _, err := ps.ImportFromFolder(ctx, plsFolder, "smart.nsp") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).To(BeNil()) // Put never called: nothing re-written + stored := storedPlaylist(ctx, ds, "smart-id") + Expect(stored.UpdatedAt).To(BeTemporally("==", originalTime)) + Expect(stored.IsSmartPlaylist()).To(BeFalse()) }) It("re-imports when the smart playlist file content changed", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir) nsp := `{"name":"My Smart","all":[{"is":{"loved":true}}]}` plsFile := filepath.Join(tmpDir, "smart.nsp") @@ -490,14 +480,13 @@ var _ = Describe("Playlists - Import", func() { OwnerID: "123", SongCount: 42, ImportedHash: hashOf("old content"), } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) plsFolder := &model.Folder{ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: ""} _, err := ps.ImportFromFolder(ctx, plsFolder, "smart.nsp") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).ToNot(BeNil()) // Put called: file changed - Expect(mockPlsRepo.Last.ImportedHash).To(Equal(hashOf(nsp))) + Expect(storedPlaylist(ctx, ds, "smart-id").ImportedHash).To(Equal(hashOf(nsp))) }) }) @@ -514,23 +503,22 @@ var _ = Describe("Playlists - Import", func() { filesystemName := nameByForm[filesystemForm] tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{}} - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(tmpDir) // Create the playlist file on disk with the filesystem's normalization form plsFile := tmpDir + "/" + filesystemName + ".m3u" Expect(os.WriteFile(plsFile, []byte("#PLAYLIST:Test\n"), 0600)).To(Succeed()) - // Pre-populate mock repo with the stored normalization form + // Pre-populate the DB with the stored normalization form storedPath := tmpDir + "/" + storedName + ".m3u" existingPls := &model.Playlist{ - ID: "existing-id", - Name: "Existing Playlist", - Path: storedPath, - Sync: true, + ID: "existing-id", + Name: "Existing Playlist", + Path: storedPath, + Sync: true, + OwnerID: "123", } - mockPlsRepo.PathMap = map[string]*model.Playlist{storedPath: existingPls} + putPlaylists(ctx, ds, existingPls) // Import using the filesystem's normalization form plsFolder := &model.Folder{ @@ -546,6 +534,7 @@ var _ = Describe("Playlists - Import", func() { // Should update existing playlist, not create new one Expect(pls.ID).To(Equal("existing-id")) Expect(pls.Name).To(Equal("Existing Playlist")) + Expect(savedPlaylists()).To(HaveLen(1)) }, Entry("finds NFD-stored playlist when filesystem provides NFC path", "NFD", "NFC"), Entry("finds NFC-stored playlist when filesystem provides NFD path", "NFC", "NFD"), @@ -563,20 +552,11 @@ var _ = Describe("Playlists - Import", func() { Expect(os.Mkdir(songsDir, 0755)).To(Succeed()) // Setup two different libraries with paths matching our temp structure - mockLibRepo.SetData([]model.Library{ - {ID: 1, Path: songsDir}, - {ID: 2, Path: plsDir}, - }) + persistencetest.SetLibraries(ctx, ds, songsDir, plsDir) - // Create a mock media file repository that returns files for both libraries // Note: The paths are relative to their respective library roots - ds.MockedMediaFile = &mockedMediaFileFromListRepo{ - data: []string{ - "abc.mp3", // This is songs/abc.mp3 relative to songsDir - "def.mp3", // This is playlists/def.mp3 relative to plsDir - }, - } - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putTracks(ctx, ds, 1, "abc.mp3") // This is songs/abc.mp3 relative to songsDir + putTracks(ctx, ds, 2, "def.mp3") // This is playlists/def.mp3 relative to plsDir }) It("handles relative paths that reference files in other libraries", func() { @@ -604,7 +584,7 @@ var _ = Describe("Playlists - Import", func() { It("ignores paths that point outside all libraries", func() { // Create a temporary playlist file with path outside libraries - plsContent := "#PLAYLIST:Outside Test\n../../outside.mp3\nabc.mp3" + plsContent := "#PLAYLIST:Outside Test\n../../outside.mp3\n../songs/abc.mp3" plsFile := plsDir + "/test.m3u" Expect(os.WriteFile(plsFile, []byte(plsContent), 0600)).To(Succeed()) @@ -628,15 +608,6 @@ var _ = Describe("Playlists - Import", func() { subFolder := plsDir + "/subfolder" Expect(os.Mkdir(subFolder, 0755)).To(Succeed()) - // Create the media file in the subfolder directory - // The mock will return it as "def.mp3" relative to plsDir - ds.MockedMediaFile = &mockedMediaFileFromListRepo{ - data: []string{ - "abc.mp3", // From songsDir library - "def.mp3", // From plsDir library root - }, - } - // From subfolder, ../../songs/abc.mp3 should resolve to songs library // ../def.mp3 should resolve to plsDir/def.mp3 plsContent := "#PLAYLIST:Nested Test\n../../songs/abc.mp3\n../def.mp3" @@ -670,18 +641,9 @@ var _ = Describe("Playlists - Import", func() { Expect(os.Mkdir(musicClassicalDir, 0755)).To(Succeed()) // Setup two libraries where one is a prefix of the other - mockLibRepo.SetData([]model.Library{ - {ID: 1, Path: musicDir}, // /tmp/xxx/music - {ID: 2, Path: musicClassicalDir}, // /tmp/xxx/music-classical - }) - - // Mock will return tracks from both libraries - ds.MockedMediaFile = &mockedMediaFileFromListRepo{ - data: []string{ - "rock.mp3", // From music library - "bach.mp3", // From music-classical library - }, - } + persistencetest.SetLibraries(ctx, ds, musicDir, musicClassicalDir) + putTracks(ctx, ds, 1, "rock.mp3") + putTracks(ctx, ds, 2, "bach.mp3") // Create playlist in music library that references music-classical plsContent := "#PLAYLIST:Cross Prefix Test\nrock.mp3\n../music-classical/bach.mp3" @@ -718,21 +680,9 @@ var _ = Describe("Playlists - Import", func() { Expect(os.WriteFile(classicalDir+"/album/track.mp3", []byte{}, 0600)).To(Succeed()) // Both libraries have a file at "album/track.mp3" - mockLibRepo.SetData([]model.Library{ - {ID: 1, Path: musicDir}, - {ID: 2, Path: classicalDir}, - }) - - // Mock returns files with same relative path but different IDs and library IDs - // Keys use the library-qualified format: "libraryID:path" - ds.MockedMediaFile = &mockedMediaFileRepo{ - data: map[string]model.MediaFile{ - "1:album/track.mp3": {ID: "music-track", Path: "album/track.mp3", LibraryID: 1, Title: "Rock Song"}, - "2:album/track.mp3": {ID: "classical-track", Path: "album/track.mp3", LibraryID: 2, Title: "Classical Piece"}, - }, - } - // Recreate playlists service to pick up new mock - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + persistencetest.SetLibraries(ctx, ds, musicDir, classicalDir) + putTracks(ctx, ds, 1, "album/track.mp3") + putTracks(ctx, ds, 2, "album/track.mp3") // Create playlist in music library that references both tracks plsContent := "#PLAYLIST:Same Path Test\nalbum/track.mp3\n../classical/album/track.mp3" @@ -771,25 +721,15 @@ var _ = Describe("Playlists - Import", func() { }) Describe("ImportFile", func() { - BeforeEach(func() { - ds.MockedMediaFile = &mockedMediaFileFromListRepo{data: []string{"test.mp3", "test.ogg"}} - }) + useLibraryWithRoot := func(dir string) { + GinkgoHelper() + useLibrary(dir, "test.mp3", "test.ogg") + putLibraryRoot(ctx, ds, model.DefaultLibraryID) + } It("resolves file inside a library and imports it", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - - mockFolderRepo := &mockFolderRepoForImport{ - folder: &model.Folder{ - ID: "1", - LibraryID: 1, - LibraryPath: tmpDir, - Path: "", - Name: "", - }, - } - ds.MockedFolder = mockFolderRepo - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibraryWithRoot(tmpDir) plsContent := "#PLAYLIST:My Playlist\ntest.mp3\ntest.ogg\n" plsFile := filepath.Join(tmpDir, "my-playlist.m3u") @@ -807,8 +747,7 @@ var _ = Describe("Playlists - Import", func() { tmpDir := GinkgoT().TempDir() libDir := filepath.Join(tmpDir, "music") Expect(os.Mkdir(libDir, 0755)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: libDir}}) - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibrary(libDir, "test.mp3", "test.ogg") plsContent := "#PLAYLIST:External Playlist\n" + libDir + "/test.mp3\n" plsFile := filepath.Join(tmpDir, "external.m3u") @@ -823,15 +762,7 @@ var _ = Describe("Playlists - Import", func() { It("imports with Sync=false", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - - mockFolderRepo := &mockFolderRepoForImport{ - folder: &model.Folder{ - ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: "", - }, - } - ds.MockedFolder = mockFolderRepo - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibraryWithRoot(tmpDir) plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte("test.mp3\n"), 0600)).To(Succeed()) @@ -843,15 +774,7 @@ var _ = Describe("Playlists - Import", func() { It("imports with Sync=true", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - - mockFolderRepo := &mockFolderRepoForImport{ - folder: &model.Folder{ - ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: "", - }, - } - ds.MockedFolder = mockFolderRepo - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibraryWithRoot(tmpDir) plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte("test.mp3\n"), 0600)).To(Succeed()) @@ -863,15 +786,7 @@ var _ = Describe("Playlists - Import", func() { It("upgrades non-synced playlist to synced on re-import with sync=true", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - - mockFolderRepo := &mockFolderRepoForImport{ - folder: &model.Folder{ - ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: "", - }, - } - ds.MockedFolder = mockFolderRepo - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibraryWithRoot(tmpDir) plsFile := filepath.Join(tmpDir, "test.m3u") Expect(os.WriteFile(plsFile, []byte("test.mp3\n"), 0600)).To(Succeed()) @@ -880,25 +795,18 @@ var _ = Describe("Playlists - Import", func() { ID: "existing-id", Name: "Existing", Path: plsFile, Sync: false, OwnerID: "123", } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) pls, err := ps.ImportFile(ctx, plsFile, true) Expect(err).ToNot(HaveOccurred()) Expect(pls.ID).To(Equal("existing-id")) Expect(pls.Sync).To(BeTrue()) + Expect(storedPlaylist(ctx, ds, "existing-id").Sync).To(BeTrue()) }) It("unsyncs a synced smart playlist with sync=false even when content is unchanged", func() { tmpDir := GinkgoT().TempDir() - mockLibRepo.SetData([]model.Library{{ID: 1, Path: tmpDir}}) - - mockFolderRepo := &mockFolderRepoForImport{ - folder: &model.Folder{ - ID: "1", LibraryID: 1, LibraryPath: tmpDir, Path: "", Name: "", - }, - } - ds.MockedFolder = mockFolderRepo - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + useLibraryWithRoot(tmpDir) nsp := `{"name":"My Smart","all":[{"is":{"loved":true}}]}` plsFile := filepath.Join(tmpDir, "smart.nsp") @@ -909,34 +817,24 @@ var _ = Describe("Playlists - Import", func() { OwnerID: "123", SongCount: 42, ImportedHash: hashOf(nsp), } - mockPlsRepo.PathMap = map[string]*model.Playlist{plsFile: existingPls} + putPlaylists(ctx, ds, existingPls) pls, err := ps.ImportFile(ctx, plsFile, false) Expect(err).ToNot(HaveOccurred()) Expect(pls.ID).To(Equal("smart-id")) Expect(pls.Sync).To(BeFalse()) - Expect(mockPlsRepo.Last).ToNot(BeNil()) - Expect(mockPlsRepo.Last.Sync).To(BeFalse()) + Expect(storedPlaylist(ctx, ds, "smart-id").Sync).To(BeFalse()) }) }) Describe("ImportM3U", func() { - var repo *mockedMediaFileFromListRepo BeforeEach(func() { - repo = &mockedMediaFileFromListRepo{} - ds.MockedMediaFile = repo - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: "/music"}, {ID: 2, Path: "/new"}}) - ctx = request.WithUser(ctx, model.User{ID: "123"}) + persistencetest.SetLibraries(ctx, ds, "/music", "/new") }) It("parses well-formed playlists", func() { - repo.data = []string{ - "tests/test.mp3", - "tests/test.ogg", - "tests/01 Invisible (RED) Edit Version.mp3", - "downloads/newfile.flac", - } + putTracks(ctx, ds, 1, "tests/test.mp3", "tests/test.ogg", "tests/01 Invisible (RED) Edit Version.mp3") + putTracks(ctx, ds, 2, "downloads/newfile.flac") m3u := strings.Join([]string{ "#PLAYLIST:playlist 1", "/music/tests/test.mp3", @@ -956,15 +854,17 @@ var _ = Describe("Playlists - Import", func() { Expect(pls.Tracks[1].Path).To(Equal("tests/test.ogg")) Expect(pls.Tracks[2].Path).To(Equal("downloads/newfile.flac")) Expect(pls.Tracks[3].Path).To(Equal("tests/01 Invisible (RED) Edit Version.mp3")) - Expect(mockPlsRepo.Last).To(Equal(pls)) + stored := storedPlaylist(ctx, ds, pls.ID) + Expect(stored.OwnerID).To(Equal("123")) + Expect(trackIDs(stored)).To(Equal(trackIDs(pls))) }) It("sets the playlist name as a timestamp if the #PLAYLIST directive is not present", func() { - repo.data = []string{ + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3", "tests/test.ogg", "/tests/01 Invisible (RED) Edit Version.mp3", - } + ) m3u := strings.Join([]string{ "/music/tests/test.mp3", "/music/tests/test.ogg", @@ -978,11 +878,11 @@ var _ = Describe("Playlists - Import", func() { }) It("returns only tracks that exist in the database and in the same order as the m3u", func() { - repo.data = []string{ + putTracks(ctx, ds, model.DefaultLibraryID, "album1/test1.mp3", "album2/test2.mp3", "album3/test3.mp3", - } + ) m3u := strings.Join([]string{ "/music/album3/test3.mp3", "/music/album1/test1.mp3", @@ -1003,7 +903,7 @@ var _ = Describe("Playlists - Import", func() { return strings.Repeat("/music/tests/test.mp3\n", n) } BeforeEach(func() { - repo.data = []string{"tests/test.mp3"} + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3") conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 3 }) }) @@ -1016,7 +916,7 @@ var _ = Describe("Playlists - Import", func() { It("rejects a playlist over the limit without saving it", func() { _, err := ps.ImportM3U(ctx, strings.NewReader(repeat(4))) Expect(err).To(MatchError(playlists.ErrTooManyEntries)) - Expect(mockPlsRepo.Last).To(BeNil()) + Expect(savedPlaylists()).To(BeEmpty()) }) It("imports any number of entries when the limit is 0", func() { @@ -1030,7 +930,7 @@ var _ = Describe("Playlists - Import", func() { tmpDir := GinkgoT().TempDir() libDir := filepath.Join(tmpDir, "music") Expect(os.Mkdir(libDir, 0755)).To(Succeed()) - mockLibRepo.SetData([]model.Library{{ID: 1, Path: libDir}}) + useLibrary(libDir) plsFile := filepath.Join(tmpDir, "big.m3u") content := strings.Repeat(libDir+"/tests/test.mp3\n", 4) Expect(os.WriteFile(plsFile, []byte(content), 0600)).To(Succeed()) @@ -1042,7 +942,7 @@ var _ = Describe("Playlists - Import", func() { }) It("makes a second upload wait for the running one, without reading its body", func() { - repo.data = []string{"tests/test.mp3"} + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3") pr, pw := io.Pipe() firstDone := make(chan error, 1) go func() { @@ -1064,19 +964,19 @@ var _ = Describe("Playlists - Import", func() { }) It("fails on a read error instead of saving a truncated playlist", func() { - repo.data = []string{"tests/test.mp3"} + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3") readErr := errors.New("body too large") body := io.MultiReader(strings.NewReader("/music/tests/test.mp3\n"), iotest.ErrReader(readErr)) _, err := ps.ImportM3U(ctx, body) Expect(err).To(MatchError(readErr)) - Expect(mockPlsRepo.Last).To(BeNil()) + Expect(savedPlaylists()).To(BeEmpty()) }) It("is case-insensitive when comparing paths", func() { - repo.data = []string{ + putTracks(ctx, ds, model.DefaultLibraryID, "abc/tEsT1.Mp3", - } + ) m3u := strings.Join([]string{ "/music/ABC/TeSt1.mP3", }, "\n") @@ -1090,7 +990,7 @@ var _ = Describe("Playlists - Import", func() { It("parses #EXTALBUMARTURL with HTTP URL via ImportM3U", func() { conf.Update(func(c *conf.Options) { c.EnableM3UExternalAlbumArt = true }) - repo.data = []string{"tests/test.mp3"} + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3") m3u := "#EXTALBUMARTURL:https://example.com/cover.jpg\n/music/tests/test.mp3\n" pls, err := ps.ImportM3U(ctx, strings.NewReader(m3u)) Expect(err).ToNot(HaveOccurred()) @@ -1098,7 +998,7 @@ var _ = Describe("Playlists - Import", func() { }) It("ignores relative #EXTALBUMARTURL when imported via API (no folder context)", func() { - repo.data = []string{"tests/test.mp3"} + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3") m3u := "#EXTALBUMARTURL:cover.jpg\n/music/tests/test.mp3\n" pls, err := ps.ImportM3U(ctx, strings.NewReader(m3u)) Expect(err).ToNot(HaveOccurred()) @@ -1108,7 +1008,7 @@ var _ = Describe("Playlists - Import", func() { DescribeTable("restricts a local #EXTALBUMARTURL to the owner's libraries", func(imageURL, expected string) { ctx = request.WithUser(ctx, model.User{ID: "123", Libraries: model.Libraries{{ID: 1, Path: "/music"}}}) - repo.data = []string{"tests/test.mp3"} + putTracks(ctx, ds, model.DefaultLibraryID, "tests/test.mp3") m3u := "#EXTALBUMARTURL:" + imageURL + "\n/music/tests/test.mp3\n" pls, err := ps.ImportM3U(ctx, strings.NewReader(m3u)) Expect(err).ToNot(HaveOccurred()) @@ -1122,9 +1022,9 @@ var _ = Describe("Playlists - Import", func() { // so we need exact matching for non-ASCII characters. It("matches fullwidth characters exactly (SQLite NOCASE limitation)", func() { // Fullwidth uppercase ACROSS (U+FF21, U+FF23, U+FF32, U+FF2F, U+FF33, U+FF33) - repo.data = []string{ + putTracks(ctx, ds, model.DefaultLibraryID, "plex/02 - ACROSS.flac", - } + ) m3u := "/music/plex/02 - ACROSS.flac\n" f := strings.NewReader(m3u) pls, err := ps.ImportM3U(ctx, f) @@ -1147,7 +1047,7 @@ var _ = Describe("Playlists - Import", func() { } else { dbPath = pathNFD } - repo.data = []string{dbPath} + putTracks(ctx, ds, model.DefaultLibraryID, dbPath) // Set up playlist with specified normalization form var playlistPath string @@ -1240,95 +1140,6 @@ var _ = Describe("Playlists - Import", func() { }) }) -// mockedMediaFileRepo's FindByPaths method returns MediaFiles for the given paths. -// If data map is provided, looks up files by key; otherwise creates them from paths. -type mockedMediaFileRepo struct { - model.MediaFileRepository - data map[string]model.MediaFile -} - -func (r *mockedMediaFileRepo) FindByPaths(ctx context.Context, paths []string) (model.MediaFiles, error) { - var mfs model.MediaFiles - - // If data map provided, look up files - if r.data != nil { - for _, path := range paths { - if mf, ok := r.data[path]; ok { - mfs = append(mfs, mf) - } - } - return mfs, nil - } - - // Otherwise, create MediaFiles from paths - for idx, path := range paths { - // Strip library qualifier if present (format: "libraryID:path") - actualPath := path - libraryID := 1 - if parts := strings.SplitN(path, ":", 2); len(parts) == 2 { - if id, err := strconv.Atoi(parts[0]); err == nil { - libraryID = id - actualPath = parts[1] - } - } - - mfs = append(mfs, model.MediaFile{ - ID: strconv.Itoa(idx), - Path: actualPath, - LibraryID: libraryID, - }) - } - return mfs, nil -} - -// mockedMediaFileFromListRepo's FindByPaths method returns a list of MediaFiles based on the data field -type mockedMediaFileFromListRepo struct { - model.MediaFileRepository - data []string -} - -func (r *mockedMediaFileFromListRepo) FindByPaths(ctx context.Context, paths []string) (model.MediaFiles, error) { - var mfs model.MediaFiles - - for idx, dataPath := range r.data { - for _, requestPath := range paths { - // Strip library qualifier if present (format: "libraryID:path") - actualPath := requestPath - libraryID := 1 - if parts := strings.SplitN(requestPath, ":", 2); len(parts) == 2 { - if id, err := strconv.Atoi(parts[0]); err == nil { - libraryID = id - actualPath = parts[1] - } - } - - // Case-insensitive comparison (like SQL's "collate nocase"), but with no - // implicit Unicode normalization (SQLite does not normalize NFC/NFD). - if strings.EqualFold(actualPath, dataPath) { - mfs = append(mfs, model.MediaFile{ - ID: strconv.Itoa(idx), - Path: dataPath, // Return original path from DB - LibraryID: libraryID, - }) - break - } - } - } - return mfs, nil -} - -type mockFolderRepoForImport struct { - model.FolderRepository - folder *model.Folder -} - -func (m *mockFolderRepoForImport) GetByPath(_ context.Context, _ model.Library, _ string) (*model.Folder, error) { - if m.folder != nil { - return m.folder, nil - } - return nil, model.ErrNotFound -} - func hashOf(content string) string { return id.Encode(xxh3.Hash128([]byte(content)).Bytes()) } diff --git a/core/playlists/parse_m3u_test.go b/core/playlists/parse_m3u_test.go index c4b366511..099706f5c 100644 --- a/core/playlists/parse_m3u_test.go +++ b/core/playlists/parse_m3u_test.go @@ -3,32 +3,25 @@ package playlists import ( "context" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("pathResolver", func() { - var ds *tests.MockDataStore - var mockLibRepo *tests.MockLibraryRepo var resolver *pathResolver var ctx context.Context BeforeEach(func() { ctx = GinkgoT().Context() tests.SkipOnWindows("path separator bug (#TBD-path-sep-playlists)") - mockLibRepo = &tests.MockLibraryRepo{} - ds = &tests.MockDataStore{ - MockedLibrary: mockLibRepo, - } + ds := persistence.New(db.Db()) - // Setup test libraries - mockLibRepo.SetData([]model.Library{ - {ID: 1, Path: "/music"}, - {ID: 2, Path: "/music-classical"}, - {ID: 3, Path: "/podcasts"}, - }) + persistencetest.SetLibraries(ctx, ds, "/music", "/music-classical", "/podcasts") var err error resolver, err = newPathResolver(ctx, ds) diff --git a/core/playlists/playlists_suite_test.go b/core/playlists/playlists_suite_test.go index cc057780d..0679e85cd 100644 --- a/core/playlists/playlists_suite_test.go +++ b/core/playlists/playlists_suite_test.go @@ -1,10 +1,16 @@ package playlists_test import ( + "context" "testing" + "time" "github.com/navidrome/navidrome/conf/configtest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +19,75 @@ import ( func TestPlaylists(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Playlists Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() + +var adminUser = model.User{ID: "admin-1", UserName: "admin-1", IsAdmin: true} + +func asAdmin(ctx context.Context) context.Context { + return request.WithUser(ctx, adminUser) +} + +// putUsers creates regular users named after their IDs, plus adminUser. +func putUsers(ctx context.Context, ds model.DataStore, ids ...string) { + GinkgoHelper() + admin := adminUser + Expect(ds.User().Put(ctx, &admin)).To(Succeed()) + for _, id := range ids { + Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: id})).To(Succeed()) + } +} + +// putTracks stores one media file per path in the library and returns their IDs, in order. +func putTracks(ctx context.Context, ds model.DataStore, libID int, paths ...string) []string { + GinkgoHelper() + ids := make([]string, 0, len(paths)) + for _, path := range paths { + mf := &model.MediaFile{LibraryID: libID, Path: path, Title: path} + Expect(ds.MediaFile().Put(ctx, mf)).To(Succeed()) + ids = append(ids, mf.ID) + } + return ids +} + +// putLibraryRoot stores the root folder of the library, as the scanner would. +func putLibraryRoot(ctx context.Context, ds model.DataStore, libID int) { + GinkgoHelper() + lib, err := ds.Library().Get(ctx, libID) + Expect(err).ToNot(HaveOccurred()) + Expect(ds.Folder().Put(ctx, model.NewFolder(*lib, "."))).To(Succeed()) +} + +func putPlaylists(ctx context.Context, ds model.DataStore, playlists ...*model.Playlist) { + GinkgoHelper() + for _, pls := range playlists { + Expect(ds.Playlist().Put(ctx, pls)).To(Succeed()) + } +} + +func storedPlaylist(ctx context.Context, ds model.DataStore, id string) *model.Playlist { + GinkgoHelper() + pls, err := ds.Playlist().GetWithTracks(asAdmin(ctx), id, false, false) + Expect(err).ToNot(HaveOccurred()) + return pls +} + +func trackIDs(pls *model.Playlist) []string { + ids := make([]string, len(pls.Tracks)) + for i, t := range pls.Tracks { + ids[i] = t.MediaFileID + } + return ids +} + +// backdate sets a playlist's updated_at, which every Put overwrites, so a spec can tell whether it was written again. +func backdate(id string, t time.Time) { + GinkgoHelper() + _, err := db.Db().Exec("UPDATE playlist SET updated_at = ? WHERE id = ?", t, id) + Expect(err).ToNot(HaveOccurred()) +} diff --git a/core/playlists/playlists_test.go b/core/playlists/playlists_test.go index a9097e592..74c4911a0 100644 --- a/core/playlists/playlists_test.go +++ b/core/playlists/playlists_test.go @@ -10,61 +10,67 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Playlists", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ps playlists.Playlists - var mockPlsRepo *tests.MockPlaylistRepo var ctx context.Context + var songs []string + + smartRules := func() *criteria.Criteria { + return &criteria.Criteria{Expression: criteria.Contains{"title": "test"}} + } + storedTracks := func(id string) []string { + return trackIDs(storedPlaylist(ctx, ds, id)) + } BeforeEach(func() { ctx = GinkgoT().Context() - mockPlsRepo = tests.CreateMockPlaylistRepo() - ds = &tests.MockDataStore{ - MockedPlaylist: mockPlsRepo, - MockedLibrary: &tests.MockLibraryRepo{}, - } + ds = persistence.New(db.Db()) + putUsers(ctx, ds, "123", "user-1", "other-user") + songs = putTracks(ctx, ds, model.DefaultLibraryID, "a/1.mp3", "a/2.mp3", "a/3.mp3", "a/4.mp3", "a/5.mp3") + ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) ctx = request.WithUser(ctx, model.User{ID: "123"}) }) Describe("Delete", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 3} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}) }) + isStored := func(id string) bool { + exists, err := ds.Playlist().Exists(asAdmin(ctx), id) + Expect(err).ToNot(HaveOccurred()) + return exists + } + It("allows owner to delete their playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) err := ps.Delete(ctx, "pls-1") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Deleted).To(ContainElement("pls-1")) + Expect(isStored("pls-1")).To(BeFalse()) }) It("allows admin to delete any playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true}) err := ps.Delete(ctx, "pls-1") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Deleted).To(ContainElement("pls-1")) + Expect(isStored("pls-1")).To(BeFalse()) }) It("denies non-owner, non-admin from deleting", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) err := ps.Delete(ctx, "pls-1") Expect(err).To(MatchError(model.ErrNotAuthorized)) - Expect(mockPlsRepo.Deleted).To(BeEmpty()) + Expect(isStored("pls-1")).To(BeTrue()) }) It("returns error when playlist not found", func() { @@ -75,127 +81,130 @@ var _ = Describe("Playlists", func() { }) Describe("Tracks", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}) + putPlaylists(ctx, ds, &model.Playlist{ID: "pls-123", Name: "Mine", OwnerID: "123"}) + _, err := ds.Playlist().Tracks(ctx, "pls-123", false).Add(ctx, songs[:2]) + Expect(err).ToNot(HaveOccurred()) }) It("returns the playlist's track repository", func() { - Expect(ps.Tracks(ctx, "pls-1")).To(BeIdenticalTo(mockTracks)) + tracks, err := ps.Tracks(ctx, "pls-123") + Expect(err).ToNot(HaveOccurred()) + Expect(tracks.GetMediaFileIDs(ctx)).To(Equal(songs[:2])) }) It("returns ErrNotFound for an unknown or invisible playlist", func() { _, err := ps.Tracks(ctx, "nonexistent") Expect(err).To(MatchError(model.ErrNotFound)) + _, err = ps.Tracks(ctx, "pls-1") + Expect(err).To(MatchError(model.ErrNotFound)) }) }) Describe("Create", func() { BeforeEach(func() { - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "Existing", OwnerID: "user-1"}, - "pls-2": {ID: "pls-2", Name: "Other's", OwnerID: "other-user"}, - "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}}, - "pls-synced": {ID: "pls-synced", Name: "Synced", OwnerID: "user-1", Sync: true}, - "pls-synced-other": {ID: "pls-synced-other", Name: "Other's Synced", OwnerID: "other-user", Sync: true, Public: true}, + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "Existing", OwnerID: "user-1"}, + &model.Playlist{ID: "pls-2", Name: "Other's", OwnerID: "other-user", Public: true}, + &model.Playlist{ID: "pls-smart", Name: "Smart", OwnerID: "user-1", Rules: smartRules()}, + &model.Playlist{ID: "pls-synced", Name: "Synced", OwnerID: "user-1", Sync: true}, + &model.Playlist{ID: "pls-synced-other", Name: "Other's Synced", OwnerID: "other-user", Sync: true, Public: true}, + ) + for _, id := range []string{"pls-1", "pls-2"} { + _, err := ds.Playlist().Tracks(asAdmin(ctx), id, false).Add(ctx, songs[:2]) + Expect(err).ToNot(HaveOccurred()) } - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) }) It("creates a new playlist with owner set from context", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - id, err := ps.Create(ctx, "", "New Playlist", []string{"song-1", "song-2"}) + id, err := ps.Create(ctx, "", "New Playlist", []string{songs[0], songs[1]}) Expect(err).ToNot(HaveOccurred()) Expect(id).ToNot(BeEmpty()) - Expect(mockPlsRepo.Last.Name).To(Equal("New Playlist")) - Expect(mockPlsRepo.Last.OwnerID).To(Equal("user-1")) + stored := storedPlaylist(ctx, ds, id) + Expect(stored.Name).To(Equal("New Playlist")) + Expect(stored.OwnerID).To(Equal("user-1")) + Expect(trackIDs(stored)).To(Equal(songs[:2])) }) It("replaces tracks on existing playlist when owner matches", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - id, err := ps.Create(ctx, "pls-1", "", []string{"song-3"}) + id, err := ps.Create(ctx, "pls-1", "", []string{songs[2]}) Expect(err).ToNot(HaveOccurred()) Expect(id).To(Equal("pls-1")) - Expect(mockPlsRepo.Last.Tracks).To(HaveLen(1)) + Expect(storedTracks("pls-1")).To(Equal([]string{songs[2]})) }) It("allows admin to replace tracks on any playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true}) - id, err := ps.Create(ctx, "pls-2", "", []string{"song-3"}) + id, err := ps.Create(ctx, "pls-2", "", []string{songs[2]}) Expect(err).ToNot(HaveOccurred()) Expect(id).To(Equal("pls-2")) + Expect(storedTracks("pls-2")).To(Equal([]string{songs[2]})) }) It("denies non-owner, non-admin from replacing tracks on existing playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.Create(ctx, "pls-2", "", []string{"song-3"}) + _, err := ps.Create(ctx, "pls-2", "", []string{songs[2]}) Expect(err).To(MatchError(model.ErrNotAuthorized)) + Expect(storedTracks("pls-2")).To(Equal(songs[:2])) }) It("returns error when existing playlistId not found", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.Create(ctx, "nonexistent", "", []string{"song-1"}) + _, err := ps.Create(ctx, "nonexistent", "", []string{songs[0]}) Expect(err).To(Equal(model.ErrNotFound)) }) It("denies replacing tracks on a smart playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.Create(ctx, "pls-smart", "", []string{"song-1"}) + _, err := ps.Create(ctx, "pls-smart", "", []string{songs[0]}) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) It("denies replacing tracks on a synced playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.Create(ctx, "pls-synced", "", []string{"song-1"}) + _, err := ps.Create(ctx, "pls-synced", "", []string{songs[0]}) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) It("denies a non-owner with authorization, not a conflict, on a public synced playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.Create(ctx, "pls-synced-other", "", []string{"song-1"}) + _, err := ps.Create(ctx, "pls-synced-other", "", []string{songs[0]}) Expect(err).To(MatchError(model.ErrNotAuthorized)) }) }) Describe("Update", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 2} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, - "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}}, - "pls-synced": {ID: "pls-synced", Name: "Synced", OwnerID: "user-1", Sync: true}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}, + &model.Playlist{ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, + &model.Playlist{ID: "pls-smart", Name: "Smart", OwnerID: "user-1", Rules: smartRules()}, + &model.Playlist{ID: "pls-synced", Name: "Synced", OwnerID: "user-1", Sync: true}, + ) }) It("allows owner to update their playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) err := ps.Update(ctx, "pls-1", new("Updated Name"), nil, nil, nil, nil) Expect(err).ToNot(HaveOccurred()) + Expect(storedPlaylist(ctx, ds, "pls-1").Name).To(Equal("Updated Name")) }) It("allows admin to update any playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true}) err := ps.Update(ctx, "pls-other", new("Updated Name"), nil, nil, nil, nil) Expect(err).ToNot(HaveOccurred()) + Expect(storedPlaylist(ctx, ds, "pls-other").Name).To(Equal("Updated Name")) }) It("denies non-owner, non-admin from updating", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) err := ps.Update(ctx, "pls-1", new("Updated Name"), nil, nil, nil, nil) Expect(err).To(MatchError(model.ErrNotAuthorized)) + Expect(storedPlaylist(ctx, ds, "pls-1").Name).To(Equal("My Playlist")) }) It("returns error when playlist not found", func() { @@ -206,7 +215,7 @@ var _ = Describe("Playlists", func() { It("denies adding tracks to a smart playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - err := ps.Update(ctx, "pls-smart", nil, nil, nil, []string{"song-1"}, nil) + err := ps.Update(ctx, "pls-smart", nil, nil, nil, []string{songs[0]}, nil) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) @@ -220,11 +229,12 @@ var _ = Describe("Playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) err := ps.Update(ctx, "pls-smart", new("Updated Smart"), nil, nil, nil, nil) Expect(err).ToNot(HaveOccurred()) + Expect(storedPlaylist(ctx, ds, "pls-smart").Name).To(Equal("Updated Smart")) }) It("denies adding tracks to a synced playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - err := ps.Update(ctx, "pls-synced", nil, nil, nil, []string{"song-1"}, nil) + err := ps.Update(ctx, "pls-synced", nil, nil, nil, []string{songs[0]}, nil) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) @@ -232,155 +242,141 @@ var _ = Describe("Playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) err := ps.Update(ctx, "pls-synced", new("Renamed Synced"), nil, nil, nil, nil) Expect(err).ToNot(HaveOccurred()) + Expect(storedPlaylist(ctx, ds, "pls-synced").Name).To(Equal("Renamed Synced")) }) }) Describe("AddTracks", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 2} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}}, - "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, - "pls-synced": {ID: "pls-synced", Name: "Synced", OwnerID: "user-1", Sync: true}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}, + &model.Playlist{ID: "pls-smart", Name: "Smart", OwnerID: "user-1", Rules: smartRules()}, + &model.Playlist{ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, + &model.Playlist{ID: "pls-synced", Name: "Synced", OwnerID: "user-1", Sync: true}, + ) }) It("allows owner to add tracks", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - count, err := ps.AddTracks(ctx, "pls-1", []string{"song-1", "song-2"}) + count, err := ps.AddTracks(ctx, "pls-1", []string{songs[0], songs[1]}) Expect(err).ToNot(HaveOccurred()) Expect(count).To(Equal(2)) - Expect(mockTracks.AddedIds).To(ConsistOf("song-1", "song-2")) + Expect(storedTracks("pls-1")).To(ConsistOf(songs[0], songs[1])) }) It("allows admin to add tracks to any playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true}) - count, err := ps.AddTracks(ctx, "pls-other", []string{"song-1"}) + count, err := ps.AddTracks(ctx, "pls-other", []string{songs[0]}) Expect(err).ToNot(HaveOccurred()) - Expect(count).To(Equal(2)) + Expect(count).To(Equal(1)) + Expect(storedTracks("pls-other")).To(Equal([]string{songs[0]})) }) It("denies non-owner, non-admin", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) - _, err := ps.AddTracks(ctx, "pls-1", []string{"song-1"}) + _, err := ps.AddTracks(ctx, "pls-1", []string{songs[0]}) Expect(err).To(MatchError(model.ErrNotAuthorized)) + Expect(storedTracks("pls-1")).To(BeEmpty()) }) It("denies editing smart playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.AddTracks(ctx, "pls-smart", []string{"song-1"}) + _, err := ps.AddTracks(ctx, "pls-smart", []string{songs[0]}) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) It("denies editing synced playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.AddTracks(ctx, "pls-synced", []string{"song-1"}) + _, err := ps.AddTracks(ctx, "pls-synced", []string{songs[0]}) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) + Expect(storedTracks("pls-synced")).To(BeEmpty()) }) It("returns error when playlist not found", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.AddTracks(ctx, "nonexistent", []string{"song-1"}) + _, err := ps.AddTracks(ctx, "nonexistent", []string{songs[0]}) Expect(err).To(Equal(model.ErrNotFound)) }) }) Describe("RemoveTracks", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}, + &model.Playlist{ID: "pls-smart", Name: "Smart", OwnerID: "user-1", Rules: smartRules()}, + ) + _, err := ds.Playlist().Tracks(asAdmin(ctx), "pls-1", false).Add(ctx, songs[:3]) + Expect(err).ToNot(HaveOccurred()) }) It("allows owner to remove tracks", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - err := ps.RemoveTracks(ctx, "pls-1", []string{"track-1", "track-2"}) + err := ps.RemoveTracks(ctx, "pls-1", []string{"1", "2"}) Expect(err).ToNot(HaveOccurred()) - Expect(mockTracks.DeletedIds).To(ConsistOf("track-1", "track-2")) + Expect(storedTracks("pls-1")).To(Equal([]string{songs[2]})) }) It("denies on smart playlist", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - err := ps.RemoveTracks(ctx, "pls-smart", []string{"track-1"}) + err := ps.RemoveTracks(ctx, "pls-smart", []string{"1"}) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) It("denies non-owner", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) - err := ps.RemoveTracks(ctx, "pls-1", []string{"track-1"}) + err := ps.RemoveTracks(ctx, "pls-1", []string{"1"}) Expect(err).To(MatchError(model.ErrNotAuthorized)) + Expect(storedTracks("pls-1")).To(Equal(songs[:3])) }) }) Describe("InsertTracks", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{AddCount: 2} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}, + &model.Playlist{ID: "pls-smart", Name: "Smart", OwnerID: "user-1", Rules: smartRules()}, + ) + _, err := ds.Playlist().Tracks(asAdmin(ctx), "pls-1", false).Add(ctx, songs[:3]) + Expect(err).ToNot(HaveOccurred()) }) It("inserts the tracks at the given position for the owner", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - count, err := ps.InsertTracks(ctx, "pls-1", []string{"song-1", "song-2"}, 3) + count, err := ps.InsertTracks(ctx, "pls-1", []string{songs[3], songs[4]}, 3) Expect(err).ToNot(HaveOccurred()) Expect(count).To(Equal(2)) - Expect(mockTracks.AddedIds).To(Equal([]string{"song-1", "song-2"})) - Expect(mockTracks.InsertPos).To(Equal(3)) + Expect(storedTracks("pls-1")).To(Equal([]string{songs[0], songs[1], songs[3], songs[4], songs[2]})) }) It("denies non-owner, non-admin", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) - _, err := ps.InsertTracks(ctx, "pls-1", []string{"song-1"}, 1) + _, err := ps.InsertTracks(ctx, "pls-1", []string{songs[3]}, 1) Expect(err).To(MatchError(model.ErrNotAuthorized)) - Expect(mockTracks.AddedIds).To(BeEmpty()) + Expect(storedTracks("pls-1")).To(Equal(songs[:3])) }) It("denies editing smart playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - _, err := ps.InsertTracks(ctx, "pls-smart", []string{"song-1"}, 1) + _, err := ps.InsertTracks(ctx, "pls-smart", []string{songs[0]}, 1) Expect(err).To(MatchError(model.ErrPlaylistNotEditable)) }) }) Describe("ReorderTrack", func() { - var mockTracks *tests.MockPlaylistTrackRepo - BeforeEach(func() { - mockTracks = &tests.MockPlaylistTrackRepo{} - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - "pls-smart": {ID: "pls-smart", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}}, - } - mockPlsRepo.TracksRepo = mockTracks - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, + &model.Playlist{ID: "pls-smart", Name: "Smart", OwnerID: "user-1", Rules: smartRules()}, + ) + _, err := ds.Playlist().Tracks(asAdmin(ctx), "pls-1", false).Add(ctx, songs[:3]) + Expect(err).ToNot(HaveOccurred()) }) It("allows owner to reorder", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) err := ps.ReorderTrack(ctx, "pls-1", 1, 3) Expect(err).ToNot(HaveOccurred()) - Expect(mockTracks.Reordered).To(BeTrue()) + Expect(storedTracks("pls-1")).To(Equal([]string{songs[1], songs[2], songs[0]})) }) It("denies on smart playlist", func() { @@ -397,11 +393,10 @@ var _ = Describe("Playlists", func() { tmpDir = GinkgoT().TempDir() conf.Update(func(c *conf.Options) { c.DataFolder = conf.NewDir(tmpDir) }) - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, - } - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}, + &model.Playlist{ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, + ) }) It("saves image file and updates UploadedImage", func() { @@ -410,7 +405,7 @@ var _ = Describe("Playlists", func() { err := ps.SetImage(ctx, "pls-1", reader, ".jpg") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.UploadedImage).To(Equal("pls-1_my_playlist.jpg")) + Expect(storedPlaylist(ctx, ds, "pls-1").UploadedImage).To(Equal("pls-1_my_playlist.jpg")) absPath := filepath.Join(tmpDir, "artwork", "playlist", "pls-1_my_playlist.jpg") data, err := os.ReadFile(absPath) Expect(err).ToNot(HaveOccurred()) @@ -438,12 +433,14 @@ var _ = Describe("Playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "admin-1", IsAdmin: true}) err := ps.SetImage(ctx, "pls-other", strings.NewReader("data"), ".jpg") Expect(err).ToNot(HaveOccurred()) + Expect(storedPlaylist(ctx, ds, "pls-other").UploadedImage).ToNot(BeEmpty()) }) It("denies non-owner", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) err := ps.SetImage(ctx, "pls-1", strings.NewReader("data"), ".jpg") Expect(err).To(MatchError(model.ErrNotAuthorized)) + Expect(storedPlaylist(ctx, ds, "pls-1").UploadedImage).To(BeEmpty()) }) It("returns error when playlist not found", func() { @@ -465,12 +462,11 @@ var _ = Describe("Playlists", func() { Expect(os.MkdirAll(imgDir, 0755)).To(Succeed()) Expect(os.WriteFile(filepath.Join(imgDir, "pls-1.jpg"), []byte("img data"), 0600)).To(Succeed()) - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", UploadedImage: "pls-1.jpg"}, - "pls-empty": {ID: "pls-empty", Name: "No Cover", OwnerID: "user-1"}, - "pls-other": {ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, - } - ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) + putPlaylists(ctx, ds, + &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true, UploadedImage: "pls-1.jpg"}, + &model.Playlist{ID: "pls-empty", Name: "No Cover", OwnerID: "user-1"}, + &model.Playlist{ID: "pls-other", Name: "Other's", OwnerID: "other-user"}, + ) }) It("removes file and clears UploadedImage", func() { @@ -478,7 +474,7 @@ var _ = Describe("Playlists", func() { err := ps.RemoveImage(ctx, "pls-1") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.UploadedImage).To(BeEmpty()) + Expect(storedPlaylist(ctx, ds, "pls-1").UploadedImage).To(BeEmpty()) absPath := filepath.Join(tmpDir, "artwork", "playlist", "pls-1.jpg") Expect(absPath).ToNot(BeAnExistingFile()) }) @@ -487,7 +483,7 @@ var _ = Describe("Playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) err := ps.RemoveImage(ctx, "pls-empty") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.UploadedImage).To(BeEmpty()) + Expect(storedPlaylist(ctx, ds, "pls-empty").UploadedImage).To(BeEmpty()) }) It("clears the resolved artwork state and re-queues after removing an upload", func() { @@ -512,6 +508,7 @@ var _ = Describe("Playlists", func() { ctx = request.WithUser(ctx, model.User{ID: "other-user", IsAdmin: false}) err := ps.RemoveImage(ctx, "pls-1") Expect(err).To(MatchError(model.ErrNotAuthorized)) + Expect(storedPlaylist(ctx, ds, "pls-1").UploadedImage).To(Equal("pls-1.jpg")) }) It("returns error when playlist not found", func() { diff --git a/core/playlists/rest_adapter_test.go b/core/playlists/rest_adapter_test.go index 899f37929..84aa4637f 100644 --- a/core/playlists/rest_adapter_test.go +++ b/core/playlists/rest_adapter_test.go @@ -7,27 +7,28 @@ import ( "github.com/deluan/rest" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("REST Adapter", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ps playlists.Playlists - var mockPlsRepo *tests.MockPlaylistRepo var ctx context.Context + stored := func(id string) *model.Playlist { + return storedPlaylist(ctx, ds, id) + } + BeforeEach(func() { ctx = GinkgoT().Context() - mockPlsRepo = tests.CreateMockPlaylistRepo() - ds = &tests.MockDataStore{ - MockedPlaylist: mockPlsRepo, - MockedLibrary: &tests.MockLibraryRepo{}, - } + ds = persistence.New(db.Db()) + putUsers(ctx, ds, "123", "user-1", "other-user") ctx = request.WithUser(ctx, model.User{ID: "123"}) }) @@ -35,9 +36,7 @@ var _ = Describe("REST Adapter", func() { var repo rest.Persistable[model.Playlist] BeforeEach(func() { - mockPlsRepo.Data = map[string]*model.Playlist{ - "pls-1": {ID: "pls-1", Name: "My Playlist", OwnerID: "user-1"}, - } + putPlaylists(ctx, ds, &model.Playlist{ID: "pls-1", Name: "My Playlist", OwnerID: "user-1", Public: true}) ps = playlists.NewPlaylists(ds, artwork.NewUploader(ds)) }) @@ -68,17 +67,17 @@ var _ = Describe("REST Adapter", func() { Name: "Legit Playlist", Comment: "A comment", Public: true, - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "test"}}, + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Contains{"title": "test"}}}, Path: "/some/path/playlist.m3u", Sync: true, UploadedImage: "injected-image-path", ExternalImageURL: "http://evil.example.com/ssrf", EvaluatedAt: new(time.Now()), } - _, err := repo.Save(ctx, pls) + id, err := repo.Save(ctx, pls) Expect(err).ToNot(HaveOccurred()) - saved := mockPlsRepo.Last + saved := stored(id) // User-settable fields are preserved Expect(saved.Name).To(Equal("Legit Playlist")) Expect(saved.Comment).To(Equal("A comment")) @@ -100,6 +99,7 @@ var _ = Describe("REST Adapter", func() { pls := &model.Playlist{Name: "Updated"} err := repo.Update(ctx, "pls-1", *pls) Expect(err).ToNot(HaveOccurred()) + Expect(stored("pls-1").Name).To(Equal("Updated")) }) It("allows admin to update any playlist", func() { @@ -108,6 +108,7 @@ var _ = Describe("REST Adapter", func() { pls := &model.Playlist{Name: "Updated"} err := repo.Update(ctx, "pls-1", *pls) Expect(err).ToNot(HaveOccurred()) + Expect(stored("pls-1").Name).To(Equal("Updated")) }) It("denies non-owner, non-admin", func() { @@ -116,6 +117,7 @@ var _ = Describe("REST Adapter", func() { pls := &model.Playlist{Name: "Updated"} err := repo.Update(ctx, "pls-1", *pls) Expect(err).To(Equal(rest.ErrPermissionDenied)) + Expect(stored("pls-1").Name).To(Equal("My Playlist")) }) It("denies regular user from changing ownership", func() { @@ -124,6 +126,7 @@ var _ = Describe("REST Adapter", func() { pls := &model.Playlist{Name: "Updated", OwnerID: "other-user"} err := repo.Update(ctx, "pls-1", *pls) Expect(err).To(Equal(rest.ErrPermissionDenied)) + Expect(stored("pls-1").OwnerID).To(Equal("user-1")) }) DescribeTable("denies regular user from changing ownership under any case-variant JSON key", @@ -146,108 +149,111 @@ var _ = Describe("REST Adapter", func() { ) It("updates smart playlist rules", func() { - mockPlsRepo.Data["smart-1"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-1", Name: "Smart Playlist", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "old"}}, - } + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Contains{"title": "old"}}}, + }) ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) repo = ps.Repository().(rest.Persistable[model.Playlist]) - newRules := &criteria.Criteria{Expression: criteria.Contains{"title": "new"}} + newRules := &criteria.Criteria{Expression: criteria.All{criteria.Contains{"title": "new"}}} pls := &model.Playlist{Name: "Smart Playlist", Rules: newRules} err := repo.Update(ctx, "smart-1", *pls) Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Rules).To(Equal(newRules)) + Expect(stored("smart-1").Rules).To(Equal(newRules)) }) It("invalidates the imported hash when rules change, so the next scan re-syncs the file", func() { - mockPlsRepo.Data["smart-1"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-1", Name: "Smart Playlist", OwnerID: "user-1", Path: "/music/smart.nsp", Sync: true, ImportedHash: hashOf("file content"), - Rules: &criteria.Criteria{Expression: criteria.Contains{"title": "old"}}, - } + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Contains{"title": "old"}}}, + }) ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) repo = ps.Repository().(rest.Persistable[model.Playlist]) - newRules := &criteria.Criteria{Expression: criteria.Contains{"title": "new"}} + newRules := &criteria.Criteria{Expression: criteria.All{criteria.Contains{"title": "new"}}} pls := &model.Playlist{Rules: newRules} err := repo.Update(ctx, "smart-1", *pls, "rules") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.ImportedHash).To(BeEmpty()) + Expect(stored("smart-1").ImportedHash).To(BeEmpty()) }) It("allows toggling sync for file-backed playlists", func() { originalTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) - mockPlsRepo.Data["file-pls"] = &model.Playlist{ - ID: "file-pls", - Name: "File Playlist", - OwnerID: "user-1", - Path: "/music/playlist.m3u", - Sync: true, - UpdatedAt: originalTime, - } + putPlaylists(ctx, ds, &model.Playlist{ + ID: "file-pls", + Name: "File Playlist", + OwnerID: "user-1", + Path: "/music/playlist.m3u", + Sync: true, + }) + backdate("file-pls", originalTime) ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) repo = ps.Repository().(rest.Persistable[model.Playlist]) pls := &model.Playlist{Name: "File Playlist", Sync: false} err := repo.Update(ctx, "file-pls", *pls) Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Sync).To(BeFalse()) - Expect(mockPlsRepo.Last.UpdatedAt).To(Equal(originalTime)) + Expect(stored("file-pls").Sync).To(BeFalse()) + Expect(stored("file-pls").UpdatedAt).To(BeTemporally("==", originalTime)) }) It("does not allow setting sync on non-file-backed playlists", func() { - mockPlsRepo.Data["manual-pls"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "manual-pls", Name: "Manual Playlist", OwnerID: "user-1", Path: "", Sync: false, - } + }) + originalTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + backdate("manual-pls", originalTime) ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) repo = ps.Repository().(rest.Persistable[model.Playlist]) pls := &model.Playlist{Name: "Manual Playlist", Sync: true} err := repo.Update(ctx, "manual-pls", *pls) Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).To(BeNil()) + Expect(stored("manual-pls").Sync).To(BeFalse()) + Expect(stored("manual-pls").UpdatedAt).To(BeTemporally("==", originalTime)) }) It("does not bump updatedAt when only public changes", func() { originalTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) - mockPlsRepo.Data["pls-pub"] = &model.Playlist{ - ID: "pls-pub", - Name: "My Playlist", - OwnerID: "user-1", - Public: false, - UpdatedAt: originalTime, - } + putPlaylists(ctx, ds, &model.Playlist{ + ID: "pls-pub", + Name: "My Playlist", + OwnerID: "user-1", + Public: false, + }) + backdate("pls-pub", originalTime) ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) repo = ps.Repository().(rest.Persistable[model.Playlist]) pls := &model.Playlist{Name: "My Playlist", Public: true} err := repo.Update(ctx, "pls-pub", *pls) Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Public).To(BeTrue()) - Expect(mockPlsRepo.Last.UpdatedAt).To(Equal(originalTime)) + Expect(stored("pls-pub").Public).To(BeTrue()) + Expect(stored("pls-pub").UpdatedAt).To(BeTemporally("==", originalTime)) }) It("bumps updatedAt when name changes along with sync", func() { - mockPlsRepo.Data["file-pls2"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "file-pls2", Name: "Old Name", OwnerID: "user-1", Path: "/music/playlist.m3u", Sync: true, - } + }) ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) repo = ps.Repository().(rest.Persistable[model.Playlist]) pls := &model.Playlist{Name: "New Name", Sync: false} err := repo.Update(ctx, "file-pls2", *pls) Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Name).To(Equal("New Name")) - Expect(mockPlsRepo.Last.Sync).To(BeFalse()) + Expect(stored("file-pls2").Name).To(Equal("New Name")) + Expect(stored("file-pls2").Sync).To(BeFalse()) }) It("returns rest.ErrNotFound when playlist doesn't exist", func() { @@ -265,158 +271,160 @@ var _ = Describe("REST Adapter", func() { Context("with partial updates (cols)", func() { BeforeEach(func() { ctx = request.WithUser(ctx, model.User{ID: "user-1", IsAdmin: false}) - mockPlsRepo.Data["partial"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "partial", Name: "Original Name", Comment: "Original comment", OwnerID: "user-1", Public: false, - } + }) }) It("preserves name and comment when only public is sent (bulk Make Public)", func() { repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "partial", model.Playlist{Public: true}, "public") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Name).To(Equal("Original Name")) - Expect(mockPlsRepo.Last.Comment).To(Equal("Original comment")) - Expect(mockPlsRepo.Last.Public).To(BeTrue()) + Expect(stored("partial").Name).To(Equal("Original Name")) + Expect(stored("partial").Comment).To(Equal("Original comment")) + Expect(stored("partial").Public).To(BeTrue()) }) It("preserves name when only sync is sent for a file-backed playlist", func() { - mockPlsRepo.Data["file-partial"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "file-partial", Name: "Keep Me", OwnerID: "user-1", Path: "/music/p.m3u", Sync: true, - } + }) repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "file-partial", model.Playlist{Sync: false}, "sync") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Name).To(Equal("Keep Me")) - Expect(mockPlsRepo.Last.Sync).To(BeFalse()) + Expect(stored("file-partial").Name).To(Equal("Keep Me")) + Expect(stored("file-partial").Sync).To(BeFalse()) }) It("renames the playlist when only name is sent", func() { repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "partial", model.Playlist{Name: "Renamed"}, "name") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Name).To(Equal("Renamed")) - Expect(mockPlsRepo.Last.Comment).To(Equal("Original comment")) - Expect(mockPlsRepo.Last.Public).To(BeFalse()) + Expect(stored("partial").Name).To(Equal("Renamed")) + Expect(stored("partial").Comment).To(Equal("Original comment")) + Expect(stored("partial").Public).To(BeFalse()) }) It("clears the comment when an empty comment is sent explicitly", func() { repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "partial", model.Playlist{Comment: ""}, "comment") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Comment).To(BeEmpty()) - Expect(mockPlsRepo.Last.Name).To(Equal("Original Name")) + Expect(stored("partial").Comment).To(BeEmpty()) + Expect(stored("partial").Name).To(Equal("Original Name")) }) It("updates rules-only on a smart playlist (Feishin-style edit)", func() { - mockPlsRepo.Data["smart-partial"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-partial", Name: "Smart Original", Comment: "smart comment", OwnerID: "user-1", Public: true, - Rules: &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}}, - } + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}}, + }) repo = ps.Repository().(rest.Persistable[model.Playlist]) - newRules := &criteria.Criteria{Expression: criteria.Is{"genre": "Jazz"}, Sort: "year DESC"} + newRules := &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Jazz"}}, Sort: "year DESC"} err := repo.Update(ctx, "smart-partial", model.Playlist{Rules: newRules}, "rules") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Rules).To(Equal(newRules)) - Expect(mockPlsRepo.Last.Name).To(Equal("Smart Original")) - Expect(mockPlsRepo.Last.Comment).To(Equal("smart comment")) - Expect(mockPlsRepo.Last.Public).To(BeTrue()) + Expect(stored("smart-partial").Rules).To(Equal(newRules)) + Expect(stored("smart-partial").Name).To(Equal("Smart Original")) + Expect(stored("smart-partial").Comment).To(Equal("smart comment")) + Expect(stored("smart-partial").Public).To(BeTrue()) }) It("resets EvaluatedAt when rules change", func() { evaluatedAt := time.Now().Add(-1 * time.Hour) - mockPlsRepo.Data["smart-reset"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-reset", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}}, + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}}, EvaluatedAt: &evaluatedAt, - } + }) repo = ps.Repository().(rest.Persistable[model.Playlist]) - newRules := &criteria.Criteria{Expression: criteria.Is{"genre": "Jazz"}} + newRules := &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Jazz"}}} err := repo.Update(ctx, "smart-reset", model.Playlist{Rules: newRules}, "rules") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.EvaluatedAt).To(BeNil()) + Expect(stored("smart-reset").EvaluatedAt).To(BeNil()) }) It("keeps EvaluatedAt when rules are not changed", func() { evaluatedAt := time.Now().Add(-1 * time.Hour) - mockPlsRepo.Data["smart-keep"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-keep", Name: "Smart", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}}, + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}}, EvaluatedAt: &evaluatedAt, - } + }) repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "smart-keep", model.Playlist{Name: "Renamed Smart"}, "name") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.EvaluatedAt).ToNot(BeNil()) - Expect(*mockPlsRepo.Last.EvaluatedAt).To(BeTemporally("~", evaluatedAt, time.Second)) + Expect(stored("smart-keep").EvaluatedAt).ToNot(BeNil()) + Expect(*stored("smart-keep").EvaluatedAt).To(BeTemporally("~", evaluatedAt, time.Second)) }) It("updates name and rules together (smart-playlist Edit form)", func() { - mockPlsRepo.Data["smart-edit"] = &model.Playlist{ + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-edit", Name: "Smart Original", Comment: "smart comment", OwnerID: "user-1", - Rules: &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}}, - } + Rules: &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}}, + }) repo = ps.Repository().(rest.Persistable[model.Playlist]) - newRules := &criteria.Criteria{Expression: criteria.Is{"artist": "Miles Davis"}, Sort: "album"} + newRules := &criteria.Criteria{Expression: criteria.All{criteria.Is{"artist": "Miles Davis"}}, Sort: "album"} err := repo.Update(ctx, "smart-edit", model.Playlist{Name: "Smart Renamed", Rules: newRules}, "name", "rules") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Name).To(Equal("Smart Renamed")) - Expect(mockPlsRepo.Last.Rules).To(Equal(newRules)) - Expect(mockPlsRepo.Last.Comment).To(Equal("smart comment")) + Expect(stored("smart-edit").Name).To(Equal("Smart Renamed")) + Expect(stored("smart-edit").Rules).To(Equal(newRules)) + Expect(stored("smart-edit").Comment).To(Equal("smart comment")) }) It("does not bump the saved rules on an idempotent rules-only PUT", func() { - rules := &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}} - mockPlsRepo.Data["smart-idempotent"] = &model.Playlist{ + rules := &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}} + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-idempotent", Name: "Smart Idempotent", OwnerID: "user-1", Rules: rules, - } + }) + originalTime := time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC) + backdate("smart-idempotent", originalTime) repo = ps.Repository().(rest.Persistable[model.Playlist]) // Same rules sent back — rulesEqual should report no change and // the request should no-op (no Put call). - sameRules := &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}} + sameRules := &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}} err := repo.Update(ctx, "smart-idempotent", model.Playlist{Rules: sameRules}, "rules") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last).To(BeNil()) // no Put happened + Expect(stored("smart-idempotent").UpdatedAt).To(BeTemporally("==", originalTime)) }) It("preserves rules when only public is sent (smart playlist + bulk Make Public)", func() { - rules := &criteria.Criteria{Expression: criteria.Is{"genre": "Rock"}} - mockPlsRepo.Data["smart-public"] = &model.Playlist{ + rules := &criteria.Criteria{Expression: criteria.All{criteria.Is{"genre": "Rock"}}} + putPlaylists(ctx, ds, &model.Playlist{ ID: "smart-public", Name: "Smart Public", OwnerID: "user-1", Public: false, Rules: rules, - } + }) repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "smart-public", model.Playlist{Public: true}, "public") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Public).To(BeTrue()) - Expect(mockPlsRepo.Last.Rules).To(Equal(rules)) - Expect(mockPlsRepo.Last.Name).To(Equal("Smart Public")) + Expect(stored("smart-public").Public).To(BeTrue()) + Expect(stored("smart-public").Rules).To(Equal(rules)) + Expect(stored("smart-public").Name).To(Equal("Smart Public")) }) It("does not treat a missing ownerId as an ownership transfer attempt", func() { @@ -435,8 +443,8 @@ var _ = Describe("REST Adapter", func() { repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Update(ctx, "partial", model.Playlist{Name: "Renamed"}, "Name") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Last.Name).To(Equal("Renamed")) - Expect(mockPlsRepo.Last.Comment).To(Equal("Original comment")) + Expect(stored("partial").Name).To(Equal("Renamed")) + Expect(stored("partial").Comment).To(Equal("Original comment")) }) }) }) @@ -447,7 +455,7 @@ var _ = Describe("REST Adapter", func() { repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Delete(ctx, "pls-1") Expect(err).ToNot(HaveOccurred()) - Expect(mockPlsRepo.Deleted).To(ContainElement("pls-1")) + Expect(ds.Playlist().Exists(asAdmin(ctx), "pls-1")).To(BeFalse()) }) It("denies non-owner", func() { @@ -455,6 +463,7 @@ var _ = Describe("REST Adapter", func() { repo = ps.Repository().(rest.Persistable[model.Playlist]) err := repo.Delete(ctx, "pls-1") Expect(err).To(Equal(rest.ErrPermissionDenied)) + Expect(ds.Playlist().Exists(asAdmin(ctx), "pls-1")).To(BeTrue()) }) }) }) diff --git a/core/scrobbler/buffered_scrobbler_test.go b/core/scrobbler/buffered_scrobbler_test.go index aec132ee9..cc8d975c1 100644 --- a/core/scrobbler/buffered_scrobbler_test.go +++ b/core/scrobbler/buffered_scrobbler_test.go @@ -9,8 +9,9 @@ import ( "time" "github.com/navidrome/navidrome/core/agents" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -20,19 +21,17 @@ var _ = Describe("BufferedScrobbler", func() { var scr *fakeScrobbler var bs *bufferedScrobbler var ctx context.Context - var buffer *tests.MockedScrobbleBufferRepo + var buffer model.ScrobbleBufferRepository BeforeEach(func() { ctx = GinkgoT().Context() - buffer = tests.CreateMockedScrobbleBufferRepo() - userRepo := tests.CreateMockUserRepo() - Expect(userRepo.Put(ctx, &model.User{ID: "user1", UserName: "alice"})).To(Succeed()) - ds = &tests.MockDataStore{ - MockedScrobbleBuffer: buffer, - MockedUser: userRepo, - } + ds = persistence.New(db.Db()) + putUsers(GinkgoT(), ds, model.User{ID: "user1", UserName: "alice"}) + putTracks(GinkgoT(), ds, "123") + buffer = ds.ScrobbleBuffer() scr = &fakeScrobbler{Authorized: true} bs = newBufferedScrobbler(ds, scr, "test") + DeferCleanup(bs.Stop) }) It("forwards IsAuthorized calls", func() { @@ -127,12 +126,12 @@ var _ = Describe("backoffDelay", func() { // Drives the real run loop and asserts the exact retry schedule + recovery. Plain // test: testing/synctest's fake clock needs a *testing.T, which Ginkgo doesn't give. func TestBufferedScrobblerBackoffSchedule(t *testing.T) { + ds := newRealDataStore(t) + putUsers(t, ds, model.User{ID: "user1", UserName: "alice"}) + putTracks(t, ds, "123") + buffer := ds.ScrobbleBuffer() synctest.Test(t, func(t *testing.T) { g := NewWithT(t) - buffer := tests.CreateMockedScrobbleBufferRepo() - userRepo := tests.CreateMockUserRepo() - g.Expect(userRepo.Put(t.Context(), &model.User{ID: "user1", UserName: "alice"})).To(Succeed()) - ds := &tests.MockDataStore{MockedScrobbleBuffer: buffer, MockedUser: userRepo} flaky := &recoveringScrobbler{} flaky.fail(ErrRetryLater) @@ -173,11 +172,10 @@ func TestBufferedScrobblerBackoffSchedule(t *testing.T) { } func TestBufferedScrobblerBackoffWindow(t *testing.T) { + ds := newRealDataStore(t) + putUsers(t, ds, model.User{ID: "user1", UserName: "alice"}) + putTracks(t, ds, "1", "2") synctest.Test(t, func(t *testing.T) { - buffer := tests.CreateMockedScrobbleBufferRepo() - userRepo := tests.CreateMockUserRepo() - _ = userRepo.Put(t.Context(), &model.User{ID: "user1", UserName: "alice"}) - ds := &tests.MockDataStore{MockedScrobbleBuffer: buffer, MockedUser: userRepo} scr := &fakeScrobbler{Authorized: true} scr.SetError(errors.Join(errors.New("boom"), ErrRetryLater)) bs := newBufferedScrobbler(ds, scr, "test") @@ -208,11 +206,10 @@ func TestBufferedScrobblerBackoffWindow(t *testing.T) { } func TestBufferedScrobblerHonorsServerDelay(t *testing.T) { + ds := newRealDataStore(t) + putUsers(t, ds, model.User{ID: "user1", UserName: "alice"}) + putTracks(t, ds, "1", "2") synctest.Test(t, func(t *testing.T) { - buffer := tests.CreateMockedScrobbleBufferRepo() - userRepo := tests.CreateMockUserRepo() - _ = userRepo.Put(t.Context(), &model.User{ID: "user1", UserName: "alice"}) - ds := &tests.MockDataStore{MockedScrobbleBuffer: buffer, MockedUser: userRepo} scr := &fakeScrobbler{Authorized: true} scr.SetError(errors.Join(errors.New("429"), &agents.RetryLaterError{RetryIn: 30 * time.Second})) bs := newBufferedScrobbler(ds, scr, "test") @@ -241,12 +238,11 @@ func TestBufferedScrobblerHonorsServerDelay(t *testing.T) { // The drain visits users in an arbitrary order, so the longest delay must win regardless // of which user was seen last. func TestBufferedScrobblerTakesTheLongestServerDelayAcrossUsers(t *testing.T) { + ds := newRealDataStore(t) + putUsers(t, ds, model.User{ID: "user1", UserName: "alice"}, model.User{ID: "user2", UserName: "bob"}) + putTracks(t, ds, "1", "2") + buffer := ds.ScrobbleBuffer() synctest.Test(t, func(t *testing.T) { - buffer := tests.CreateMockedScrobbleBufferRepo() - userRepo := tests.CreateMockUserRepo() - _ = userRepo.Put(t.Context(), &model.User{ID: "user1", UserName: "alice"}) - _ = userRepo.Put(t.Context(), &model.User{ID: "user2", UserName: "bob"}) - ds := &tests.MockDataStore{MockedScrobbleBuffer: buffer, MockedUser: userRepo} scr := &recoveringScrobbler{delays: map[string]time.Duration{ "user1": 10 * time.Second, "user2": 45 * time.Second, diff --git a/core/scrobbler/play_tracker_test.go b/core/scrobbler/play_tracker_test.go index 94d6039ae..e3928bbbd 100644 --- a/core/scrobbler/play_tracker_test.go +++ b/core/scrobbler/play_tracker_test.go @@ -2,6 +2,7 @@ package scrobbler import ( "context" + "database/sql" "errors" "fmt" "net/http" @@ -11,12 +12,13 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" - + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/events" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -46,24 +48,10 @@ func (m *mockPluginLoader) LoadScrobbler(name string) (Scrobbler, bool) { return s, ok } -// flipOnPlayRepo reports one filter verdict before the play is counted and another -// after, reproducing a filter that reads annotations incPlay mutates. -type flipOnPlayRepo struct { - model.MediaFileRepository - before, after bool - played atomic.Bool -} +type failingCriteriaRepo struct{ model.MediaFileRepository } -func (r *flipOnPlayRepo) IncPlayCount(ctx context.Context, id string, ts time.Time) error { - r.played.Store(true) - return r.MediaFileRepository.IncPlayCount(ctx, id, ts) -} - -func (r *flipOnPlayRepo) MatchesCriteria(context.Context, string, criteria.Criteria) (bool, error) { - if r.played.Load() { - return r.after, nil - } - return r.before, nil +func (failingCriteriaRepo) MatchesCriteria(context.Context, string, criteria.Criteria) (bool, error) { + return false, errors.New("boom") } // slowMediaFileRepo widens the window between a report's session check and its @@ -77,6 +65,33 @@ func (s *slowMediaFileRepo) GetWithParticipants(ctx context.Context, id string) return s.MediaFileRepository.GetWithParticipants(ctx, id) } +// playCount reads u-1's play count for an item straight from the annotation table. +func playCount(itemType, id string) int64 { + GinkgoHelper() + var n int64 + err := db.Db().QueryRow("SELECT play_count FROM annotation WHERE user_id = 'u-1' AND item_type = ? AND item_id = ?", itemType, id).Scan(&n) + if errors.Is(err, sql.ErrNoRows) { + return 0 + } + Expect(err).ToNot(HaveOccurred()) + return n +} + +func recordedScrobbles() []model.Scrobble { + GinkgoHelper() + rows, err := db.Db().Query("SELECT media_file_id, user_id, submission_time FROM scrobbles") + Expect(err).ToNot(HaveOccurred()) + defer rows.Close() + var res []model.Scrobble + for rows.Next() { + var s model.Scrobble + Expect(rows.Scan(&s.MediaFileID, &s.UserID, &s.SubmissionTime)).To(Succeed()) + res = append(res, s) + } + Expect(rows.Err()).To(Succeed()) + return res +} + var _ = Describe("PlayTracker", func() { var ctx context.Context var ds model.DataStore @@ -90,9 +105,10 @@ var _ = Describe("PlayTracker", func() { BeforeEach(func() { ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + putUsers(GinkgoT(), ds, model.User{ID: "u-1", UserName: "user-1"}, model.User{ID: "u-2", UserName: "user-2"}) ctx = request.WithUser(ctx, model.User{ID: "u-1", Libraries: model.Libraries{{ID: 1}}}) ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true}) - ds = &tests.MockDataStore{} fake = &fakeScrobbler{Authorized: true} Register("fake", func(model.DataStore) Scrobbler { return fake @@ -107,6 +123,7 @@ var _ = Describe("PlayTracker", func() { track = model.MediaFile{ ID: "123", LibraryID: 1, + Path: "123.mp3", Title: "Track Title", Album: "Track Album", AlbumID: "al-1", @@ -117,13 +134,13 @@ var _ = Describe("PlayTracker", func() { model.RoleArtist: []model.Participant{_p("ar-1", "Artist 1"), _p("ar-2", "Artist 2")}, }, } - _ = ds.MediaFile().Put(ctx, &track) - artist1 = model.Artist{ID: "ar-1"} - _ = ds.Artist().Put(ctx, &artist1) - artist2 = model.Artist{ID: "ar-2"} - _ = ds.Artist().Put(ctx, &artist2) - album = model.Album{ID: "al-1"} - _ = ds.Album().(*tests.MockAlbumRepo).Put(ctx, &album) + artist1 = model.Artist{ID: "ar-1", Name: "Artist 1"} + Expect(ds.Artist().Put(ctx, &artist1)).To(Succeed()) + artist2 = model.Artist{ID: "ar-2", Name: "Artist 2"} + Expect(ds.Artist().Put(ctx, &artist2)).To(Succeed()) + album = model.Album{ID: "al-1", LibraryID: 1, Name: "Track Album"} + Expect(ds.Album().Put(ctx, &album)).To(Succeed()) + Expect(ds.MediaFile().Put(ctx, &track)).To(Succeed()) }) AfterEach(func() { @@ -150,16 +167,22 @@ var _ = Describe("PlayTracker", func() { }) Describe("GetNowPlaying", func() { + BeforeEach(func() { + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Library 2", Path: "/music2"})).To(Succeed()) + Expect(ds.User().SetUserLibraries(ctx, "u-2", []int{1, 2})).To(Succeed()) + }) + It("returns current playing music", func() { track2 := track track2.ID = "456" - _ = ds.MediaFile().Put(ctx, &track2) - ctx1 := request.WithUser(GinkgoT().Context(), model.User{UserName: "user-1"}) + track2.Path = "456.mp3" + Expect(ds.MediaFile().Put(ctx, &track2)).To(Succeed()) + ctx1 := request.WithUser(GinkgoT().Context(), model.User{ID: "u-1", UserName: "user-1"}) ctx1 = request.WithPlayer(ctx1, model.Player{ScrobbleEnabled: true}) _ = tracker.ReportPlayback(ctx1, ReportPlaybackParams{ MediaId: "123", PositionMs: 0, State: StatePlaying, PlaybackRate: 1.0, ClientId: "player-1", ClientName: "player-one", }) - ctx2 := request.WithUser(GinkgoT().Context(), model.User{UserName: "user-2"}) + ctx2 := request.WithUser(GinkgoT().Context(), model.User{ID: "u-2", UserName: "user-2"}) ctx2 = request.WithPlayer(ctx2, model.Player{ScrobbleEnabled: true}) _ = tracker.ReportPlayback(ctx2, ReportPlaybackParams{ MediaId: "456", PositionMs: 0, State: StatePlaying, PlaybackRate: 1.0, ClientId: "player-2", ClientName: "player-two", @@ -183,8 +206,9 @@ var _ = Describe("PlayTracker", func() { It("hides sessions playing from libraries the caller cannot access", func() { hidden := track hidden.ID = "789" + hidden.Path = "789.mp3" hidden.LibraryID = 2 - _ = ds.MediaFile().Put(ctx, &hidden) + Expect(ds.MediaFile().Put(ctx, &hidden)).To(Succeed()) reporter := request.WithPlayer( request.WithUser(GinkgoT().Context(), model.User{ID: "u-2", UserName: "user-2"}), model.Player{ScrobbleEnabled: true}, @@ -202,8 +226,9 @@ var _ = Describe("PlayTracker", func() { It("shows every session to an admin", func() { hidden := track hidden.ID = "789" + hidden.Path = "789.mp3" hidden.LibraryID = 2 - _ = ds.MediaFile().Put(ctx, &hidden) + Expect(ds.MediaFile().Put(ctx, &hidden)).To(Succeed()) reporter := request.WithPlayer( request.WithUser(GinkgoT().Context(), model.User{ID: "u-2", UserName: "user-2"}), model.Player{ScrobbleEnabled: true}, @@ -302,12 +327,12 @@ var _ = Describe("PlayTracker", func() { err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: ts}}) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) - Expect(album.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) + Expect(playCount("album", "al-1")).To(Equal(int64(1))) // It should increment play counts for all artists - Expect(artist1.PlayCount).To(Equal(int64(1))) - Expect(artist2.PlayCount).To(Equal(int64(1))) + Expect(playCount("artist", "ar-1")).To(Equal(int64(1))) + Expect(playCount("artist", "ar-2")).To(Equal(int64(1))) }) It("does not send track to agent if user has not authorized", func() { @@ -325,14 +350,15 @@ var _ = Describe("PlayTracker", func() { err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) - Expect(album.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) + Expect(playCount("album", "al-1")).To(Equal(int64(1))) Expect(fake.ScrobbleCalled.Load()).To(BeFalse()) }) It("does not send track to agent if artist is unknown", func() { track.Artist = consts.UnknownArtist + Expect(ds.MediaFile().Put(ctx, &track)).To(Succeed()) err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) @@ -348,12 +374,12 @@ var _ = Describe("PlayTracker", func() { Expect(err).ToNot(HaveOccurred()) Expect(fake.ScrobbleCalled.Load()).To(BeFalse()) - Expect(track.PlayCount).To(Equal(int64(1))) - Expect(album.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) + Expect(playCount("album", "al-1")).To(Equal(int64(1))) // It should increment play counts for all artists - Expect(artist1.PlayCount).To(Equal(int64(1))) - Expect(artist2.PlayCount).To(Equal(int64(1))) + Expect(playCount("artist", "ar-1")).To(Equal(int64(1))) + Expect(playCount("artist", "ar-2")).To(Equal(int64(1))) }) Context("Scrobble History", func() { @@ -366,12 +392,11 @@ var _ = Describe("PlayTracker", func() { Expect(err).ToNot(HaveOccurred()) - mockDS := ds.(*tests.MockDataStore) - mockScrobble := mockDS.Scrobble().(*tests.MockScrobbleRepo) - Expect(mockScrobble.RecordedScrobbles).To(HaveLen(1)) - Expect(mockScrobble.RecordedScrobbles[0].MediaFileID).To(Equal("123")) - Expect(mockScrobble.RecordedScrobbles[0].UserID).To(Equal("u-1")) - Expect(mockScrobble.RecordedScrobbles[0].SubmissionTime).To(Equal(ts.Unix())) + recorded := recordedScrobbles() + Expect(recorded).To(HaveLen(1)) + Expect(recorded[0].MediaFileID).To(Equal("123")) + Expect(recorded[0].UserID).To(Equal("u-1")) + Expect(recorded[0].SubmissionTime).To(Equal(ts.Unix())) }) It("does not record scrobble when history is disabled", func() { @@ -382,24 +407,21 @@ var _ = Describe("PlayTracker", func() { err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: ts}}) Expect(err).ToNot(HaveOccurred()) - mockDS := ds.(*tests.MockDataStore) - mockScrobble := mockDS.Scrobble().(*tests.MockScrobbleRepo) - Expect(mockScrobble.RecordedScrobbles).To(BeEmpty()) + Expect(recordedScrobbles()).To(BeEmpty()) }) }) }) Describe("Scrobble filter", func() { - var repo *tests.MockMediaFileRepo + withFilter := func(filter string) { + ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1", ScrobbleFilter: filter}) + } BeforeEach(func() { - ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1", - ScrobbleFilter: `{"all":[{"contains":{"title":"Track"}}]}`}) - repo = ds.MediaFile().(*tests.MockMediaFileRepo) + withFilter(`{"all":[{"contains":{"title":"Track"}}]}`) }) It("does not send a matching track to the agent", func() { - repo.MatchesCriteriaValue = true err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) @@ -408,17 +430,16 @@ var _ = Describe("PlayTracker", func() { }) It("still increments play counts for a filtered track", func() { - repo.MatchesCriteriaValue = true err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) - Expect(album.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) + Expect(playCount("album", "al-1")).To(Equal(int64(1))) }) It("sends a non-matching track to the agent", func() { - repo.MatchesCriteriaValue = false + withFilter(`{"all":[{"contains":{"title":"Nope"}}]}`) err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) @@ -427,7 +448,9 @@ var _ = Describe("PlayTracker", func() { }) It("fails open when evaluation errors", func() { - repo.MatchesCriteriaErr = errors.New("boom") + tracker.ds = persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return failingCriteriaRepo{r} + }}) err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) @@ -436,8 +459,7 @@ var _ = Describe("PlayTracker", func() { }) It("fails open when the stored filter is not valid JSON", func() { - ctx = request.WithUser(ctx, model.User{ID: "u-1", UserName: "user-1", ScrobbleFilter: `{broken`}) - repo.MatchesCriteriaValue = true + withFilter(`{broken`) err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) @@ -446,7 +468,6 @@ var _ = Describe("PlayTracker", func() { }) It("does not send now-playing for a filtered track", func() { - repo.MatchesCriteriaValue = true err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StateStarting, ClientId: "player-1", ClientName: "player"}) @@ -456,7 +477,6 @@ var _ = Describe("PlayTracker", func() { }) It("does not send playback reports for a filtered track", func() { - repo.MatchesCriteriaValue = true err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StateStarting, ClientId: "player-1", ClientName: "player"}) @@ -466,7 +486,7 @@ var _ = Describe("PlayTracker", func() { }) It("sends playback reports for a non-matching track", func() { - repo.MatchesCriteriaValue = false + withFilter(`{"all":[{"contains":{"title":"Nope"}}]}`) err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StateStarting, ClientId: "player-1", ClientName: "player"}) @@ -479,7 +499,6 @@ var _ = Describe("PlayTracker", func() { // The verdict is stored on the session and dispatched at expiry, by which // time a plugin scrobbler may have been enabled. tracker.builtinScrobblers = map[string]Scrobbler{} - repo.MatchesCriteriaValue = true err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StatePlaying, ClientId: "player-12", ClientName: "player"}) @@ -493,32 +512,28 @@ var _ = Describe("PlayTracker", func() { Context("when incPlay itself flips the filter", func() { // A filter on playCount or lastPlayed changes verdict the moment incPlay // commits, so the verdict has to be taken before it, not at dispatch time. - var flip *flipOnPlayRepo - - install := func(before, after bool) { - flip = &flipOnPlayRepo{MediaFileRepository: ds.MediaFile(), before: before, after: after} - ds.(*tests.MockDataStore).MockedMediaFile = flip - } + const unplayedFilter = `{"all":[{"is":{"playcount":0}}]}` + const playedFilter = `{"all":[{"gt":{"playcount":0}}]}` It("does not scrobble a track the filter matched before the play was counted", func() { - install(true, false) + withFilter(unplayedFilter) err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StateStopped, PositionMs: 120_000, ClientId: "player-1", ClientName: "player"}) Expect(err).ToNot(HaveOccurred()) - Expect(flip.played.Load()).To(BeTrue(), "incPlay must still have run") + Expect(playCount("media_file", "123")).To(Equal(int64(1)), "incPlay must still have run") Expect(fake.ScrobbleCalled.Load()).To(BeFalse()) }) It("still sends the stopped report when the filter only starts matching after the play", func() { - install(false, true) + withFilter(playedFilter) err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StateStopped, PositionMs: 120_000, ClientId: "player-1", ClientName: "player"}) Expect(err).ToNot(HaveOccurred()) - Expect(flip.played.Load()).To(BeTrue(), "incPlay must still have run") + Expect(playCount("media_file", "123")).To(Equal(int64(1)), "incPlay must still have run") Eventually(func() bool { return fake.PlaybackReportCalled.Load() }).Should(BeTrue()) }) @@ -545,7 +560,6 @@ var _ = Describe("PlayTracker", func() { }) It("stores the verdict on the session so expiry can reuse it", func() { - repo.MatchesCriteriaValue = true err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", State: StatePlaying, ClientId: "player-11", ClientName: "player"}) @@ -557,12 +571,12 @@ var _ = Describe("PlayTracker", func() { }) It("does not scrobble a Submit whose filter matched before the play was counted", func() { - install(true, false) + withFilter(unplayedFilter) err := tracker.Submit(ctx, []Submission{{TrackID: "123", Timestamp: time.Now()}}) Expect(err).ToNot(HaveOccurred()) - Expect(flip.played.Load()).To(BeTrue(), "incPlay must still have run") + Expect(playCount("media_file", "123")).To(Equal(int64(1)), "incPlay must still have run") Expect(fake.ScrobbleCalled.Load()).To(BeFalse()) }) }) @@ -639,7 +653,8 @@ var _ = Describe("PlayTracker", func() { It("starting replaces existing entry when switching tracks on same player", func() { track2 := track track2.ID = "456" - _ = ds.MediaFile().Put(ctx, &track2) + track2.Path = "456.mp3" + Expect(ds.MediaFile().Put(ctx, &track2)).To(Succeed()) err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "123", PositionMs: 50000, State: "playing", PlaybackRate: 1.0, ClientId: defaultClientId, @@ -666,7 +681,8 @@ var _ = Describe("PlayTracker", func() { track2 := track track2.ID = "456" - _ = ds.MediaFile().Put(ctx, &track2) + track2.Path = "456.mp3" + Expect(ds.MediaFile().Put(ctx, &track2)).To(Succeed()) err := tracker.ReportPlayback(ctx1, ReportPlaybackParams{ MediaId: "123", PositionMs: 0, State: "playing", PlaybackRate: 1.0, ClientId: "client-1", @@ -754,20 +770,20 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 90000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) - Expect(album.PlayCount).To(Equal(int64(1))) - Expect(artist1.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) + Expect(playCount("album", "al-1")).To(Equal(int64(1))) + Expect(playCount("artist", "ar-1")).To(Equal(int64(1))) }) It("scrobbles on stopped when positionMs >= 4 min for long tracks", func() { longTrack := model.MediaFile{ - ID: "long", Title: "Long Song", Album: "Album", AlbumID: "al-1", + ID: "long", LibraryID: 1, Path: "long.mp3", Title: "Long Song", Album: "Album", AlbumID: "al-1", Duration: 600, Participants: map[model.Role]model.ParticipantList{ model.RoleArtist: []model.Participant{_p("ar-1", "Artist 1")}, }, } - _ = ds.MediaFile().Put(ctx, &longTrack) + Expect(ds.MediaFile().Put(ctx, &longTrack)).To(Succeed()) err := tracker.ReportPlayback(ctx, ReportPlaybackParams{ MediaId: "long", PositionMs: 0, State: "starting", PlaybackRate: 1.0, ClientId: defaultClientId, @@ -777,7 +793,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "long", PositionMs: 240000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(longTrack.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "long")).To(Equal(int64(1))) }) It("does NOT scrobble when positionMs below threshold", func() { @@ -789,7 +805,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 10000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(0))) + Expect(playCount("media_file", "123")).To(Equal(int64(0))) }) It("does NOT scrobble when ignoreScrobble=true even if threshold met", func() { @@ -803,7 +819,7 @@ var _ = Describe("PlayTracker", func() { IgnoreScrobble: true, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(0))) + Expect(playCount("media_file", "123")).To(Equal(int64(0))) Consistently(func() bool { return fake.ScrobbleCalled.Load() }).Should(BeFalse()) }) @@ -818,7 +834,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 90000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) Consistently(func() bool { return fake.ScrobbleCalled.Load() }).Should(BeFalse()) }) @@ -839,7 +855,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 90000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(2))) + Expect(playCount("media_file", "123")).To(Equal(int64(2))) }) It("dispatches to external scrobblers on auto-scrobble", func() { @@ -950,7 +966,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 90000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) }) It("stopped without prior starting does NOT scrobble if below threshold", func() { @@ -958,7 +974,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 10000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(0))) + Expect(playCount("media_file", "123")).To(Equal(int64(0))) }) }) @@ -966,7 +982,8 @@ var _ = Describe("PlayTracker", func() { BeforeEach(func() { track2 := track track2.ID = "456" - _ = ds.MediaFile().Put(ctx, &track2) + track2.Path = "456.mp3" + Expect(ds.MediaFile().Put(ctx, &track2)).To(Succeed()) }) It("does not downgrade an actively playing session when a late starting report arrives for the same track", func() { @@ -1012,7 +1029,7 @@ var _ = Describe("PlayTracker", func() { MediaId: "123", PositionMs: 90000, State: "stopped", PlaybackRate: 1.0, ClientId: defaultClientId, }) Expect(err).ToNot(HaveOccurred()) - Expect(track.PlayCount).To(Equal(int64(1))) + Expect(playCount("media_file", "123")).To(Equal(int64(1))) }) It("does not dispatch NowPlaying from an ignored out-of-order starting report", func() { @@ -1031,7 +1048,9 @@ var _ = Describe("PlayTracker", func() { }) It("never lets a concurrent starting report downgrade the playing session", func() { - ds.(*tests.MockDataStore).MockedMediaFile = &slowMediaFileRepo{MediaFileRepository: ds.MediaFile()} + tracker.ds = persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return &slowMediaFileRepo{r} + }}) for i := range 20 { raceClientId := fmt.Sprintf("race-client-%d", i) var wg sync.WaitGroup @@ -1282,7 +1301,6 @@ var _ = Describe("PlayTracker", func() { ctx = GinkgoT().Context() ctx = request.WithUser(ctx, model.User{ID: "u-1"}) ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true}) - ds = &tests.MockDataStore{} // Setup plugin scrobbler pluginScr = &fakeScrobbler{Authorized: true} @@ -1327,7 +1345,6 @@ var _ = Describe("PlayTracker", func() { ctx = GinkgoT().Context() ctx = request.WithUser(ctx, model.User{ID: "u-1"}) ctx = request.WithPlayer(ctx, model.Player{ScrobbleEnabled: true}) - ds = &tests.MockDataStore{} // Setup initial plugin scrobbler originalScrobbler = &fakeScrobbler{Authorized: true} diff --git a/core/scrobbler/scrobbler_suite_test.go b/core/scrobbler/scrobbler_suite_test.go index 039581e8f..bf23c029b 100644 --- a/core/scrobbler/scrobbler_suite_test.go +++ b/core/scrobbler/scrobbler_suite_test.go @@ -1,10 +1,15 @@ package scrobbler import ( + "context" "testing" "github.com/navidrome/navidrome/conf/configtest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +18,47 @@ import ( func TestAgents(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Scrobbler Test Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() + +// newRealDataStore gives a plain (non-Ginkgo) test its own database. Call it outside the +// synctest bubble, so the connection pool's goroutines do not belong to the bubble. +func newRealDataStore(t *testing.T) model.DataStore { + t.Helper() + log.SetLevel(log.LevelFatal) + persistencetest.Init(t) + return persistence.New(db.Db()) +} + +// testingT is the part of *testing.T and GinkgoT() that putUsers and putTracks need. +type testingT interface { + Helper() + Context() context.Context + Fatalf(format string, args ...any) +} + +func putUsers(t testingT, ds model.DataStore, users ...model.User) { + t.Helper() + for _, u := range users { + if err := ds.User().Put(t.Context(), &u); err != nil { + t.Fatalf("storing user %s: %v", u.ID, err) + } + } +} + +// putTracks stores one media file per ID, in library 1. +func putTracks(t testingT, ds model.DataStore, ids ...string) { + t.Helper() + ctx := t.Context() + for _, id := range ids { + mf := &model.MediaFile{ID: id, LibraryID: model.DefaultLibraryID, Path: id + ".mp3", Title: "Track " + id} + if err := ds.MediaFile().Put(ctx, mf); err != nil { + t.Fatalf("storing track %s: %v", id, err) + } + } +} diff --git a/core/share_test.go b/core/share_test.go index 777da0055..6c705f003 100644 --- a/core/share_test.go +++ b/core/share_test.go @@ -4,9 +4,10 @@ import ( "context" "github.com/deluan/rest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -14,13 +15,20 @@ import ( var _ = Describe("Share", func() { var ds model.DataStore var share Share - var mockedRepo rest.Persistable[model.Share] var ctx context.Context + putTrack := func(id, title string) { + GinkgoHelper() + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: id, LibraryID: model.DefaultLibraryID, Path: id + ".mp3", Title: title})).To(Succeed()) + } + BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - mockedRepo = ds.Share().(rest.Persistable[model.Share]) + ds = persistence.New(db.Db()) + for _, id := range []string{"user-1", "logged-in-user", "victim-user"} { + Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: id})).To(Succeed()) + } + ctx = request.WithUser(ctx, model.User{ID: "user-1", UserName: "user-1"}) share = NewShare(ds) }) @@ -29,7 +37,7 @@ var _ = Describe("Share", func() { BeforeEach(func() { repo = share.Repository().(rest.Persistable[model.Share]) - _ = ds.Album().Put(ctx, &model.Album{ID: "123", Name: "Album"}) + Expect(ds.Album().Put(ctx, &model.Album{ID: "123", Name: "Album", LibraryID: model.DefaultLibraryID})).To(Succeed()) }) Describe("Save", func() { @@ -48,10 +56,13 @@ var _ = Describe("Share", func() { _, err := repo.Save(loggedInCtx, entity) Expect(err).ToNot(HaveOccurred()) Expect(entity.UserID).To(Equal("logged-in-user")) + stored, err := ds.Share().Get(loggedInCtx, entity.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(stored.UserID).To(Equal("logged-in-user")) }) It("does not truncate ASCII labels shorter than 30 characters", func() { - _ = ds.MediaFile().Put(ctx, &model.MediaFile{ID: "456", Title: "Example Media File"}) + putTrack("456", "Example Media File") entity := &model.Share{Description: "test", ResourceIDs: "456"} _, err := repo.Save(ctx, entity) Expect(err).ToNot(HaveOccurred()) @@ -59,7 +70,7 @@ var _ = Describe("Share", func() { }) It("truncates ASCII labels longer than 30 characters", func() { - _ = ds.MediaFile().Put(ctx, &model.MediaFile{ID: "789", Title: "Example Media File But The Title Is Really Long For Testing Purposes"}) + putTrack("789", "Example Media File But The Title Is Really Long For Testing Purposes") entity := &model.Share{Description: "test", ResourceIDs: "789"} _, err := repo.Save(ctx, entity) Expect(err).ToNot(HaveOccurred()) @@ -67,7 +78,7 @@ var _ = Describe("Share", func() { }) It("does not truncate CJK labels shorter than 30 runes", func() { - _ = ds.MediaFile().Put(ctx, &model.MediaFile{ID: "456", Title: "青春コンプレックス"}) + putTrack("456", "青春コンプレックス") entity := &model.Share{Description: "test", ResourceIDs: "456"} _, err := repo.Save(ctx, entity) Expect(err).ToNot(HaveOccurred()) @@ -75,7 +86,7 @@ var _ = Describe("Share", func() { }) It("truncates CJK labels longer than 30 runes", func() { - _ = ds.MediaFile().Put(ctx, &model.MediaFile{ID: "789", Title: "私の中の幻想的世界観及びその顕現を想起させたある現実での出来事に関する一考察"}) + putTrack("789", "私の中の幻想的世界観及びその顕現を想起させたある現実での出来事に関する一考察") entity := &model.Share{Description: "test", ResourceIDs: "789"} _, err := repo.Save(ctx, entity) Expect(err).ToNot(HaveOccurred()) @@ -89,7 +100,7 @@ var _ = Describe("Share", func() { }) It("fails when the resource IDs are of mixed types", func() { - _ = ds.MediaFile().Put(ctx, &model.MediaFile{ID: "456", Title: "Example Media File"}) + putTrack("456", "Example Media File") entity := &model.Share{Description: "test", ResourceIDs: "123,456"} _, err := repo.Save(ctx, entity) Expect(err).To(HaveOccurred()) @@ -98,9 +109,21 @@ var _ = Describe("Share", func() { Describe("Update", func() { It("filters out read-only fields", func() { - err := repo.Update(ctx, "id", model.Share{}) + id, err := repo.Save(ctx, &model.Share{Description: "old", ResourceIDs: "123"}) Expect(err).ToNot(HaveOccurred()) - Expect(mockedRepo.(*tests.MockShareRepo).Cols).To(ConsistOf("description", "downloadable")) + before, err := ds.Share().Get(ctx, id) + Expect(err).ToNot(HaveOccurred()) + + err = repo.Update(ctx, id, model.Share{Description: "new", Downloadable: true, Contents: "changed", ResourceIDs: "456", VisitCount: 99}) + Expect(err).ToNot(HaveOccurred()) + + after, err := ds.Share().Get(ctx, id) + Expect(err).ToNot(HaveOccurred()) + Expect(after.Description).To(Equal("new")) + Expect(after.Downloadable).To(BeTrue()) + Expect(after.Contents).To(Equal(before.Contents)) + Expect(after.ResourceIDs).To(Equal("123")) + Expect(after.VisitCount).To(BeZero()) }) }) }) diff --git a/core/sonic/sonic_suite_test.go b/core/sonic/sonic_suite_test.go index 7058e5de9..c77cd3ed9 100644 --- a/core/sonic/sonic_suite_test.go +++ b/core/sonic/sonic_suite_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -12,6 +13,9 @@ import ( func TestSonic(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Sonic Suite") } + +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/core/sonic/sonic_test.go b/core/sonic/sonic_test.go index 813fceea9..119e4f926 100644 --- a/core/sonic/sonic_test.go +++ b/core/sonic/sonic_test.go @@ -7,8 +7,10 @@ import ( "github.com/navidrome/navidrome/core/agents" "github.com/navidrome/navidrome/core/matcher" "github.com/navidrome/navidrome/core/sonic" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -48,14 +50,14 @@ func (m *mockProvider) FindSonicPath(_ context.Context, _, _ *model.MediaFile, _ var _ = Describe("Sonic", func() { var ( ctx context.Context - ds *tests.MockDataStore + ds model.DataStore loader *mockPluginLoader service *sonic.Sonic ) BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) loader = &mockPluginLoader{} }) @@ -85,19 +87,16 @@ var _ = Describe("Sonic", func() { loader.names = []string{"test-plugin"} loader.provider = &mockProvider{} loader.loadOk = true - ds.MockedMediaFile = &tests.MockMediaFileRepo{} service = sonic.New(ds, loader, matcher.New(ds)) _, err := service.GetSonicSimilarTracks(ctx, "nonexistent", 10) - Expect(err).To(HaveOccurred()) + Expect(err).To(MatchError(model.ErrNotFound)) }) It("returns matched results from plugin", func() { - mf1 := model.MediaFile{ID: "song-1", Title: "Test Song", Artist: "Test Artist"} - mf2 := model.MediaFile{ID: "song-2", Title: "Similar Song", Artist: "Test Artist"} - - mockRepo := tests.CreateMockMediaFileRepo() - mockRepo.SetData(model.MediaFiles{mf1, mf2}) - ds.MockedMediaFile = mockRepo + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Test Song", Artist: "Test Artist"}, + model.MediaFile{ID: "song-2", Title: "Similar Song", Artist: "Test Artist"}, + ) provider := &mockProvider{ similarResults: []sonic.SimilarResult{ @@ -126,12 +125,10 @@ var _ = Describe("Sonic", func() { }) It("returns error when plugin call fails", func() { - mf1 := model.MediaFile{ID: "song-1", Title: "Start", Artist: "Artist"} - mf2 := model.MediaFile{ID: "song-2", Title: "End", Artist: "Artist"} - - mockRepo := tests.CreateMockMediaFileRepo() - mockRepo.SetData(model.MediaFiles{mf1, mf2}) - ds.MockedMediaFile = mockRepo + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "song-1", Title: "Start", Artist: "Artist"}, + model.MediaFile{ID: "song-2", Title: "End", Artist: "Artist"}, + ) provider := &mockProvider{pathErr: errors.New("plugin error")} loader.names = []string{"test-plugin"} diff --git a/core/stream/decider_test.go b/core/stream/decider_test.go index e1747f6fc..a4145f601 100644 --- a/core/stream/decider_test.go +++ b/core/stream/decider_test.go @@ -8,8 +8,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/ffmpeg" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/gg" . "github.com/onsi/ginkgo/v2" @@ -32,9 +34,18 @@ func withProbe(mf *model.MediaFile) *model.MediaFile { return mf } +// setDefaultBitRate stores a custom default bitrate for format, so a spec can tell it from the built-in default. +func setDefaultBitRate(ctx context.Context, ds model.DataStore, format string, bitRate int) { + GinkgoHelper() + t, err := ds.Transcoding().FindByFormat(ctx, format) + Expect(err).ToNot(HaveOccurred()) + t.DefaultBitRate = bitRate + Expect(ds.Transcoding().Put(request.WithUser(ctx, model.User{IsAdmin: true}), t)).To(Succeed()) +} + var _ = Describe("Decider", func() { var ( - ds *tests.MockDataStore + ds model.DataStore ff *tests.MockFFmpeg svc TranscodeDecider ctx context.Context @@ -42,10 +53,7 @@ var _ = Describe("Decider", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedTranscoding: &tests.MockTranscodingRepo{}, - } + ds = persistence.New(db.Db()) ff = tests.NewMockFFmpeg("") auth.Init(ds) svc = NewTranscodeDecider(ds, ff) @@ -288,7 +296,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - Expect(decision.TargetBitrate).To(Equal(160)) // mp3 default from mock transcoding repo + Expect(decision.TargetBitrate).To(Equal(192)) // mp3 default stored in the DB }) It("preserves lossy bitrate when under max", func() { @@ -1206,6 +1214,7 @@ var _ = Describe("Decider", func() { Context("Format-aware default bitrate", func() { It("uses opus default bitrate from DB", func() { + setDefaultBitRate(ctx, ds, "opus", 96) mf := withProbe(&model.MediaFile{ID: "1", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 48000, BitDepth: new(16)}) ci := &ClientInfo{ TranscodingProfiles: []Profile{ @@ -1215,7 +1224,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - Expect(decision.TargetBitrate).To(Equal(96)) // opus default from mock + Expect(decision.TargetBitrate).To(Equal(96)) }) It("uses aac default bitrate from DB", func() { @@ -1228,7 +1237,7 @@ var _ = Describe("Decider", func() { decision, err := svc.MakeDecision(ctx, mf, ci, TranscodeOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(decision.CanTranscode).To(BeTrue()) - Expect(decision.TargetBitrate).To(Equal(256)) // aac default from mock + Expect(decision.TargetBitrate).To(Equal(256)) }) It("falls back to 256 for unknown format", func() { @@ -1316,16 +1325,9 @@ var _ = Describe("Decider", func() { }) Describe("ensureProbed", func() { - var mockMFRepo *tests.MockMediaFileRepo - - BeforeEach(func() { - mockMFRepo = tests.CreateMockMediaFileRepo() - ds.MockedMediaFile = mockMFRepo - }) - It("calls ffprobe and populates ProbeData when empty", func() { - mf := &model.MediaFile{ID: "probe-1", Suffix: "mp3", BitRate: 320, Channels: 2} - mockMFRepo.SetData(model.MediaFiles{*mf}) + mf := &model.MediaFile{ID: "probe-1", LibraryID: model.DefaultLibraryID, Path: "probe-1.mp3", Suffix: "mp3", BitRate: 320, Channels: 2} + Expect(ds.MediaFile().Put(ctx, mf)).To(Succeed()) ff.ProbeAudioResult = &ffmpeg.AudioProbeResult{ Codec: "mp3", BitRate: 320, SampleRate: 44100, Channels: 2, @@ -1341,8 +1343,8 @@ var _ = Describe("Decider", func() { Expect(probe.SampleRate).To(Equal(44100)) Expect(probe.Channels).To(Equal(2)) - // Verify persisted to DB - stored := mockMFRepo.Data["probe-1"] + stored, err := ds.MediaFile().Get(ctx, "probe-1") + Expect(err).ToNot(HaveOccurred()) Expect(stored.ProbeData).To(Equal(mf.ProbeData)) }) diff --git a/core/stream/legacy_client_test.go b/core/stream/legacy_client_test.go index f03a94675..1bdfd982f 100644 --- a/core/stream/legacy_client_test.go +++ b/core/stream/legacy_client_test.go @@ -5,8 +5,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -149,10 +151,7 @@ var _ = Describe("ResolveRequest", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds := &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedTranscoding: &tests.MockTranscodingRepo{}, - } + ds := persistence.New(db.Db()) ff := tests.NewMockFFmpeg("") auth.Init(ds) svc = NewTranscodeDecider(ds, ff) @@ -281,8 +280,8 @@ var _ = Describe("ResolveRequest", func() { req := decider.ResolveRequest(overrideCtx, mf, "", 0, 0) Expect(req.Format).To(Equal("mp3")) - // With no cap, lossless→lossy uses format default bitrate (160 for mp3 from mock) - Expect(req.BitRate).To(Equal(160)) + // With no cap, lossless→lossy uses the mp3 default bitrate stored in the DB + Expect(req.BitRate).To(Equal(192)) }) It("serves a lossy source raw when the override targets a lossless format", func() { @@ -455,10 +454,7 @@ var _ = Describe("ResolveClientRequest", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds := &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedTranscoding: &tests.MockTranscodingRepo{}, - } + ds := persistence.New(db.Db()) auth.Init(ds) svc = NewTranscodeDecider(ds, tests.NewMockFFmpeg("")) }) diff --git a/core/stream/media_streamer_test.go b/core/stream/media_streamer_test.go index f211f591a..5b142deac 100644 --- a/core/stream/media_streamer_test.go +++ b/core/stream/media_streamer_test.go @@ -16,9 +16,12 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/stream" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -37,10 +40,13 @@ var _ = Describe("MediaStreamer", func() { c.CacheFolder = conf.NewDir(cacheDir) c.TranscodingCacheSize = "100MB" }) - ds = &tests.MockDataStore{MockedTranscoding: &tests.MockTranscodingRepo{}} - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: "123", Path: "tests/fixtures/test.mp3", Suffix: "mp3", BitRate: 128, Duration: 257.0}, - }) + ds = persistence.New(db.Db()) + cwd, err := os.Getwd() + Expect(err).ToNot(HaveOccurred()) + persistencetest.SetLibraries(ctx, ds, cwd) + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ + ID: "123", LibraryID: model.DefaultLibraryID, Path: "tests/fixtures/test.mp3", Suffix: "mp3", BitRate: 128, Duration: 257.0, + })).To(Succeed()) testCache := stream.NewTranscodingCache() Eventually(func() bool { return testCache.Available(ctx) }, 10*time.Second).Should(BeTrue()) streamer = stream.NewMediaStreamer(ds, ffmpeg, testCache) diff --git a/core/stream/stream_suite_test.go b/core/stream/stream_suite_test.go index db6c774de..090e13347 100644 --- a/core/stream/stream_suite_test.go +++ b/core/stream/stream_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestStream(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Stream Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/core/stream/token_test.go b/core/stream/token_test.go index 4f0d8066c..45c6303ff 100644 --- a/core/stream/token_test.go +++ b/core/stream/token_test.go @@ -6,7 +6,9 @@ import ( "github.com/go-chi/jwtauth/v5" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -14,7 +16,7 @@ import ( var _ = Describe("Token", func() { var ( - ds *tests.MockDataStore + ds model.DataStore ff *tests.MockFFmpeg svc TranscodeDecider ctx context.Context @@ -22,10 +24,7 @@ var _ = Describe("Token", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedTranscoding: &tests.MockTranscodingRepo{}, - } + ds = persistence.New(db.Db()) ff = tests.NewMockFFmpeg("") auth.Init(ds) svc = NewTranscodeDecider(ds, ff) diff --git a/core/user_test.go b/core/user_test.go index 880637770..492d59f36 100644 --- a/core/user_test.go +++ b/core/user_test.go @@ -6,26 +6,26 @@ import ( "github.com/deluan/rest" "github.com/navidrome/navidrome/core" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("User Service", func() { var service core.User - var ds *tests.MockDataStore - var userRepo *tests.MockedUserRepo + var ds model.DataStore var pluginManager *mockPluginUnloader var ctx context.Context BeforeEach(func() { - ds = &tests.MockDataStore{} - userRepo = tests.CreateMockUserRepo() - ds.MockedUser = userRepo + ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin-1", IsAdmin: true}) + ds = persistence.New(db.Db()) pluginManager = &mockPluginUnloader{} service = core.NewUser(ds, pluginManager) - ctx = GinkgoT().Context() }) Describe("NewRepository", func() { @@ -50,7 +50,7 @@ var _ = Describe("User Service", func() { IsAdmin: false, } user.NewPassword = "password" - Expect(userRepo.Put(ctx, user)).To(Succeed()) + Expect(ds.User().Put(ctx, user)).To(Succeed()) }) It("deletes the user successfully", func() { @@ -58,7 +58,7 @@ var _ = Describe("User Service", func() { Expect(err).NotTo(HaveOccurred()) // Verify user is deleted - _, err = userRepo.Get(ctx, "user-123") + _, err = ds.User().Get(ctx, "user-123") Expect(err).To(Equal(model.ErrNotFound)) }) @@ -78,13 +78,16 @@ var _ = Describe("User Service", func() { err := repo.Delete(ctx, "user-123", "non-existent") Expect(err).To(MatchError(model.ErrNotFound)) - _, err = userRepo.Get(ctx, "user-123") + _, err = ds.User().Get(ctx, "user-123") Expect(err).To(Equal(model.ErrNotFound)) Expect(pluginManager.unloadCalls).To(Equal(1)) }) It("returns error when repository fails", func() { - userRepo.Error = errors.New("database error") + failing := persistencetest.Stub(ds, persistencetest.Repos{User: func(r model.UserRepository) model.UserRepository { + return &failingUserDeleteRepo{UserRepository: r} + }}) + repo := core.NewUser(failing, pluginManager).Repository().(rest.Persistable[model.User]) err := repo.Delete(ctx, "user-123") Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("database error")) @@ -92,3 +95,9 @@ var _ = Describe("User Service", func() { }) }) }) + +type failingUserDeleteRepo struct{ model.UserRepository } + +func (r *failingUserDeleteRepo) Delete(context.Context, ...string) error { + return errors.New("database error") +} diff --git a/model/get_entity_test.go b/model/get_entity_test.go index 73e21a036..f9a8188e5 100644 --- a/model/get_entity_test.go +++ b/model/get_entity_test.go @@ -2,24 +2,27 @@ package model_test import ( "context" + "errors" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("GetEntityByID", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ctx context.Context BeforeEach(func() { - ds = &tests.MockDataStore{} ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) It("returns the entity matching the id", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "a1", Name: "One"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "a1", Name: "One"}) entity, err := model.GetEntityByID(ctx, ds, "a1") Expect(err).ToNot(HaveOccurred()) Expect(entity).To(BeAssignableToTypeOf(&model.Album{})) @@ -27,29 +30,32 @@ var _ = Describe("GetEntityByID", func() { }) It("returns ErrNotFound when no entity matches", func() { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "a1", Name: "One"}) _, err := model.GetEntityByID(ctx, ds, "missing") Expect(err).To(MatchError(model.ErrNotFound)) }) It("propagates unexpected repository errors instead of reporting not-found", func() { - ds.Album().(*tests.MockAlbumRepo).SetError(true) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "a1", Name: "One"}) + ds = persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return failingAlbumRepo{r} + }}) _, err := model.GetEntityByID(ctx, ds, "a1") - Expect(err).To(HaveOccurred()) - Expect(err).ToNot(MatchError(model.ErrNotFound)) + Expect(err).To(MatchError(errAlbumGet)) }) }) var _ = Describe("GetEntityKindByID", func() { - var ds *tests.MockDataStore + var ds model.DataStore var ctx context.Context BeforeEach(func() { - ds = &tests.MockDataStore{} ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) It("returns the artwork kind for the matching id", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: "a1"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "a1"}) kind, err := model.GetEntityKindByID(ctx, ds, "a1") Expect(err).ToNot(HaveOccurred()) Expect(kind).To(Equal(model.KindAlbumArtwork)) @@ -60,3 +66,9 @@ var _ = Describe("GetEntityKindByID", func() { Expect(err).To(MatchError(model.ErrNotFound)) }) }) + +var errAlbumGet = errors.New("album lookup failed") + +type failingAlbumRepo struct{ model.AlbumRepository } + +func (failingAlbumRepo) Get(context.Context, string) (*model.Album, error) { return nil, errAlbumGet } diff --git a/model/model_suite_test.go b/model/model_suite_test.go index 53d33d36c..a546d97fc 100644 --- a/model/model_suite_test.go +++ b/model/model_suite_test.go @@ -6,6 +6,7 @@ import ( _ "github.com/mattn/go-sqlite3" "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -14,8 +15,10 @@ import ( func TestModel(t *testing.T) { tests.Init(t, true) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Model Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/persistence/e2e/e2e_suite_test.go b/persistence/e2e/e2e_suite_test.go index b47b5b544..20f6fb634 100644 --- a/persistence/e2e/e2e_suite_test.go +++ b/persistence/e2e/e2e_suite_test.go @@ -3,7 +3,6 @@ package e2e import ( "context" "encoding/json" - "os" "path/filepath" "sort" "testing" @@ -23,6 +22,7 @@ import ( "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" @@ -47,12 +47,11 @@ var track = storagetest.Track var ( ctx context.Context - ds *tests.MockDataStore + ds model.DataStore lib model.Library - dbFilePath string - snapshotPath string - snapshotTables []string + dbFilePath string + snapshotPath string adminUser = model.User{ ID: "sp-test-user-1", @@ -252,7 +251,7 @@ var _ = BeforeSuite(func() { db.Init(ctx) - initDS := &tests.MockDataStore{RealDS: persistence.New(db.Db())} + initDS := persistence.New(db.Db()) userWithPass := adminUser userWithPass.NewPassword = "password" @@ -283,7 +282,7 @@ var _ = BeforeSuite(func() { _, err = s.ScanAll(ctx, true) Expect(err).ToNot(HaveOccurred()) - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds = persistence.New(db.Db()) comeTogetherID := findMediaFileByTitle("Come Together") Expect(ds.MediaFile().SetStar(ctx, true, comeTogetherID)).To(Succeed()) @@ -295,21 +294,7 @@ var _ = BeforeSuite(func() { } Expect(ds.MediaFile().IncPlayCount(ctx, findMediaFileByTitle("Black Dog"), time.Now())).To(Succeed()) - rows, err := db.Db().Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '%_fts' AND name NOT LIKE '%_fts_%'") - Expect(err).ToNot(HaveOccurred()) - defer rows.Close() - for rows.Next() { - var name string - Expect(rows.Scan(&name)).To(Succeed()) - snapshotTables = append(snapshotTables, name) - } - Expect(rows.Err()).To(Succeed()) - - _, err = db.Db().Exec("PRAGMA wal_checkpoint(TRUNCATE)") - Expect(err).ToNot(HaveOccurred()) - data, err := os.ReadFile(dbFilePath) - Expect(err).ToNot(HaveOccurred()) - Expect(os.WriteFile(snapshotPath, data, 0600)).To(Succeed()) + Expect(persistencetest.Snapshot(snapshotPath)).To(Succeed()) }) var _ = AfterSuite(func() { @@ -317,29 +302,7 @@ var _ = AfterSuite(func() { }) func restoreDB() { - sqlDB := db.Db() - - _, err := sqlDB.Exec("PRAGMA foreign_keys = OFF") - Expect(err).ToNot(HaveOccurred()) - defer func() { _, _ = sqlDB.Exec("PRAGMA foreign_keys = ON") }() - - _, err = sqlDB.Exec("ATTACH DATABASE ? AS snapshot", snapshotPath) - Expect(err).ToNot(HaveOccurred()) - defer func() { _, _ = sqlDB.Exec("DETACH DATABASE snapshot") }() - - _, err = sqlDB.Exec("BEGIN TRANSACTION") - Expect(err).ToNot(HaveOccurred()) - defer func() { _, _ = sqlDB.Exec("ROLLBACK") }() - - for _, table := range snapshotTables { - _, err = sqlDB.Exec(`DELETE FROM main."` + table + `"`) //nolint:gosec - Expect(err).ToNot(HaveOccurred()) - _, err = sqlDB.Exec(`INSERT INTO main."` + table + `" SELECT * FROM snapshot."` + table + `"`) //nolint:gosec - Expect(err).ToNot(HaveOccurred()) - } - - _, err = sqlDB.Exec("COMMIT") - Expect(err).ToNot(HaveOccurred()) + Expect(persistencetest.RestoreFrom(snapshotPath)).To(Succeed()) } func setupTestDB() { @@ -352,5 +315,5 @@ func setupTestDB() { }) restoreDB() - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds = persistence.New(db.Db()) } diff --git a/persistence/library_repository.go b/persistence/library_repository.go index f4b079c6d..0e05ad09d 100644 --- a/persistence/library_repository.go +++ b/persistence/library_repository.go @@ -25,6 +25,14 @@ var ( libLock sync.RWMutex ) +// ClearLibraryPathCache drops the cached library paths. Call it after rewriting the library table +// without the repository, as test suites do when they restore a database snapshot. +func ClearLibraryPathCache() { + libLock.Lock() + defer libLock.Unlock() + clear(libCache) +} + func NewLibraryRepository(db dbx.Builder) model.LibraryRepository { r := &libraryRepository{} r.db = db diff --git a/persistence/persistencetest/overlay.go b/persistence/persistencetest/overlay.go new file mode 100644 index 000000000..dfeba0758 --- /dev/null +++ b/persistence/persistencetest/overlay.go @@ -0,0 +1,164 @@ +package persistencetest + +import ( + "context" + + "github.com/navidrome/navidrome/model" +) + +type overlay struct { + model.DataStore + wrap func(model.DataStore) model.DataStore +} + +// Overlay returns wrap(ds), and also wraps every transaction ds opens, so a stub that overrides +// one repository still applies inside WithTx. wrap's result must embed the DataStore it receives. +func Overlay(ds model.DataStore, wrap func(model.DataStore) model.DataStore) model.DataStore { + return wrap(&overlay{DataStore: ds, wrap: wrap}) +} + +func (o *overlay) WithTx(block func(tx model.DataStore) error, scope ...string) error { + return o.DataStore.WithTx(func(tx model.DataStore) error { + return block(Overlay(tx, o.wrap)) + }, scope...) +} + +func (o *overlay) WithTxImmediate(block func(tx model.DataStore) error, scope ...string) error { + return o.DataStore.WithTxImmediate(func(tx model.DataStore) error { + return block(Overlay(tx, o.wrap)) + }, scope...) +} + +func (o *overlay) WithTxRetry(ctx context.Context, block func(ctx context.Context, tx model.DataStore) error, scope ...string) error { + return o.DataStore.WithTxRetry(ctx, func(ctx context.Context, tx model.DataStore) error { + return block(ctx, Overlay(tx, o.wrap)) + }, scope...) +} + +// Repos holds optional wrappers for the repositories of a DataStore, one per accessor. Each +// receives the repository the accessor would return, the transaction's one inside a transaction. +type Repos struct { + Library func(model.LibraryRepository) model.LibraryRepository + Folder func(model.FolderRepository) model.FolderRepository + Album func(model.AlbumRepository) model.AlbumRepository + Artist func(model.ArtistRepository) model.ArtistRepository + MediaFile func(model.MediaFileRepository) model.MediaFileRepository + Genre func(model.GenreRepository) model.GenreRepository + Tag func(model.TagRepository) model.TagRepository + Playlist func(model.PlaylistRepository) model.PlaylistRepository + PlayQueue func(model.PlayQueueRepository) model.PlayQueueRepository + Transcoding func(model.TranscodingRepository) model.TranscodingRepository + Player func(model.PlayerRepository) model.PlayerRepository + Radio func(model.RadioRepository) model.RadioRepository + Share func(model.ShareRepository) model.ShareRepository + Property func(model.PropertyRepository) model.PropertyRepository + User func(model.UserRepository) model.UserRepository + UserProps func(model.UserPropsRepository) model.UserPropsRepository + ScrobbleBuffer func(model.ScrobbleBufferRepository) model.ScrobbleBufferRepository + Scrobble func(model.ScrobbleRepository) model.ScrobbleRepository + Plugin func(model.PluginRepository) model.PluginRepository + Artwork func(model.ArtworkRepository) model.ArtworkRepository + ArtworkQueue func(model.ArtworkQueueRepository) model.ArtworkQueueRepository +} + +// Stub returns ds with the non-nil Repos wrappers applied, also inside every transaction it opens. +// A wrapper runs on every accessor call, so state shared across calls must live outside the repository it returns. +func Stub(ds model.DataStore, repos Repos) model.DataStore { + return Overlay(ds, func(ds model.DataStore) model.DataStore { return &stubbed{DataStore: ds, repos: repos} }) +} + +type stubbed struct { + model.DataStore + repos Repos +} + +func wrapRepo[R any](wrap func(R) R, repo R) R { + if wrap == nil { + return repo + } + return wrap(repo) +} + +func (s *stubbed) Library() model.LibraryRepository { + return wrapRepo(s.repos.Library, s.DataStore.Library()) +} + +func (s *stubbed) Folder() model.FolderRepository { + return wrapRepo(s.repos.Folder, s.DataStore.Folder()) +} + +func (s *stubbed) Album() model.AlbumRepository { + return wrapRepo(s.repos.Album, s.DataStore.Album()) +} + +func (s *stubbed) Artist() model.ArtistRepository { + return wrapRepo(s.repos.Artist, s.DataStore.Artist()) +} + +func (s *stubbed) MediaFile() model.MediaFileRepository { + return wrapRepo(s.repos.MediaFile, s.DataStore.MediaFile()) +} + +func (s *stubbed) Genre() model.GenreRepository { + return wrapRepo(s.repos.Genre, s.DataStore.Genre()) +} + +func (s *stubbed) Tag() model.TagRepository { + return wrapRepo(s.repos.Tag, s.DataStore.Tag()) +} + +func (s *stubbed) Playlist() model.PlaylistRepository { + return wrapRepo(s.repos.Playlist, s.DataStore.Playlist()) +} + +func (s *stubbed) PlayQueue() model.PlayQueueRepository { + return wrapRepo(s.repos.PlayQueue, s.DataStore.PlayQueue()) +} + +func (s *stubbed) Transcoding() model.TranscodingRepository { + return wrapRepo(s.repos.Transcoding, s.DataStore.Transcoding()) +} + +func (s *stubbed) Player() model.PlayerRepository { + return wrapRepo(s.repos.Player, s.DataStore.Player()) +} + +func (s *stubbed) Radio() model.RadioRepository { + return wrapRepo(s.repos.Radio, s.DataStore.Radio()) +} + +func (s *stubbed) Share() model.ShareRepository { + return wrapRepo(s.repos.Share, s.DataStore.Share()) +} + +func (s *stubbed) Property() model.PropertyRepository { + return wrapRepo(s.repos.Property, s.DataStore.Property()) +} + +func (s *stubbed) User() model.UserRepository { + return wrapRepo(s.repos.User, s.DataStore.User()) +} + +func (s *stubbed) UserProps() model.UserPropsRepository { + return wrapRepo(s.repos.UserProps, s.DataStore.UserProps()) +} + +func (s *stubbed) ScrobbleBuffer() model.ScrobbleBufferRepository { + return wrapRepo(s.repos.ScrobbleBuffer, s.DataStore.ScrobbleBuffer()) +} + +func (s *stubbed) Scrobble() model.ScrobbleRepository { + return wrapRepo(s.repos.Scrobble, s.DataStore.Scrobble()) +} + +func (s *stubbed) Plugin() model.PluginRepository { + return wrapRepo(s.repos.Plugin, s.DataStore.Plugin()) +} + +func (s *stubbed) Artwork() model.ArtworkRepository { + return wrapRepo(s.repos.Artwork, s.DataStore.Artwork()) +} + +func (s *stubbed) ArtworkQueue() model.ArtworkQueueRepository { + return wrapRepo(s.repos.ArtworkQueue, s.DataStore.ArtworkQueue()) +} diff --git a/persistence/persistencetest/overlay_test.go b/persistence/persistencetest/overlay_test.go new file mode 100644 index 000000000..6ae36943d --- /dev/null +++ b/persistence/persistencetest/overlay_test.go @@ -0,0 +1,144 @@ +package persistencetest_test + +import ( + "context" + "errors" + "reflect" + + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var errStub = errors.New("stubbed album error") + +type failingAlbumRepo struct{ model.AlbumRepository } + +func (failingAlbumRepo) Get(context.Context, string) (*model.Album, error) { return nil, errStub } + +type failingAlbums struct{ model.DataStore } + +func (f failingAlbums) Album() model.AlbumRepository { + return failingAlbumRepo{f.DataStore.Album()} +} + +type txRunner func(ctx context.Context, ds model.DataStore, block func(tx model.DataStore) error) error + +var txRunners = []TableEntry{ + Entry("WithTx", txRunner(func(_ context.Context, ds model.DataStore, block func(tx model.DataStore) error) error { + return ds.WithTx(block) + })), + Entry("WithTxImmediate", txRunner(func(_ context.Context, ds model.DataStore, block func(tx model.DataStore) error) error { + return ds.WithTxImmediate(block) + })), + Entry("WithTxRetry", txRunner(func(ctx context.Context, ds model.DataStore, block func(tx model.DataStore) error) error { + return ds.WithTxRetry(ctx, func(_ context.Context, tx model.DataStore) error { return block(tx) }) + })), + Entry("a nested WithTx", txRunner(func(_ context.Context, ds model.DataStore, block func(tx model.DataStore) error) error { + return ds.WithTx(func(tx model.DataStore) error { return tx.WithTx(block) }) + })), +} + +func albumGetErrInTx(ctx context.Context, ds model.DataStore, run txRunner) error { + GinkgoHelper() + var err error + Expect(run(ctx, ds, func(tx model.DataStore) error { + _, err = tx.Album().Get(ctx, "any") + return nil + })).To(Succeed()) + return err +} + +var _ = Describe("Overlay", func() { + var ctx context.Context + var ds model.DataStore + + BeforeEach(func() { + ctx = GinkgoT().Context() + ds = persistencetest.Overlay(persistence.New(db.Db()), func(ds model.DataStore) model.DataStore { + return failingAlbums{ds} + }) + }) + + It("applies the stub outside a transaction", func() { + _, err := ds.Album().Get(ctx, "any") + Expect(err).To(MatchError(errStub)) + }) + + DescribeTable("applies the stub inside a transaction", func(run txRunner) { + Expect(albumGetErrInTx(ctx, ds, run)).To(MatchError(errStub)) + }, txRunners) +}) + +func repoAccessors() []reflect.Method { + var accessors []reflect.Method + for m := range reflect.TypeFor[model.DataStore]().Methods() { + if m.Type.NumIn() == 0 && m.Type.NumOut() == 1 { + accessors = append(accessors, m) + } + } + return accessors +} + +func callAccessor(ds model.DataStore, name string) any { + return reflect.ValueOf(ds).MethodByName(name).Call(nil)[0].Interface() +} + +var _ = Describe("Stub", func() { + var ctx context.Context + var realDS model.DataStore + + BeforeEach(func() { + ctx = GinkgoT().Context() + realDS = persistence.New(db.Db()) + }) + + It("has a wrapper for every repository accessor of model.DataStore", func() { + repos := reflect.TypeFor[persistencetest.Repos]() + for _, m := range repoAccessors() { + _, ok := repos.FieldByName(m.Name) + Expect(ok).To(BeTrue(), "Repos has no %s field", m.Name) + } + }) + + DescribeTable("returns the wrapper's result from its accessor, given the real repository", + func(name string) { + var repos persistencetest.Repos + field := reflect.ValueOf(&repos).Elem().FieldByName(name) + var received any + field.Set(reflect.MakeFunc(field.Type(), func(args []reflect.Value) []reflect.Value { + received = args[0].Interface() + return []reflect.Value{reflect.Zero(field.Type().Out(0))} + })) + + Expect(callAccessor(persistencetest.Stub(realDS, repos), name)).To(BeNil()) + Expect(reflect.TypeOf(received)).To(Equal(reflect.TypeOf(callAccessor(realDS, name)))) + }, + func() []TableEntry { + var entries []TableEntry + for _, f := range reflect.VisibleFields(reflect.TypeFor[persistencetest.Repos]()) { + entries = append(entries, Entry(f.Name, f.Name)) + } + return entries + }(), + ) + + It("returns the real repository from every accessor without a wrapper", func() { + stub := persistencetest.Stub(realDS, persistencetest.Repos{}) + for _, m := range repoAccessors() { + got := callAccessor(stub, m.Name) + Expect(got).ToNot(BeNil(), m.Name) + Expect(reflect.TypeOf(got)).To(Equal(reflect.TypeOf(callAccessor(realDS, m.Name))), m.Name) + } + }) + + DescribeTable("applies the wrappers inside a transaction", func(run txRunner) { + ds := persistencetest.Stub(realDS, persistencetest.Repos{ + Album: func(r model.AlbumRepository) model.AlbumRepository { return failingAlbumRepo{r} }, + }) + Expect(albumGetErrInTx(ctx, ds, run)).To(MatchError(errStub)) + }, txRunners) +}) diff --git a/persistence/persistencetest/persistencetest.go b/persistence/persistencetest/persistencetest.go new file mode 100644 index 000000000..8dd85e8a1 --- /dev/null +++ b/persistence/persistencetest/persistencetest.go @@ -0,0 +1,143 @@ +// Package persistencetest gives a test suite a real, migrated SQLite database that is restored to +// its post-migration state before each spec. It must only be imported from test code. +package persistencetest + +import ( + "context" + "database/sql" + "fmt" + "path/filepath" + "strings" + "testing" + + "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/consts" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/utils/singleton" + "github.com/onsi/ginkgo/v2" +) + +var baselinePath string + +// Init migrates a fresh database for the suite and snapshots it as the baseline Reset restores. +// Call it in the suite's TestXxx, before RunSpecs: the database is a process-wide singleton. +func Init(t testing.TB) { + t.Helper() + dir := t.TempDir() + _, options, _ := strings.Cut(consts.DefaultDbPath, "?") + singleton.DeleteInstance[*sql.DB]() + conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(dir, "test.db") + "?" + options }) + db.Init(t.Context()) + + baselinePath = filepath.Join(dir, "baseline.db") + if err := Snapshot(baselinePath); err != nil { + t.Fatalf("snapshotting baseline database: %v", err) + } + t.Cleanup(func() { + db.Close(context.Background()) + singleton.DeleteInstance[*sql.DB]() + }) +} + +// Reset restores the database to the baseline Init saved, including rows seeded by migrations. +func Reset() { + ginkgo.GinkgoHelper() + if baselinePath == "" { + ginkgo.Fail("persistencetest.Reset called before persistencetest.Init") + } + if err := RestoreFrom(baselinePath); err != nil { + ginkgo.Fail("restoring baseline database: " + err.Error()) + } +} + +// ResetBeforeEachSpec registers a top-level BeforeEach that calls Reset before every spec, and +// once before each Ordered container, whose specs share state on purpose. +func ResetBeforeEachSpec() bool { + return ginkgo.BeforeEach(ginkgo.OncePerOrdered, Reset) +} + +// Tables lists the tables a restore rewrites. FTS shadow tables are excluded: their content +// tables' triggers keep them in sync, and writing them directly corrupts the index. +func Tables() ([]string, error) { + return tables(context.Background(), db.Db()) +} + +type querier interface { + QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) +} + +func tables(ctx context.Context, q querier) ([]string, error) { + rows, err := q.QueryContext(ctx, "SELECT name FROM main.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '%_fts' AND name NOT LIKE '%_fts_%'") + if err != nil { + return nil, err + } + defer rows.Close() + var names []string + for rows.Next() { + var name string + if err := rows.Scan(&name); err != nil { + return nil, err + } + names = append(names, name) + } + return names, rows.Err() +} + +// Snapshot writes a copy of the database to path, which must not exist, for RestoreFrom to restore. +func Snapshot(path string) error { + _, err := db.Db().Exec("VACUUM INTO ?", path) + return err +} + +// RestoreFrom replaces every table's rows with those in the SQLite file at path. +func RestoreFrom(path string) error { + ctx := context.Background() + // ATTACH and PRAGMA foreign_keys are per connection and refused inside a transaction, so they + // run on one pinned connection, before it. + conn, err := db.Db().Conn(ctx) + if err != nil { + return err + } + defer conn.Close() + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys = OFF"); err != nil { + return err + } + defer func() { _, _ = conn.ExecContext(ctx, "PRAGMA foreign_keys = ON") }() + if _, err := conn.ExecContext(ctx, "ATTACH DATABASE ? AS snapshot", path); err != nil { + return err + } + defer func() { _, _ = conn.ExecContext(ctx, "DETACH DATABASE snapshot") }() + + names, err := tables(ctx, conn) + if err != nil { + return err + } + // A raw BEGIN on the pinned connection skips the per-statement cost of database/sql's Tx. + if _, err := conn.ExecContext(ctx, "BEGIN"); err != nil { + return err + } + committed := false + defer func() { + if !committed { + _, _ = conn.ExecContext(ctx, "ROLLBACK") + } + }() + for _, table := range names { + // Table names come from sqlite_master, not user input. + for _, query := range []string{ + `DELETE FROM main."` + table + `"`, + `INSERT INTO main."` + table + `" SELECT * FROM snapshot."` + table + `"`, + } { + if _, err := conn.ExecContext(ctx, query); err != nil { + return fmt.Errorf("%s: %w", query, err) + } + } + } + if _, err := conn.ExecContext(ctx, "COMMIT"); err != nil { + return err + } + committed = true + persistence.ClearLibraryPathCache() + return nil +} diff --git a/persistence/persistencetest/persistencetest_suite_test.go b/persistence/persistencetest/persistencetest_suite_test.go new file mode 100644 index 000000000..ff2fe444a --- /dev/null +++ b/persistence/persistencetest/persistencetest_suite_test.go @@ -0,0 +1,23 @@ +package persistencetest_test + +import ( + "testing" + + "github.com/navidrome/navidrome/conf/configtest" + "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/tests" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestPersistenceTest(t *testing.T) { + tests.Init(t, false) + log.SetLevel(log.LevelFatal) + persistencetest.Init(t) + RegisterFailHandler(Fail) + RunSpecs(t, "PersistenceTest Suite") +} + +var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/persistence/persistencetest/persistencetest_test.go b/persistence/persistencetest/persistencetest_test.go new file mode 100644 index 000000000..947d4994c --- /dev/null +++ b/persistence/persistencetest/persistencetest_test.go @@ -0,0 +1,138 @@ +package persistencetest_test + +import ( + "context" + "fmt" + "testing" + + "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/tests" + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func newAlbum(id, name string) *model.Album { + return &model.Album{ + ID: id, Name: name, LibraryID: model.DefaultLibraryID, + Discs: model.Discs{}, Tags: model.Tags{}, Participants: model.Participants{}, + } +} + +func countProperties(prefix string) int { + var n int + Expect(db.Db().QueryRow("SELECT count(*) FROM property WHERE id LIKE ?", prefix+"%").Scan(&n)).To(Succeed()) + return n +} + +var _ = Describe("Reset", func() { + var ctx context.Context + var ds model.DataStore + + BeforeEach(func() { + ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "admin", UserName: "admin", IsAdmin: true}) + ds = persistence.New(db.Db()) + }) + + It("restores rows seeded by migrations", func() { + transcodings, err := ds.Transcoding().CountAll(ctx) + Expect(err).ToNot(HaveOccurred()) + Expect(transcodings).To(BeNumerically(">", 0)) + _, err = db.Db().Exec("DELETE FROM transcoding") + Expect(err).ToNot(HaveOccurred()) + _, err = db.Db().Exec("DELETE FROM library") + Expect(err).ToNot(HaveOccurred()) + + persistencetest.Reset() + + lib, err := ds.Library().Get(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + Expect(lib.Name).To(Equal(model.DefaultLibraryName)) + Expect(ds.Transcoding().CountAll(ctx)).To(Equal(transcodings)) + }) + + It("removes rows a spec added", func() { + Expect(ds.Album().Put(ctx, newAlbum("al-1", "Kept"))).To(Succeed()) + + persistencetest.Reset() + + _, err := ds.Album().Get(ctx, "al-1") + Expect(err).To(MatchError(model.ErrNotFound)) + }) + + It("keeps full-text search in sync with the restored rows", func() { + Expect(ds.Album().Put(ctx, newAlbum("al-1", "Zyxwvu"))).To(Succeed()) + Expect(ds.Album().Search(ctx, "Zyxwvu")).To(HaveLen(1)) + + persistencetest.Reset() + Expect(ds.Album().Search(ctx, "Zyxwvu")).To(BeEmpty()) + + Expect(ds.Album().Put(ctx, newAlbum("al-2", "Zyxwvu"))).To(Succeed()) + Expect(ds.Album().Search(ctx, "Zyxwvu")).To(HaveLen(1)) + }) + + It("forgets library paths cached before the reset", func() { + baseline, err := ds.Library().GetPath(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + persistencetest.SetLibraries(ctx, ds, "/somewhere/else") + Expect(ds.Library().GetPath(ctx, model.DefaultLibraryID)).To(Equal("/somewhere/else")) + + persistencetest.Reset() + + Expect(ds.Library().GetPath(ctx, model.DefaultLibraryID)).To(Equal(baseline)) + }) +}) + +var _ = Describe("ResetBeforeEachSpec", func() { + // Without the hook, whichever of these two specs runs second would see the other's row. + for _, name := range []string{"first", "second"} { + It("starts the "+name+" spec from the baseline", func() { + Expect(countProperties("isolated-")).To(BeZero()) + Expect(persistence.New(db.Db()).Property().Put(GinkgoT().Context(), "isolated-"+name, "v")).To(Succeed()) + }) + } + + // Without the reset before each container, whichever container runs second would see the other's row. + for _, name := range []string{"first", "second"} { + Describe("in the "+name+" Ordered container", Ordered, func() { + It("starts from the baseline", func() { + Expect(countProperties("ordered-")).To(BeZero()) + Expect(persistence.New(db.Db()).Property().Put(GinkgoT().Context(), "ordered-"+name, "v")).To(Succeed()) + }) + + It("still sees the row from the previous spec", func() { + Expect(countProperties("ordered-")).To(Equal(1)) + }) + }) + } +}) + +func BenchmarkReset(b *testing.B) { + tests.Init(b, false) + b.Cleanup(conf.SnapshotConfig()) + persistencetest.Init(b) + ctx := request.WithUser(b.Context(), model.User{ID: "admin", UserName: "admin", IsAdmin: true}) + ds := persistence.New(db.Db()) + for b.Loop() { + // A typical spec leaves a user, an album and a few songs behind. + b.StopTimer() + if err := ds.User().Put(ctx, &model.User{ID: "u1", UserName: "u1"}); err != nil { + b.Fatal(err) + } + if err := ds.Album().Put(ctx, newAlbum("al-1", "Album")); err != nil { + b.Fatal(err) + } + for i := range 5 { + mf := &model.MediaFile{ID: fmt.Sprintf("mf-%d", i), Path: fmt.Sprintf("%d.mp3", i), LibraryID: model.DefaultLibraryID, AlbumID: "al-1"} + if err := ds.MediaFile().Put(ctx, mf); err != nil { + b.Fatal(err) + } + } + b.StartTimer() + persistencetest.Reset() + } +} diff --git a/persistence/persistencetest/seed.go b/persistence/persistencetest/seed.go new file mode 100644 index 000000000..9440be143 --- /dev/null +++ b/persistence/persistencetest/seed.go @@ -0,0 +1,100 @@ +package persistencetest + +import ( + "cmp" + "context" + "encoding/json" + "strconv" + "strings" + + "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/model/id" + "github.com/navidrome/navidrome/model/request" + "github.com/onsi/ginkgo/v2" + "github.com/onsi/gomega" +) + +// SetLibraries points library 1 at paths[0], creates libraries 2, 3, ... for the other paths, and +// grants every existing user access to all of them. It returns the library IDs in order. +func SetLibraries(ctx context.Context, ds model.DataStore, paths ...string) []int { + ginkgo.GinkgoHelper() + // Library().Put refuses to change library 1's path; StoreMusicFolder is the only way. + conf.Update(func(c *conf.Options) { c.MusicFolder = paths[0] }) + gomega.Expect(ds.Library().StoreMusicFolder(ctx)).To(gomega.Succeed()) + ids := []int{model.DefaultLibraryID} + for i, path := range paths[1:] { + lib := &model.Library{ID: i + 2, Name: "Library " + strconv.Itoa(i+2), Path: path} + gomega.Expect(ds.Library().Put(ctx, lib)).To(gomega.Succeed()) + ids = append(ids, lib.ID) + } + users, err := ds.User().GetAll(request.WithUser(ctx, model.User{IsAdmin: true})) + gomega.Expect(err).ToNot(gomega.HaveOccurred()) + for _, u := range users { + gomega.Expect(ds.User().SetUserLibraries(ctx, u.ID, ids)).To(gomega.Succeed()) + } + return ids +} + +// PutMediaFiles stores copies of mfs, in library 1 unless they name another and at ID+".mp3" unless +// they have a path. It returns the stored copies, which carry the IDs the repository generated. +func PutMediaFiles(ctx context.Context, ds model.DataStore, mfs ...model.MediaFile) model.MediaFiles { + ginkgo.GinkgoHelper() + stored := make(model.MediaFiles, len(mfs)) + for i, mf := range mfs { + mf.LibraryID = cmp.Or(mf.LibraryID, model.DefaultLibraryID) + if mf.Path == "" { + // Put matches an ID-less file by path, so files with neither would overwrite each other. + mf.ID = cmp.Or(mf.ID, id.NewRandom()) + mf.Path = mf.ID + ".mp3" + } + gomega.Expect(ds.MediaFile().Put(ctx, &mf)).To(gomega.Succeed()) + stored[i] = mf + } + return stored +} + +// PutAlbums stores copies of albums, in library 1 unless they name another, sorted by their +// lowercased name unless they set OrderAlbumName. +func PutAlbums(ctx context.Context, ds model.DataStore, albums ...model.Album) { + ginkgo.GinkgoHelper() + for _, al := range albums { + al.LibraryID = cmp.Or(al.LibraryID, model.DefaultLibraryID) + al.OrderAlbumName = cmp.Or(al.OrderAlbumName, strings.ToLower(al.Name)) + gomega.Expect(ds.Album().Put(ctx, &al)).To(gomega.Succeed()) + } +} + +// PutArtists stores copies of artists linked to library libID: no query returns an artist outside +// every library. +func PutArtists(ctx context.Context, ds model.DataStore, libID int, artists ...model.Artist) { + ginkgo.GinkgoHelper() + for _, ar := range artists { + gomega.Expect(ds.Artist().Put(ctx, &ar)).To(gomega.Succeed()) + gomega.Expect(ds.Library().AddArtist(ctx, libID, ar.ID)).To(gomega.Succeed()) + } +} + +// SetArtistStats replaces the per-role stats of artists already linked to library libID. The +// scanner computes them, and role-filtered artist queries skip an artist without them. +func SetArtistStats(ctx context.Context, libID int, stats map[model.Role]model.ArtistStats, artistIDs ...string) { + ginkgo.GinkgoHelper() + if len(artistIDs) == 0 { + return + } + counters := make(map[string]map[string]int64, len(stats)) + for role, s := range stats { + counters[role.String()] = map[string]int64{"m": int64(s.SongCount), "a": int64(s.AlbumCount), "s": s.Size} + } + js, err := json.Marshal(counters) + gomega.Expect(err).ToNot(gomega.HaveOccurred()) + args := []any{string(js), libID} + for _, id := range artistIDs { + args = append(args, id) + } + res, err := db.Db().ExecContext(ctx, "UPDATE library_artist SET stats = ? WHERE library_id = ? AND artist_id IN (?"+ + strings.Repeat(",?", len(artistIDs)-1)+")", args...) + gomega.Expect(err).ToNot(gomega.HaveOccurred()) + gomega.Expect(res.RowsAffected()).To(gomega.BeEquivalentTo(len(artistIDs)), "artists not linked to library %d", libID) +} diff --git a/persistence/user_repository_test.go b/persistence/user_repository_test.go index b6052a520..5579da9e6 100644 --- a/persistence/user_repository_test.go +++ b/persistence/user_repository_test.go @@ -13,7 +13,6 @@ import ( "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/id" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -284,13 +283,13 @@ var _ = Describe("UserRepository", func() { }) Describe("validateUsernameUnique", func() { - var repo *tests.MockedUserRepo var existingUser *model.User BeforeEach(func() { - existingUser = &model.User{ID: "1", UserName: "johndoe"} - repo = tests.CreateMockUserRepo() - err := repo.Put(ctx, existingUser) - Expect(err).ToNot(HaveOccurred()) + existingUser = &model.User{ID: "unique-check-user", UserName: "unique_check_johndoe"} + Expect(repo.Put(ctx, existingUser)).To(Succeed()) + DeferCleanup(func() { + Expect(repo.(*userRepository).Delete(request.WithUser(ctx, adminUser), existingUser.ID)).To(Succeed()) + }) }) It("allows unique usernames", func() { var newUser = &model.User{ID: "2", UserName: "unique_username"} @@ -298,7 +297,7 @@ var _ = Describe("UserRepository", func() { Expect(err).ToNot(HaveOccurred()) }) It("returns ValidationError if username already exists", func() { - var newUser = &model.User{ID: "2", UserName: "johndoe"} + var newUser = &model.User{ID: "2", UserName: "unique_check_johndoe"} err := validateUsernameUnique(ctx, repo, newUser) var verr *rest.ValidationError isValidationError := errors.As(err, &verr) @@ -307,10 +306,10 @@ var _ = Describe("UserRepository", func() { Expect(verr.Errors).To(HaveKeyWithValue("userName", "ra.validation.unique")) }) It("returns generic error if repository call fails", func() { - repo.Error = errors.New("fake error") + failing := &findByUsernameErrorRepo{UserRepository: repo, err: errors.New("fake error")} var newUser = &model.User{ID: "2", UserName: "newuser"} - err := validateUsernameUnique(ctx, repo, newUser) + err := validateUsernameUnique(ctx, failing, newUser) Expect(err).To(MatchError("fake error")) }) }) @@ -883,3 +882,12 @@ var _ = Describe("UserRepository", func() { }) }) }) + +type findByUsernameErrorRepo struct { + model.UserRepository + err error +} + +func (r *findByUsernameErrorRepo) FindByUsername(context.Context, string) (*model.User, error) { + return nil, r.err +} diff --git a/plugins/host_artwork_test.go b/plugins/host_artwork_test.go index 2e3f75844..3188f8b80 100644 --- a/plugins/host_artwork_test.go +++ b/plugins/host_artwork_test.go @@ -14,7 +14,6 @@ import ( "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -50,23 +49,14 @@ var _ = Describe("ArtworkService", Ordered, func() { c.Plugins.AutoReload = false }) - // Initialize auth (required for token generation) - ds := &tests.MockDataStore{MockedProperty: &tests.MockedPropertyRepo{}} - auth.Init(ds) - - // Setup mock DataStore with pre-enabled plugin - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-artwork", Path: destPath, SHA256: hashHex, Enabled: true, - }}) - dataStore := &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedPlugin: mockPluginRepo, - } + }) + // Initialize auth (required for token generation) + auth.Init(dataStore) // Create and start manager manager = &Manager{ diff --git a/plugins/host_cache_test.go b/plugins/host_cache_test.go index 20c490a40..e8e758494 100644 --- a/plugins/host_cache_test.go +++ b/plugins/host_cache_test.go @@ -15,7 +15,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -347,16 +346,12 @@ var _ = Describe("CacheService Integration", Ordered, func() { c.Plugins.AutoReload = false }) - // Setup mock DataStore with pre-enabled plugin - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-cache-plugin", Path: destPath, SHA256: hashHex, Enabled: true, - }}) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + }) // Create and start manager manager = &Manager{ diff --git a/plugins/host_config_test.go b/plugins/host_config_test.go index bd81b5cd4..2a8209bf4 100644 --- a/plugins/host_config_test.go +++ b/plugins/host_config_test.go @@ -12,7 +12,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -59,18 +58,14 @@ func setupTestConfigPlugin(configJSON string) (*Manager, func(context.Context, t c.Plugins.AutoReload = false }) - // Setup mock DataStore - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-config", Path: destPath, SHA256: hashHex, Enabled: true, AllUsers: true, Config: configJSON, - }}) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + }) // Create and start manager manager := &Manager{ diff --git a/plugins/host_kvstore_test.go b/plugins/host_kvstore_test.go index ec795ad88..4dc48b093 100644 --- a/plugins/host_kvstore_test.go +++ b/plugins/host_kvstore_test.go @@ -14,7 +14,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -704,16 +703,12 @@ var _ = Describe("KVStoreService Integration", Ordered, func() { c.DataFolder = conf.NewDir(tmpDir) }) - // Setup mock DataStore with pre-enabled plugin - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-kvstore", Path: destPath, SHA256: hashHex, Enabled: true, - }}) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + }) // Create and start manager manager = &Manager{ diff --git a/plugins/host_library_test.go b/plugins/host_library_test.go index 5df64c33d..5b5354a8b 100644 --- a/plugins/host_library_test.go +++ b/plugins/host_library_test.go @@ -12,12 +12,11 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("LibraryService", Ordered, func() { +var _ = Describe("LibraryService", func() { var ( ctx context.Context ds model.DataStore @@ -27,7 +26,7 @@ var _ = Describe("LibraryService", Ordered, func() { BeforeEach(func() { ctx = GinkgoT().Context() DeferCleanup(conf.SnapshotConfig()) - ds = &tests.MockDataStore{} + ds = newTestDataStore() }) Describe("GetLibrary", func() { @@ -46,8 +45,7 @@ var _ = Describe("LibraryService", Ordered, func() { } lib.LastScanAt = lib.LastScanAt.Add(0) // Ensure time is set - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(model.Libraries{*lib}) + putLibraries(ds, *lib) result, err := service.GetLibrary(ctx, 1) Expect(err).ToNot(HaveOccurred()) @@ -76,8 +74,7 @@ var _ = Describe("LibraryService", Ordered, func() { TotalDuration: 1800.0, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(model.Libraries{*lib}) + putLibraries(ds, *lib) result, err := service.GetLibrary(ctx, 2) Expect(err).ToNot(HaveOccurred()) @@ -90,9 +87,6 @@ var _ = Describe("LibraryService", Ordered, func() { It("should return error for non-existent library", func() { service = newLibraryService(ds, &LibraryPermission{Reason: new("test")}, newLibraryAccess(nil, true)).(*libraryServiceImpl) - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(model.Libraries{}) - _, err := service.GetLibrary(ctx, 999) Expect(err).To(HaveOccurred()) Expect(err.Error()).To(ContainSubstring("library not found")) @@ -108,8 +102,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 2, Name: "Jazz", Path: "/music/jazz", TotalSongs: 50}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) results, err := service.GetAllLibraries(ctx) Expect(err).ToNot(HaveOccurred()) @@ -130,8 +123,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 2, Name: "Jazz", Path: "/music/jazz", TotalSongs: 50}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) results, err := service.GetAllLibraries(ctx) Expect(err).ToNot(HaveOccurred()) @@ -153,8 +145,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 3, Name: "Classical", Path: "/music/classical", TotalSongs: 75}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) results, err := service.GetAllLibraries(ctx) Expect(err).ToNot(HaveOccurred()) @@ -171,8 +162,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 2, Name: "Jazz", Path: "/music/jazz", TotalSongs: 50}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) // Requesting library 1 which is not in the allowed list _, err := service.GetLibrary(ctx, 1) @@ -188,8 +178,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 2, Name: "Jazz", Path: "/music/jazz", TotalSongs: 50}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) result, err := service.GetLibrary(ctx, 2) Expect(err).ToNot(HaveOccurred()) @@ -205,8 +194,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 2, Name: "Jazz", Path: "/music/jazz", TotalSongs: 50}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) results, err := service.GetAllLibraries(ctx) Expect(err).ToNot(HaveOccurred()) @@ -221,8 +209,7 @@ var _ = Describe("LibraryService", Ordered, func() { {ID: 2, Name: "Jazz", Path: "/music/jazz", TotalSongs: 50}, } - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(libs) + putLibraries(ds, libs...) results, err := service.GetAllLibraries(ctx) Expect(err).ToNot(HaveOccurred()) @@ -231,49 +218,6 @@ var _ = Describe("LibraryService", Ordered, func() { }) Describe("Plugin Integration", func() { - var ( - manager *Manager - tmpDir string - ) - - BeforeEach(func() { - var err error - tmpDir, err = os.MkdirTemp("", "library-test-*") - Expect(err).ToNot(HaveOccurred()) - - // Note: Since we don't have WASM test plugins yet, we can test - // the service registration and configuration without full plugin execution - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { - c.Plugins.Enabled = true - c.Plugins.Folder = conf.NewDir(tmpDir) - }) - - // Create mock &tests.MockLibraryRepo{} - mockLibRepo := &tests.MockLibraryRepo{} - mockLibRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test", Path: "/tmp/test-music", TotalSongs: 10}, - }) - - ds := &tests.MockDataStore{ - MockedProperty: &tests.MockedPropertyRepo{}, - MockedPlugin: tests.CreateMockPluginRepo(), - MockedLibrary: mockLibRepo, - } - - manager = &Manager{ - plugins: make(map[string]*plugin), - ds: ds, - } - - DeferCleanup(func() { - if manager != nil { - _ = manager.Stop() - } - _ = os.RemoveAll(tmpDir) - }) - }) - It("should register library service in hostServices table", func() { // Verify the library service is in the hostServices table found := false @@ -285,21 +229,6 @@ var _ = Describe("LibraryService", Ordered, func() { } Expect(found).To(BeTrue(), "Library service should be registered in hostServices") }) - - It("should configure AllowedPaths when filesystem permission is granted", func() { - // This test verifies the AllowedPaths configuration logic - // We can't fully test without a real WASM plugin, but we can verify the setup - Expect(manager.ds).ToNot(BeNil()) - - libs, err := manager.ds.Library().GetAll(adminContext(ctx)) - Expect(err).ToNot(HaveOccurred()) - Expect(libs).To(HaveLen(1)) - Expect(libs[0].Path).To(Equal("/tmp/test-music")) - - // Verify mount point format - mountPoint := "/libraries/1" - Expect(mountPoint).To(MatchRegexp(`^/libraries/\d+$`)) - }) }) }) @@ -345,20 +274,16 @@ var _ = Describe("LibraryService Integration", Ordered, func() { c.Plugins.AutoReload = false }) - // Setup mock DataStore with pre-enabled plugin and library - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-library", Path: destPath, SHA256: hashHex, Enabled: true, AllLibraries: true, // Grant access to all libraries for testing - }}) + }) - mockLibraryRepo := &tests.MockLibraryRepo{} - mockLibraryRepo.SetData(model.Libraries{ - { + putLibraries(dataStore, + model.Library{ ID: 1, Name: "Test Library", Path: libraryDir, @@ -368,7 +293,7 @@ var _ = Describe("LibraryService Integration", Ordered, func() { TotalSize: 1024000, TotalDuration: 3600.5, }, - { + model.Library{ ID: 2, Name: "Jazz Collection", Path: "/nonexistent/jazz", @@ -378,12 +303,7 @@ var _ = Describe("LibraryService Integration", Ordered, func() { TotalSize: 512000, TotalDuration: 1800.0, }, - }) - - dataStore := &tests.MockDataStore{ - MockedPlugin: mockPluginRepo, - MockedLibrary: mockLibraryRepo, - } + ) // Create and start manager manager = &Manager{ diff --git a/plugins/host_matcher_test.go b/plugins/host_matcher_test.go index 2f0c6de95..928c1642a 100644 --- a/plugins/host_matcher_test.go +++ b/plugins/host_matcher_test.go @@ -14,14 +14,14 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/plugins/host" "github.com/navidrome/navidrome/plugins/types" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("MatcherService", Ordered, func() { +var _ = Describe("MatcherService", func() { BeforeEach(func() { DeferCleanup(conf.SnapshotConfig()) }) @@ -142,10 +142,13 @@ var _ = Describe("MatcherService", Ordered, func() { }) Describe("MatchSongs", func() { - // The mock MediaFileRepo returns stored files (with annotations) verbatim, - // ignoring QueryOptions and the context user. These tests therefore cover the - // adapter's gating/access logic, not the SQL per-user join (a persistence-layer - // concern). + var ctx context.Context + var ds model.DataStore + + BeforeEach(func() { + ctx = GinkgoT().Context() + ds = newTestDataStore() + }) // allowAll returns a service permitted to match as any user across all // libraries. @@ -154,14 +157,9 @@ var _ = Describe("MatcherService", Ordered, func() { } It("returns one entry per input song in order, with nil for no-match", func() { - mediaFileRepo := tests.CreateMockMediaFileRepo() - // First (ID) phase returns the match for input song 0 only. - mediaFileRepo.SetData(model.MediaFiles{ - {ID: "mf-100", Title: "Hit", Artist: "Band"}, - }) - ds := &tests.MockDataStore{MockedMediaFile: mediaFileRepo} + putMatcherTracks(ctx, ds, model.MediaFile{ID: "mf-100", Title: "Hit", Artist: "Band"}) - results, err := allowAll(ds).MatchSongs(GinkgoT().Context(), []types.SongRef{ + results, err := allowAll(ds).MatchSongs(ctx, []types.SongRef{ {ID: "mf-100", Name: "Hit", Artist: "Band"}, {ID: "missing-id", Name: "Ghost", Artist: "Nobody"}, }, host.MatchOptions{}) @@ -174,34 +172,27 @@ var _ = Describe("MatcherService", Ordered, func() { }) It("returns an empty slice for empty input", func() { - ds := &tests.MockDataStore{MockedMediaFile: tests.CreateMockMediaFileRepo()} - results, err := allowAll(ds).MatchSongs(GinkgoT().Context(), nil, host.MatchOptions{}) + results, err := allowAll(ds).MatchSongs(ctx, nil, host.MatchOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(results).To(BeEmpty()) }) Context("with a scoped user", func() { - var ds *tests.MockDataStore - var userRepo *tests.MockedUserRepo + alice := model.User{ID: "u-alice", UserName: "alice"} + // caller has library access but no annotations, so a match run as caller is observable + caller := model.User{ID: "u-caller", UserName: "caller"} BeforeEach(func() { - mediaFileRepo := tests.CreateMockMediaFileRepo() - mf := model.MediaFile{ID: "mf-1", Title: "Hit", Artist: "Band", LibraryID: 1, - Starred: true, - Rating: 5} - mediaFileRepo.SetData(model.MediaFiles{mf}) - - userRepo = tests.CreateMockUserRepo() - Expect(userRepo.Put(GinkgoT().Context(), &model.User{ID: "u-alice", UserName: "alice"})).To(Succeed()) - - ds = &tests.MockDataStore{MockedMediaFile: mediaFileRepo, MockedUser: userRepo} + putUsers(ds, alice, caller) + putMatcherTracks(request.WithUser(ctx, alice), ds, model.MediaFile{ID: "mf-1", Title: "Hit", Artist: "Band", + LibraryID: 1, Starred: true, Rating: 5}) }) input := []types.SongRef{{ID: "mf-1", Name: "Hit", Artist: "Band"}} It("does not expose annotations when no username is given", func() { svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - results, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{}) + results, err := svc.MatchSongs(ctx, input, host.MatchOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(results[0]).ToNot(BeNil()) Expect(results[0].Starred).To(BeFalse()) @@ -210,7 +201,7 @@ var _ = Describe("MatcherService", Ordered, func() { It("exposes the user's annotations when an allowed username is given", func() { svc := newMatcherService(ds, false, newUserAccess([]string{"u-alice"}, false), newLibraryAccess(nil, true)) - results, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "alice"}) + results, err := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "alice"}) Expect(err).ToNot(HaveOccurred()) Expect(results[0]).ToNot(BeNil()) Expect(results[0].Starred).To(BeTrue()) @@ -219,28 +210,28 @@ var _ = Describe("MatcherService", Ordered, func() { It("allows any username when allUsers is set", func() { svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - results, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "alice"}) + results, err := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "alice"}) Expect(err).ToNot(HaveOccurred()) Expect(results[0].Starred).To(BeTrue()) }) It("returns an error for an unknown username", func() { svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - _, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "ghost"}) + _, err := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "ghost"}) Expect(err).To(MatchError(ContainSubstring("not found"))) }) It("surfaces a backend error rather than masking it as not-found", func() { - userRepo.Error = errors.New("db is locked") - svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - _, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "alice"}) + failing := failingUsers(ds, errors.New("db is locked")) + svc := newMatcherService(failing, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) + _, err := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "alice"}) Expect(err).To(MatchError(ContainSubstring("db is locked"))) Expect(err.Error()).ToNot(ContainSubstring("not found")) }) It("returns an error for a username the plugin is not allowed to use", func() { svc := newMatcherService(ds, false, newUserAccess([]string{"u-bob"}, false), newLibraryAccess(nil, true)) - _, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "alice"}) + _, err := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "alice"}) Expect(err).To(MatchError(ContainSubstring("not allowed"))) }) @@ -249,8 +240,8 @@ var _ = Describe("MatcherService", Ordered, func() { // be in) must not leak whether a username exists via the error text. svc := newMatcherService(ds, false, newUserAccess(nil, false), newLibraryAccess(nil, true)) - _, errExisting := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "alice"}) - _, errMissing := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{Username: "ghost"}) + _, errExisting := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "alice"}) + _, errMissing := svc.MatchSongs(ctx, input, host.MatchOptions{Username: "ghost"}) Expect(errExisting).To(HaveOccurred()) Expect(errExisting.Error()).To(Equal(errMissing.Error())) @@ -261,43 +252,31 @@ var _ = Describe("MatcherService", Ordered, func() { It("does not inherit the caller's request user for an unscoped match", func() { // The plugin may be invoked while handling another user's request; an // unscoped match must run as admin, not as that inherited user. - capturing := &ctxCapturingDataStore{MockDataStore: ds} - svc := newMatcherService(capturing, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) + Expect(ds.User().SetUserLibraries(ctx, caller.ID, []int{})).To(Succeed()) + svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - callerCtx := request.WithUser(GinkgoT().Context(), model.User{ID: "u-caller", UserName: "caller"}) - _, err := svc.MatchSongs(callerCtx, input, host.MatchOptions{}) + results, err := svc.MatchSongs(request.WithUser(ctx, caller), input, host.MatchOptions{}) Expect(err).ToNot(HaveOccurred()) - - usr, ok := request.UserFrom(capturing.lastMediaFileCtx()) - Expect(ok).To(BeTrue()) - Expect(usr.IsAdmin).To(BeTrue()) - Expect(usr.ID).ToNot(Equal("u-caller")) + Expect(results[0]).ToNot(BeNil(), "the match ran with the caller's library access") }) It("uses the requested user, overriding an inherited caller user", func() { - capturing := &ctxCapturingDataStore{MockDataStore: ds} - svc := newMatcherService(capturing, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) + svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - callerCtx := request.WithUser(GinkgoT().Context(), model.User{ID: "u-caller", UserName: "caller"}) - _, err := svc.MatchSongs(callerCtx, input, host.MatchOptions{Username: "alice"}) + results, err := svc.MatchSongs(request.WithUser(ctx, caller), input, host.MatchOptions{Username: "alice"}) Expect(err).ToNot(HaveOccurred()) - - usr, ok := request.UserFrom(capturing.lastMediaFileCtx()) - Expect(ok).To(BeTrue()) - Expect(usr.ID).To(Equal("u-alice")) + Expect(results[0]).ToNot(BeNil()) + Expect(results[0].Starred).To(BeTrue(), "the match ran with the caller's annotations") }) }) Context("with plugin library access", func() { - var ds *tests.MockDataStore - BeforeEach(func() { - mediaFileRepo := tests.CreateMockMediaFileRepo() - mediaFileRepo.SetData(model.MediaFiles{ - {ID: "mf-lib1", Title: "A", Artist: "Band", LibraryID: 1}, - {ID: "mf-lib2", Title: "B", Artist: "Band", LibraryID: 2}, - }) - ds = &tests.MockDataStore{MockedMediaFile: mediaFileRepo} + putLibraries(ds, model.Library{ID: 2, Name: "Library 2", Path: "/music/lib2"}) + putMatcherTracks(ctx, ds, + model.MediaFile{ID: "mf-lib1", Title: "A", Artist: "Band", LibraryID: 1}, + model.MediaFile{ID: "mf-lib2", Title: "B", Artist: "Band", LibraryID: 2}, + ) }) input := []types.SongRef{ @@ -307,7 +286,7 @@ var _ = Describe("MatcherService", Ordered, func() { It("drops matches from libraries the plugin cannot access", func() { svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess([]int{1}, false)) - results, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{}) + results, err := svc.MatchSongs(ctx, input, host.MatchOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(results[0]).ToNot(BeNil()) Expect(results[0].ID).To(Equal("mf-lib1")) @@ -316,7 +295,7 @@ var _ = Describe("MatcherService", Ordered, func() { It("keeps all matches when allLibraries is set", func() { svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, true)) - results, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{}) + results, err := svc.MatchSongs(ctx, input, host.MatchOptions{}) Expect(err).ToNot(HaveOccurred()) Expect(results[0]).ToNot(BeNil()) Expect(results[1]).ToNot(BeNil()) @@ -324,7 +303,7 @@ var _ = Describe("MatcherService", Ordered, func() { It("errors when the plugin has no library scope configured", func() { svc := newMatcherService(ds, false, newUserAccess(nil, true), newLibraryAccess(nil, false)) - _, err := svc.MatchSongs(GinkgoT().Context(), input, host.MatchOptions{}) + _, err := svc.MatchSongs(ctx, input, host.MatchOptions{}) Expect(err).To(MatchError(ContainSubstring("no libraries configured"))) }) }) @@ -378,31 +357,20 @@ var _ = Describe("MatcherService Integration", Ordered, func() { c.Plugins.AutoReload = false }) - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true // AllLibraries: the matcher requires a library scope. - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-matcher", Path: destPath, SHA256: hashHex, Enabled: true, AllUsers: true, AllLibraries: true, - }}) + }) - mediaFileRepo := tests.CreateMockMediaFileRepo() - hit := model.MediaFile{ID: "mf-hit", Title: "Hit", Artist: "Band", - Starred: true} - mediaFileRepo.SetData(model.MediaFiles{hit}) - - userRepo := tests.CreateMockUserRepo() - Expect(userRepo.Put(GinkgoT().Context(), &model.User{ID: "u-alice", UserName: "alice"})).To(Succeed()) - - dataStore := &tests.MockDataStore{ - MockedPlugin: mockPluginRepo, - MockedMediaFile: mediaFileRepo, - MockedUser: userRepo, - } + alice := model.User{ID: "u-alice", UserName: "alice"} + putUsers(dataStore, alice) + putMatcherTracks(request.WithUser(GinkgoT().Context(), alice), dataStore, + model.MediaFile{ID: "mf-hit", Title: "Hit", Artist: "Band", Starred: true}) manager = &Manager{ plugins: make(map[string]*plugin), @@ -476,38 +444,16 @@ var _ = Describe("MatcherService Integration", Ordered, func() { }) }) -// ctxCapturingDataStore records the context the media file queries run with, so tests -// can assert which user the matcher resolved before querying the library. -type ctxCapturingDataStore struct { - *tests.MockDataStore - repo *ctxCapturingMediaFileRepo -} - -func (d *ctxCapturingDataStore) MediaFile() model.MediaFileRepository { - if d.repo == nil { - d.repo = &ctxCapturingMediaFileRepo{MediaFileRepository: d.MockDataStore.MediaFile()} +// putMatcherTracks stores tracks at distinct paths, saving Starred and Rating as the context user's annotations. +func putMatcherTracks(ctx context.Context, ds model.DataStore, tracks ...model.MediaFile) { + GinkgoHelper() + persistencetest.PutMediaFiles(ctx, ds, tracks...) + for _, mf := range tracks { + if mf.Starred { + Expect(ds.MediaFile().SetStar(ctx, true, mf.ID)).To(Succeed()) + } + if mf.Rating > 0 { + Expect(ds.MediaFile().SetRating(ctx, mf.Rating, mf.ID)).To(Succeed()) + } } - return d.repo -} - -func (d *ctxCapturingDataStore) lastMediaFileCtx() context.Context { - if d.repo == nil { - return nil - } - return d.repo.lastCtx -} - -type ctxCapturingMediaFileRepo struct { - model.MediaFileRepository - lastCtx context.Context -} - -func (r *ctxCapturingMediaFileRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { - r.lastCtx = ctx - return r.MediaFileRepository.GetAll(ctx, options...) -} - -func (r *ctxCapturingMediaFileRepo) GetAllByTags(ctx context.Context, tag model.TagName, values []string, options ...model.QueryOptions) (model.MediaFiles, error) { - r.lastCtx = ctx - return r.MediaFileRepository.GetAllByTags(ctx, tag, values, options...) } diff --git a/plugins/host_scheduler_test.go b/plugins/host_scheduler_test.go index 4c68caba4..57de4bf24 100644 --- a/plugins/host_scheduler_test.go +++ b/plugins/host_scheduler_test.go @@ -13,7 +13,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/scheduler" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -61,16 +60,12 @@ var _ = Describe("SchedulerService", Ordered, func() { origAfterFn = timeAfterFunc timeAfterFunc = mockTimers.AfterFunc - // Setup mock DataStore with pre-enabled plugin - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-scheduler", Path: destPath, SHA256: hashHex, Enabled: true, - }}) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + }) // Create and start manager manager = &Manager{ diff --git a/plugins/host_scrobbleretriever_test.go b/plugins/host_scrobbleretriever_test.go index f1a80cb49..4f5f37e8c 100644 --- a/plugins/host_scrobbleretriever_test.go +++ b/plugins/host_scrobbleretriever_test.go @@ -11,12 +11,9 @@ import ( extism "github.com/extism/go-sdk" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/plugins/host" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -31,7 +28,7 @@ var _ = Describe("Scrobble Retriever Host Function", Ordered, func() { var ( manager *Manager tmpDir string - dataStore *tests.MockDataStore + dataStore model.DataStore ) p := func(val int64) *int64 { @@ -52,13 +49,7 @@ var _ = Describe("Scrobble Retriever Host Function", Ordered, func() { tmpDir, err = os.MkdirTemp("", "scrobble-retriever-test-*") Expect(err).ToNot(HaveOccurred()) - conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") }) - - db.Init(ctx) - DeferCleanup(func() { - Expect(tests.ClearDB(ctx)).To(Succeed()) - }) - dataStore = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + dataStore = newTestDataStore() // Copy test plugin to temp dir srcPath := filepath.Join(testdataDir, "test-scrobble-retriever"+PackageExtension) @@ -116,7 +107,7 @@ var _ = Describe("Scrobble Retriever Host Function", Ordered, func() { router := &fakeSubsonicRouter{} manager.SetSubsonicRouter(router) - // Pre-enable the plugin in the mock repo so it loads on startup + // Pre-enable the plugin in the DB so it loads on startup // Compute SHA256 of the plugin file to match what syncPlugins will compute pluginPath := filepath.Join(tmpDir, "test-scrobble-retriever"+PackageExtension) wasmData, err := os.ReadFile(pluginPath) @@ -124,18 +115,13 @@ var _ = Describe("Scrobble Retriever Host Function", Ordered, func() { hash := sha256.Sum256(wasmData) hashHex := hex.EncodeToString(hash[:]) - dataStore.MockedPlugin = tests.CreateMockPluginRepo() - - mockPluginRepo := dataStore.Plugin().(*tests.MockPluginRepo) - mockPluginRepo.Permitted = true - enabledPlugin := model.Plugin{ + newTestDataStore(model.Plugin{ ID: "test-scrobble-retriever", Path: pluginPath, SHA256: hashHex, Enabled: true, Users: `["user1","admin1"]`, - } - mockPluginRepo.SetData(model.Plugins{enabledPlugin}) + }) // Start the manager err = manager.Start(GinkgoT().Context()) diff --git a/plugins/host_storage_test.go b/plugins/host_storage_test.go index e7cfc7315..a1ef3b0dd 100644 --- a/plugins/host_storage_test.go +++ b/plugins/host_storage_test.go @@ -10,7 +10,6 @@ import ( extism "github.com/extism/go-sdk" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -71,21 +70,6 @@ var _ = Describe("Storage Host Function", Ordered, func() { tmpDir, err = os.MkdirTemp("", "storage-test-*") Expect(err).ToNot(HaveOccurred()) - // Setup mock router and data store - router := &fakeSubsonicRouter{} - userRepo := tests.CreateMockUserRepo() - dataStore := &tests.MockDataStore{MockedUser: userRepo} - - // Create and configure manager - manager = &Manager{ - plugins: make(map[string]*plugin), - ds: dataStore, - } - manager.SetSubsonicRouter(router) - - mockPluginRepo := dataStore.Plugin().(*tests.MockPluginRepo) - mockPluginRepo.Permitted = true - // Setup config DeferCleanup(conf.SnapshotConfig()) conf.Update(func(c *conf.Options) { @@ -108,7 +92,7 @@ var _ = Describe("Storage Host Function", Ordered, func() { err = os.WriteFile(destPath, data, 0600) Expect(err).ToNot(HaveOccurred()) - // Pre-enable the plugin in the mock repo so it loads on startup + // Pre-enable the plugin in the DB so it loads on startup // Compute SHA256 of the plugin file to match what syncPlugins will compute pluginPath := filepath.Join(tmpDir, path) wasmData, err := os.ReadFile(pluginPath) @@ -125,7 +109,12 @@ var _ = Describe("Storage Host Function", Ordered, func() { }) } - mockPluginRepo.SetData(plugins) + // Create and configure manager + manager = &Manager{ + plugins: make(map[string]*plugin), + ds: newTestDataStore(plugins...), + } + manager.SetSubsonicRouter(&fakeSubsonicRouter{}) // Start the manager err = manager.Start(GinkgoT().Context()) diff --git a/plugins/host_subsonicapi_test.go b/plugins/host_subsonicapi_test.go index 942e1cfd4..0e94e6a68 100644 --- a/plugins/host_subsonicapi_test.go +++ b/plugins/host_subsonicapi_test.go @@ -12,18 +12,15 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("SubsonicAPI Host Function", Ordered, func() { var ( - manager *Manager - tmpDir string - router *fakeSubsonicRouter - userRepo *tests.MockedUserRepo - dataStore *tests.MockDataStore + manager *Manager + tmpDir string + router *fakeSubsonicRouter ) BeforeAll(func() { @@ -47,31 +44,7 @@ var _ = Describe("SubsonicAPI Host Function", Ordered, func() { c.Plugins.AutoReload = false }) - // Setup mock router and data store - router = &fakeSubsonicRouter{} - userRepo = tests.CreateMockUserRepo() - dataStore = &tests.MockDataStore{MockedUser: userRepo} - - // Add test users - _ = userRepo.Put(GinkgoT().Context(), &model.User{ - ID: "user1", - UserName: "testuser", - IsAdmin: false, - }) - _ = userRepo.Put(GinkgoT().Context(), &model.User{ - ID: "admin1", - UserName: "adminuser", - IsAdmin: true, - }) - - // Create and configure manager - manager = &Manager{ - plugins: make(map[string]*plugin), - ds: dataStore, - } - manager.SetSubsonicRouter(router) - - // Pre-enable the plugin in the mock repo so it loads on startup + // Pre-enable the plugin in the DB so it loads on startup // Compute SHA256 of the plugin file to match what syncPlugins will compute pluginPath := filepath.Join(tmpDir, "test-subsonicapi-plugin"+PackageExtension) wasmData, err := os.ReadFile(pluginPath) @@ -79,16 +52,25 @@ var _ = Describe("SubsonicAPI Host Function", Ordered, func() { hash := sha256.Sum256(wasmData) hashHex := hex.EncodeToString(hash[:]) - mockPluginRepo := dataStore.Plugin().(*tests.MockPluginRepo) - mockPluginRepo.Permitted = true - enabledPlugin := model.Plugin{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-subsonicapi-plugin", Path: pluginPath, SHA256: hashHex, Enabled: true, AllUsers: true, // Allow all users for test plugin + }) + putUsers(dataStore, + model.User{ID: "user1", UserName: "testuser", IsAdmin: false}, + model.User{ID: "admin1", UserName: "adminuser", IsAdmin: true}, + ) + + // Create and configure manager + router = &fakeSubsonicRouter{} + manager = &Manager{ + plugins: make(map[string]*plugin), + ds: dataStore, } - mockPluginRepo.SetData(model.Plugins{enabledPlugin}) + manager.SetSubsonicRouter(router) // Start the manager err = manager.Start(GinkgoT().Context()) @@ -238,31 +220,18 @@ var _ = Describe("SubsonicAPIService", func() { var ( ctx context.Context router *fakeSubsonicRouter - userRepo *tests.MockedUserRepo - dataStore *tests.MockDataStore + dataStore model.DataStore ) BeforeEach(func() { ctx = GinkgoT().Context() router = &fakeSubsonicRouter{} - userRepo = tests.CreateMockUserRepo() - dataStore = &tests.MockDataStore{MockedUser: userRepo} - - _ = userRepo.Put(ctx, &model.User{ - ID: "user1", - UserName: "testuser", - IsAdmin: false, - }) - _ = userRepo.Put(ctx, &model.User{ - ID: "admin1", - UserName: "adminuser", - IsAdmin: true, - }) - _ = userRepo.Put(ctx, &model.User{ - ID: "user2", - UserName: "alloweduser", - IsAdmin: false, - }) + dataStore = newTestDataStore() + putUsers(dataStore, + model.User{ID: "user1", UserName: "testuser", IsAdmin: false}, + model.User{ID: "admin1", UserName: "adminuser", IsAdmin: true}, + model.User{ID: "user2", UserName: "alloweduser", IsAdmin: false}, + ) }) Describe("Permission Enforcement", func() { diff --git a/plugins/host_taskqueue_test.go b/plugins/host_taskqueue_test.go index 68748a74b..c8e459714 100644 --- a/plugins/host_taskqueue_test.go +++ b/plugins/host_taskqueue_test.go @@ -19,7 +19,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/plugins/host" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -847,16 +846,12 @@ var _ = Describe("TaskQueueService Integration", Ordered, func() { c.DataFolder = conf.NewDir(tmpDir) }) - // Setup mock DataStore with pre-enabled plugin - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-taskqueue", Path: destPath, SHA256: hashHex, Enabled: true, - }}) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + }) // Create and start manager manager = &Manager{ diff --git a/plugins/host_users_test.go b/plugins/host_users_test.go index 8441d9cbf..76077980a 100644 --- a/plugins/host_users_test.go +++ b/plugins/host_users_test.go @@ -12,13 +12,13 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/plugins/host" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("UsersService", Ordered, func() { +var _ = Describe("UsersService", func() { var ( ctx context.Context ds model.DataStore @@ -27,33 +27,13 @@ var _ = Describe("UsersService", Ordered, func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = newTestDataStore() }) Describe("GetUsers", func() { - var mockUserRepo *tests.MockedUserRepo - BeforeEach(func() { - mockUserRepo = ds.User().(*tests.MockedUserRepo) // Add test users - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user1", - UserName: "alice", - Name: "Alice Admin", - IsAdmin: true, - }) - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user2", - UserName: "bob", - Name: "Bob User", - IsAdmin: false, - }) - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user3", - UserName: "charlie", - Name: "Charlie User", - IsAdmin: false, - }) + createTestUsers(ds) }) Context("with allUsers=true", func() { @@ -128,8 +108,8 @@ var _ = Describe("UsersService", Ordered, func() { Context("when datastore returns error", func() { BeforeEach(func() { - mockUserRepo.Error = model.ErrNotFound - service = newUsersService(ds, newUserAccess(nil, true)) + failing := failingUsers(ds, errors.New("db is locked")) + service = newUsersService(failing, newUserAccess(nil, true)) }) It("should propagate the error", func() { @@ -140,29 +120,9 @@ var _ = Describe("UsersService", Ordered, func() { }) Describe("GetAdmins", func() { - var mockUserRepo *tests.MockedUserRepo - BeforeEach(func() { - mockUserRepo = ds.User().(*tests.MockedUserRepo) // Add test users - alice is admin, bob and charlie are not - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user1", - UserName: "alice", - Name: "Alice Admin", - IsAdmin: true, - }) - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user2", - UserName: "bob", - Name: "Bob User", - IsAdmin: false, - }) - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user3", - UserName: "charlie", - Name: "Charlie User", - IsAdmin: false, - }) + createTestUsers(ds) }) Context("with allUsers=true", func() { @@ -208,8 +168,8 @@ var _ = Describe("UsersService", Ordered, func() { Context("when datastore returns error", func() { BeforeEach(func() { - mockUserRepo.Error = model.ErrNotFound - service = newUsersService(ds, newUserAccess(nil, true)) + failing := failingUsers(ds, errors.New("db is locked")) + service = newUsersService(failing, newUserAccess(nil, true)) }) It("should propagate the error", func() { @@ -456,26 +416,14 @@ func setupTestUsersPlugin() (*testUsersSetup, error) { }, nil } -// createTestUsers creates standard test users in the mock repo -func createTestUsers(ctx context.Context, mockUserRepo *tests.MockedUserRepo) { - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user1", - UserName: "alice", - Name: "Alice Admin", - IsAdmin: true, - }) - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user2", - UserName: "bob", - Name: "Bob User", - IsAdmin: false, - }) - _ = mockUserRepo.Put(ctx, &model.User{ - ID: "user3", - UserName: "charlie", - Name: "Charlie User", - IsAdmin: false, - }) +// createTestUsers stores the standard test users +func createTestUsers(ds model.DataStore) { + GinkgoHelper() + putUsers(ds, + model.User{ID: "user1", UserName: "alice", Name: "Alice Admin", IsAdmin: true}, + model.User{ID: "user2", UserName: "bob", Name: "Bob User", IsAdmin: false}, + model.User{ID: "user3", UserName: "charlie", Name: "Charlie User", IsAdmin: false}, + ) } // setupTestUsersConfig sets up common plugin configuration @@ -551,25 +499,16 @@ func setupUsersIntegrationManagerWithEnabled(enabled, allUsers bool, allowedUser cleanupConfig := conf.SnapshotConfig() setupTestUsersConfig(setup.tmpDir) - // Setup mock DataStore with plugin and users - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + persistencetest.Reset() + dataStore := newTestDataStore(model.Plugin{ ID: "test-users", Path: setup.destPath, SHA256: setup.hashHex, Enabled: enabled, AllUsers: allUsers, Users: allowedUsers, - }}) - - mockUserRepo := tests.CreateMockUserRepo() - createTestUsers(GinkgoT().Context(), mockUserRepo) - - dataStore := &tests.MockDataStore{ - MockedPlugin: mockPluginRepo, - MockedUser: mockUserRepo, - } + }) + createTestUsers(dataStore) // Create and start manager manager := &Manager{ diff --git a/plugins/host_websocket_test.go b/plugins/host_websocket_test.go index eb046e1c2..3599310e8 100644 --- a/plugins/host_websocket_test.go +++ b/plugins/host_websocket_test.go @@ -16,7 +16,6 @@ import ( "github.com/gorilla/websocket" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -53,16 +52,12 @@ var _ = Describe("WebSocketService", Ordered, func() { c.Plugins.AutoReload = false }) - // Setup mock DataStore with pre-enabled plugin - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(model.Plugins{{ + dataStore := newTestDataStore(model.Plugin{ ID: "test-websocket", Path: destPath, SHA256: hashHex, Enabled: true, - }}) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + }) // Create and start manager manager = &Manager{ diff --git a/plugins/manager_loader_load_test.go b/plugins/manager_loader_load_test.go index 0ce07ec88..685f23e1d 100644 --- a/plugins/manager_loader_load_test.go +++ b/plugins/manager_loader_load_test.go @@ -9,7 +9,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -36,17 +35,15 @@ var _ = Describe("loadPluginWithConfig", func() { c.DataFolder = conf.NewDir(dataDir) }) - repo := tests.CreateMockPluginRepo() - repo.Permitted = true - repo.SetData(model.Plugins{{ + ds := newTestDataStore(model.Plugin{ ID: "test-taskqueue", Path: dest, SHA256: hex.EncodeToString(hash[:]), Enabled: false, - }}) + }) manager = &Manager{ plugins: make(map[string]*plugin), - ds: &tests.MockDataStore{MockedPlugin: repo}, + ds: ds, metrics: noopMetricsRecorder{}, subsonicRouter: http.NotFoundHandler(), } diff --git a/plugins/manager_readonly_test.go b/plugins/manager_readonly_test.go index 24d0e6339..64049f5bb 100644 --- a/plugins/manager_readonly_test.go +++ b/plugins/manager_readonly_test.go @@ -7,7 +7,6 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -16,7 +15,7 @@ var _ = Describe("Manager.LoadPlugins", func() { var ( ctx context.Context mgr *Manager - repo *tests.MockPluginRepo + repo model.PluginRepository tmpDir string ) @@ -45,12 +44,11 @@ var _ = Describe("Manager.LoadPlugins", func() { rows[i].AllUsers = true } } - repo = tests.CreateMockPluginRepo() - repo.Permitted = true - repo.SetData(rows) + ds := newTestDataStore(rows...) + repo = ds.Plugin() m := &Manager{ plugins: make(map[string]*plugin), - ds: &tests.MockDataStore{MockedPlugin: repo}, + ds: ds, metrics: noopMetricsRecorder{}, } DeferCleanup(func() { _ = m.Stop() }) @@ -78,7 +76,7 @@ var _ = Describe("Manager.LoadPlugins", func() { Expect(mgr.LoadPlugins(ctx, []string{"test-metadata-agent", "broken"}, false)).To(Succeed()) - stored, err := repo.Get(ctx, "broken") + stored, err := repo.Get(adminContext(ctx), "broken") Expect(err).ToNot(HaveOccurred()) Expect(stored.Enabled).To(BeTrue(), "inspecting a plugin must never disable it") Expect(stored.LastError).To(BeEmpty()) @@ -91,7 +89,7 @@ var _ = Describe("Manager.LoadPlugins", func() { Expect(mgr.loadEnabledPlugins(ctx)).To(Succeed()) - stored, err := repo.Get(ctx, "broken") + stored, err := repo.Get(adminContext(ctx), "broken") Expect(err).ToNot(HaveOccurred()) Expect(stored.Enabled).To(BeFalse()) Expect(stored.LastError).ToNot(BeEmpty()) diff --git a/plugins/manager_sync_test.go b/plugins/manager_sync_test.go index 2e9ca6012..c7bf6caf2 100644 --- a/plugins/manager_sync_test.go +++ b/plugins/manager_sync_test.go @@ -7,7 +7,6 @@ import ( "github.com/navidrome/navidrome/core/scrobbler" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -15,15 +14,15 @@ import ( var _ = Describe("syncPlugins", func() { var ctx context.Context var m *Manager - var repo *tests.MockPluginRepo + var repo model.PluginRepository var folder string BeforeEach(func() { - ctx = GinkgoT().Context() + ctx = adminContext(GinkgoT().Context()) folder = GinkgoT().TempDir() - repo = tests.CreateMockPluginRepo() - repo.SetData(model.Plugins{}) - m = &Manager{ds: &tests.MockDataStore{MockedPlugin: repo}} + ds := newTestDataStore() + repo = ds.Plugin() + m = &Manager{ds: ds} }) writePackage := func(name string) { @@ -56,25 +55,28 @@ var _ = Describe("syncPlugins", func() { var _ = Describe("removePluginFromDB", func() { var ctx context.Context + var ds model.DataStore BeforeEach(func() { - ctx = GinkgoT().Context() + ctx = adminContext(GinkgoT().Context()) + ds = newTestDataStore() + putUsers(ds, model.User{ID: "user1", UserName: "user1"}) + for _, id := range []string{"track1", "track2"} { + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: id, Path: id + ".mp3", LibraryID: model.DefaultLibraryID})).To(Succeed()) + } }) It("discards buffered scrobbles for the removed plugin", func() { - buffer := tests.CreateMockedScrobbleBufferRepo() + buffer := ds.ScrobbleBuffer() Expect(buffer.Enqueue(ctx, "my-plugin", "user1", "track1", time.Now())).To(Succeed()) Expect(buffer.Enqueue(ctx, "other-plugin", "user1", "track2", time.Now())).To(Succeed()) - repo := tests.CreateMockPluginRepo() plugin := model.Plugin{ID: "my-plugin", Enabled: false} - repo.SetData(model.Plugins{plugin}) + repo := newTestDataStore(plugin).Plugin() // No broker: sendPluginRefreshEvent is nil-safe, and testBroker is // defined in manager_test.go, which is excluded on Windows. - m := &Manager{ - ds: &tests.MockDataStore{MockedScrobbleBuffer: buffer}, - } + m := &Manager{ds: ds} Expect(m.removePluginFromDB(ctx, repo, &plugin)).To(Succeed()) _, err := repo.Get(ctx, "my-plugin") @@ -90,16 +92,13 @@ var _ = Describe("removePluginFromDB", func() { It("keeps buffered scrobbles of a builtin scrobbler sharing the removed plugin's name", func() { scrobbler.Register("builtin-svc", func(model.DataStore) scrobbler.Scrobbler { return nil }) - buffer := tests.CreateMockedScrobbleBufferRepo() + buffer := ds.ScrobbleBuffer() Expect(buffer.Enqueue(ctx, "builtin-svc", "user1", "track1", time.Now())).To(Succeed()) - repo := tests.CreateMockPluginRepo() plugin := model.Plugin{ID: "builtin-svc", Enabled: false} - repo.SetData(model.Plugins{plugin}) + repo := newTestDataStore(plugin).Plugin() - m := &Manager{ - ds: &tests.MockDataStore{MockedScrobbleBuffer: buffer}, - } + m := &Manager{ds: ds} Expect(m.removePluginFromDB(ctx, repo, &plugin)).To(Succeed()) remaining, err := buffer.Length(ctx) diff --git a/plugins/manager_test.go b/plugins/manager_test.go index 6cf90994a..fb41fd44b 100644 --- a/plugins/manager_test.go +++ b/plugins/manager_test.go @@ -17,6 +17,7 @@ var _ = Describe("Manager", Ordered, func() { BeforeAll(func() { ctx = GinkgoT().Context() + newTestDataStore(testManagerPlugins...) }) Describe("Plugin Loading", func() { diff --git a/plugins/manager_watcher_test.go b/plugins/manager_watcher_test.go index c9b9f1ca7..2ac84693c 100644 --- a/plugins/manager_watcher_test.go +++ b/plugins/manager_watcher_test.go @@ -7,7 +7,6 @@ import ( "path/filepath" "github.com/navidrome/navidrome/conf" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -22,7 +21,7 @@ var _ = Describe("Plugin Watcher", func() { ) BeforeAll(func() { - ctx = GinkgoT().Context() + ctx = adminContext(GinkgoT().Context()) // Create manager for watcher lifecycle tests (no plugin preloaded - tests copy plugin as needed) manager, tmpDir = createTestManager(nil) @@ -132,14 +131,9 @@ var _ = Describe("Plugin Watcher", func() { conf.Update(func(c *conf.Options) { c.Plugins.AutoReload = true }) - // Set up a mock DataStore for the auto-reload manager - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} - autoReloadManager := &Manager{ plugins: make(map[string]*plugin), - ds: dataStore, + ds: newTestDataStore(), subsonicRouter: http.NotFoundHandler(), } err := autoReloadManager.Start(ctx) diff --git a/plugins/plugins_suite_test.go b/plugins/plugins_suite_test.go index 5bd31807f..88e3ef02a 100644 --- a/plugins/plugins_suite_test.go +++ b/plugins/plugins_suite_test.go @@ -14,8 +14,11 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf/configtest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -31,6 +34,8 @@ var ( testdataDir string // Path to testdata folder with test plugin .ndp packages tmpPluginsDir string // Temp directory for plugin tests that modify files testManager *Manager + // testManagerPlugins are testManager's DB rows, for Ordered specs that need them after a reset + testManagerPlugins model.Plugins ) func TestPlugins(t *testing.T) { @@ -44,11 +49,54 @@ func TestPlugins(t *testing.T) { }) // the default evicts the cache mid-run log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Plugins Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() + +// newTestDataStore stores the plugin rows in the real database and returns a DataStore over it. +func newTestDataStore(plugins ...model.Plugin) model.DataStore { + GinkgoHelper() + ds := persistence.New(db.Db()) + ctx := adminContext(GinkgoT().Context()) + for i := range plugins { + Expect(ds.Plugin().Put(ctx, &plugins[i])).To(Succeed()) + } + return ds +} + +// putUsers stores users, giving non-admins access to the libraries marked for new users. +func putUsers(ds model.DataStore, users ...model.User) { + GinkgoHelper() + ctx := GinkgoT().Context() + for i := range users { + Expect(ds.User().Put(ctx, &users[i])).To(Succeed()) + } +} + +// putLibraries stores libs, including library 1's path and the stats columns Put does not write. +func putLibraries(ds model.DataStore, libs ...model.Library) { + GinkgoHelper() + ctx := adminContext(GinkgoT().Context()) + for i := range libs { + lib := libs[i] + if lib.ID == model.DefaultLibraryID { + // Library().Put refuses to change library 1's path; StoreMusicFolder is the only way. + restore := conf.SnapshotConfig() + conf.Update(func(c *conf.Options) { c.MusicFolder = lib.Path }) + Expect(ds.Library().StoreMusicFolder(ctx)).To(Succeed()) + restore() + } + Expect(ds.Library().Put(ctx, &lib)).To(Succeed()) + _, err := db.Db().Exec(`UPDATE library SET total_songs = ?, total_albums = ?, total_artists = ?, + total_size = ?, total_duration = ? WHERE id = ?`, + lib.TotalSongs, lib.TotalAlbums, lib.TotalArtists, lib.TotalSize, lib.TotalDuration, lib.ID) + Expect(err).ToNot(HaveOccurred()) + } +} // stubLocalhostDNS resolves "localhost." without real DNS: the trailing dot never matches /etc/hosts. func stubLocalhostDNS() { @@ -117,11 +165,7 @@ func createTestManagerWithPluginsAndMetrics(pluginConfig map[string]map[string]s c.Plugins.AutoReload = false }) - // Setup mock DataStore with pre-enabled plugins - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(enabledPlugins) - dataStore := &tests.MockDataStore{MockedPlugin: mockPluginRepo} + dataStore := newTestDataStore(enabledPlugins...) // Create and start manager manager := &Manager{ @@ -152,6 +196,9 @@ var _ = SynchronizedBeforeSuite(func() { // Create shared manager for most tests testManager, tmpPluginsDir = createTestManager(nil) + var err error + testManagerPlugins, err = testManager.ds.Plugin().GetAll(adminContext(GinkgoT().Context())) + Expect(err).ToNot(HaveOccurred()) }) var _ = AfterSuite(func() { @@ -167,3 +214,23 @@ var _ = AfterSuite(func() { type noopMetricsRecorder struct{} func (noopMetricsRecorder) RecordPluginRequest(context.Context, string, string, bool, int64) {} + +// failingUsers makes the user lookups host services run fail with err. +func failingUsers(ds model.DataStore, err error) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{User: func(r model.UserRepository) model.UserRepository { + return failingUserRepo{UserRepository: r, err: err} + }}) +} + +type failingUserRepo struct { + model.UserRepository + err error +} + +func (r failingUserRepo) GetAll(context.Context, ...model.QueryOptions) (model.Users, error) { + return nil, r.err +} + +func (r failingUserRepo) FindByUsername(context.Context, string) (*model.User, error) { + return nil, r.err +} diff --git a/plugins/sandbox_fs_test.go b/plugins/sandbox_fs_test.go index d1e44c630..bba566a4a 100644 --- a/plugins/sandbox_fs_test.go +++ b/plugins/sandbox_fs_test.go @@ -8,7 +8,7 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -39,16 +39,13 @@ func startSandboxManager(tmpDir, libraryDir string, grant func(*model.Plugin)) * c.Plugins.AutoReload = false }) - mockPluginRepo := tests.CreateMockPluginRepo() - mockPluginRepo.Permitted = true - mockPluginRepo.SetData(installed) - - mockLibraryRepo := &tests.MockLibraryRepo{} - mockLibraryRepo.SetData(model.Libraries{{ID: 1, Name: "Test Library", Path: libraryDir}}) + persistencetest.Reset() + ds := newTestDataStore(installed...) + putLibraries(ds, model.Library{ID: 1, Name: "Test Library", Path: libraryDir}) manager := &Manager{ plugins: make(map[string]*plugin), - ds: &tests.MockDataStore{MockedPlugin: mockPluginRepo, MockedLibrary: mockLibraryRepo}, + ds: ds, subsonicRouter: http.NotFoundHandler(), } Expect(manager.Start(GinkgoT().Context())).To(Succeed()) diff --git a/scanner/controller_test.go b/scanner/controller_test.go index 0b49f74b9..a249eafb2 100644 --- a/scanner/controller_test.go +++ b/scanner/controller_test.go @@ -2,7 +2,6 @@ package scanner_test import ( "context" - "time" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/artwork" @@ -13,14 +12,13 @@ import ( "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Controller", func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore var ctrl model.Scanner BeforeEach(func() { @@ -29,10 +27,7 @@ var _ = Describe("Controller", func() { Describe("Status", func() { BeforeEach(func() { - db.Init(ctx) - DeferCleanup(func() { Expect(tests.ClearDB(ctx)).To(Succeed()) }) - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} - ds.MockedProperty = &tests.MockedPropertyRepo{} + ds = persistence.New(db.Db()) ctrl = scanner.New(ctx, ds, events.NoopBroker(), playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance()) }) @@ -70,18 +65,20 @@ var _ = Describe("LockForMaintenance", func() { var _ = Describe("EffectiveFullScan", func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + libs := ds.Library() + Expect(libs.Put(ctx, &model.Library{ID: 2, Name: "Library 2", Path: "/music2"})).To(Succeed()) + Expect(libs.Put(ctx, &model.Library{ID: 3, Name: "Library 3", Path: "/music3", PIDAlbum: "folder"})).To(Succeed()) pid := model.Library{}.EffectivePID() - libraries := &tests.MockLibraryRepo{} - libraries.SetData(model.Libraries{ - {ID: 1, FullScanInProgress: true, ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track}, - {ID: 2, ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track}, - {ID: 3, LastScanAt: time.Now(), PIDAlbum: "folder", ScannedPIDAlbum: pid.Album, ScannedPIDTrack: pid.Track}, - }) - ds = &tests.MockDataStore{MockedLibrary: libraries} + for _, id := range []int{1, 2, 3} { + Expect(libs.SetScannedPID(ctx, id, pid)).To(Succeed()) + } + Expect(libs.ScanEnd(ctx, 3)).To(Succeed()) + Expect(libs.ScanBegin(ctx, 1, true)).To(Succeed()) }) It("detects a library that needs a full rescan for a PID change", func() { @@ -106,7 +103,7 @@ var _ = Describe("EffectiveFullScan", func() { var _ = Describe("GetInstance", func() { It("returns the same controller to every caller", func() { - ds := &tests.MockDataStore{} + ds := persistence.New(db.Db()) pls := playlists.NewPlaylists(ds, artwork.NewUploader(ds)) ctx := context.WithoutCancel(GinkgoT().Context()) a := scanner.GetInstance(ctx, ds, events.NoopBroker(), pls, metrics.NewNoopInstance()) diff --git a/scanner/phase_2_missing_tracks_test.go b/scanner/phase_2_missing_tracks_test.go index 808c7d698..b1be4fc05 100644 --- a/scanner/phase_2_missing_tracks_test.go +++ b/scanner/phase_2_missing_tracks_test.go @@ -3,13 +3,16 @@ package scanner import ( "context" "errors" - "maps" "time" + "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -19,17 +22,45 @@ var _ = Describe("phaseMissingTracks", func() { phase *phaseMissingTracks ctx context.Context ds model.DataStore - mr *tests.MockMediaFileRepo - lr *tests.MockLibraryRepo state *scanState ) + // putTracks stores the tracks, in library 1 unless they name another one. + putTracks := func(mfs ...*model.MediaFile) { + GinkgoHelper() + for _, mf := range mfs { + if mf.LibraryID == 0 { + mf.LibraryID = 1 + } + Expect(ds.MediaFile().Put(ctx, mf)).To(Succeed()) + } + } + withStub := func(repos persistencetest.Repos) { + phase = createPhaseMissingTracks(ctx, state, persistencetest.Stub(ds, repos)) + } + albumStarred := func(albumID string) bool { + GinkgoHelper() + var n int + Expect(db.Db().QueryRow("SELECT count(*) FROM annotation WHERE item_type = 'album' AND item_id = ? AND starred", + albumID).Scan(&n)).To(Succeed()) + return n > 0 + } + missingCount := func() int64 { + GinkgoHelper() + n, err := ds.MediaFile().CountAll(ctx, model.QueryOptions{Filters: squirrel.Eq{"missing": true}}) + Expect(err).ToNot(HaveOccurred()) + return n + } + BeforeEach(func() { - ctx = GinkgoT().Context() - mr = tests.CreateMockMediaFileRepo() - lr = &tests.MockLibraryRepo{} - lr.SetData(model.Libraries{{ID: 1, LastScanStartedAt: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}}) - ds = &tests.MockDataStore{MockedMediaFile: mr, MockedLibrary: lr} + // The scanner runs as an admin, which purging missing files requires + admin := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true} + ctx = request.WithUser(GinkgoT().Context(), admin) + ds = persistence.New(db.Db()) + Expect(ds.User().Put(ctx, &admin)).To(Succeed()) + persistencetest.SetLibraries(ctx, ds, conf.Server().MusicFolder, "/lib2", "/lib3") + _, err := db.Db().Exec("UPDATE library SET last_scan_started_at = ? WHERE id = 1", time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) + Expect(err).ToNot(HaveOccurred()) state = &scanState{ libraries: model.Libraries{{ID: 1, LastScanStartedAt: time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)}}, totalLibraryCount: 1, @@ -52,10 +83,10 @@ var _ = Describe("phaseMissingTracks", func() { When("there are no missing tracks", func() { It("should not call put", func() { - mr.SetData(model.MediaFiles{ - {ID: "1", PID: "A", Missing: false}, - {ID: "2", PID: "A", Missing: false}, - }) + putTracks( + &model.MediaFile{ID: "1", PID: "A", Missing: false}, + &model.MediaFile{ID: "2", PID: "A", Missing: false}, + ) err := phase.produce(put) Expect(err).ToNot(HaveOccurred()) @@ -65,11 +96,11 @@ var _ = Describe("phaseMissingTracks", func() { When("there are missing tracks", func() { It("should call put for any missing tracks with corresponding matches", func() { - mr.SetData(model.MediaFiles{ - {ID: "1", PID: "A", Missing: true, LibraryID: 1}, - {ID: "2", PID: "B", Missing: true, LibraryID: 1}, - {ID: "3", PID: "A", Missing: false, LibraryID: 1}, - }) + putTracks( + &model.MediaFile{ID: "1", PID: "A", Missing: true, LibraryID: 1}, + &model.MediaFile{ID: "2", PID: "B", Missing: true, LibraryID: 1}, + &model.MediaFile{ID: "3", PID: "A", Missing: false, LibraryID: 1}, + ) err := phase.produce(put) Expect(err).ToNot(HaveOccurred()) @@ -98,11 +129,11 @@ var _ = Describe("phaseMissingTracks", func() { Expect(pidB.matched).To(BeEmpty()) }) It("should call put for any missing tracks even without matches", func() { - mr.SetData(model.MediaFiles{ - {ID: "1", PID: "A", Missing: true, LibraryID: 1}, - {ID: "2", PID: "B", Missing: true, LibraryID: 1}, - {ID: "3", PID: "C", Missing: false, LibraryID: 1}, - }) + putTracks( + &model.MediaFile{ID: "1", PID: "A", Missing: true, LibraryID: 1}, + &model.MediaFile{ID: "2", PID: "B", Missing: true, LibraryID: 1}, + &model.MediaFile{ID: "3", PID: "C", Missing: false, LibraryID: 1}, + ) err := phase.produce(put) Expect(err).ToNot(HaveOccurred()) @@ -132,8 +163,8 @@ var _ = Describe("phaseMissingTracks", func() { missingTrack := model.MediaFile{ID: "1", PID: "A", Path: "dir1/path1.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} matchedTrack := model.MediaFile{ID: "2", PID: "A", Path: "dir2/path2.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -154,11 +185,10 @@ var _ = Describe("phaseMissingTracks", func() { missingTrack := model.MediaFile{ID: "1", PID: "A", AlbumID: "old-album", Path: "dir1/path1.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} matchedTrack := model.MediaFile{ID: "2", PID: "A", AlbumID: "new-album", Path: "dir2/path2.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} BeforeEach(func() { - probe = &probeTxDS{MockDataStore: ds.(*tests.MockDataStore)} - probe.MockedAlbum = tests.CreateMockAlbumRepo() + probe = &probeTxDS{DataStore: ds} phase = createPhaseMissingTracks(ctx, state, probe) - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) }) It("claims the target album before the transaction, so a concurrent move skips it", func() { @@ -180,19 +210,15 @@ var _ = Describe("phaseMissingTracks", func() { Context("when the move transaction is rerun after a busy rollback", func() { var rerunDS *rerunTxDS BeforeEach(func() { - rerunDS = &rerunTxDS{MockDataStore: ds.(*tests.MockDataStore)} - rerunDS.snapshot = func() func() { - saved := maps.Clone(mr.Data) - return func() { mr.Data = saved } - } + rerunDS = &rerunTxDS{DataStore: ds} phase = createPhaseMissingTracks(ctx, state, rerunDS) }) It("keeps the moved track", func() { missingTrack := model.MediaFile{ID: "1", PID: "A", Path: "dir1/path1.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} matchedTrack := model.MediaFile{ID: "2", PID: "A", Path: "dir2/path2.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) _, err := phase.processMissingTracks(&missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -206,27 +232,19 @@ var _ = Describe("phaseMissingTracks", func() { }) It("reassigns the album annotations in the attempt that commits", func() { - albumRepo := tests.CreateMockAlbumRepo() - rerunDS.MockedAlbum = albumRepo - restoreTracks := rerunDS.snapshot - rerunDS.snapshot = func() func() { - restore := restoreTracks() - return func() { - restore() - albumRepo.ReassignAnnotationCalls = nil - } - } + Expect(ds.Album().SetStar(ctx, true, "old-album")).To(Succeed()) missingTrack := model.MediaFile{ID: "1", PID: "A", AlbumID: "old-album", Path: "dir1/path1.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} matchedTrack := model.MediaFile{ID: "2", PID: "A", AlbumID: "new-album", Path: "dir2/path2.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) _, err := phase.processMissingTracks(&missingTracks{ missing: []model.MediaFile{missingTrack}, matched: []model.MediaFile{matchedTrack}, }) Expect(err).ToNot(HaveOccurred()) - Expect(albumRepo.ReassignAnnotationCalls).To(HaveKeyWithValue("old-album", "new-album")) + Expect(albumStarred("new-album")).To(BeTrue()) + Expect(albumStarred("old-album")).To(BeFalse()) }) }) @@ -234,8 +252,8 @@ var _ = Describe("phaseMissingTracks", func() { missingTrack := model.MediaFile{ID: "1", PID: "A", Path: "path1.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} matchedTrack := model.MediaFile{ID: "2", PID: "A", Path: "path1.flac", Tags: model.Tags{"title": []string{"title1"}}, Size: 200} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -256,8 +274,8 @@ var _ = Describe("phaseMissingTracks", func() { missingTrack := model.MediaFile{ID: "1", PID: "A", Path: "dir1/path1.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} matchedTrack := model.MediaFile{ID: "2", PID: "A", Path: "dir2/path2.flac", Tags: model.Tags{"title": []string{"different title"}}, Size: 200} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -279,9 +297,9 @@ var _ = Describe("phaseMissingTracks", func() { matchedEquivalent := model.MediaFile{ID: "2", PID: "A", Path: "dir1/file1.flac", Tags: model.Tags{"title": []string{"title1"}}, Size: 200} matchedExact := model.MediaFile{ID: "3", PID: "A", Path: "dir2/file2.mp3", Tags: model.Tags{"title": []string{"title1"}}, Size: 100} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedEquivalent) - _ = ds.MediaFile().Put(ctx, &matchedExact) + putTracks(&missingTrack) + putTracks(&matchedEquivalent) + putTracks(&matchedExact) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -304,9 +322,9 @@ var _ = Describe("phaseMissingTracks", func() { matched1 := model.MediaFile{ID: "2", PID: "A", Path: "dir1/file2.flac", Title: "another title", Size: 200} matched2 := model.MediaFile{ID: "3", PID: "A", Path: "dir2/file3.mp3", Title: "different title", Size: 100} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matched1) - _ = ds.MediaFile().Put(ctx, &matched2) + putTracks(&missingTrack) + putTracks(&matched1) + putTracks(&matched2) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -334,9 +352,9 @@ var _ = Describe("phaseMissingTracks", func() { missingTrack2 := model.MediaFile{ID: "2", PID: "A", Path: "old_dir2/song.mp3", Title: "title1", Size: 100} matchedTrack := model.MediaFile{ID: "3", PID: "A", Path: "new_dir/song.mp3", Title: "title1", Size: 200} - _ = ds.MediaFile().Put(ctx, &missingTrack1) - _ = ds.MediaFile().Put(ctx, &missingTrack2) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack1) + putTracks(&missingTrack2) + putTracks(&matchedTrack) in := &missingTracks{ missing: []model.MediaFile{missingTrack1, missingTrack2}, @@ -362,16 +380,15 @@ var _ = Describe("phaseMissingTracks", func() { missingTrack := model.MediaFile{ID: "1", PID: "A", Path: "path1.mp3", Tags: model.Tags{"title": []string{"title1"}}} matchedTrack := model.MediaFile{ID: "2", PID: "A", Path: "path1.mp3", Tags: model.Tags{"title": []string{"title1"}}} - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, matched: []model.MediaFile{matchedTrack}, } - // Simulate an error when moving the matched track by deleting the track from the DB - _ = ds.MediaFile().Delete(ctx, "2") + withStub(failingMediaFiles(errors.New("db error"))) _, err := phase.processMissingTracks(in) Expect(err).To(HaveOccurred()) @@ -395,28 +412,35 @@ var _ = Describe("phaseMissingTracks", func() { When("PurgeMissing is 'always'", func() { BeforeEach(func() { conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingAlways }) - mr.SetCountAll(3) - mr.DeleteAllMissingValue = 3 + putTracks( + &model.MediaFile{ID: "m1", Path: "m1.mp3", Missing: true}, + &model.MediaFile{ID: "m2", Path: "m2.mp3", Missing: true}, + &model.MediaFile{ID: "m3", Path: "m3.mp3", Missing: true}, + ) }) It("should purge missing files", func() { Expect(state.changesDetected.Load()).To(BeFalse()) err := phase.finalize(nil) Expect(err).ToNot(HaveOccurred()) Expect(state.changesDetected.Load()).To(BeTrue()) + Expect(missingCount()).To(BeZero()) }) }) When("PurgeMissing is 'full'", func() { BeforeEach(func() { conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingFull }) - mr.SetCountAll(2) - mr.DeleteAllMissingValue = 2 + putTracks( + &model.MediaFile{ID: "m1", Path: "m1.mp3", Missing: true}, + &model.MediaFile{ID: "m2", Path: "m2.mp3", Missing: true}, + ) }) It("should not purge missing files if not a full scan", func() { state.fullScan = false err := phase.finalize(nil) Expect(err).ToNot(HaveOccurred()) Expect(state.changesDetected.Load()).To(BeFalse()) + Expect(missingCount()).To(Equal(int64(2))) }) It("should purge missing files if full scan", func() { Expect(state.changesDetected.Load()).To(BeFalse()) @@ -424,19 +448,20 @@ var _ = Describe("phaseMissingTracks", func() { err := phase.finalize(nil) Expect(err).ToNot(HaveOccurred()) Expect(state.changesDetected.Load()).To(BeTrue()) + Expect(missingCount()).To(BeZero()) }) }) When("PurgeMissing is 'never'", func() { BeforeEach(func() { conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingNever }) - mr.SetCountAll(1) - mr.DeleteAllMissingValue = 1 + putTracks(&model.MediaFile{ID: "m1", Path: "m1.mp3", Missing: true}) }) It("should not purge missing files", func() { err := phase.finalize(nil) Expect(err).ToNot(HaveOccurred()) Expect(state.changesDetected.Load()).To(BeFalse()) + Expect(missingCount()).To(Equal(int64(1))) }) }) }) @@ -515,8 +540,8 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: scanStartTime.Add(-10 * time.Minute), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &movedTrack) + putTracks(&missingTrack) + putTracks(&movedTrack) in := &missingTracks{ lib: model.Library{ID: 1, Name: "Library 1"}, @@ -567,8 +592,8 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: scanStartTime.Add(-10 * time.Minute), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &movedTrack) + putTracks(&missingTrack) + putTracks(&movedTrack) in := &missingTracks{ lib: model.Library{ID: 1, Name: "Library 1"}, @@ -613,8 +638,8 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: scanStartTime.Add(-10 * time.Minute), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &sameLibTrack) + putTracks(&missingTrack) + putTracks(&sameLibTrack) in := &missingTracks{ lib: model.Library{ID: 1, Name: "Library 1"}, @@ -671,9 +696,9 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: scanStartTime.Add(-5 * time.Minute), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &mbzTrack) - _ = ds.MediaFile().Put(ctx, &intrinsicTrack) + putTracks(&missingTrack) + putTracks(&mbzTrack) + putTracks(&intrinsicTrack) in := &missingTracks{ lib: model.Library{ID: 1, Name: "Library 1"}, @@ -719,8 +744,8 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: scanStartTime.Add(-10 * time.Minute), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &equivalentTrack) + putTracks(&missingTrack) + putTracks(&equivalentTrack) in := &missingTracks{ lib: model.Library{ID: 1, Name: "Library 1"}, @@ -789,9 +814,9 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: scanStartTime.Add(-5 * time.Minute), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &match1) - _ = ds.MediaFile().Put(ctx, &match2) + putTracks(&missingTrack) + putTracks(&match1) + putTracks(&match2) in := &missingTracks{ lib: model.Library{ID: 1, Name: "Library 1"}, @@ -811,8 +836,7 @@ var _ = Describe("phaseMissingTracks", func() { }) It("should handle errors gracefully", func() { - // Set up mock to return error - mr.Err = true + withStub(failingMediaFiles(errors.New("db error"))) missingTrack := model.MediaFile{ ID: "missing7", @@ -842,12 +866,11 @@ var _ = Describe("phaseMissingTracks", func() { }) Describe("CreatedAt preservation (#5050)", func() { - var albumRepo *tests.MockAlbumRepo + var spy *albumSpy BeforeEach(func() { - albumRepo = ds.Album().(*tests.MockAlbumRepo) - albumRepo.ReassignAnnotationCalls = make(map[string]string) - albumRepo.CopyAttributesCalls = make(map[string]string) + spy = &albumSpy{reassigned: map[string]string{}, copied: map[string]string{}} + withStub(spy.repos()) }) It("should preserve the missing track's created_at when moving within a library", func() { @@ -869,8 +892,8 @@ var _ = Describe("phaseMissingTracks", func() { Size: 100, } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) in := &missingTracks{ missing: []model.MediaFile{missingTrack}, @@ -901,13 +924,11 @@ var _ = Describe("phaseMissingTracks", func() { } // Set up albums so CopyAttributes can find them - albumRepo.SetData(model.Albums{ - {ID: "old-album", LibraryID: 1, CreatedAt: originalTime}, - {ID: "new-album", LibraryID: 2, CreatedAt: time.Now()}, - }) + Expect(ds.Album().Put(ctx, &model.Album{ID: "old-album", LibraryID: 1, CreatedAt: originalTime})).To(Succeed()) + Expect(ds.Album().Put(ctx, &model.Album{ID: "new-album", LibraryID: 2, CreatedAt: time.Now()})).To(Succeed()) - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) err := phase.moveMatched(matchedTrack, missingTrack) Expect(err).ToNot(HaveOccurred()) @@ -916,11 +937,8 @@ var _ = Describe("phaseMissingTracks", func() { movedTrack, _ := ds.MediaFile().Get(ctx, "missing-ca") Expect(movedTrack.CreatedAt).To(Equal(originalTime)) - // Album's created_at should be copied from old to new - Expect(albumRepo.CopyAttributesCalls).To(HaveKeyWithValue("old-album", "new-album")) - - // Verify the new album's CreatedAt was actually updated - newAlbum, err := albumRepo.Get(ctx, "new-album") + // Verify the new album's CreatedAt was copied from the old one + newAlbum, err := ds.Album().Get(ctx, "new-album") Expect(err).ToNot(HaveOccurred()) Expect(newAlbum.CreatedAt).To(Equal(originalTime)) }) @@ -940,8 +958,8 @@ var _ = Describe("phaseMissingTracks", func() { CreatedAt: time.Now(), } - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) err := phase.moveMatched(matchedTrack, missingTrack) Expect(err).ToNot(HaveOccurred()) @@ -951,13 +969,13 @@ var _ = Describe("phaseMissingTracks", func() { Expect(movedTrack.CreatedAt).To(Equal(originalTime)) // CopyAttributes should NOT have been called (same album) - Expect(albumRepo.CopyAttributesCalls).To(BeEmpty()) + Expect(spy.copied).To(BeEmpty()) }) }) Describe("Album Annotation Reassignment", func() { var ( - albumRepo *tests.MockAlbumRepo + spy *albumSpy missingTrack model.MediaFile matchedTrack model.MediaFile oldAlbumID string @@ -965,8 +983,8 @@ var _ = Describe("phaseMissingTracks", func() { ) BeforeEach(func() { - albumRepo = ds.Album().(*tests.MockAlbumRepo) - albumRepo.ReassignAnnotationCalls = make(map[string]string) + spy = &albumSpy{reassigned: map[string]string{}, copied: map[string]string{}} + withStub(spy.repos()) oldAlbumID = "old-album-id" newAlbumID = "new-album-id" @@ -996,17 +1014,19 @@ var _ = Describe("phaseMissingTracks", func() { } // Store both tracks in the database - _ = ds.MediaFile().Put(ctx, &missingTrack) - _ = ds.MediaFile().Put(ctx, &matchedTrack) + putTracks(&missingTrack) + putTracks(&matchedTrack) }) When("album ID changes during cross-library move", func() { It("should reassign album annotations when AlbumID changes", func() { + Expect(ds.Album().SetStar(ctx, true, oldAlbumID)).To(Succeed()) + err := phase.moveMatched(matchedTrack, missingTrack) Expect(err).ToNot(HaveOccurred()) - // Verify that ReassignAnnotation was called - Expect(albumRepo.ReassignAnnotationCalls).To(HaveKeyWithValue(oldAlbumID, newAlbumID)) + Expect(albumStarred(newAlbumID)).To(BeTrue()) + Expect(albumStarred(oldAlbumID)).To(BeFalse()) }) It("should not reassign annotations when AlbumID is the same", func() { @@ -1016,14 +1036,14 @@ var _ = Describe("phaseMissingTracks", func() { Expect(err).ToNot(HaveOccurred()) // Verify that ReassignAnnotation was NOT called - Expect(albumRepo.ReassignAnnotationCalls).To(BeEmpty()) + Expect(spy.reassigned).To(BeEmpty()) }) }) When("error handling", func() { It("should handle ReassignAnnotation errors gracefully", func() { // Make the album repo return an error - albumRepo.SetError(true) + spy.err = errors.New("db error") // The move should still succeed even if annotation reassignment fails err := phase.moveMatched(matchedTrack, missingTrack) @@ -1038,33 +1058,98 @@ var _ = Describe("phaseMissingTracks", func() { }) }) -// rerunTxDS runs every WithTxRetry block twice, as a retry after a rolled-back busy attempt would. -// The mock is not transactional, so snapshot returns the function that plays the rollback. +// rerunTxDS runs every WithTxRetry block twice, rolling back the first attempt as a busy retry would. type rerunTxDS struct { - *tests.MockDataStore - snapshot func() (rollback func()) + model.DataStore } -func (d *rerunTxDS) WithTxRetry(ctx context.Context, block func(context.Context, model.DataStore) error, _ ...string) error { - rollback := d.snapshot() - _ = block(ctx, d.MockDataStore) - rollback() - return block(ctx, d.MockDataStore) +func (d *rerunTxDS) WithTxRetry(ctx context.Context, block func(context.Context, model.DataStore) error, label ...string) error { + rolledBack := errors.New("rolled back") + err := d.DataStore.WithTxRetry(ctx, func(ctx context.Context, tx model.DataStore) error { + if err := block(ctx, tx); err != nil { + return err + } + return rolledBack + }, label...) + if !errors.Is(err, rolledBack) { + return err + } + return d.DataStore.WithTxRetry(ctx, block, label...) } // probeTxDS runs a hook inside each WithTxRetry block, and can fail the transaction after it. type probeTxDS struct { - *tests.MockDataStore + model.DataStore during func() err error } -func (d *probeTxDS) WithTxRetry(ctx context.Context, block func(context.Context, model.DataStore) error, _ ...string) error { - if err := block(ctx, d.MockDataStore); err != nil { - return err +func (d *probeTxDS) WithTxRetry(ctx context.Context, block func(context.Context, model.DataStore) error, label ...string) error { + return d.DataStore.WithTxRetry(ctx, func(ctx context.Context, tx model.DataStore) error { + if err := block(ctx, tx); err != nil { + return err + } + if d.during != nil { + d.during() + } + return d.err + }, label...) +} + +// failingMediaFiles fails media file deletes and cross-library match lookups. +func failingMediaFiles(err error) persistencetest.Repos { + return persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return &failingMediaFileRepo{MediaFileRepository: r, err: err} + }} +} + +type failingMediaFileRepo struct { + model.MediaFileRepository + err error +} + +func (r *failingMediaFileRepo) Delete(context.Context, string) error { + return r.err +} + +func (r *failingMediaFileRepo) FindRecentFilesByMBZTrackID(context.Context, model.MediaFile, time.Time) (model.MediaFiles, error) { + return nil, r.err +} + +func (r *failingMediaFileRepo) FindRecentFilesByProperties(context.Context, model.MediaFile, time.Time) (model.MediaFiles, error) { + return nil, r.err +} + +// albumSpy records album annotation reassignments and attribute copies (from -> to), and can fail them. +type albumSpy struct { + reassigned map[string]string + copied map[string]string + err error +} + +func (s *albumSpy) repos() persistencetest.Repos { + return persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return &albumSpyRepo{AlbumRepository: r, spy: s} + }} +} + +type albumSpyRepo struct { + model.AlbumRepository + spy *albumSpy +} + +func (r *albumSpyRepo) ReassignAnnotation(ctx context.Context, prevID, newID string) error { + r.spy.reassigned[prevID] = newID + if r.spy.err != nil { + return r.spy.err } - if d.during != nil { - d.during() + return r.AlbumRepository.ReassignAnnotation(ctx, prevID, newID) +} + +func (r *albumSpyRepo) CopyAttributes(ctx context.Context, fromID, toID string, columns ...string) error { + r.spy.copied[fromID] = toID + if r.spy.err != nil { + return r.spy.err } - return d.err + return r.AlbumRepository.CopyAttributes(ctx, fromID, toID, columns...) } diff --git a/scanner/phase_3_refresh_albums_test.go b/scanner/phase_3_refresh_albums_test.go index 911d5f64a..cc5d8c86b 100644 --- a/scanner/phase_3_refresh_albums_test.go +++ b/scanner/phase_3_refresh_albums_test.go @@ -2,32 +2,29 @@ package scanner import ( "context" + "errors" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("phaseRefreshAlbums", func() { var ( - phase *phaseRefreshAlbums - ctx context.Context - albumRepo *tests.MockAlbumRepo - mfRepo *tests.MockMediaFileRepo - ds *tests.MockDataStore - libs model.Libraries - state *scanState + phase *phaseRefreshAlbums + ctx context.Context + ds model.DataStore + libs model.Libraries + state *scanState ) BeforeEach(func() { ctx = GinkgoT().Context() - albumRepo = tests.CreateMockAlbumRepo() - mfRepo = tests.CreateMockMediaFileRepo() - ds = &tests.MockDataStore{ - MockedAlbum: albumRepo, - MockedMediaFile: mfRepo, - } + ds = persistence.New(db.Db()) + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Library 2", Path: "/music2"})).To(Succeed()) libs = model.Libraries{ {ID: 1, Name: "Library 1"}, {ID: 2, Name: "Library 2"}, @@ -44,9 +41,9 @@ var _ = Describe("phaseRefreshAlbums", func() { Describe("producer", func() { It("produces albums that need refreshing", func() { - albumRepo.SetData(model.Albums{ - {LibraryID: 1, ID: "album1", Name: "Album 1"}, - }) + Expect(ds.Album().Put(ctx, &model.Album{LibraryID: 2, ID: "album2", Name: "Album 2"})).To(Succeed()) + Expect(ds.Library().ScanEnd(ctx, 2)).To(Succeed()) + Expect(ds.Album().Put(ctx, &model.Album{LibraryID: 1, ID: "album1", Name: "Album 1"})).To(Succeed()) var produced []*model.Album err := phase.produce(func(album *model.Album) { @@ -59,9 +56,7 @@ var _ = Describe("phaseRefreshAlbums", func() { }) It("returns an error if there is an error loading albums", func() { - albumRepo.SetData(model.Albums{ - {ID: "error"}, - }) + phase = createPhaseRefreshAlbums(ctx, state, withFailingAlbums(ds, errors.New("db error"))) err := phase.produce(func(album *model.Album) {}) @@ -71,11 +66,10 @@ var _ = Describe("phaseRefreshAlbums", func() { Describe("filterUnmodified", func() { It("filters out unmodified albums", func() { - album := &model.Album{ID: "album1", Name: "Album 1", SongCount: 1, + album := &model.Album{ID: "album1", Name: "Album 1", SongCount: 1, LibraryID: 1, FolderIDs: []string{"folder1"}, Discs: model.Discs{1: ""}} - mfRepo.SetData(model.MediaFiles{ - {AlbumID: "album1", Title: "Song 1", Album: "Album 1", FolderID: "folder1"}, - }) + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: "mf1", LibraryID: 1, AlbumID: "album1", + Title: "Song 1", Album: "Album 1", FolderID: "folder1"})).To(Succeed()) result, err := phase.filterUnmodified(album) Expect(err).ToNot(HaveOccurred()) @@ -83,9 +77,8 @@ var _ = Describe("phaseRefreshAlbums", func() { }) It("keep modified albums", func() { album := &model.Album{ID: "album1", Name: "Album 1"} - mfRepo.SetData(model.MediaFiles{ - {AlbumID: "album1", Title: "Song 1", Album: "Album 2"}, - }) + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: "mf1", LibraryID: 1, AlbumID: "album1", + Title: "Song 1", Album: "Album 2"})).To(Succeed()) result, err := phase.filterUnmodified(album) Expect(err).ToNot(HaveOccurred()) @@ -94,7 +87,6 @@ var _ = Describe("phaseRefreshAlbums", func() { }) It("skips albums with no media files", func() { album := &model.Album{ID: "album1", Name: "Album 1"} - mfRepo.SetData(model.MediaFiles{}) result, err := phase.filterUnmodified(album) Expect(err).ToNot(HaveOccurred()) @@ -104,26 +96,26 @@ var _ = Describe("phaseRefreshAlbums", func() { Describe("refreshAlbum", func() { It("refreshes the album in the database", func() { - Expect(albumRepo.CountAll(ctx)).To(Equal(int64(0))) + Expect(ds.Album().CountAll(ctx)).To(Equal(int64(0))) - album := &model.Album{ID: "album1", Name: "Album 1"} + album := &model.Album{ID: "album1", Name: "Album 1", LibraryID: 1} result, err := phase.refreshAlbum(album) Expect(err).ToNot(HaveOccurred()) Expect(result).ToNot(BeNil()) Expect(result.ID).To(Equal("album1")) - savedAlbum, err := albumRepo.Get(ctx, "album1") + savedAlbum, err := ds.Album().Get(ctx, "album1") Expect(err).ToNot(HaveOccurred()) Expect(savedAlbum).ToNot(BeNil()) - Expect(savedAlbum.ID).To(Equal("album1")) + Expect(savedAlbum.Name).To(Equal("Album 1")) Expect(phase.refreshed.Load()).To(Equal(uint32(1))) Expect(state.changesDetected.Load()).To(BeTrue()) }) It("returns an error if there is an error refreshing the album", func() { - album := &model.Album{ID: "album1", Name: "Album 1"} - albumRepo.SetError(true) + phase = createPhaseRefreshAlbums(ctx, state, withFailingAlbums(ds, errors.New("db error"))) + album := &model.Album{ID: "album1", Name: "Album 1", LibraryID: 1} result, err := phase.refreshAlbum(album) Expect(result).To(BeNil()) @@ -133,3 +125,23 @@ var _ = Describe("phaseRefreshAlbums", func() { }) }) }) + +// withFailingAlbums fails reading touched albums and saving albums. +func withFailingAlbums(ds model.DataStore, err error) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return &failingAlbumRepo{AlbumRepository: r, err: err} + }}) +} + +type failingAlbumRepo struct { + model.AlbumRepository + err error +} + +func (r *failingAlbumRepo) GetTouchedAlbums(context.Context, int) (model.AlbumCursor, error) { + return nil, r.err +} + +func (r *failingAlbumRepo) Put(context.Context, *model.Album) error { + return r.err +} diff --git a/scanner/phase_4_playlists_test.go b/scanner/phase_4_playlists_test.go index fa9df3602..584f57d6d 100644 --- a/scanner/phase_4_playlists_test.go +++ b/scanner/phase_4_playlists_test.go @@ -10,7 +10,11 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -19,30 +23,37 @@ import ( var _ = Describe("phasePlaylists", func() { var ( - phase *phasePlaylists - ctx context.Context - state *scanState - folderRepo *mockFolderRepository - ds *tests.MockDataStore - pls *mockPlaylists + phase *phasePlaylists + ctx context.Context + state *scanState + ds model.DataStore + pls *mockPlaylists ) - var userRepo *tests.MockedUserRepo - var propRepo *tests.MockedPropertyRepo + putPlaylistFolders := func(paths ...string) { + GinkgoHelper() + lib, err := ds.Library().Get(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + for _, path := range paths { + f := model.NewFolder(*lib, path) + f.NumPlaylists = 1 + Expect(ds.Folder().Put(ctx, f)).To(Succeed()) + } + } + removeAdmin := func() { + GinkgoHelper() + Expect(ds.User().Delete(request.WithUser(ctx, model.User{IsAdmin: true}), "123")).To(Succeed()) + } + withStub := func(repos persistencetest.Repos) { + phase = createPhasePlaylists(ctx, state, persistencetest.Stub(ds, repos), pls) + } BeforeEach(func() { ctx = GinkgoT().Context() conf.Update(func(c *conf.Options) { c.AutoImportPlaylists = true }) - folderRepo = &mockFolderRepository{} - userRepo = tests.CreateMockUserRepo() + ds = persistence.New(db.Db()) // An admin user exists by default, so playlist import proceeds. - Expect(userRepo.Put(ctx, &model.User{ID: "123", UserName: "admin", IsAdmin: true})).To(Succeed()) - propRepo = &tests.MockedPropertyRepo{} - ds = &tests.MockDataStore{ - MockedFolder: folderRepo, - MockedUser: userRepo, - MockedProperty: propRepo, - } + Expect(ds.User().Put(ctx, &model.User{ID: "123", UserName: "admin", IsAdmin: true})).To(Succeed()) pls = &mockPlaylists{} state = &scanState{} phase = createPhasePlaylists(ctx, state, ds, pls) @@ -56,29 +67,31 @@ var _ = Describe("phasePlaylists", func() { Describe("producer", func() { It("produces folders with playlists", func() { - folderRepo.SetData(map[*model.Folder]error{ - {Path: "/path/to/folder1"}: nil, - {Path: "/path/to/folder2"}: nil, - }) + putPlaylistFolders("path/to/folder1", "path/to/folder2") + lib, err := ds.Library().Get(ctx, model.DefaultLibraryID) + Expect(err).ToNot(HaveOccurred()) + Expect(ds.Folder().Put(ctx, model.NewFolder(*lib, "path/to/no-playlists"))).To(Succeed()) var produced []*model.Folder - err := phase.produce(func(folder *model.Folder) { + err = phase.produce(func(folder *model.Folder) { produced = append(produced, folder) }) sort.Slice(produced, func(i, j int) bool { - return produced[i].Path < produced[j].Path + return produced[i].Name < produced[j].Name }) Expect(err).ToNot(HaveOccurred()) Expect(produced).To(HaveLen(2)) - Expect(produced[0].Path).To(Equal("/path/to/folder1")) - Expect(produced[1].Path).To(Equal("/path/to/folder2")) + Expect(produced[0].Path).To(Equal("path/to")) + Expect(produced[0].Name).To(Equal("folder1")) + Expect(produced[1].Name).To(Equal("folder2")) }) It("returns an error if there is an error loading folders", func() { - folderRepo.SetData(map[*model.Folder]error{ - nil: errors.New("error loading folders"), - }) + putPlaylistFolders("path/to/folder1") + withStub(persistencetest.Repos{Folder: func(r model.FolderRepository) model.FolderRepository { + return &failingFolderRepo{FolderRepository: r, err: errors.New("error loading folders")} + }}) called := false err := phase.produce(func(folder *model.Folder) { called = true }) @@ -90,34 +103,36 @@ var _ = Describe("phasePlaylists", func() { It("sets the pending flag and imports nothing when no admin user exists", func() { // Remove the admin user; produce resolves the admin at phase time. - userRepo.Data = map[string]*model.User{} - folderRepo.SetData(map[*model.Folder]error{ - {Path: "/path/to/folder1"}: nil, - }) + removeAdmin() + putPlaylistFolders("path/to/folder1") called := false err := phase.produce(func(folder *model.Folder) { called = true }) Expect(err).ToNot(HaveOccurred()) Expect(called).To(BeFalse()) - v, _ := propRepo.Get(ctx, consts.PlaylistsImportPendingFlagKey) + v, _ := ds.Property().Get(ctx, consts.PlaylistsImportPendingFlagKey) Expect(v).To(Equal("1")) }) It("returns an error (not a silent defer) on a datastore failure resolving the admin", func() { - userRepo.Error = errors.New("db is locked") + withStub(persistencetest.Repos{User: func(r model.UserRepository) model.UserRepository { + return &failingAdminRepo{UserRepository: r, err: errors.New("db is locked")} + }}) err := phase.produce(func(folder *model.Folder) {}) Expect(err).To(MatchError(ContainSubstring("finding admin user"))) // Must NOT have set the pending flag on a real error. - _, getErr := propRepo.Get(ctx, consts.PlaylistsImportPendingFlagKey) + _, getErr := ds.Property().Get(ctx, consts.PlaylistsImportPendingFlagKey) Expect(getErr).To(HaveOccurred()) }) It("returns an error when the pending flag cannot be persisted", func() { - userRepo.Data = map[string]*model.User{} // no admin -> defer path - propRepo.Error = errors.New("property table unavailable") + removeAdmin() // no admin -> defer path + withStub(persistencetest.Repos{Property: func(r model.PropertyRepository) model.PropertyRepository { + return &failingPropertyRepo{PropertyRepository: r, err: errors.New("property table unavailable")} + }}) err := phase.produce(func(folder *model.Folder) {}) @@ -125,16 +140,20 @@ var _ = Describe("phasePlaylists", func() { }) It("imports all playlist folders when the pending flag is set", func() { - Expect(propRepo.Put(ctx, consts.PlaylistsImportPendingFlagKey, "1")).To(Succeed()) - folderRepo.SetAllData(map[*model.Folder]error{ - {Path: "/path/to/folder1"}: nil, - {Path: "/path/to/folder2"}: nil, - }) + Expect(ds.Property().Put(ctx, consts.PlaylistsImportPendingFlagKey, "1")).To(Succeed()) + putPlaylistFolders("path/to/folder1", "path/to/folder2") + Expect(ds.Library().ScanEnd(ctx, model.DefaultLibraryID)).To(Succeed()) // Touched set is empty: proves selection used GetAllWithPlaylists. - folderRepo.SetData(map[*model.Folder]error{}) + touched, err := ds.Folder().GetTouchedWithPlaylists(ctx) + Expect(err).ToNot(HaveOccurred()) + count := 0 + for range touched { + count++ + } + Expect(count).To(BeZero()) var produced []*model.Folder - err := phase.produce(func(folder *model.Folder) { produced = append(produced, folder) }) + err = phase.produce(func(folder *model.Folder) { produced = append(produced, folder) }) Expect(err).ToNot(HaveOccurred()) Expect(produced).To(HaveLen(2)) @@ -144,22 +163,22 @@ var _ = Describe("phasePlaylists", func() { Describe("finalize", func() { It("clears the pending flag after a successful pending import", func() { - Expect(propRepo.Put(ctx, consts.PlaylistsImportPendingFlagKey, "1")).To(Succeed()) + Expect(ds.Property().Put(ctx, consts.PlaylistsImportPendingFlagKey, "1")).To(Succeed()) phase.pendingImport = true Expect(phase.finalize(nil)).To(Succeed()) - _, err := propRepo.Get(ctx, consts.PlaylistsImportPendingFlagKey) + _, err := ds.Property().Get(ctx, consts.PlaylistsImportPendingFlagKey) Expect(err).To(HaveOccurred()) // deleted }) It("keeps the pending flag when the import failed", func() { - Expect(propRepo.Put(ctx, consts.PlaylistsImportPendingFlagKey, "1")).To(Succeed()) + Expect(ds.Property().Put(ctx, consts.PlaylistsImportPendingFlagKey, "1")).To(Succeed()) phase.pendingImport = true Expect(phase.finalize(errors.New("boom"))).ToNot(Succeed()) - v, _ := propRepo.Get(ctx, consts.PlaylistsImportPendingFlagKey) + v, _ := ds.Property().Get(ctx, consts.PlaylistsImportPendingFlagKey) Expect(v).To(Equal("1")) }) }) @@ -240,40 +259,30 @@ func (p *mockPlaylists) ImportFromFolder(ctx context.Context, folder *model.Fold return args.Get(0).(*model.Playlist), args.Error(1) } -type mockFolderRepository struct { +// failingFolderRepo's cursor fails on its first row. +type failingFolderRepo struct { model.FolderRepository - data map[*model.Folder]error - allData map[*model.Folder]error + err error } -func cursorFromData(data map[*model.Folder]error) model.FolderCursor { - return func(yield func(model.Folder, error) bool) { - for folder, err := range data { - if err != nil { - if !yield(model.Folder{}, err) { - return - } - continue - } - if !yield(*folder, err) { - return - } - } - } +func (f *failingFolderRepo) GetTouchedWithPlaylists(context.Context) (model.FolderCursor, error) { + return func(yield func(model.Folder, error) bool) { yield(model.Folder{}, f.err) }, nil } -func (f *mockFolderRepository) GetTouchedWithPlaylists(context.Context) (model.FolderCursor, error) { - return cursorFromData(f.data), nil +type failingAdminRepo struct { + model.UserRepository + err error } -func (f *mockFolderRepository) GetAllWithPlaylists(context.Context) (model.FolderCursor, error) { - return cursorFromData(f.allData), nil +func (r *failingAdminRepo) FindFirstAdmin(context.Context) (*model.User, error) { + return nil, r.err } -func (f *mockFolderRepository) SetData(m map[*model.Folder]error) { - f.data = m +type failingPropertyRepo struct { + model.PropertyRepository + err error } -func (f *mockFolderRepository) SetAllData(m map[*model.Folder]error) { - f.allData = m +func (r *failingPropertyRepo) Put(context.Context, string, string) error { + return r.err } diff --git a/scanner/scanner_benchmark_test.go b/scanner/scanner_benchmark_test.go index 588177792..92c4be0a9 100644 --- a/scanner/scanner_benchmark_test.go +++ b/scanner/scanner_benchmark_test.go @@ -22,6 +22,7 @@ import ( "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/singleton" + "github.com/onsi/gomega" "go.uber.org/goleak" ) @@ -41,6 +42,8 @@ func BenchmarkScan(b *testing.B) { ) tests.Init(b, false) + // storagetest builds its fixtures with Gomega assertions + gomega.RegisterTestingT(b) tmpDir := b.TempDir() conf.Update(func(c *conf.Options) { diff --git a/scanner/scanner_multilibrary_test.go b/scanner/scanner_multilibrary_test.go index 21074996c..dde3e25a3 100644 --- a/scanner/scanner_multilibrary_test.go +++ b/scanner/scanner_multilibrary_test.go @@ -3,8 +3,6 @@ package scanner_test import ( "context" "errors" - "os" - "path/filepath" "testing/fstest" "time" @@ -16,22 +14,22 @@ import ( "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/core/storage/storagetest" "github.com/navidrome/navidrome/db" - "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" - "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("Scanner - Multi-Library", Ordered, func() { +var _ = Describe("Scanner - Multi-Library", func() { var ctx context.Context var lib1, lib2 model.Library - var ds *tests.MockDataStore + var ds model.DataStore + var spy *scannerSpy var s model.Scanner createFS := func(path string, files fstest.MapFS) storagetest.FakeFS { @@ -41,40 +39,20 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { return fs } - BeforeAll(func() { - ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) - // db.Db() is a process-wide singleton, so this dir may hold the open DB until - // the suite ends, and Windows can't delete an open file - tmpDir, err := os.MkdirTemp("", "scanner-test") - Expect(err).ToNot(HaveOccurred()) - DeferCleanup(func() { _ = os.RemoveAll(tmpDir) }) - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { - c.DbPath = filepath.Join(tmpDir, "test-scanner-multilibrary.db?_journal_mode=WAL") - }) - log.Warn("Using DB at " + conf.Server().DbPath) - db.Db().SetMaxOpenConns(1) - }) - BeforeEach(func() { - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { - c.MusicFolder = "default:///music" // Use a distinct schema for the default library - c.DevExternalScanner = false + ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) + conf.Update(func(c *conf.Options) { c.DevExternalScanner = false }) + + // Storage registrations are global, so start every library empty, whatever earlier specs registered. + for _, scheme := range []string{"default", "rock", "jazz"} { + _ = createFS(scheme, fstest.MapFS{}) + } + + spy = &scannerSpy{} + ds = persistencetest.Overlay(persistence.New(db.Db()), func(ds model.DataStore) model.DataStore { + return &scannerSpyDS{DataStore: ds, spy: spy} }) - // Register an empty fake storage for the default library - emptyFS := storagetest.FakeFS{} - emptyFS.SetFiles(fstest.MapFS{}) - storagetest.Register("default", &emptyFS) - - db.Init(ctx) - DeferCleanup(func() { - Expect(tests.ClearDB(ctx)).To(Succeed()) - }) - - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} - // Create the admin user in the database to match the context adminUser := model.User{ ID: "123", @@ -84,6 +62,8 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { NewPassword: "password", } Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) + // Use a distinct schema for the default library + persistencetest.SetLibraries(ctx, ds, "default:///music") s = scanner.New(ctx, ds, events.NoopBroker(), playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance()) @@ -629,12 +609,7 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { }) It("should propagate database errors and stop scanning", func() { - // Install mock repo that injects DB error - mfRepo := &mockMediaFileRepo{ - MediaFileRepository: ds.RealDS.MediaFile(), - GetMissingAndMatchingError: errors.New("database connection failed"), - } - ds.MockedMediaFile = mfRepo + spy.getMissingAndMatchingErr = errors.New("database connection failed") // Scan should return the database error Expect(runScanner(ctx, false)).To(MatchError(ContainSubstring("database connection failed"))) @@ -646,12 +621,7 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { }) It("should preserve error information in scanner properties", func() { - // Install mock repo that injects DB error - mfRepo := &mockMediaFileRepo{ - MediaFileRepository: ds.RealDS.MediaFile(), - GetMissingAndMatchingError: errors.New("critical database error"), - } - ds.MockedMediaFile = mfRepo + spy.getMissingAndMatchingErr = errors.New("critical database error") // Attempt scan (should fail) Expect(runScanner(ctx, false)).ToNot(Succeed()) @@ -846,9 +816,6 @@ var _ = Describe("Scanner - Multi-Library", Ordered, func() { Context("Per-library PID config", func() { albumsOf := func(libID int) model.Albums { - // The mock datastore's GC is a no-op, so run the real one to purge the albums left - // empty by a regroup, as the scanner does in production - Expect(ds.RealDS.GC(ctx)).To(Succeed()) albums, err := ds.Album().GetAll(ctx, model.QueryOptions{ Filters: squirrel.Eq{"library_id": libID, "missing": false}, Sort: "name", diff --git a/scanner/scanner_selective_test.go b/scanner/scanner_selective_test.go index f31cf4b03..4514808dd 100644 --- a/scanner/scanner_selective_test.go +++ b/scanner/scanner_selective_test.go @@ -2,7 +2,6 @@ package scanner_test import ( "context" - "os" "path/filepath" "testing/fstest" "time" @@ -15,49 +14,27 @@ import ( "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/core/storage/storagetest" "github.com/navidrome/navidrome/db" - "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" - "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -var _ = Describe("ScanFolders", Ordered, func() { +var _ = Describe("ScanFolders", func() { var ctx context.Context var lib model.Library var ds model.DataStore var s model.Scanner var fsys storagetest.FakeFS - BeforeAll(func() { - ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) - // db.Db() is a process-wide singleton, so this dir may hold the open DB until - // the suite ends, and Windows can't delete an open file - tmpDir, err := os.MkdirTemp("", "scanner-test") - Expect(err).ToNot(HaveOccurred()) - DeferCleanup(func() { _ = os.RemoveAll(tmpDir) }) - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-selective-scan.db?_journal_mode=WAL") }) - log.Warn("Using DB at " + conf.Server().DbPath) - db.Db().SetMaxOpenConns(1) - }) - BeforeEach(func() { - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { - c.MusicFolder = "fake:///music" - c.DevExternalScanner = false - }) - - db.Init(ctx) - DeferCleanup(func() { - Expect(tests.ClearDB(ctx)).To(Succeed()) - }) + ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) + conf.Update(func(c *conf.Options) { c.DevExternalScanner = false }) ds = persistence.New(db.Db()) @@ -70,6 +47,7 @@ var _ = Describe("ScanFolders", Ordered, func() { NewPassword: "password", } Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) + persistencetest.SetLibraries(ctx, ds, "fake:///music") s = scanner.New(ctx, ds, events.NoopBroker(), playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance()) @@ -214,6 +192,7 @@ var _ = Describe("ScanFolders", Ordered, func() { Expect(err).ToNot(HaveOccurred()) Expect(allTracks).To(HaveLen(4)) + album1TrackIDs, album2TrackIDs = nil, nil // Store track IDs for later verification for _, t := range allTracks { switch t.Album { diff --git a/scanner/scanner_suite_test.go b/scanner/scanner_suite_test.go index c5d066782..bfa4e8b25 100644 --- a/scanner/scanner_suite_test.go +++ b/scanner/scanner_suite_test.go @@ -10,6 +10,7 @@ import ( "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model/metadata" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -41,10 +42,13 @@ func TestScanner(t *testing.T) { ) tests.Init(t, true) - defer db.Close(t.Context()) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) + // goleak runs before t.Cleanup, so the DB must close before it + defer db.Close(t.Context()) RegisterFailHandler(Fail) RunSpecs(t, "Scanner Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/scanner/scanner_test.go b/scanner/scanner_test.go index c7db9ed12..92c5832b0 100644 --- a/scanner/scanner_test.go +++ b/scanner/scanner_test.go @@ -5,8 +5,6 @@ import ( "database/sql" "errors" "fmt" - "os" - "path/filepath" "sync/atomic" "testing/fstest" "time" @@ -21,10 +19,10 @@ import ( "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/core/storage/storagetest" "github.com/navidrome/navidrome/db" - "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" @@ -46,44 +44,22 @@ func createFS(files fstest.MapFS) storagetest.FakeFS { return fs } -var _ = Describe("Scanner", Ordered, func() { +var _ = Describe("Scanner", func() { var ctx context.Context var lib model.Library - var ds *tests.MockDataStore - var mfRepo *mockMediaFileRepo + var ds model.DataStore + var spy *scannerSpy var s model.Scanner - BeforeAll(func() { - ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) - // The DB stays open until the suite ends, and Windows can't delete an open file - tmpDir, err := os.MkdirTemp("", "scanner-test") - Expect(err).ToNot(HaveOccurred()) - DeferCleanup(func() { _ = os.RemoveAll(tmpDir) }) - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { c.DbPath = filepath.Join(tmpDir, "test-scanner.db?_journal_mode=WAL") }) - log.Warn("Using DB at " + conf.Server().DbPath) - //conf.Server.DbPath = ":memory:" - db.Db().SetMaxOpenConns(1) - }) - BeforeEach(func() { - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { - c.MusicFolder = "fake:///music" // Set to match test library path - c.DevExternalScanner = false - }) + ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "123", IsAdmin: true}) + conf.Update(func(c *conf.Options) { c.DevExternalScanner = false }) - db.Init(ctx) - DeferCleanup(func() { - Expect(tests.ClearDB(ctx)).To(Succeed()) + spy = &scannerSpy{} + ds = persistencetest.Overlay(persistence.New(db.Db()), func(ds model.DataStore) model.DataStore { + return &scannerSpyDS{DataStore: ds, spy: spy} }) - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} - mfRepo = &mockMediaFileRepo{ - MediaFileRepository: ds.RealDS.MediaFile(), - } - ds.MockedMediaFile = mfRepo - // Create the admin user in the database to match the context adminUser := model.User{ ID: "123", @@ -93,6 +69,7 @@ var _ = Describe("Scanner", Ordered, func() { NewPassword: "password", } Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) + persistencetest.SetLibraries(ctx, ds, "fake:///music") s = scanner.New(ctx, ds, events.NoopBroker(), playlists.NewPlaylists(ds, artwork.NewUploader(ds)), metrics.NewNoopInstance()) @@ -639,7 +616,7 @@ var _ = Describe("Scanner", Ordered, func() { fsys.Move("The Beatles/Revolver/01 - Taxman.mp3", "The Beatles/Help!/01 - Taxman.mp3") By("Interrupting the scan with an error before the move is processed") - mfRepo.GetMissingAndMatchingError = errors.New("I/O read error") + spy.getMissingAndMatchingErr = errors.New("I/O read error") Expect(runScanner(ctx, false)).To(MatchError(ContainSubstring("I/O read error"))) By("Checking the both instances of the file are in the lib") @@ -648,7 +625,7 @@ var _ = Describe("Scanner", Ordered, func() { })).To(Equal(int64(2))) By("Rescanning the library without error") - mfRepo.GetMissingAndMatchingError = nil + spy.getMissingAndMatchingErr = nil Expect(runScanner(ctx, false)).To(Succeed()) By("Checking the old file is not in the library") @@ -804,6 +781,8 @@ var _ = Describe("Scanner", Ordered, func() { // must then mark it missing (see markOrphansMissing). DeferCleanup(conf.SnapshotConfig()) conf.Update(func(c *conf.Options) { c.Scanner.PurgeMissing = consts.PurgeMissingAlways }) + // GC would delete the orphan outright, hiding whether RefreshStats marked it missing + spy.skipGC = true By("Starting from a library where Pink Floyd has its own single album") floyd := template(_t{"artist": "Pink Floyd", "album": "The Wall", "year": 1979}) @@ -1157,20 +1136,10 @@ var _ = Describe("Scanner", Ordered, func() { }) Describe("RefreshStats", func() { - var refreshStatsCalls []bool var fsys storagetest.FakeFS var help func(...map[string]any) *fstest.MapFile BeforeEach(func() { - refreshStatsCalls = nil - - // Create a mock artist repository that tracks RefreshStats calls - originalArtistRepo := ds.RealDS.Artist() - ds.MockedArtist = &testArtistRepo{ - ArtistRepository: originalArtistRepo, - callTracker: &refreshStatsCalls, - } - // Create a simple filesystem for testing help = template(_t{"albumartist": "The Beatles", "album": "Help!", "year": 1965}) fsys = createFS(fstest.MapFS{ @@ -1181,8 +1150,8 @@ var _ = Describe("Scanner", Ordered, func() { It("should call RefreshStats with allArtists=true for full scans", func() { Expect(runScanner(ctx, true)).To(Succeed()) - Expect(refreshStatsCalls).To(HaveLen(1)) - Expect(refreshStatsCalls[0]).To(BeTrue(), "RefreshStats should be called with allArtists=true for full scans") + Expect(spy.refreshStatsCalls).To(HaveLen(1)) + Expect(spy.refreshStatsCalls[0]).To(BeTrue(), "RefreshStats should be called with allArtists=true for full scans") }) It("should call RefreshStats with allArtists=false for incremental scans", func() { @@ -1190,7 +1159,7 @@ var _ = Describe("Scanner", Ordered, func() { Expect(runScanner(ctx, true)).To(Succeed()) // Reset the tracker to only track the incremental scan - refreshStatsCalls = nil + spy.refreshStatsCalls = nil // Add a new file to trigger changes detection fsys.Add("The Beatles/Help!/02 - The Night Before.mp3", help(track(2, "The Night Before"))) @@ -1198,14 +1167,12 @@ var _ = Describe("Scanner", Ordered, func() { // Do an incremental scan Expect(runScanner(ctx, false)).To(Succeed()) - Expect(refreshStatsCalls).To(HaveLen(1)) - Expect(refreshStatsCalls[0]).To(BeFalse(), "RefreshStats should be called with allArtists=false for incremental scans") + Expect(spy.refreshStatsCalls).To(HaveLen(1)) + Expect(spy.refreshStatsCalls[0]).To(BeFalse(), "RefreshStats should be called with allArtists=false for incremental scans") }) It("should update artist stats during quick scans when new albums are added", func() { tests.SkipOnWindows("path separator bug (#TBD-path-sep-scanner)") - // Don't use the mocked artist repo for this test - we need the real one - ds.MockedArtist = nil By("Initial scan with one album") Expect(runScanner(ctx, true)).To(Succeed()) @@ -1253,14 +1220,14 @@ var _ = Describe("Scanner", Ordered, func() { Context("when the database is busy", func() { var busyDS *busyPersistDS BeforeEach(func() { - // One album across many folders: the suite's single DB connection deadlocks phase 3 on many albums + // Many folders, so a scan that gives up early leaves some of them unvisited album := template(_t{"albumartist": "Artist", "album": "Album"}) files := fstest.MapFS{} for i := range 30 { files[fmt.Sprintf("Artist/Part %02d/%02d - Song.mp3", i, i+1)] = album(track(i+1, fmt.Sprintf("Song %02d", i+1))) } createFS(files) - busyDS = &busyPersistDS{MockDataStore: ds} + busyDS = &busyPersistDS{DataStore: ds} s = scanner.New(ctx, busyDS, events.NoopBroker(), playlists.NewPlaylists(busyDS, artwork.NewUploader(busyDS)), metrics.NewNoopInstance()) }) @@ -1270,7 +1237,7 @@ var _ = Describe("Scanner", Ordered, func() { Expect(runScanner(ctx, true)).To(MatchError(ContainSubstring("database is locked"))) - Expect(mfRepo.cursorCalls.Load()).To(BeNumerically("<", 30)) + Expect(spy.cursorCalls.Load()).To(BeNumerically("<", 30)) }) It("does not mark unvisited folders missing when the scan gives up", func() { @@ -1287,7 +1254,7 @@ var _ = Describe("Scanner", Ordered, func() { // busyPersistDS fails the scanner's folder saves with SQLITE_BUSY, as if WithTxRetry ran out of retries. type busyPersistDS struct { - *tests.MockDataStore + model.DataStore failures atomic.Int32 } @@ -1295,7 +1262,7 @@ func (b *busyPersistDS) WithTxRetry(ctx context.Context, block func(context.Cont if len(label) > 0 && label[0] == "scanner: persist changes" && b.failures.Add(-1) >= 0 { return sqlite3.Error{Code: sqlite3.ErrBusy} } - return b.MockDataStore.WithTxRetry(ctx, block, label...) + return b.DataStore.WithTxRetry(ctx, block, label...) } func createFindByPath(ctx context.Context, ds model.DataStore) func(string) (*model.MediaFile, error) { @@ -1311,30 +1278,57 @@ func createFindByPath(ctx context.Context, ds model.DataStore) func(string) (*mo } } -type mockMediaFileRepo struct { - model.MediaFileRepository - GetMissingAndMatchingError error - cursorCalls atomic.Int32 +// scannerSpy fails GetMissingAndMatching or skips GC on demand, and records cursor reads and artist stats refreshes. +type scannerSpy struct { + getMissingAndMatchingErr error + cursorCalls atomic.Int32 + refreshStatsCalls []bool + skipGC bool } -func (m *mockMediaFileRepo) GetCursor(ctx context.Context, options ...model.QueryOptions) (model.MediaFileCursor, error) { - m.cursorCalls.Add(1) +type scannerSpyDS struct { + model.DataStore + spy *scannerSpy +} + +func (d *scannerSpyDS) MediaFile() model.MediaFileRepository { + return &spyMediaFileRepo{MediaFileRepository: d.DataStore.MediaFile(), spy: d.spy} +} + +func (d *scannerSpyDS) GC(ctx context.Context, libraryIDs ...int) error { + if d.spy.skipGC { + return nil + } + return d.DataStore.GC(ctx, libraryIDs...) +} + +func (d *scannerSpyDS) Artist() model.ArtistRepository { + return &spyArtistRepo{ArtistRepository: d.DataStore.Artist(), spy: d.spy} +} + +type spyMediaFileRepo struct { + model.MediaFileRepository + spy *scannerSpy +} + +func (m *spyMediaFileRepo) GetCursor(ctx context.Context, options ...model.QueryOptions) (model.MediaFileCursor, error) { + m.spy.cursorCalls.Add(1) return m.MediaFileRepository.GetCursor(ctx, options...) } -func (m *mockMediaFileRepo) GetMissingAndMatching(ctx context.Context, libId int) (model.MediaFileCursor, error) { - if m.GetMissingAndMatchingError != nil { - return nil, m.GetMissingAndMatchingError +func (m *spyMediaFileRepo) GetMissingAndMatching(ctx context.Context, libId int) (model.MediaFileCursor, error) { + if m.spy.getMissingAndMatchingErr != nil { + return nil, m.spy.getMissingAndMatchingErr } return m.MediaFileRepository.GetMissingAndMatching(ctx, libId) } -type testArtistRepo struct { +type spyArtistRepo struct { model.ArtistRepository - callTracker *[]bool + spy *scannerSpy } -func (m *testArtistRepo) RefreshStats(ctx context.Context, allArtists bool) (int64, error) { - *m.callTracker = append(*m.callTracker, allArtists) +func (m *spyArtistRepo) RefreshStats(ctx context.Context, allArtists bool) (int64, error) { + m.spy.refreshStatsCalls = append(m.spy.refreshStatsCalls, allArtists) return m.ArtistRepository.RefreshStats(ctx, allArtists) } diff --git a/scanner/watcher_test.go b/scanner/watcher_test.go index c1d5a2655..f2d0b694d 100644 --- a/scanner/watcher_test.go +++ b/scanner/watcher_test.go @@ -9,7 +9,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/storage/storagetest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -19,7 +22,7 @@ var _ = Describe("Watcher", func() { var ctx context.Context var cancel context.CancelFunc var mockScanner *tests.MockScanner - var mockDS *tests.MockDataStore + var ds model.DataStore var w *watcher var lib *model.Library @@ -39,16 +42,13 @@ var _ = Describe("Watcher", func() { Path: "fake-watcher:///test/library", } - // Set up mocks mockScanner = tests.NewMockScanner() - mockDS = &tests.MockDataStore{} - mockLibRepo := &tests.MockLibraryRepo{} - mockLibRepo.SetData(model.Libraries{*lib}) - mockDS.MockedLibrary = mockLibRepo + ds = persistence.New(db.Db()) + persistencetest.SetLibraries(ctx, ds, lib.Path) // Create a new watcher instance (not singleton) for testing w = &watcher{ - ds: mockDS, + ds: ds, scanner: mockScanner, triggerWait: conf.Server().Scanner.WatcherWait, watcherNotify: make(chan scanNotification, 10), @@ -240,8 +240,7 @@ var _ = Describe("Watcher", func() { Path: "fake-watcher:///test/library2", } - mockLibRepo := mockDS.MockedLibrary.(*tests.MockLibraryRepo) - mockLibRepo.SetData(model.Libraries{*lib, *lib2}) + persistencetest.SetLibraries(ctx, ds, lib.Path, lib2.Path) // Start watcher in background go func() { diff --git a/server/apiv1/api_test.go b/server/apiv1/api_test.go index 20571a049..9a276fe58 100644 --- a/server/apiv1/api_test.go +++ b/server/apiv1/api_test.go @@ -4,7 +4,8 @@ import ( "net/http" "net/http/httptest" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -13,7 +14,7 @@ var _ = Describe("Router", func() { var router *Router BeforeEach(func() { - router = New(&tests.MockDataStore{}) + router = New(persistence.New(db.Db())) }) It("returns a 404 problem for unknown paths", func() { diff --git a/server/apiv1/apiv1_suite_test.go b/server/apiv1/apiv1_suite_test.go index b3686af69..62ace33b3 100644 --- a/server/apiv1/apiv1_suite_test.go +++ b/server/apiv1/apiv1_suite_test.go @@ -16,6 +16,7 @@ import ( "github.com/navidrome/navidrome/api" "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -24,11 +25,13 @@ import ( func TestAPIv1(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "API v1 Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() var specRouter routers.Router diff --git a/server/apiv1/server_info_test.go b/server/apiv1/server_info_test.go index b9dae6f8d..dde38d62f 100644 --- a/server/apiv1/server_info_test.go +++ b/server/apiv1/server_info_test.go @@ -9,21 +9,21 @@ import ( "github.com/navidrome/navidrome/api" "github.com/navidrome/navidrome/consts" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("GET /server", func() { var ctx context.Context - var ds *tests.MockDataStore - var users *tests.MockedUserRepo + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() - users = tests.CreateMockUserRepo() - ds = &tests.MockDataStore{MockedUser: users} + ds = persistence.New(db.Db()) }) get := func() (*httptest.ResponseRecorder, ServerInfo) { @@ -47,15 +47,26 @@ var _ = Describe("GET /server", func() { }) It("reports setupRequired=false once a user exists", func() { - Expect(users.Put(ctx, &model.User{ID: "u1", UserName: "admin", IsAdmin: true})).To(Succeed()) + Expect(ds.User().Put(ctx, &model.User{ID: "u1", UserName: "admin", IsAdmin: true})).To(Succeed()) _, info := get() Expect(info.SetupRequired).To(BeFalse()) }) It("returns a 500 problem when the user count fails", func() { - users.Error = errors.New("db down") + ds = persistencetest.Stub(ds, persistencetest.Repos{User: func(r model.UserRepository) model.UserRepository { + return &countErrorUserRepo{UserRepository: r, err: errors.New("db down")} + }}) w, _ := get() Expect(w.Code).To(Equal(http.StatusInternalServerError)) Expect(decodeProblem(w).Code).To(Equal(ProblemCodeInternal)) }) }) + +type countErrorUserRepo struct { + model.UserRepository + err error +} + +func (r *countErrorUserRepo) CountAll(context.Context, ...model.QueryOptions) (int64, error) { + return 0, r.err +} diff --git a/server/apiv1/spec_test.go b/server/apiv1/spec_test.go index a7a2bee45..3fd89ede2 100644 --- a/server/apiv1/spec_test.go +++ b/server/apiv1/spec_test.go @@ -9,7 +9,7 @@ import ( "github.com/navidrome/navidrome/api" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/model" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "gopkg.in/yaml.v3" @@ -19,7 +19,7 @@ var _ = Describe("OpenAPI document routes", func() { var router *Router BeforeEach(func() { - router = New(&tests.MockDataStore{}) + router = New(struct{ model.DataStore }{}) }) get := func(path string, headers map[string]string) *httptest.ResponseRecorder { @@ -93,7 +93,7 @@ var _ = Describe("OpenAPI document routes", func() { BeforeEach(func() { plainETag = get("/api/v1/openapi.json", nil).Header().Get("ETag") conf.Update(func(c *conf.Options) { c.BasePath = "/music" }) - router = New(&tests.MockDataStore{}) + router = New(struct{ model.DataStore }{}) }) DescribeTable("advertises the server under the base path and changes nothing else", @@ -118,7 +118,7 @@ var _ = Describe("OpenAPI document routes", func() { It("escapes base paths that need quoting", func() { conf.Update(func(c *conf.Options) { c.BasePath = "/my music: \"live\"" }) - router = New(&tests.MockDataStore{}) + router = New(struct{ model.DataStore }{}) Expect(serverURL(decode("json", get("/api/v1/openapi.json", nil).Body.Bytes()))).To(Equal("/my music: \"live\"/api/v1")) Expect(serverURL(decode("yaml", get("/api/v1/openapi.yaml", nil).Body.Bytes()))).To(Equal("/my music: \"live\"/api/v1")) }) diff --git a/server/auth_test.go b/server/auth_test.go index 79fffc849..f8e7cbbc0 100644 --- a/server/auth_test.go +++ b/server/auth_test.go @@ -15,11 +15,12 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/id" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" @@ -39,7 +40,7 @@ var _ = Describe("Auth", func() { var resp *httptest.ResponseRecorder BeforeEach(func() { - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) }) @@ -75,15 +76,15 @@ var _ = Describe("Auth", func() { Describe("createAdminUser", func() { It("returns the error when the user cannot be saved", func() { - ds = &tests.MockDataStore{MockedUser: &tests.MockedUserRepo{Error: errors.New("db is down")}} - err := createAdminUser(ctx, ds, "johndoe", "secret") + failing := withUserErrors(ds, userErrors{put: errors.New("db is down")}) + err := createAdminUser(ctx, failing, "johndoe", "secret") Expect(err).To(MatchError(ContainSubstring("db is down"))) }) }) Describe("createAdmin when the user cannot be stored", func() { It("responds 500 rather than falling through to login", func() { - failing := dsWithFailingPut(errors.New("db is down")) + failing := withUserErrors(ds, userErrors{put: errors.New("db is down")}) req = httptest.NewRequest(http.MethodPost, "/createAdmin", strings.NewReader(`{"username":"johndoe", "password":"secret"}`)) resp = httptest.NewRecorder() @@ -105,7 +106,7 @@ var _ = Describe("Auth", func() { BeforeEach(func() { usr := ds.User() - _ = usr.Put(ctx, &model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false}) + Expect(usr.Put(ctx, &model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false})).To(Succeed()) req = httptest.NewRequest(http.MethodGet, "/index.html", nil) req.Header.Add("Remote-User", "janedoe") resp = httptest.NewRecorder() @@ -244,7 +245,7 @@ var _ = Describe("Auth", func() { It("logs in successfully if user exists", func() { usr := ds.User() - _ = usr.Put(ctx, &model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false}) + Expect(usr.Put(ctx, &model.User{ID: "111", UserName: "janedoe", NewPassword: "abc123", Name: "Jane", IsAdmin: false})).To(Succeed()) login(ds)(resp, req) Expect(resp.Code).To(Equal(http.StatusOK)) @@ -392,7 +393,7 @@ var _ = Describe("Auth", func() { const trustedIP = "192.168.0.42" BeforeEach(func() { - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) req = httptest.NewRequest(http.MethodGet, "/", nil) req = req.WithContext(request.WithReverseProxyIp(req.Context(), trustedIP)) conf.Update(func(c *conf.Options) { @@ -417,12 +418,12 @@ var _ = Describe("Auth", func() { It("does not make subsequent users admins", func() { // Create the first user - _ = ds.User().Put(ctx, &model.User{ + Expect(ds.User().Put(ctx, &model.User{ ID: "existing-user-id", UserName: "existinguser", Name: "Existing User", IsAdmin: true, - }) + })).To(Succeed()) // Try to create a second user via proxy header req.Header.Set("Remote-User", "seconduser") @@ -439,16 +440,22 @@ var _ = Describe("Auth", func() { }) Describe("Authenticator token gating", func() { - var ds *tests.MockDataStore + var ds model.DataStore var usr *model.User + setTokenEpoch := func(epoch int) { + GinkgoHelper() + _, err := db.Db().Exec("UPDATE user SET token_epoch = ? WHERE id = ?", epoch, usr.ID) + Expect(err).ToNot(HaveOccurred()) + } + BeforeEach(func() { conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Hour }) - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - ur := ds.User().(*tests.MockedUserRepo) usr = &model.User{ID: "u1", UserName: "johndoe", NewPassword: "pw", TokenEpoch: 2} - Expect(ur.Put(ctx, usr)).To(Succeed()) + Expect(ds.User().Put(ctx, usr)).To(Succeed()) + setTokenEpoch(usr.TokenEpoch) }) serve := func(token string) *httptest.ResponseRecorder { @@ -477,7 +484,7 @@ var _ = Describe("Auth", func() { It("rejects a token with a stale epoch", func() { tokenStr, err := auth.CreateToken(usr) Expect(err).ToNot(HaveOccurred()) - usr.TokenEpoch = 3 + setTokenEpoch(3) Expect(serve(tokenStr).Code).To(Equal(http.StatusUnauthorized)) }) @@ -491,7 +498,7 @@ var _ = Describe("Auth", func() { It("rejects a stale-epoch token whose subject differs only in case from the resolved user", func() { tokenStr, err := auth.CreateToken(&model.User{UserName: strings.ToUpper(usr.UserName), TokenEpoch: usr.TokenEpoch}) Expect(err).ToNot(HaveOccurred()) - usr.TokenEpoch = 5 + setTokenEpoch(5) Expect(serve(tokenStr).Code).To(Equal(http.StatusUnauthorized)) }) }) @@ -500,7 +507,7 @@ var _ = Describe("Auth", func() { BeforeEach(func() { // TouchClaims reads this; left at zero every refreshed token is born expired. conf.Update(func(c *conf.Options) { c.SessionTimeout = time.Hour }) - auth.Init(&tests.MockDataStore{}) + auth.Init(persistence.New(db.Db())) }) serveWith := func(handler http.HandlerFunc) *httptest.ResponseRecorder { diff --git a/server/initial_setup_test.go b/server/initial_setup_test.go index 9492fa5c0..ba7ca7727 100644 --- a/server/initial_setup_test.go +++ b/server/initial_setup_test.go @@ -3,7 +3,6 @@ package server import ( "context" "errors" - "path/filepath" "time" "github.com/navidrome/navidrome/conf" @@ -11,20 +10,38 @@ import ( "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/persistence" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -type failingPutUserRepo struct { - model.UserRepository - err error +type userErrors struct { + put, countAll error } -func (r *failingPutUserRepo) Put(context.Context, *model.User) error { return r.err } +func withUserErrors(ds model.DataStore, errs userErrors) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{User: func(r model.UserRepository) model.UserRepository { + return &userErrorsRepo{UserRepository: r, errs: errs} + }}) +} -func dsWithFailingPut(err error) model.DataStore { - return &tests.MockDataStore{MockedUser: &failingPutUserRepo{UserRepository: tests.CreateMockUserRepo(), err: err}} +type userErrorsRepo struct { + model.UserRepository + errs userErrors +} + +func (r *userErrorsRepo) Put(ctx context.Context, u *model.User) error { + if r.errs.put != nil { + return r.errs.put + } + return r.UserRepository.Put(ctx, u) +} + +func (r *userErrorsRepo) CountAll(ctx context.Context, qo ...model.QueryOptions) (int64, error) { + if r.errs.countAll != nil { + return 0, r.errs.countAll + } + return r.UserRepository.CountAll(ctx, qo...) } var _ = Describe("initial_setup", func() { @@ -32,15 +49,15 @@ var _ = Describe("initial_setup", func() { var ctx context.Context BeforeEach(func() { - ds = &tests.MockDataStore{} ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) Describe("createInitialAdminUser", func() { It("creates a new admin user with specified password if User table is empty", func() { Expect(createInitialAdminUser(ctx, ds, "pass123")).To(Succeed()) ur := ds.User() - admin, err := ur.FindByUsername(ctx, "admin") + admin, err := ur.FindByUsernameWithPassword(ctx, "admin") Expect(err).ToNot(HaveOccurred()) Expect(admin.Password).To(Equal("pass123")) }) @@ -55,19 +72,17 @@ var _ = Describe("initial_setup", func() { It("returns the error when the user cannot be stored", func() { boom := errors.New("db is down") - Expect(createInitialAdminUser(ctx, dsWithFailingPut(boom), "pass123")).To(MatchError(boom)) + Expect(createInitialAdminUser(ctx, withUserErrors(ds, userErrors{put: boom}), "pass123")).To(MatchError(boom)) }) It("returns the error when the user table cannot be read", func() { boom := errors.New("db is down") - ds = &tests.MockDataStore{MockedUser: &tests.MockedUserRepo{Error: boom}} - Expect(createInitialAdminUser(ctx, ds, "pass123")).To(MatchError(boom)) + Expect(createInitialAdminUser(ctx, withUserErrors(ds, userErrors{countAll: boom}), "pass123")).To(MatchError(boom)) }) }) }) -// db.Db() is a process-wide singleton that the BeforeAll cleanup closes; keep these the only real-DB specs in this package. -var _ = Describe("initialSetup with a real database", Ordered, func() { +var _ = Describe("initialSetup with a real database", func() { var ctx context.Context var ds model.DataStore @@ -86,17 +101,9 @@ var _ = Describe("initialSetup with a real database", Ordered, func() { DeferCleanup(func() { <-released }) } - BeforeAll(func() { - DeferCleanup(conf.SnapshotConfig()) - conf.Update(func(c *conf.Options) { - c.DbPath = filepath.Join(GinkgoT().TempDir(), "initial-setup.db") + "?_journal_mode=WAL&_busy_timeout=1000" - }) - DeferCleanup(db.Init(GinkgoT().Context())) - ds = persistence.New(db.Db()) - }) - BeforeEach(func() { ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) It("completes the first-run setup when the write lock is held briefly", func() { @@ -107,12 +114,17 @@ var _ = Describe("initialSetup with a real database", Ordered, func() { }) It("does not need the write lock when setup already ran and the music folder is unchanged", func() { - holdWriteLock(1500 * time.Millisecond) - Expect(initialSetup(ctx, ds)).To(Succeed()) + const lockHeld = 1500 * time.Millisecond + holdWriteLock(lockHeld) + + start := time.Now() + Expect(initialSetup(ctx, ds)).To(Succeed()) + Expect(time.Since(start)).To(BeNumerically("<", lockHeld/2)) }) It("stores a changed music folder when the write lock is held briefly", func() { + Expect(initialSetup(ctx, ds)).To(Succeed()) newFolder := conf.Server().MusicFolder + "-moved" conf.Update(func(c *conf.Options) { c.MusicFolder = newFolder }) holdWriteLock(300 * time.Millisecond) diff --git a/server/jellyfin/annotations_test.go b/server/jellyfin/annotations_test.go index f00a4f56d..385b79abc 100644 --- a/server/jellyfin/annotations_test.go +++ b/server/jellyfin/annotations_test.go @@ -2,40 +2,54 @@ package jellyfin import ( "context" + "database/sql" "encoding/json" + "errors" "net/http" "net/http/httptest" "strings" "time" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Annotations", func() { + var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore var broker *fakeEventBroker + alice := model.User{ID: testID("u1"), UserName: "alice"} // alice has access to library 1 only. ctxUser := func() context.Context { - return request.WithUser(GinkgoT().Context(), model.User{ID: testID("u1"), UserName: "alice", Libraries: model.Libraries{{ID: 1, Name: "Music"}}}) + u := alice + u.Libraries = model.Libraries{{ID: 1, Name: "Music"}} + return request.WithUser(ctx, u) } BeforeEach(func() { - ds = &tests.MockDataStore{} + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + putUser(ctx, ds, alice) + persistencetest.SetLibraries(ctx, ds, "/music1", "/music2") + Expect(ds.User().SetUserLibraries(ctx, alice.ID, []int{1})).To(Succeed()) broker = &fakeEventBroker{} api = &Router{ds: ds, broker: broker} }) - songWith := func(ann model.Annotations) *tests.MockMediaFileRepo { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Annotations: ann}}) - return mfRepo + songWith := func(ann model.Annotations) { + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 1}) + annotate(alice.ID, "media_file", testID("s1"), ann) + } + stored := func(label string) model.Annotations { + return storedAnnotation(alice.ID, testID(label)) } songReq := func(method, target, body string, params ...string) *http.Request { r := httptest.NewRequest(method, target, strings.NewReader(body)).WithContext(ctxUser()) @@ -44,8 +58,7 @@ var _ = Describe("Annotations", func() { Describe("markFavorite / unmarkFavorite", func() { It("stars a song and returns IsFavorite=true", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) + songWith(model.Annotations{}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -54,12 +67,11 @@ var _ = Describe("Annotations", func() { var d dto.UserItemDataDto Expect(json.Unmarshal(w.Body.Bytes(), &d)).To(Succeed()) Expect(d.IsFavorite).To(BeTrue()) - Expect(mfRepo.Data[testID("s1")].Starred).To(BeTrue()) + Expect(stored("s1").Starred).To(BeTrue()) }) It("stars an album and returns IsFavorite=true", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) @@ -68,12 +80,11 @@ var _ = Describe("Annotations", func() { var d dto.UserItemDataDto Expect(json.Unmarshal(w.Body.Bytes(), &d)).To(Succeed()) Expect(d.IsFavorite).To(BeTrue()) - Expect(albumRepo.Data[testID("a1")].Starred).To(BeTrue()) + Expect(stored("a1").Starred).To(BeTrue()) }) It("stars an artist without checking library access (artists span multiple libraries)", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Artist"}) w := httptest.NewRecorder() // alice only has access to library 1, but artists aren't gated per-library. r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/ar1", nil).WithContext(ctxUser()) @@ -83,23 +94,21 @@ var _ = Describe("Annotations", func() { var d dto.UserItemDataDto Expect(json.Unmarshal(w.Body.Bytes(), &d)).To(Succeed()) Expect(d.IsFavorite).To(BeTrue()) - Expect(artistRepo.Data[testID("ar1")].Starred).To(BeTrue()) + Expect(stored("ar1").Starred).To(BeTrue()) }) It("stars a visible playlist", func() { - playlistRepo := ds.Playlist().(*tests.MockPlaylistRepo) - playlistRepo.SetData(model.Playlists{{ID: testID("p1"), Name: "Mix", OwnerID: testID("u1")}}) + Expect(ds.Playlist().Put(ctxUser(), &model.Playlist{ID: testID("p1"), Name: "Mix", OwnerID: alice.ID})).To(Succeed()) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("p1")), nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("p1"))) invoke(api.markFavorite, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(playlistRepo.Starred[testID("p1")]).To(BeTrue()) + Expect(stored("p1").Starred).To(BeTrue()) }) It("unstars a song and returns IsFavorite=false", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Starred: true}}) + songWith(model.Annotations{Starred: true}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodDelete, "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -108,29 +117,27 @@ var _ = Describe("Annotations", func() { var d dto.UserItemDataDto Expect(json.Unmarshal(w.Body.Bytes(), &d)).To(Succeed()) Expect(d.IsFavorite).To(BeFalse()) - Expect(mfRepo.Data[testID("s1")].Starred).To(BeFalse()) + Expect(stored("s1").Starred).To(BeFalse()) }) It("returns 404 and does not star an album in a library the user can't access", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 2}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) // only has access to library 1 r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) invoke(api.markFavorite, w, r) Expect(w.Code).To(Equal(http.StatusNotFound)) - Expect(albumRepo.Data[testID("a1")].Starred).To(BeFalse()) + Expect(stored("a1").Starred).To(BeFalse()) }) It("returns 404 and does not star a song in a library the user can't access", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 2}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser()) // only has access to library 1 r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) invoke(api.markFavorite, w, r) Expect(w.Code).To(Equal(http.StatusNotFound)) - Expect(mfRepo.Data[testID("s1")].Starred).To(BeFalse()) + Expect(stored("s1").Starred).To(BeFalse()) }) It("returns 404 when the id doesn't match any entity", func() { @@ -142,7 +149,9 @@ var _ = Describe("Annotations", func() { }) It("returns 500 (not 404) when a repository lookup fails for a reason other than not-found", func() { - ds.Album().(*tests.MockAlbumRepo).SetError(true) + api.ds = persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return failingAlbumRepo{AlbumRepository: r, err: errors.New("db down")} + }}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/x1", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("x1"))) @@ -151,8 +160,7 @@ var _ = Describe("Annotations", func() { }) It("emits a refreshResource event when starring a song", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) + songWith(model.Annotations{}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/s1", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -162,8 +170,7 @@ var _ = Describe("Annotations", func() { }) It("emits a refreshResource event when starring an album", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) @@ -173,8 +180,7 @@ var _ = Describe("Annotations", func() { }) It("does not emit an event when the item is not accessible", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 2}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/FavoriteItems/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) @@ -186,14 +192,13 @@ var _ = Describe("Annotations", func() { Describe("setRating / removeRating", func() { It("maps a Jellyfin 0-10 rating to Navidrome's 0-5 scale", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) + songWith(model.Annotations{}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/s1/Rating?Rating=8", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) var d dto.UserItemDataDto Expect(json.Unmarshal(w.Body.Bytes(), &d)).To(Succeed()) Expect(d.Rating).NotTo(BeNil()) @@ -201,83 +206,76 @@ var _ = Describe("Annotations", func() { }) It("rates an album", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/"+dto.EncodeID(testID("a1"))+"/Rating?Rating=10", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Data[testID("a1")].Rating).To(Equal(5)) + Expect(stored("a1").Rating).To(Equal(5)) }) It("rates a visible playlist", func() { - playlistRepo := ds.Playlist().(*tests.MockPlaylistRepo) - playlistRepo.SetData(model.Playlists{{ID: testID("p1"), Name: "Mix", OwnerID: testID("u1")}}) + Expect(ds.Playlist().Put(ctxUser(), &model.Playlist{ID: testID("p1"), Name: "Mix", OwnerID: alice.ID})).To(Succeed()) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/"+dto.EncodeID(testID("p1"))+"/Rating?Rating=8", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("p1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(playlistRepo.Ratings[testID("p1")]).To(Equal(4)) + Expect(stored("p1").Rating).To(Equal(4)) }) It("removes a rating", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Rating: 4}}) + songWith(model.Annotations{Rating: 4}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodDelete, "/Users/u1/Items/s1/Rating", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) invoke(api.removeRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(0)) + Expect(stored("s1").Rating).To(Equal(0)) var d dto.UserItemDataDto Expect(json.Unmarshal(w.Body.Bytes(), &d)).To(Succeed()) Expect(d.Rating).To(BeNil()) }) It("returns 404 and does not rate an album in a library the user can't access", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 2}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/"+dto.EncodeID(testID("a1"))+"/Rating?Rating=10", nil).WithContext(ctxUser()) // only has access to library 1 r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusNotFound)) - Expect(albumRepo.Data[testID("a1")].Rating).To(Equal(0)) + Expect(stored("a1").Rating).To(Equal(0)) }) It("rounds an odd rating to the nearest star instead of truncating", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) + songWith(model.Annotations{}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/s1/Rating?Rating=9", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(5)) + Expect(stored("s1").Rating).To(Equal(5)) }) It("stores the minimum star for Rating=1 instead of clearing the rating", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1, Rating: 4}}) + songWith(model.Annotations{Rating: 4}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/s1/Rating?Rating=1", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(1)) + Expect(stored("s1").Rating).To(Equal(1)) }) It("accepts a fractional rating (UserItemDataDto.Rating is a double)", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) + songWith(model.Annotations{}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/u1/Items/s1/Rating?Rating=7.5", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) invoke(api.setRating, w, r) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) }) It("emits a refreshResource event when rating a song", func() { @@ -289,54 +287,54 @@ var _ = Describe("Annotations", func() { Context("Jellyfin likes semantics", func() { It("stores likes=true as 5 stars and reports Rating 10 / Likes true", func() { - mfRepo := songWith(model.Annotations{}) + songWith(model.Annotations{}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/UserItems/s1/Rating?likes=true", "")) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(5)) + Expect(stored("s1").Rating).To(Equal(5)) d := parseUserData(w) Expect(*d.Rating).To(Equal(10.0)) Expect(*d.Likes).To(BeTrue()) }) It("stores likes=false as 1 star (Jellyfin's dislike is Rating 1), not a clear", func() { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/UserItems/s1/Rating?Likes=False", "")) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(1)) + Expect(stored("s1").Rating).To(Equal(1)) d := parseUserData(w) Expect(*d.Rating).To(Equal(2.0)) Expect(*d.Likes).To(BeFalse()) }) It("prefers likes over the numeric rating extension when both are sent", func() { - mfRepo := songWith(model.Annotations{}) + songWith(model.Annotations{}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/UserItems/s1/Rating?likes=false&rating=10", "")) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(1)) + Expect(stored("s1").Rating).To(Equal(1)) }) It("still clears on an explicit rating=0 from numeric clients", func() { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/UserItems/s1/Rating?rating=0", "")) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(0)) + Expect(stored("s1").Rating).To(Equal(0)) Expect(parseUserData(w).Rating).To(BeNil()) }) It("keeps the favorite and play state and reports them in the response", func() { playDate := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) - mfRepo := songWith(model.Annotations{Starred: true, PlayCount: 3, PlayDate: &playDate}) + songWith(model.Annotations{Starred: true, PlayCount: 3, PlayDate: &playDate}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/UserItems/s1/Rating?likes=true", "")) Expect(w.Code).To(Equal(http.StatusOK)) - song := mfRepo.Data[testID("s1")] + song := stored("s1") Expect(song.Starred).To(BeTrue()) Expect(song.PlayCount).To(Equal(int64(3))) - Expect(song.PlayDate).To(Equal(&playDate)) + Expect(*song.PlayDate).To(BeTemporally("==", playDate)) d := parseUserData(w) Expect(d.IsFavorite).To(BeTrue()) Expect(d.PlayCount).To(Equal(3)) @@ -345,11 +343,11 @@ var _ = Describe("Annotations", func() { DescribeTable("rejects a missing or malformed value without touching the stored rating", func(query string) { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/UserItems/s1/Rating"+query, "")) Expect(w.Code).To(Equal(http.StatusBadRequest)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) Expect(broker.Events).To(BeEmpty()) }, Entry("no params (Jellyfin would clear)", ""), @@ -373,11 +371,11 @@ var _ = Describe("Annotations", func() { if method == "DELETE" { handler = api.removeRating } - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) w := httptest.NewRecorder() invoke(handler, w, songReq(method, target, "", params...)) Expect(w.Code).To(Equal(http.StatusForbidden)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) Expect(broker.Events).To(BeEmpty()) }, Entry("path userId", "POST", "/Users/u2/Items/s1/Rating?likes=true", "userId", dto.EncodeID(testID("u2"))), @@ -386,11 +384,11 @@ var _ = Describe("Annotations", func() { ) It("accepts the caller's own userId", func() { - mfRepo := songWith(model.Annotations{}) + songWith(model.Annotations{}) w := httptest.NewRecorder() invoke(api.setRating, w, songReq("POST", "/Users/u1/Items/s1/Rating?likes=true", "", "userId", dto.EncodeID(testID("u1")))) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(5)) + Expect(stored("s1").Rating).To(Equal(5)) }) }) }) @@ -403,10 +401,10 @@ var _ = Describe("Annotations", func() { } It("maps a 0-10 Rating to stars and answers with the full UserData", func() { - mfRepo := songWith(model.Annotations{Starred: true, PlayCount: 2}) + songWith(model.Annotations{Starred: true, PlayCount: 2}) w := post(`{"Rating":8}`) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) d := parseUserData(w) Expect(*d.Rating).To(Equal(8.0)) Expect(*d.Likes).To(BeTrue()) @@ -418,9 +416,9 @@ var _ = Describe("Annotations", func() { DescribeTable("stores the personal rating", func(body string, before, expected int) { - mfRepo := songWith(model.Annotations{Rating: before}) + songWith(model.Annotations{Rating: before}) Expect(post(body).Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(expected)) + Expect(stored("s1").Rating).To(Equal(expected)) }, Entry("Likes true", `{"Likes":true}`, 0, 5), Entry("Likes false (Rating 1)", `{"Likes":false}`, 4, 1), @@ -432,10 +430,10 @@ var _ = Describe("Annotations", func() { DescribeTable("leaves the rating untouched when Rating and Likes are omitted or null", func(body string, wantEvents int) { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) w := post(body) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) Expect(*parseUserData(w).Rating).To(Equal(8.0)) Expect(broker.Events).To(HaveLen(wantEvents)) }, @@ -445,30 +443,30 @@ var _ = Describe("Annotations", func() { ) It("sets and unsets the favorite without touching the rating", func() { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) Expect(post(`{"IsFavorite":true}`).Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Starred).To(BeTrue()) + Expect(stored("s1").Starred).To(BeTrue()) Expect(post(`{"IsFavorite":false}`).Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Starred).To(BeFalse()) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Starred).To(BeFalse()) + Expect(stored("s1").Rating).To(Equal(4)) }) It("ignores play-state fields, which only change through playback reporting", func() { - mfRepo := songWith(model.Annotations{PlayCount: 2}) + songWith(model.Annotations{PlayCount: 2}) w := post(`{"Played":true,"PlayCount":99,"LastPlayedDate":"2026-01-01T00:00:00Z","PlaybackPositionTicks":5}`) Expect(w.Code).To(Equal(http.StatusOK)) - song := mfRepo.Data[testID("s1")] + song := stored("s1") Expect(song.PlayCount).To(Equal(int64(2))) Expect(song.PlayDate).To(BeNil()) Expect(broker.Events).To(BeEmpty()) }) It("leaves state unchanged when a client echoes back the UserData it read", func() { - mfRepo := songWith(model.Annotations{Rating: 3, Starred: true, PlayCount: 1}) - echo, err := json.Marshal(dto.UserData(mfRepo.Data[testID("s1")].Annotations, testID("s1"))) + songWith(model.Annotations{Rating: 3, Starred: true, PlayCount: 1}) + echo, err := json.Marshal(dto.UserData(stored("s1"), testID("s1"))) Expect(err).ToNot(HaveOccurred()) Expect(post(string(echo)).Code).To(Equal(http.StatusOK)) - song := mfRepo.Data[testID("s1")] + song := stored("s1") Expect(song.Rating).To(Equal(3)) Expect(song.Starred).To(BeTrue()) Expect(song.PlayCount).To(Equal(int64(1))) @@ -476,9 +474,9 @@ var _ = Describe("Annotations", func() { DescribeTable("rejects an invalid body without writing anything", func(body string) { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) Expect(post(body).Code).To(Equal(http.StatusBadRequest)) - song := mfRepo.Data[testID("s1")] + song := stored("s1") Expect(song.Rating).To(Equal(4)) Expect(song.Starred).To(BeFalse()) Expect(broker.Events).To(BeEmpty()) @@ -498,25 +496,25 @@ var _ = Describe("Annotations", func() { ) It("accepts trailing whitespace after the object", func() { - mfRepo := songWith(model.Annotations{}) + songWith(model.Annotations{}) Expect(post("{\"Rating\":8}\r\n\t ").Code).To(Equal(http.StatusOK)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) }) It("rejects a body larger than the limit", func() { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) big := `{"Rating":8,"Pad":"` + strings.Repeat("x", 70<<10) + `"}` Expect(post(big).Code).To(Equal(http.StatusRequestEntityTooLarge)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) + Expect(stored("s1").Rating).To(Equal(4)) }) Context("authorization", func() { It("refuses a userId naming another user without writing", func() { - mfRepo := songWith(model.Annotations{Rating: 4}) + songWith(model.Annotations{Rating: 4}) w := post(`{"Rating":10,"IsFavorite":true}`, "userId", dto.EncodeID(testID("u2"))) Expect(w.Code).To(Equal(http.StatusForbidden)) - Expect(mfRepo.Data[testID("s1")].Rating).To(Equal(4)) - Expect(mfRepo.Data[testID("s1")].Starred).To(BeFalse()) + Expect(stored("s1").Rating).To(Equal(4)) + Expect(stored("s1").Starred).To(BeFalse()) }) It("accepts the caller's own userId", func() { @@ -525,14 +523,13 @@ var _ = Describe("Annotations", func() { }) It("returns 404 and writes nothing for an album in a library the user can't access", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 2}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/UserItems/a1/UserData", strings.NewReader(`{"Rating":10,"IsFavorite":true}`)).WithContext(ctxUser()) invoke(api.updateUserItemData, w, withChiURLParam(r, "itemId", dto.EncodeID(testID("a1")))) Expect(w.Code).To(Equal(http.StatusNotFound)) - Expect(albumRepo.Data[testID("a1")].Rating).To(Equal(0)) - Expect(albumRepo.Data[testID("a1")].Starred).To(BeFalse()) + Expect(stored("a1").Rating).To(Equal(0)) + Expect(stored("a1").Starred).To(BeFalse()) }) It("returns 404 for an unknown item", func() { @@ -563,3 +560,35 @@ func (f *fakeEventBroker) SendBroadcastMessage(_ context.Context, event events.E } var _ events.Broker = (*fakeEventBroker)(nil) + +// annotate stores a user's annotations on an item, as starring, rating and playback would. +func annotate(userID, itemType, itemID string, ann model.Annotations) { + GinkgoHelper() + _, err := db.Db().Exec(`INSERT INTO annotation (user_id, item_id, item_type, play_count, play_date, rating, starred) + VALUES (?, ?, ?, ?, ?, ?, ?)`, userID, itemID, itemType, ann.PlayCount, ann.PlayDate, ann.Rating, ann.Starred) + Expect(err).ToNot(HaveOccurred()) +} + +// storedAnnotation reads a user's annotations on an item, whatever library it is in. +func storedAnnotation(userID, itemID string) model.Annotations { + GinkgoHelper() + var ann model.Annotations + var playDate sql.NullTime + err := db.Db().QueryRow("SELECT play_count, play_date, rating, starred FROM annotation WHERE user_id = ? AND item_id = ?", + userID, itemID).Scan(&ann.PlayCount, &playDate, &ann.Rating, &ann.Starred) + if errors.Is(err, sql.ErrNoRows) { + return ann + } + Expect(err).ToNot(HaveOccurred()) + if playDate.Valid { + ann.PlayDate = &playDate.Time + } + return ann +} + +type failingAlbumRepo struct { + model.AlbumRepository + err error +} + +func (f failingAlbumRepo) Get(context.Context, string) (*model.Album, error) { return nil, f.err } diff --git a/server/jellyfin/api_test.go b/server/jellyfin/api_test.go index 99f56d655..5181837fd 100644 --- a/server/jellyfin/api_test.go +++ b/server/jellyfin/api_test.go @@ -11,21 +11,23 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/quickconnect" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Router", func() { var ctx context.Context + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) It("serves the public handshake through the mounted handler", func() { - ds := &tests.MockDataStore{} api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/System/Info/Public", nil) @@ -34,7 +36,7 @@ var _ = Describe("Router", func() { }) It("returns 404 JSON for unknown routes", func() { - api := New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Nonexistent/Route", nil) api.ServeHTTP(w, r) @@ -44,7 +46,7 @@ var _ = Describe("Router", func() { }) It("returns 404 JSON for a known path with an unsupported method", func() { - api := New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPatch, "/System/Info/Public", nil) api.ServeHTTP(w, r) @@ -53,10 +55,8 @@ var _ = Describe("Router", func() { }) It("registers a player on a general authenticated request, not just playback reports", func() { - ds := &tests.MockDataStore{} auth.Init(ds) - ur := ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) + Expect(ds.User().Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) token, err := auth.CreateToken(&model.User{ID: testID("u1"), UserName: "alice"}) Expect(err).ToNot(HaveOccurred()) @@ -79,7 +79,7 @@ var _ = Describe("Router", func() { c.AuthRequestLimit = 2 c.AuthWindowLength = time.Minute }) - api := New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) login := func() int { w := httptest.NewRecorder() @@ -100,7 +100,6 @@ var _ = Describe("Router", func() { c.AuthWindowLength = time.Minute c.Jellyfin.QuickConnect = true }) - ds := &tests.MockDataStore{} auth.Init(ds) usr := model.User{ID: testID("alice"), UserName: "alice"} Expect(ds.User().Put(ctx, &usr)).To(Succeed()) @@ -127,7 +126,7 @@ var _ = Describe("Router", func() { c.AuthRequestLimit = 1 c.AuthWindowLength = time.Minute }) - api := New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + api := New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) // Every request arrives on the same proxy connection, so only the resolved client IP // can separate the buckets. handler := middleware.ClientIPFromHeader("X-Real-IP")(api) diff --git a/server/jellyfin/auth_test.go b/server/jellyfin/auth_test.go index d659a86fb..d9f069987 100644 --- a/server/jellyfin/auth_test.go +++ b/server/jellyfin/auth_test.go @@ -8,10 +8,11 @@ import ( "strings" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -19,13 +20,12 @@ import ( var _ = Describe("AuthenticateByName", func() { var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - ur := ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) + Expect(ds.User().Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) api = &Router{ds: ds} }) @@ -107,15 +107,13 @@ var _ = Describe("AuthenticateByName", func() { api.authenticateByName(w, r) Expect(w.Code).To(Equal(http.StatusOK)) - ur := ds.User().(*tests.MockedUserRepo) - usr, err := ur.FindByUsername(ctx, "alice") + usr, err := ds.User().FindByUsername(ctx, "alice") Expect(err).ToNot(HaveOccurred()) Expect(usr.LastLoginAt).ToNot(BeNil()) }) It("reflects an administrator in the User.Policy", func() { - ur := ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(ctx, &model.User{ID: testID("admin1"), UserName: "root", NewPassword: "secret", IsAdmin: true})).To(Succeed()) + Expect(ds.User().Put(ctx, &model.User{ID: testID("admin1"), UserName: "root", NewPassword: "secret", IsAdmin: true})).To(Succeed()) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/AuthenticateByName", @@ -138,8 +136,7 @@ var _ = Describe("AuthenticateByName", func() { }) It("rejects an empty password even for a user with an empty stored password with 401", func() { - ur := ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(ctx, &model.User{ID: testID("e"), UserName: "empty", NewPassword: ""})).To(Succeed()) + Expect(ds.User().Put(ctx, &model.User{ID: testID("e"), UserName: "empty", NewPassword: ""})).To(Succeed()) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Users/AuthenticateByName", @@ -151,8 +148,7 @@ var _ = Describe("AuthenticateByName", func() { var _ = Describe("AuthenticateByName body limit", func() { It("rejects a request body larger than the limit", func() { - ds := &tests.MockDataStore{} - api := &Router{ds: ds} + api := &Router{ds: struct{ model.DataStore }{}} w := httptest.NewRecorder() body := `{"Username":"alice","Pw":"secret","Padding":"` + strings.Repeat("x", server.MaxLoginBodySize) + `"}` r := httptest.NewRequest(http.MethodPost, "/Users/AuthenticateByName", strings.NewReader(body)) diff --git a/server/jellyfin/browsing_test.go b/server/jellyfin/browsing_test.go index f22a48736..0f657c8e7 100644 --- a/server/jellyfin/browsing_test.go +++ b/server/jellyfin/browsing_test.go @@ -3,13 +3,16 @@ package jellyfin import ( "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -17,161 +20,142 @@ import ( var _ = Describe("Browsing", func() { var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore + alice := model.User{ID: testID("u1"), UserName: "alice"} + admin := model.User{ID: testID("admin"), UserName: "admin", IsAdmin: true} + + // ctxUser grants alice exactly libs, in the DB and in the request user. ctxUser := func(libs model.Libraries) context.Context { - return request.WithUser(ctx, model.User{ID: testID("u1"), UserName: "alice", Libraries: libs}) + ids := make([]int, len(libs)) + for i, lib := range libs { + ids[i] = lib.ID + } + Expect(ds.User().SetUserLibraries(ctx, alice.ID, ids)).To(Succeed()) + u := alice + u.Libraries = libs + return request.WithUser(ctx, u) } // admin has no explicit Libraries; access is granted via the IsAdmin bypass, not membership. ctxAdmin := func() context.Context { - return request.WithUser(ctx, model.User{ID: testID("admin"), IsAdmin: true, Libraries: nil}) + u := admin + u.Libraries = nil + return request.WithUser(ctx, u) + } + + get := func(handler http.HandlerFunc, url string, ctx context.Context) dto.QueryResult { + GinkgoHelper() + w := httptest.NewRecorder() + invoke(handler, w, httptest.NewRequest(http.MethodGet, url, nil).WithContext(ctx)) + Expect(w.Code).To(Equal(http.StatusOK)) + var res dto.QueryResult + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + return res } BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) + putUser(ctx, ds, alice) + putUser(ctx, ds, admin) + persistencetest.SetLibraries(ctx, ds, "/music1", "/music2", "/music3") api = &Router{ds: ds} }) Describe("getArtists", func() { It("lists artists via /Artists", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "A"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Artists", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "A"}) + res := get(api.getArtists, "/Artists", ctxUser(model.Libraries{{ID: 1}})) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Type).To(Equal("MusicArtist")) }) - It("handles /Artists/AlbumArtists the same way", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "A"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Artists/AlbumArtists", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) + It("lists only album artists on /Artists/AlbumArtists", func() { + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "A"}) + performer := model.Artist{ID: testID("ar2"), Name: "Performer", OrderArtistName: "performer"} + persistencetest.PutArtists(ctx, ds, 1, performer) + persistencetest.SetArtistStats(ctx, 1, map[model.Role]model.ArtistStats{model.RoleArtist: {SongCount: 1}}, performer.ID) + res := get(api.getAlbumArtists, "/Artists/AlbumArtists", ctxUser(model.Libraries{{ID: 1}})) + Expect(itemNames(res)).To(ConsistOf("A")) }) - It("scopes results to the user's accessible libraries", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Artists", nil).WithContext(ctxUser(libs)) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := artistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_artist.library_id")) - Expect(args).To(ContainElements(1, 2)) - }) + Context("with one artist in each library", func() { + BeforeEach(func() { + putArtistsIn(ctx, ds, 1, model.Artist{ID: testID("ar1"), Name: "One"}) + putArtistsIn(ctx, ds, 2, model.Artist{ID: testID("ar2"), Name: "Two"}) + putArtistsIn(ctx, ds, 3, model.Artist{ID: testID("ar3"), Name: "Three"}) + }) - It("scopes to a single library when ParentId is an accessible library id", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Artists?ParentId="+dto.EncodeLibraryID(2), nil).WithContext(ctxUser(libs)) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := artistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_artist.library_id")) - Expect(args).To(ContainElement(2)) - Expect(args).NotTo(ContainElement(1)) - }) + It("scopes results to the user's accessible libraries", func() { + res := get(api.getArtists, "/Artists", ctxUser(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("One", "Two")) + }) - It("does not let ParentId= narrow the scope", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}} // no access to library 99 - r := httptest.NewRequest(http.MethodGet, "/Artists?ParentId="+dto.EncodeLibraryID(99), nil).WithContext(ctxUser(libs)) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := artistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_artist.library_id")) - Expect(args).To(ContainElement(1)) - Expect(args).NotTo(ContainElement(99)) + It("scopes to a single library when ParentId is an accessible library id", func() { + res := get(api.getArtists, "/Artists?ParentId="+dto.EncodeLibraryID(2), ctxUser(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("Two")) + }) + + It("does not let ParentId= narrow the scope", func() { + res := get(api.getArtists, "/Artists?ParentId="+dto.EncodeLibraryID(3), ctxUser(model.Libraries{{ID: 1}})) + Expect(itemNames(res)).To(ConsistOf("One")) + }) + + It("does not restrict results for an admin user", func() { + res := get(api.getArtists, "/Artists", ctxAdmin()) + Expect(itemNames(res)).To(ConsistOf("One", "Two", "Three")) + }) }) It("forwards SearchTerm to the repo's Search method", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Artists?SearchTerm=art", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Artist"}, model.Artist{ID: testID("ar2"), Name: "Other"}) + res := get(api.getArtists, "/Artists?SearchTerm=art", ctxUser(model.Libraries{{ID: 1}})) + Expect(itemNames(res)).To(ConsistOf("Artist")) }) It("bounds a search the client left unbounded, and clamps an oversized one", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) + artists := make([]model.Artist, maxSearchLimit+1) + for i := range artists { + artists[i] = model.Artist{ID: testID(fmt.Sprintf("ar%05d", i)), Name: fmt.Sprintf("Artist %05d", i)} + } + putArtists(ctx, ds, artists...) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Artists?SearchTerm=art", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(artistRepo.Options.Max).To(Equal(defaultSearchLimit + 1)) + res := get(api.getArtists, "/Artists?SearchTerm=art", ctxUser(model.Libraries{{ID: 1}})) + Expect(res.Items).To(HaveLen(defaultSearchLimit)) + Expect(res.TotalRecordCount).To(Equal(defaultSearchLimit + 1)) - w = httptest.NewRecorder() - r = httptest.NewRequest(http.MethodGet, "/Artists?SearchTerm=art&Limit=999999", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(artistRepo.Options.Max).To(Equal(maxSearchLimit + 1)) + res = get(api.getArtists, "/Artists?SearchTerm=art&Limit=999999", ctxUser(model.Libraries{{ID: 1}})) + Expect(res.Items).To(HaveLen(maxSearchLimit)) + Expect(res.TotalRecordCount).To(Equal(maxSearchLimit + 1)) }) It("forwards StartIndex/Limit as Offset/Max", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Artists?StartIndex=5&Limit=10", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(artistRepo.Options.Offset).To(Equal(5)) - Expect(artistRepo.Options.Max).To(Equal(10)) - }) - - It("does not restrict results for an admin user", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Artists", nil).WithContext(ctxAdmin()) - invoke(api.getArtists, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - // accessibleLibraryIDs is empty for an admin (Libraries is nil), so - // ApplyArtistLibraryFilter([]) is a no-op: no library_id restriction is added. - if artistRepo.Options.Filters == nil { - return + var artists []model.Artist + for i := range 20 { + name := fmt.Sprintf("Artist %02d", i) + artists = append(artists, model.Artist{ID: testID(name), Name: name}) } - sql, _, err := artistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).NotTo(ContainSubstring("library_artist.library_id")) + putArtists(ctx, ds, artists...) + all := itemNames(get(api.getArtists, "/Artists", ctxUser(model.Libraries{{ID: 1}}))) + Expect(all).To(HaveLen(20)) + + res := get(api.getArtists, "/Artists?StartIndex=5&Limit=10", ctxUser(model.Libraries{{ID: 1}})) + Expect(itemNames(res)).To(Equal(all[5:15])) + Expect(res.TotalRecordCount).To(Equal(20)) }) DescribeTable("restricts to favorites", func(url string, handler func(*Router) http.HandlerFunc) { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, url, nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(handler(api), w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := artistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("starred")) + putArtists(ctx, ds, + model.Artist{ID: testID("ar1"), Name: "Starred"}, + model.Artist{ID: testID("ar2"), Name: "Plain"}, + model.Artist{ID: testID("ar3"), Name: "Starred Missing", Missing: true}, + ) + userCtx := ctxUser(model.Libraries{{ID: 1}}) + Expect(ds.Artist().SetStar(userCtx, true, testID("ar1"), testID("ar3"))).To(Succeed()) + res := get(handler(api), url, userCtx) // listArtists always ANDs notMissing, favorites filter or not. - Expect(sql).To(ContainSubstring("missing")) - Expect(args).To(ContainElement(true)) + Expect(itemNames(res)).To(ConsistOf("Starred")) }, Entry("Filters=IsFavorite", "/Artists?Filters=IsFavorite", func(a *Router) http.HandlerFunc { return a.getArtists }), @@ -182,8 +166,7 @@ var _ = Describe("Browsing", func() { ) It("404s a malformed ParentId instead of listing every library's artists", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Artist"}) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Artists?ParentId=not-a-valid-id", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) invoke(api.getArtists, w, r) @@ -193,55 +176,42 @@ var _ = Describe("Browsing", func() { Describe("getGenres", func() { It("lists genres via /Genres", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Genres", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getGenres, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + res := get(api.getGenres, "/Genres", ctxUser(model.Libraries{{ID: 1}})) Expect(res.Items).NotTo(BeNil()) }) It("handles /MusicGenres the same way", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/MusicGenres", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getGenres, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) + get(api.getGenres, "/MusicGenres", ctxUser(model.Libraries{{ID: 1}})) }) It("treats a negative StartIndex as 0 instead of panicking", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Genres?StartIndex=-1&Limit=5", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getGenres, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + res := get(api.getGenres, "/Genres?StartIndex=-1&Limit=5", ctxUser(model.Libraries{{ID: 1}})) Expect(res.StartIndex).To(Equal(0)) }) }) + // putTagPerLibrary stores one tag named after each library it is in. + putTagPerLibrary := func(name model.TagName, prefix string) { + for _, libID := range []int{1, 2, 3} { + Expect(ds.Tag().Add(ctx, libID, model.NewTag(name, fmt.Sprintf("%s%d", prefix, libID)))).To(Succeed()) + } + } + Describe("getStudios", func() { + BeforeEach(func() { + putTagPerLibrary(model.TagRecordLabel, "Label ") + }) + It("scopes results to the user's accessible libraries", func() { - tagRepo := ds.Tag().(*tests.MockTagRepo) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Studios", nil).WithContext(ctxUser(model.Libraries{{ID: 1}, {ID: 2}})) - invoke(api.getStudios, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := tagRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_tag.library_id")) - Expect(args).To(ContainElements(1, 2)) + res := get(api.getStudios, "/Studios", ctxUser(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("Label 1", "Label 2")) }) // An empty scope (admin, or a non-admin with no explicit library grants) must be treated // as unrestricted, matching accessibleLibraryIDs' documented contract, not as "match nothing". It("does not restrict results for an admin user", func() { - tagRepo := ds.Tag().(*tests.MockTagRepo) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Studios", nil).WithContext(ctxAdmin()) - invoke(api.getStudios, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(tagRepo.Options.Filters).To(BeNil()) + res := get(api.getStudios, "/Studios", ctxAdmin()) + Expect(itemNames(res)).To(ConsistOf("Label 1", "Label 2", "Label 3")) }) It("404s a malformed ParentId instead of listing every library's studios", func() { @@ -252,36 +222,32 @@ var _ = Describe("Browsing", func() { }) It("treats a negative StartIndex as 0 instead of panicking", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Studios?StartIndex=-1&Limit=5", nil).WithContext(ctxUser(model.Libraries{{ID: 1}})) - invoke(api.getStudios, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + res := get(api.getStudios, "/Studios?StartIndex=-1&Limit=5", ctxUser(model.Libraries{{ID: 1}})) Expect(res.StartIndex).To(Equal(0)) }) }) Describe("getQueryFiltersLegacy", func() { - It("scopes genres to the user's accessible libraries", func() { - genreRepo := ds.Genre().(*tests.MockedGenreRepo) + filters := func(ctx context.Context) dto.QueryFiltersLegacy { + GinkgoHelper() w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/Filters", nil).WithContext(ctxUser(model.Libraries{{ID: 1}, {ID: 2}})) - invoke(api.getQueryFiltersLegacy, w, r) + invoke(api.getQueryFiltersLegacy, w, httptest.NewRequest(http.MethodGet, "/Items/Filters", nil).WithContext(ctx)) Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := genreRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_tag.library_id")) - Expect(args).To(ContainElements(1, 2)) + var res dto.QueryFiltersLegacy + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + return res + } + + BeforeEach(func() { + putTagPerLibrary(model.TagGenre, "Genre ") + }) + + It("scopes genres to the user's accessible libraries", func() { + Expect(filters(ctxUser(model.Libraries{{ID: 1}, {ID: 2}})).Genres).To(ConsistOf("Genre 1", "Genre 2")) }) It("does not restrict genres for an admin user", func() { - genreRepo := ds.Genre().(*tests.MockedGenreRepo) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/Filters", nil).WithContext(ctxAdmin()) - invoke(api.getQueryFiltersLegacy, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(genreRepo.Options.Filters).To(BeNil()) + Expect(filters(ctxAdmin()).Genres).To(ConsistOf("Genre 1", "Genre 2", "Genre 3")) }) It("404s a malformed ParentId instead of listing every library's filters", func() { @@ -292,3 +258,11 @@ var _ = Describe("Browsing", func() { }) }) }) + +func itemNames(res dto.QueryResult) []string { + names := make([]string, len(res.Items)) + for i, it := range res.Items { + names[i] = it.Name + } + return names +} diff --git a/server/jellyfin/e2e/e2e_suite_test.go b/server/jellyfin/e2e/e2e_suite_test.go index 3b5cb7d25..8ee229801 100644 --- a/server/jellyfin/e2e/e2e_suite_test.go +++ b/server/jellyfin/e2e/e2e_suite_test.go @@ -89,7 +89,7 @@ var ( // Shared test state var ( ctx context.Context - ds *tests.MockDataStore + ds model.DataStore router http.Handler streamerSpy *harness.SpyStreamer artworkSpy *spyArtwork @@ -330,7 +330,7 @@ func setupTestDB() { goldenDB.Restore() - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds = persistence.New(db.Db()) auth.Init(ds) streamerSpy = &harness.SpyStreamer{} diff --git a/server/jellyfin/images_test.go b/server/jellyfin/images_test.go index d2eb620c0..96e611fb4 100644 --- a/server/jellyfin/images_test.go +++ b/server/jellyfin/images_test.go @@ -16,13 +16,16 @@ import ( "strings" "time" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/go-chi/chi/v5" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -62,12 +65,17 @@ func newImageRequest(itemId string) (*httptest.ResponseRecorder, *http.Request) } var _ = Describe("Images", func() { + var ctx context.Context + BeforeEach(func() { + ctx = GinkgoT().Context() + }) + // Real Jellyfin fits the image inside either bound, so a client that sends only MaxHeight must // still get a resized image rather than the full-size original. DescribeTable("derives the requested size from the Jellyfin size params", func(query string, wantSize int) { - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) fa := &fakeArtwork{} api := &Router{ds: ds, artwork: fa} @@ -95,8 +103,8 @@ var _ = Describe("Images", func() { ) It("streams album artwork", func() { - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) fa := &fakeArtwork{} api := &Router{ds: ds, artwork: fa} @@ -110,9 +118,8 @@ var _ = Describe("Images", func() { // A malformed itemId now 404s via itemIDParam instead of falling through to a placeholder image. It("404s a malformed itemId instead of serving a placeholder", func() { - ds := &tests.MockDataStore{} fa := &fakeArtwork{} - api := &Router{ds: ds, artwork: fa} + api := &Router{ds: struct{ model.DataStore }{}, artwork: fa} w, r := newImageRequest("not-a-valid-id") api.getItemImage(w, r) @@ -123,7 +130,7 @@ var _ = Describe("Images", func() { // resolveArtworkID probes the entity tables, so a deleted item yields no artwork id at all. It("asks for no artwork once the item is deleted, rather than its lingering state", func() { - ds := &tests.MockDataStore{} // no albums/artists/tracks/playlists at all + ds := persistence.New(db.Db()) fa := &fakeArtwork{} api := &Router{ds: ds, artwork: fa} @@ -136,8 +143,8 @@ var _ = Describe("Images", func() { }) It("sniffs the Content-Type instead of hardcoding it", func() { - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) png := append([]byte{0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'}, make([]byte, 512)...) fa := &fakeArtwork{data: png} @@ -151,8 +158,9 @@ var _ = Describe("Images", func() { }) It("resolves a playlist's cover regardless of visibility, even for an anonymous caller", func() { - ds := &tests.MockDataStore{} - ds.Playlist().(*tests.MockPlaylistRepo).SetData(model.Playlists{{ID: testID("pl1"), Name: "Mix", OwnerID: testID("someone")}}) + ds := persistence.New(db.Db()) + putUser(ctx, ds, model.User{ID: testID("someone"), UserName: "someone"}) + Expect(ds.Playlist().Put(ctx, &model.Playlist{ID: testID("pl1"), Name: "Mix", OwnerID: testID("someone")})).To(Succeed()) fa := &fakeArtwork{} api := &Router{ds: ds, artwork: fa} @@ -167,8 +175,8 @@ var _ = Describe("Images", func() { // elevated context; otherwise a private playlist's cover fails its visibility filter and // silently falls back to the placeholder. It("resolves artwork under an elevated admin context", func() { - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) fa := &fakeArtwork{} api := &Router{ds: ds, artwork: fa} @@ -183,8 +191,8 @@ var _ = Describe("Images", func() { It("serves immutable when the tag param asserts the current hash", func() { const hash = "0123456789abcdef" - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) fa := &fakeArtwork{hash: hash} api := &Router{ds: ds, artwork: fa} @@ -201,8 +209,8 @@ var _ = Describe("Images", func() { It("revalidates via no-cache when no tag is provided", func() { const hash = "0123456789abcdef" - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) fa := &fakeArtwork{hash: hash} api := &Router{ds: ds, artwork: fa} diff --git a/server/jellyfin/items_test.go b/server/jellyfin/items_test.go index 1545f58f8..207ef2d6e 100644 --- a/server/jellyfin/items_test.go +++ b/server/jellyfin/items_test.go @@ -3,18 +3,19 @@ package jellyfin import ( "context" "encoding/json" + "errors" "fmt" "math" "net/http" "net/http/httptest" - "slices" - "strings" "github.com/go-chi/chi/v5" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/req" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -30,43 +31,190 @@ func withChiURLParam(r *http.Request, kv ...string) *http.Request { return r.WithContext(context.WithValue(r.Context(), chi.RouteCtxKey, rctx)) } +// queryRecorder records the options of the last list query each repository ran, for specs about what +// reaches the query (sort keys, window sizes, id batching) rather than about the rows it returns. +type queryRecorder struct { + albums *recordedQuery + songs *recordedQuery +} + +type recordedQuery struct { + Options model.QueryOptions + SearchQuery string + GetAlls int + Gets int +} + +func newQueryRecorder() *queryRecorder { + return &queryRecorder{albums: &recordedQuery{}, songs: &recordedQuery{}} +} + +func (q *queryRecorder) stub(ds model.DataStore) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{ + Album: func(r model.AlbumRepository) model.AlbumRepository { + return recordingAlbums{AlbumRepository: r, rec: q.albums} + }, + MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return recordingSongs{MediaFileRepository: r, rec: q.songs} + }, + }) +} + +func (r *recordedQuery) record(options []model.QueryOptions) { + r.Options = model.QueryOptions{} + if len(options) > 0 { + r.Options = options[0] + } +} + +type recordingAlbums struct { + model.AlbumRepository + rec *recordedQuery +} + +func (r recordingAlbums) GetAll(ctx context.Context, options ...model.QueryOptions) (model.Albums, error) { + r.rec.record(options) + return r.AlbumRepository.GetAll(ctx, options...) +} + +func (r recordingAlbums) GetCursor(ctx context.Context, options ...model.QueryOptions) (model.AlbumCursor, error) { + r.rec.record(options) + return r.AlbumRepository.GetCursor(ctx, options...) +} + +func (r recordingAlbums) Search(ctx context.Context, q string, options ...model.QueryOptions) (model.Albums, error) { + r.rec.record(options) + r.rec.SearchQuery = q + return r.AlbumRepository.Search(ctx, q, options...) +} + +type recordingSongs struct { + model.MediaFileRepository + rec *recordedQuery +} + +func (r recordingSongs) GetAll(ctx context.Context, options ...model.QueryOptions) (model.MediaFiles, error) { + r.rec.record(options) + r.rec.GetAlls++ + return r.MediaFileRepository.GetAll(ctx, options...) +} + +func (r recordingSongs) Get(ctx context.Context, id string) (*model.MediaFile, error) { + r.rec.Gets++ + return r.MediaFileRepository.Get(ctx, id) +} + +func (r recordingSongs) GetCursorWithArtwork(ctx context.Context, options ...model.QueryOptions) (model.MediaFileCursor, error) { + r.rec.record(options) + return r.MediaFileRepository.GetCursorWithArtwork(ctx, options...) +} + +func (r recordingSongs) Search(ctx context.Context, q string, options ...model.QueryOptions) (model.MediaFiles, error) { + r.rec.record(options) + r.rec.SearchQuery = q + return r.MediaFileRepository.Search(ctx, q, options...) +} + +func failingSongs(ds model.DataStore) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return failingSongRepo{MediaFileRepository: r} + }}) +} + +type failingSongRepo struct { + model.MediaFileRepository +} + +func (failingSongRepo) GetCursorWithArtwork(context.Context, ...model.QueryOptions) (model.MediaFileCursor, error) { + return nil, errors.New("db down") +} + var _ = Describe("Items", func() { var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore + var rec *queryRecorder var fp *fakePlaylists + alice := model.User{ID: testID("u1"), UserName: "alice"} + admin := model.User{ID: testID("admin"), UserName: "admin", IsAdmin: true} + // ctxUserWithLibraries grants alice exactly libs, in the DB and in the request user. + ctxUserWithLibraries := func(libs model.Libraries) context.Context { + ids := make([]int, len(libs)) + for i, lib := range libs { + ids[i] = lib.ID + } + Expect(ds.User().SetUserLibraries(ctx, alice.ID, ids)).To(Succeed()) + u := alice + u.Libraries = libs + return request.WithUser(ctx, u) + } // alice has access to library 1 only; used by tests that don't care about scoping. ctxUser := func() context.Context { - return request.WithUser(ctx, model.User{ID: testID("u1"), UserName: "alice", Libraries: model.Libraries{{ID: 1, Name: "Music"}}}) - } - ctxUserWithLibraries := func(libs model.Libraries) context.Context { - return request.WithUser(ctx, model.User{ID: testID("u1"), UserName: "alice", Libraries: libs}) + return ctxUserWithLibraries(model.Libraries{{ID: 1, Name: "Music"}}) } // admin has no explicit Libraries; access is granted via the IsAdmin bypass, not membership. ctxAdmin := func() context.Context { - return request.WithUser(ctx, model.User{ID: testID("admin"), IsAdmin: true, Libraries: nil}) + return request.WithUser(ctx, admin) + } + getItems := func(url string, ctx context.Context) (int, dto.QueryResult) { + GinkgoHelper() + w := httptest.NewRecorder() + invoke(api.getItems, w, httptest.NewRequest(http.MethodGet, url, nil).WithContext(ctx)) + var res dto.QueryResult + if w.Code == http.StatusOK { + Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + } + return w.Code, res + } + // albumsPerLibrary stores the albums One, Two and Three in libraries 1, 2 and 3. + albumsPerLibrary := func() { + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}, + model.Album{ID: testID("a2"), Name: "Two", LibraryID: 2}, + model.Album{ID: testID("a3"), Name: "Three", LibraryID: 3}, + ) + } + // manySongs stores n songs titled "Song 00000", "Song 00001", ... and returns their ids in that order. + manySongs := func(n int) []string { + ids := make([]string, n) + inTx(ds, func(tx model.DataStore) { + for i := range ids { + ids[i] = testID(fmt.Sprintf("s%05d", i)) + persistencetest.PutMediaFiles(ctx, tx, model.MediaFile{ID: ids[i], Title: fmt.Sprintf("Song %05d", i)}) + } + }) + return ids + } + manyAlbums := func(n int) { + inTx(ds, func(tx model.DataStore) { + for i := range n { + persistencetest.PutAlbums(ctx, tx, model.Album{ID: testID(fmt.Sprintf("a%05d", i)), Name: fmt.Sprintf("One %05d", i)}) + } + }) } BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - fp = &fakePlaylists{} - api = &Router{ds: ds, playlists: fp} + ds = persistence.New(db.Db()) + putUser(ctx, ds, alice) + putUser(ctx, ds, admin) + persistencetest.SetLibraries(ctx, ds, "/music1", "/music2", "/music3") + rec = newQueryRecorder() + fp = &fakePlaylists{ds: ds} + api = &Router{ds: rec.stub(ds), playlists: fp} }) Describe("getItems", func() { Describe("at the user root", func() { libs := model.Libraries{{ID: 1, Name: "Music"}, {ID: 2, Name: "Audiobooks"}} getRoot := func(query string, ctx context.Context) dto.QueryResult { - w := httptest.NewRecorder() - invoke(api.getItems, w, httptest.NewRequest(http.MethodGet, "/Items?"+query, nil).WithContext(ctx)) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + GinkgoHelper() + code, res := getItems("/Items?"+query, ctx) + Expect(code).To(Equal(http.StatusOK)) return res } BeforeEach(func() { - ds.Library().(*tests.MockLibraryRepo).SetData(libs) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) + putLibraries(ctx, ds, libs) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", MaxYear: 2020, MinYear: 2020}) }) It("lists the user's libraries for an unfiltered, non-recursive query", func() { @@ -121,55 +269,49 @@ var _ = Describe("Items", func() { }) It("lists albums when IncludeItemTypes=MusicAlbum", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&Recursive=true", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&Recursive=true", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) Expect(res.Items[0].Type).To(Equal("MusicAlbum")) Expect(res.TotalRecordCount).To(Equal(2)) }) - It("lists an album's songs when ParentId is an album and type is Audio", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) - Expect(res.Items[0].Type).To(Equal("Audio")) - Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) - }) + Context("with songs in two albums", func() { + BeforeEach(func() { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}, + model.MediaFile{ID: testID("s2"), Title: "Other", AlbumID: testID("a2")}, + ) + }) - It("ignores IncludeItemTypes names that aren't Jellyfin item kinds", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", AlbumID: testID("a1")}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=music", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) - Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) + It("lists an album's songs when ParentId is an album and type is Audio", func() { + _, res := getItems("/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio", ctxUser()) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Type).To(Equal("Audio")) + Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) + }) + + It("ignores IncludeItemTypes names that aren't Jellyfin item kinds", func() { + _, res := getItems("/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=music", ctxUser()) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) + }) + + It("falls through to the type dispatch when ParentId is not a playlist", func() { + code, res := getItems("/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) + }) }) It("lists a playlist's tracks when ParentId is a playlist, whatever the type", func() { - fp.getPls = &model.Playlist{ID: testID("pl1"), Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}}, - {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}}, - }} - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("pl1"))+"&IncludeItemTypes=Audio", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + putSongsByID(ctx, ds, testID("s1"), testID("s2")) + putPlaylist(ctx, ds, testID("pl1"), testID("s1"), testID("s2")) + code, res := getItems("/Items?ParentId="+dto.EncodeID(testID("pl1"))+"&IncludeItemTypes=Audio", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) Expect(res.Items[0].PlaylistItemId).To(Equal(dto.EncodePlaylistEntryID("1"))) @@ -177,18 +319,10 @@ var _ = Describe("Items", func() { }) It("pages a playlist parent's tracks in the query, not in memory", func() { - fp.getPls = &model.Playlist{ID: testID("pl1"), Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}}, - {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}}, - {ID: "3", MediaFileID: testID("s3"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s3")}}, - }} - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("pl1"))+"&StartIndex=1&Limit=1", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + putSongsByID(ctx, ds, testID("s1"), testID("s2"), testID("s3")) + putPlaylist(ctx, ds, testID("pl1"), testID("s1"), testID("s2"), testID("s3")) + code, res := getItems("/Items?ParentId="+dto.EncodeID(testID("pl1"))+"&StartIndex=1&Limit=1", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.TotalRecordCount).To(Equal(3)) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s2")))) @@ -196,147 +330,85 @@ var _ = Describe("Items", func() { Expect(fp.tracksRepo.Options.Max).To(Equal(1)) }) - It("falls through to the type dispatch when ParentId is not a playlist", func() { - fp.getErr = model.ErrNotFound - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), AlbumID: testID("a1")}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) - Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) - }) - It("returns 500 when the song cursor fails to open, instead of a truncated 200", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetError(true) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio&Recursive=true", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusInternalServerError)) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + api.ds = failingSongs(ds) + code, _ := getItems("/Items?IncludeItemTypes=Audio&Recursive=true", ctxUser()) + Expect(code).To(Equal(http.StatusInternalServerError)) }) // Recursive=false asks for direct children only. Finamp's sync probes a library this way // looking for tracks outside any album; answering with every track streams the whole library. Describe("Recursive=false", func() { BeforeEach(func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), AlbumID: testID("a1")}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), AlbumID: testID("a1")}) }) It("returns no songs for a library parent, as tracks are never its direct children", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=Audio&Recursive=false", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + code, res := getItems("/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=Audio&Recursive=false", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(BeEmpty()) Expect(res.TotalRecordCount).To(BeZero()) }) It("drops only Audio from a multi-type library query", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=Audio,MusicAlbum&Recursive=false", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=Audio,MusicAlbum&Recursive=false", ctxUser()) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Type).To(Equal("MusicAlbum")) }) It("still lists albums for a library parent, as they are its direct children", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=MusicAlbum&Recursive=false", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=MusicAlbum&Recursive=false", ctxUser()) Expect(res.Items).To(HaveLen(1)) }) It("still lists an album's tracks, as they are its direct children", func() { - fp.getErr = model.ErrNotFound - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio&Recursive=false", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?ParentId="+dto.EncodeID(testID("a1"))+"&IncludeItemTypes=Audio&Recursive=false", ctxUser()) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) }) It("keeps returning every song when no parent scopes the query", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio&Recursive=false", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?IncludeItemTypes=Audio&Recursive=false", ctxUser()) Expect(res.Items).To(HaveLen(1)) }) // Jellyfin's own default: ItemsController binds `bool? recursive` and reads it as // `recursive ?? false`, so an omitted Recursive is a non-recursive request. It("treats an omitted Recursive as false, like Jellyfin", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=Audio", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?ParentId="+dto.EncodeLibraryID(1)+"&IncludeItemTypes=Audio", ctxUser()) Expect(res.Items).To(BeEmpty()) }) }) It("lists an artist's albums when ParentId is an artist and type is MusicAlbum", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", AlbumArtistID: testID("ar1")}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeID(testID("ar1"))+"&IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) - albumRepo := ds.Album().(*tests.MockAlbumRepo) - sql, _, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("album_artists")) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Artist"}, model.Artist{ID: testID("ar2"), Name: "Other"}) + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: testID("a1"), Name: "One", AlbumArtistID: testID("ar1"), Participants: credits(model.RoleAlbumArtist, testID("ar1"))}, + model.Album{ID: testID("a2"), Name: "Two", AlbumArtistID: testID("ar2"), Participants: credits(model.RoleAlbumArtist, testID("ar2"))}, + ) + _, res := getItems("/Items?ParentId="+dto.EncodeID(testID("ar1"))+"&IncludeItemTypes=MusicAlbum", ctxUser()) + Expect(itemNames(res)).To(ConsistOf("One")) }) It("lists artists when IncludeItemTypes=MusicArtist", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicArtist", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Artist"}) + _, res := getItems("/Items?IncludeItemTypes=MusicArtist", ctxUser()) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Type).To(Equal("MusicArtist")) }) It("lists genres when IncludeItemTypes=MusicGenre", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicGenre", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + code, res := getItems("/Items?IncludeItemTypes=MusicGenre", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).NotTo(BeNil()) }) It("lists playlists when IncludeItemTypes=Playlist", func() { - ds.Playlist().(*tests.MockPlaylistRepo).SetData(model.Playlists{{ID: testID("p1"), Name: "My Mix", SongCount: 5}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Playlist", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + Expect(ds.Playlist().Put(ctxUser(), &model.Playlist{ID: testID("p1"), Name: "My Mix", OwnerID: alice.ID})).To(Succeed()) + code, res := getItems("/Items?IncludeItemTypes=Playlist", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Type).To(Equal("Playlist")) Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("p1")))) @@ -344,212 +416,160 @@ var _ = Describe("Items", func() { }) It("merges results from every requested type in IncludeItemTypes", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + code, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) types := []string{res.Items[0].Type, res.Items[1].Type} Expect(types).To(ConsistOf("Audio", "MusicAlbum")) Expect(res.TotalRecordCount).To(Equal(2)) }) - // @jellyfin/sdk (Jellify) sends array params as repeated keys. - It("merges results from every repeated IncludeItemTypes key", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Salt"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Salt"}}) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "Salt"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?SearchTerm=Salt&IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio&IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(3)) - types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} - Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) - Expect(res.TotalRecordCount).To(Equal(3)) - }) + Context("with an artist, a song and an album all named Salt", func() { + BeforeEach(func() { + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Salt"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Salt"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "Salt"}) + }) - It("mixes a repeated IncludeItemTypes key with a comma-separated one", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1"), Name: "Salt"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Salt"}}) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "Salt"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio,MusicAlbum", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} - Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + // @jellyfin/sdk (Jellify) sends array params as repeated keys. + It("merges results from every repeated IncludeItemTypes key", func() { + code, res := getItems("/Items?SearchTerm=Salt&IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio&IncludeItemTypes=MusicAlbum", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(3)) + types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} + Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + Expect(res.TotalRecordCount).To(Equal(3)) + }) + + It("mixes a repeated IncludeItemTypes key with a comma-separated one", func() { + code, res := getItems("/Items?IncludeItemTypes=MusicArtist&IncludeItemTypes=Audio,MusicAlbum", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(3)) + types := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type} + Expect(types).To(ConsistOf("MusicArtist", "Audio", "MusicAlbum")) + }) }) It("merges favorite songs, albums, and playlists", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - playlistRepo := ds.Playlist().(*tests.MockPlaylistRepo) - playlistRepo.SetData(model.Playlists{{ID: testID("p1"), Name: "My Mix", Starred: true}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum,Playlist&Filters=IsFavorite", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}, model.MediaFile{ID: testID("s2"), Title: "Plain Song"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Plain Album"}) + Expect(ds.Playlist().Put(ctxUser(), &model.Playlist{ID: testID("p1"), Name: "My Mix", OwnerID: alice.ID})).To(Succeed()) + Expect(ds.Playlist().Put(ctxUser(), &model.Playlist{ID: testID("p2"), Name: "Plain Mix", OwnerID: alice.ID})).To(Succeed()) + annotate(alice.ID, "media_file", testID("s1"), model.Annotations{Starred: true}) + annotate(alice.ID, "album", testID("a1"), model.Annotations{Starred: true}) + annotate(alice.ID, "playlist", testID("p1"), model.Annotations{Starred: true}) + code, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum,Playlist&Filters=IsFavorite", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(3)) + Expect(itemNames(res)).To(ConsistOf("Song", "One", "My Mix")) types := []string{res.Items[0].Type, res.Items[1].Type} types = append(types, res.Items[2].Type) Expect(types).To(ConsistOf("Audio", "MusicAlbum", "Playlist")) - sql, _, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("starred")) - playlistSQL, _, err := playlistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(playlistSQL).To(ContainSubstring("starred")) }) - It("applies every repeated Filters key", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&Filters=IsFavorite&Filters=IsPlayed", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, _, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("starred")) - Expect(sql).To(ContainSubstring("play_count")) + Context("with albums in every favorite and played combination", func() { + BeforeEach(func() { + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Artist"}) + byArtist := credits(model.RoleAlbumArtist, testID("ar1")) + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: testID("fav-played"), Name: "Favorite Played", Participants: byArtist}, + model.Album{ID: testID("fav-unplayed"), Name: "Favorite Unplayed", Participants: byArtist}, + model.Album{ID: testID("played"), Name: "Played", Participants: byArtist}, + model.Album{ID: testID("unplayed"), Name: "Unplayed", Participants: byArtist}, + model.Album{ID: testID("fav-missing"), Name: "Favorite Missing", Missing: true, Participants: byArtist}, + ) + annotate(alice.ID, "album", testID("fav-played"), model.Annotations{Starred: true, PlayCount: 1}) + annotate(alice.ID, "album", testID("fav-unplayed"), model.Annotations{Starred: true}) + annotate(alice.ID, "album", testID("played"), model.Annotations{PlayCount: 1}) + annotate(alice.ID, "album", testID("fav-missing"), model.Annotations{Starred: true}) + }) + + It("applies every repeated Filters key", func() { + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&Filters=IsFavorite&Filters=IsPlayed", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf("Favorite Played")) + }) + + DescribeTable("translates the Filters list and its standalone equivalents", + func(query string, want ...string) { + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&"+query, ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf(want)) + }, + Entry("IsFavorite", "Filters=IsFavorite", "Favorite Played", "Favorite Unplayed"), + Entry("IsFavorite,IsUnplayed combined", "Filters=IsFavorite,IsUnplayed", "Favorite Unplayed"), + Entry("IsUnplayed", "Filters=IsUnplayed", "Favorite Unplayed", "Unplayed"), + Entry("IsPlayed", "Filters=IsPlayed", "Favorite Played", "Played"), + Entry("IsFavoriteOrLikes is treated as favorites", "Filters=IsFavoriteOrLikes", "Favorite Played", "Favorite Unplayed"), + Entry("isPlayed=false", "isPlayed=false", "Favorite Unplayed", "Unplayed"), + Entry("isFavorite=false still filters", "isFavorite=false", "Played", "Unplayed"), + // Jellyfin builds the query from the standalone params, then applies Filters over the top. + Entry("Filters wins over the standalone param", "isFavorite=false&Filters=IsFavorite", + "Favorite Played", "Favorite Unplayed"), + // No Navidrome equivalent: these must be dropped, not half-applied. + Entry("Likes is ignored", "Filters=Likes", "Favorite Played", "Favorite Unplayed", "Played", "Unplayed"), + Entry("IsResumable is ignored", "Filters=IsResumable", "Favorite Played", "Favorite Unplayed", "Played", "Unplayed"), + // The artist-parent branch gets notMissing from filter.AlbumsByArtistID, not the default + // branch, so favorites must not be the only predicate left on it. + Entry("keeps missing excluded under an artist parent", + "Filters=IsFavorite&ArtistIds="+dto.EncodeID(testID("ar1")), "Favorite Played", "Favorite Unplayed"), + ) }) It("applies StartIndex/Limit to the merged multi-type result set", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}}) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=1&Limit=2", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}, model.MediaFile{ID: testID("s2"), Title: "Song2"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + code, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=1&Limit=2", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) Expect(res.TotalRecordCount).To(Equal(4)) Expect(res.StartIndex).To(Equal(1)) }) It("caps each per-type query at StartIndex+Limit instead of fetching everything", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}}) - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=1&Limit=2", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}, model.MediaFile{ID: testID("s2"), Title: "Song2"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + code, _ := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=1&Limit=2", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) // The merged window is [1, 3): each type needs at most its first 3 rows, not the table. - Expect(mfRepo.Options.Max).To(Equal(3)) - Expect(albumRepo.Options.Max).To(Equal(3)) + Expect(rec.songs.Options.Max).To(Equal(3)) + Expect(rec.albums.Options.Max).To(Equal(3)) }) It("treats a negative StartIndex as 0 on the multi-type merge instead of panicking", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}, {ID: testID("s2"), Title: "Song2"}}) - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=-1&Limit=2", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}, model.MediaFile{ID: testID("s2"), Title: "Song2"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + code, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&StartIndex=-1&Limit=2", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.StartIndex).To(Equal(0)) Expect(res.Items).To(HaveLen(2)) Expect(res.TotalRecordCount).To(Equal(4)) // The clamped offset must feed the per-type window too: 0+Limit, not -1+Limit. - Expect(mfRepo.Options.Max).To(Equal(2)) - Expect(albumRepo.Options.Max).To(Equal(2)) + Expect(rec.songs.Options.Max).To(Equal(2)) + Expect(rec.albums.Options.Max).To(Equal(2)) }) It("clamps a negative StartIndex to 0 on the single-type path", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&StartIndex=-1&Limit=10", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Offset).To(Equal(0)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&StartIndex=-1&Limit=10", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(rec.albums.Options.Offset).To(Equal(0)) Expect(res.StartIndex).To(Equal(0)) Expect(res.Items).To(HaveLen(1)) }) - DescribeTable("translates the Filters list and its standalone equivalents", - func(query string, wantSQL, notWantSQL []string) { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&"+query, nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, _, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - for _, want := range wantSQL { - Expect(sql).To(ContainSubstring(want)) - } - for _, not := range notWantSQL { - Expect(sql).NotTo(ContainSubstring(not)) - } - }, - Entry("IsFavorite", "Filters=IsFavorite", []string{"starred"}, nil), - Entry("IsFavorite,IsUnplayed combined", "Filters=IsFavorite,IsUnplayed", - []string{"starred", "play_count"}, nil), - Entry("IsUnplayed", "Filters=IsUnplayed", []string{"play_count"}, []string{"starred"}), - Entry("IsPlayed", "Filters=IsPlayed", []string{"play_count"}, []string{"starred"}), - Entry("IsFavoriteOrLikes is treated as favorites", "Filters=IsFavoriteOrLikes", []string{"starred"}, nil), - Entry("isPlayed=false", "isPlayed=false", []string{"play_count"}, nil), - Entry("isFavorite=false still filters", "isFavorite=false", []string{"starred"}, nil), - // Jellyfin builds the query from the standalone params, then applies Filters over the top. - Entry("Filters wins over the standalone param", "isFavorite=false&Filters=IsFavorite", - []string{"starred = "}, nil), - // No Navidrome equivalent: these must be dropped, not half-applied. - Entry("Likes is ignored", "Filters=Likes", nil, []string{"starred", "play_count"}), - Entry("IsResumable is ignored", "Filters=IsResumable", nil, []string{"starred", "play_count"}), - // The artist-parent branch gets notMissing from filter.AlbumsByArtistID, not the default - // branch, so favorites must not be the only predicate left on it. - Entry("keeps missing excluded under an artist parent", - "Filters=IsFavorite&ArtistIds="+dto.EncodeID(testID("ar1")), - []string{"starred", "missing"}, nil), - ) - // Search runs a two-phase FTS query whose first phase has no annotation join, so an // annotation predicate there is "no such column: starred" -> 500. DescribeTable("does not push annotation filters into a search", func(itemType, filters string) { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes="+itemType+"&SearchTerm=one&Filters="+filters, nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var opts model.QueryOptions - if itemType == "MusicAlbum" { - opts = ds.Album().(*tests.MockAlbumRepo).Options - } else { - opts = ds.MediaFile().(*tests.MockMediaFileRepo).Options - } - if opts.Filters == nil { - return - } - sql, _, err := opts.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).NotTo(ContainSubstring("starred")) - Expect(sql).NotTo(ContainSubstring("play_count")) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "One Song"}) + annotate(alice.ID, "album", testID("a1"), model.Annotations{Starred: true, PlayCount: 1}) + annotate(alice.ID, "media_file", testID("s1"), model.Annotations{Starred: true, PlayCount: 1}) + code, _ := getItems("/Items?IncludeItemTypes="+itemType+"&SearchTerm=one&Filters="+filters, ctxUser()) + Expect(code).To(Equal(http.StatusOK)) }, Entry("albums, IsFavorite", "MusicAlbum", "IsFavorite"), Entry("albums, IsUnplayed", "MusicAlbum", "IsUnplayed"), @@ -559,216 +579,143 @@ var _ = Describe("Items", func() { ) It("forwards SearchTerm to the repo's Search method", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(1)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf("One")) }) It("caps a search the client left unbounded", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Max).To(Equal(defaultSearchLimit + 1)) + manyAlbums(defaultSearchLimit + 2) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(defaultSearchLimit)) + Expect(res.TotalRecordCount).To(Equal(defaultSearchLimit + 1)) }) It("honors an explicit search Limit up to the ceiling", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one&Limit=500", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Max).To(Equal(501)) + manyAlbums(502) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one&Limit=500", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(500)) + Expect(res.TotalRecordCount).To(Equal(501)) }) It("clamps a search Limit that would materialize the library", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one&Limit=999999", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Max).To(Equal(maxSearchLimit + 1)) + manyAlbums(maxSearchLimit + 2) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&SearchTerm=one&Limit=999999", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(maxSearchLimit)) + Expect(res.TotalRecordCount).To(Equal(maxSearchLimit + 1)) }) It("treats an all-whitespace SearchTerm as no search, streaming the unfiltered list", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&SearchTerm=%20%20", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&SearchTerm=%20%20", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) - Expect(albumRepo.SearchQuery).To(BeEmpty()) - }) - - It("reports a multi-type search total past the page, so clients keep paging", func() { - songs := make(model.MediaFiles, defaultSearchLimit*2) - for i := range songs { - songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"} - } - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&Limit=10", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(10)) - Expect(res.TotalRecordCount).To(BeNumerically(">", 10)) + Expect(rec.albums.SearchQuery).To(BeEmpty()) }) DescribeTable("bounds the multi-type search window however large StartIndex is", func(startIndex int) { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", startIndex), nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Max).To(Equal(maxSearchLimit + 1)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "Song Album"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + code, _ := getItems(fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", startIndex), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(rec.albums.Options.Max).To(Equal(maxSearchLimit + 1)) }, Entry("large", 500000), // StartIndex+Limit would wrap negative and slice out of range in a worker goroutine. Entry("near the int limit", math.MaxInt), ) - It("stops a multi-type search at the ceiling rather than serving another type's rows", func() { - // Bounding the per-type window is what keeps StartIndex from driving it without limit, and - // past that window the merged order is no longer the true one. - songs := make(model.MediaFiles, maxSearchLimit+1) - for i := range songs { - songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"} - } - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", maxSearchLimit), - nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(BeEmpty()) - Expect(res.TotalRecordCount).To(Equal(maxSearchLimit)) + // The specs in each container only read, so they share one seeding of n songs and an album. + withSongsAndAnAlbum := func(n int, specs func(songs func() []string)) { + Describe(fmt.Sprintf("with %d matching songs and an album", n), Ordered, func() { + var songs []string + BeforeAll(func() { + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + songs = manySongs(n) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "Song Album"}) + }) + specs(func() []string { return songs }) + }) + } + + withSongsAndAnAlbum(maxSearchLimit+1, func(songs func() []string) { + It("stops a multi-type search at the ceiling rather than serving another type's rows", func() { + // Bounding the per-type window is what keeps StartIndex from driving it without limit, and + // past that window the merged order is no longer the true one. + code, res := getItems(fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=1", maxSearchLimit), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(BeEmpty()) + Expect(res.TotalRecordCount).To(Equal(maxSearchLimit)) + }) + + It("serves the last page below the ceiling in full", func() { + code, res := getItems(fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=10", maxSearchLimit-1), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + // Clipped to the window; the interleaved album takes one slot, shifting this song in by one. + Expect(res.Items).To(HaveLen(1)) + Expect(res.Items[0].Id).To(Equal(dto.EncodeID(songs()[maxSearchLimit-2]))) + }) }) - It("serves the last page below the ceiling in full", func() { - songs := make(model.MediaFiles, maxSearchLimit+1) - for i := range songs { - songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"} - } - // The mock repo returns rows sorted by ID; reorder to match so index-based assertions hold. - slices.SortFunc(songs, func(a, b model.MediaFile) int { return strings.Compare(a.ID, b.ID) }) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d&Limit=10", maxSearchLimit-1), - nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - // Clipped to the window; the interleaved album takes one slot, shifting this song in by one. - Expect(res.Items).To(HaveLen(1)) - Expect(res.Items[0].Id).To(Equal(dto.EncodeID(songs[maxSearchLimit-2].ID))) - }) + withSongsAndAnAlbum(defaultSearchLimit*2, func(songs func() []string) { + It("bounds an unbounded multi-type search to the default in total, not per type", func() { + code, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(defaultSearchLimit)) + }) - It("bounds an unbounded multi-type search to the default in total, not per type", func() { - songs := make(model.MediaFiles, defaultSearchLimit*2) - for i := range songs { - songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"} - } - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song", nil). - WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).To(HaveLen(defaultSearchLimit)) - }) + It("pages an unbounded multi-type search past the default without dropping matches", func() { + code, res := getItems(fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d", defaultSearchLimit+50), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).ToNot(BeEmpty()) + // The interleaved album takes one slot ahead of it, shifting this song in by one. + Expect(res.Items[0].Id).To(Equal(dto.EncodeID(songs()[defaultSearchLimit+49]))) + }) - It("pages an unbounded multi-type search past the default without dropping matches", func() { - songs := make(model.MediaFiles, defaultSearchLimit*2) - for i := range songs { - songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("s%05d", i)), Title: "Song"} - } - // The mock repo returns rows sorted by ID; reorder to match so index-based assertions hold. - slices.SortFunc(songs, func(a, b model.MediaFile) int { return strings.Compare(a.ID, b.ID) }) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - fmt.Sprintf("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&StartIndex=%d", defaultSearchLimit+50), - nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) - Expect(res.Items).ToNot(BeEmpty()) - // The interleaved album takes one slot ahead of it, shifting this song in by one. - Expect(res.Items[0].Id).To(Equal(dto.EncodeID(songs[defaultSearchLimit+49].ID))) + It("reports a multi-type search total past the page, so clients keep paging", func() { + code, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&SearchTerm=song&Limit=10", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(HaveLen(10)) + Expect(res.TotalRecordCount).To(BeNumerically(">", 10)) + }) }) It("reports a search total beyond the fetched page instead of the page length", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{ - {ID: testID("r1"), Name: "Alpha"}, {ID: testID("r2"), Name: "Beta"}, {ID: testID("r3"), Name: "Gamma"}, - }) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicArtist&SearchTerm=a&Limit=1", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + putArtists(ctx, ds, + model.Artist{ID: testID("r1"), Name: "Alpha"}, model.Artist{ID: testID("r2"), Name: "Alpine"}, model.Artist{ID: testID("r3"), Name: "Alps"}, + ) + code, res := getItems("/Items?IncludeItemTypes=MusicArtist&SearchTerm=al&StartIndex=1&Limit=1", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(1)) Expect(res.TotalRecordCount).To(Equal(3)) }) It("forwards StartIndex/Limit as Offset/Max", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&StartIndex=5&Limit=10", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Offset).To(Equal(5)) - Expect(albumRepo.Options.Max).To(Equal(10)) + for i := range 20 { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID(fmt.Sprintf("a%02d", i)), Name: fmt.Sprintf("Album %02d", i)}) + } + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&SortBy=SortName&StartIndex=5&Limit=10", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(Equal([]string{ + "Album 05", "Album 06", "Album 07", "Album 08", "Album 09", + "Album 10", "Album 11", "Album 12", "Album 13", "Album 14", + })) + Expect(res.TotalRecordCount).To(Equal(20)) }) Describe("Ids batch-fetch", func() { // Finamp's download/sync fetches a track's BaseItemDto via /Items?ids=; without // this, queryItems ignored Ids and returned the default type-dispatched list instead. It("returns exactly the requested item when Ids has a single id", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?Ids="+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 1}, model.MediaFile{ID: testID("s2"), Title: "Other", LibraryID: 1}) + code, res := getItems("/Items?Ids="+dto.EncodeID(testID("s1")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("s1")))) Expect(res.Items[0].Name).To(Equal("Song")) @@ -776,14 +723,10 @@ var _ = Describe("Items", func() { }) It("returns items of different types for a lowercase ids param with multiple ids", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ids="+dto.EncodeID(testID("a1"))+","+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 1}) + code, res := getItems("/Items?ids="+dto.EncodeID(testID("a1"))+","+dto.EncodeID(testID("s1")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) ids := []string{res.Items[0].Id, res.Items[1].Id} Expect(ids).To(ConsistOf(dto.EncodeID(testID("a1")), dto.EncodeID(testID("s1")))) @@ -793,30 +736,23 @@ var _ = Describe("Items", func() { }) It("resolves song ids with one batched IN query, not a Get per id", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 1}, {ID: testID("s2"), Title: "Song2", LibraryID: 1}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?ids="+dto.EncodeID(testID("s1"))+","+dto.EncodeID(testID("s2")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 1}, model.MediaFile{ID: testID("s2"), Title: "Song2", LibraryID: 1}) + code, res := getItems("/Items?ids="+dto.EncodeID(testID("s1"))+","+dto.EncodeID(testID("s2")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(2)) - sql, args, err := mfRepo.Options.Filters.ToSql() + sql, args, err := rec.songs.Options.Filters.ToSql() Expect(err).ToNot(HaveOccurred()) Expect(sql).To(ContainSubstring("media_file.id IN")) Expect(args).To(ConsistOf(testID("s1"), testID("s2"))) + Expect(rec.songs.GetAlls).To(Equal(1)) + Expect(rec.songs.Gets).To(BeZero()) }) It("omits an id in a library the user can't access, without erroring the whole batch", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}}) // alice only has access to library 1 - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?Ids="+dto.EncodeID(testID("a1"))+","+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 2}) // alice only has access to library 1 + code, res := getItems("/Items?Ids="+dto.EncodeID(testID("a1"))+","+dto.EncodeID(testID("s1")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(res.Items).To(HaveLen(1)) Expect(res.Items[0].Id).To(Equal(dto.EncodeID(testID("a1")))) Expect(res.TotalRecordCount).To(Equal(1)) @@ -824,19 +760,18 @@ var _ = Describe("Items", func() { }) Describe("sorting", func() { + BeforeEach(func() { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + }) + DescribeTable("translates SortBy into the repo's sort keys", func(itemType, sortBy, want string) { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes="+itemType+"&SortBy="+sortBy, nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - got := mfRepo.Options.Sort + code, _ := getItems("/Items?IncludeItemTypes="+itemType+"&SortBy="+sortBy, ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + got := rec.songs.Options.Sort if itemType == "MusicAlbum" { - got = albumRepo.Options.Sort + got = rec.albums.Options.Sort } Expect(got).To(Equal(want)) }, @@ -862,268 +797,188 @@ var _ = Describe("Items", func() { // Jellyfin reuses the first SortOrder for keys past the end of the list. DescribeTable("applies one SortOrder to every sort key", func(sortOrder, want string) { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder="+sortOrder, nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Sort).To(Equal("duration, name")) - Expect(albumRepo.Options.Order).To(Equal(want)) - Expect(albumRepo.Options.SortOrders).To(BeEmpty()) + code, _ := getItems("/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder="+sortOrder, ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(rec.albums.Options.Sort).To(Equal("duration, name")) + Expect(rec.albums.Options.Order).To(Equal(want)) + Expect(rec.albums.Options.SortOrders).To(BeEmpty()) }, Entry("ascending", "Ascending", ""), Entry("descending", "Descending", "desc"), ) It("pairs each SortOrder with its SortBy key", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName,PlayCount&SortOrder=Descending,Ascending", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Sort).To(Equal("duration, name, play_count")) - Expect(albumRepo.Options.Order).To(BeEmpty()) - Expect(albumRepo.Options.SortOrders).To(Equal([]string{"desc", "asc", "desc"})) + code, _ := getItems("/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName,PlayCount&SortOrder=Descending,Ascending", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(rec.albums.Options.Sort).To(Equal("duration, name, play_count")) + Expect(rec.albums.Options.Order).To(BeEmpty()) + Expect(rec.albums.Options.SortOrders).To(Equal([]string{"desc", "asc", "desc"})) }) It("keeps every key of a repeated SortBy", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime&SortBy=SortName", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Sort).To(Equal("duration, name")) + code, _ := getItems("/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime&SortBy=SortName", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(rec.albums.Options.Sort).To(Equal("duration, name")) }) It("pairs a repeated SortOrder key with its SortBy key", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder=Ascending&SortOrder=Descending", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(albumRepo.Options.Sort).To(Equal("duration, name")) - Expect(albumRepo.Options.Order).To(BeEmpty()) - Expect(albumRepo.Options.SortOrders).To(Equal([]string{"asc", "desc"})) + code, _ := getItems("/Items?IncludeItemTypes=MusicAlbum&SortBy=Runtime,SortName&SortOrder=Ascending&SortOrder=Descending", ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(rec.albums.Options.Sort).To(Equal("duration, name")) + Expect(rec.albums.Options.Order).To(BeEmpty()) + Expect(rec.albums.Options.SortOrders).To(Equal([]string{"asc", "desc"})) }) }) Describe("library scoping", func() { It("scopes a MusicAlbum listing (no ParentId) to the user's accessible libraries", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUserWithLibraries(libs)) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_id")) - Expect(args).To(ContainElements(1, 2)) + albumsPerLibrary() + _, res := getItems("/Items?IncludeItemTypes=MusicAlbum", ctxUserWithLibraries(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("One", "Two")) }) It("scopes a Audio listing (no ParentId) to the user's accessible libraries", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio", nil).WithContext(ctxUserWithLibraries(libs)) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := mfRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_id")) - Expect(args).To(ContainElements(1, 2)) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "One", LibraryID: 1}, + model.MediaFile{ID: testID("s2"), Title: "Two", LibraryID: 2}, + model.MediaFile{ID: testID("s3"), Title: "Three", LibraryID: 3}, + ) + _, res := getItems("/Items?IncludeItemTypes=Audio", ctxUserWithLibraries(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("One", "Two")) }) It("scopes a MusicArtist listing to the user's accessible libraries", func() { - artistRepo := ds.Artist().(*tests.MockArtistRepo) - artistRepo.SetData(model.Artists{{ID: testID("ar1"), Name: "Artist"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicArtist", nil).WithContext(ctxUserWithLibraries(libs)) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := artistRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_artist.library_id")) - Expect(args).To(ContainElements(1, 2)) + putArtistsIn(ctx, ds, 1, model.Artist{ID: testID("ar1"), Name: "One"}) + putArtistsIn(ctx, ds, 2, model.Artist{ID: testID("ar2"), Name: "Two"}) + putArtistsIn(ctx, ds, 3, model.Artist{ID: testID("ar3"), Name: "Three"}) + _, res := getItems("/Items?IncludeItemTypes=MusicArtist", ctxUserWithLibraries(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("One", "Two")) }) It("treats a numeric ParentId matching an accessible library as a library scope, not an artist id", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeLibraryID(2)+"&IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUserWithLibraries(libs)) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).NotTo(ContainSubstring("album_artists")) // not treated as an artist-parent filter - Expect(sql).To(ContainSubstring("library_id")) - Expect(args).To(ContainElement(2)) + albumsPerLibrary() + _, res := getItems("/Items?ParentId="+dto.EncodeLibraryID(2)+"&IncludeItemTypes=MusicAlbum", ctxUserWithLibraries(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(res)).To(ConsistOf("Two")) }) It("does not let ParentId= scope results to that library", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}} // no access to library 99 - r := httptest.NewRequest(http.MethodGet, "/Items?ParentId="+dto.EncodeLibraryID(99)+"&IncludeItemTypes=MusicAlbum", nil).WithContext(ctxUserWithLibraries(libs)) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - // Falls back to treating "99" as an (empty-matching) artist-parent id... - Expect(sql).To(ContainSubstring("album_artists")) - // ...while still scoping to the user's own accessible libraries. - Expect(sql).To(ContainSubstring("library_id")) - Expect(args).To(ContainElement(1)) - Expect(args).NotTo(ContainElement(99)) + // The library GUID decodes to "3", so an artist with that id shows the artist-parent fallback. + putArtistsIn(ctx, ds, 1, model.Artist{ID: "3", Name: "Three"}) + byArtist := credits(model.RoleAlbumArtist, "3") + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: testID("a1"), Name: "One", LibraryID: 1, Participants: byArtist}, + model.Album{ID: testID("a2"), Name: "Two", LibraryID: 1}, + model.Album{ID: testID("a3"), Name: "Three", LibraryID: 3, Participants: byArtist}, + ) + code, res := getItems("/Items?ParentId="+dto.EncodeLibraryID(3)+"&IncludeItemTypes=MusicAlbum", ctxUserWithLibraries(model.Libraries{{ID: 1}})) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf("One")) }) It("does not restrict a default MusicAlbum listing for an admin user", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}, {ID: testID("a2"), Name: "Two", LibraryID: 2}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum", nil).WithContext(ctxAdmin()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - // accessibleLibraryIDs is empty for an admin (Libraries is nil), so - // ApplyLibraryFilter([]) is a no-op: no library_id restriction is added. - if albumRepo.Options.Filters == nil { - return - } - sql, _, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).NotTo(ContainSubstring("library_id")) + albumsPerLibrary() + _, res := getItems("/Items?IncludeItemTypes=MusicAlbum", ctxAdmin()) + Expect(itemNames(res)).To(ConsistOf("One", "Two", "Three")) }) }) // A malformed id must 404, not silently drop the filter; a well-formed but unknown one must // still reach the entity filter, not the unfiltered default. Describe("stale and malformed id filtering", func() { + BeforeEach(func() { + putArtists(ctx, ds, + model.Artist{ID: testID("ar1"), Name: "One"}, + model.Artist{ID: testID("ar2"), Name: "Two"}, + model.Artist{ID: testID("ar3"), Name: "Three"}, + ) + }) + It("404s a malformed ParentId instead of listing every song", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio&ParentId=not-a-valid-id", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + code, _ := getItems("/Items?IncludeItemTypes=Audio&ParentId=not-a-valid-id", ctxUser()) + Expect(code).To(Equal(http.StatusNotFound)) }) It("404s a malformed AlbumArtistIds instead of listing every album", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds=not-a-valid-id", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + code, _ := getItems("/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds=not-a-valid-id", ctxUser()) + Expect(code).To(Equal(http.StatusNotFound)) }) It("404s a malformed ArtistIds instead of listing every song", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio&ArtistIds=not-a-valid-id", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + code, _ := getItems("/Items?IncludeItemTypes=Audio&ArtistIds=not-a-valid-id", ctxUser()) + Expect(code).To(Equal(http.StatusNotFound)) }) It("404s when a later repeated ArtistIds value is malformed", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds=not-a-valid-id", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + code, _ := getItems("/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds=not-a-valid-id", ctxUser()) + Expect(code).To(Equal(http.StatusNotFound)) }) It("filters songs by every repeated ArtistIds key", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds="+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - _, args, err := mfRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "One", Participants: credits(model.RoleArtist, testID("ar1"))}, + model.MediaFile{ID: testID("s2"), Title: "Two", Participants: credits(model.RoleArtist, testID("ar2"))}, + model.MediaFile{ID: testID("s3"), Title: "Three", Participants: credits(model.RoleArtist, testID("ar3"))}, + ) + code, res := getItems("/Items?IncludeItemTypes=Audio&ArtistIds="+dto.EncodeID(testID("ar1"))+"&ArtistIds="+dto.EncodeID(testID("ar2")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf("One", "Two")) }) It("filters albums by every artist in a comma-separated AlbumArtistIds", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - _, args, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: testID("a1"), Name: "One", Participants: credits(model.RoleAlbumArtist, testID("ar1"))}, + model.Album{ID: testID("a2"), Name: "Two", Participants: credits(model.RoleAlbumArtist, testID("ar2"))}, + model.Album{ID: testID("a3"), Name: "Three", Participants: credits(model.RoleAlbumArtist, testID("ar3"))}, + ) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf("One", "Two")) }) It("excludes an album artist from a multi-id contributingArtistIds Featured On filter", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, - "/Items?IncludeItemTypes=MusicAlbum&contributingArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("NOT IN")) - Expect(args).To(ContainElements(testID("ar1"), testID("ar2"))) - Expect(strings.Count(sql, "album_artists")).To(Equal(2)) + albumBy := func(albumArtist, artist string) model.Participants { + p := credits(model.RoleAlbumArtist, testID(albumArtist)) + p.Add(model.RoleArtist, model.Artist{ID: testID(artist)}) + return p + } + persistencetest.PutAlbums(ctx, ds, + model.Album{ID: testID("a1"), Name: "Own Album", Participants: albumBy("ar1", "ar1")}, + model.Album{ID: testID("a2"), Name: "Featured On", Participants: albumBy("ar3", "ar2")}, + model.Album{ID: testID("a3"), Name: "Other Artist", Participants: albumBy("ar3", "ar3")}, + model.Album{ID: testID("a4"), Name: "Other Id's Album", Participants: albumBy("ar2", "ar1")}, + ) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&contributingArtistIds="+dto.EncodeID(testID("ar1"))+","+dto.EncodeID(testID("ar2")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(itemNames(res)).To(ConsistOf("Featured On")) }) It("still applies the artist filter (rather than dropping it) for a well-formed but unknown AlbumArtistIds", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds="+dto.EncodeID(testID("no-such-artist")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, _, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("album_artists")) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}) + code, res := getItems("/Items?IncludeItemTypes=MusicAlbum&AlbumArtistIds="+dto.EncodeID(testID("no-such-artist")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(BeEmpty()) }) It("still applies the album filter (rather than dropping it) for a well-formed but unknown ParentId", func() { - mfRepo := ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio&ParentId="+dto.EncodeID(testID("no-such-album")), nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := mfRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("album_id")) - Expect(args).To(ContainElement(testID("no-such-album"))) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song"}) + code, res := getItems("/Items?IncludeItemTypes=Audio&ParentId="+dto.EncodeID(testID("no-such-album")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) + Expect(res.Items).To(BeEmpty()) }) }) Describe("mixed IncludeItemTypes merge", func() { BeforeEach(func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One"}, {ID: testID("a2"), Name: "Two"}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "S1"}, {ID: testID("s2"), Title: "S2"}}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One"}, model.Album{ID: testID("a2"), Name: "Two"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "S1"}, model.MediaFile{ID: testID("s2"), Title: "S2"}) }) It("returns a mix of both types, not all of one", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", ctxUser()) Expect(res.Items).To(HaveLen(4)) Expect(res.TotalRecordCount).To(Equal(4)) types := map[string]int{} @@ -1135,21 +990,13 @@ var _ = Describe("Items", func() { }) It("interleaves types round-robin (Audio first, per IncludeItemTypes order)", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", ctxUser()) got := []string{res.Items[0].Type, res.Items[1].Type, res.Items[2].Type, res.Items[3].Type} Expect(got).To(Equal([]string{"Audio", "MusicAlbum", "Audio", "MusicAlbum"})) }) It("honors Limit across the merged set", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=1", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=1", ctxUser()) Expect(res.Items).To(HaveLen(1)) Expect(res.TotalRecordCount).To(Equal(4)) }) @@ -1157,88 +1004,70 @@ var _ = Describe("Items", func() { It("serves a full random page from offset 0 regardless of StartIndex", func() { // A deep StartIndex on a random merge must not materialize offset+limit rows; since random // reshuffles per request, offset 0 is an equivalent fresh draw. Old behavior returned empty. - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&SortBy=Random&Recursive=true&StartIndex=1000&Limit=4", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - var res dto.QueryResult - Expect(json.Unmarshal(w.Body.Bytes(), &res)).To(Succeed()) + _, res := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&SortBy=Random&Recursive=true&StartIndex=1000&Limit=4", ctxUser()) Expect(res.Items).To(HaveLen(4)) }) It("propagates a per-type query error", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetError(true) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", nil).WithContext(ctxUser()) - invoke(api.getItems, w, r) - Expect(w.Code).To(Equal(http.StatusInternalServerError)) + api.ds = failingSongs(ds) + code, _ := getItems("/Items?IncludeItemTypes=Audio,MusicAlbum&Recursive=true&Limit=4", ctxUser()) + Expect(code).To(Equal(http.StatusInternalServerError)) }) }) }) Describe("getItem", func() { - It("returns an album by id", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) + getItem := func(itemID string, ctx context.Context) (int, dto.BaseItemDto) { + GinkgoHelper() w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) + r := httptest.NewRequest(http.MethodGet, "/Items/"+itemID, nil).WithContext(ctx) + invoke(api.getItem, w, withChiURLParam(r, "itemId", itemID)) var item dto.BaseItemDto - Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + if w.Code == http.StatusOK { + Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + } + return w.Code, item + } + + It("returns an album by id", func() { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) + code, item := getItem(dto.EncodeID(testID("a1")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(item.Id).To(Equal(dto.EncodeID(testID("a1")))) Expect(item.Type).To(Equal("MusicAlbum")) }) It("returns 404 when the id doesn't match any entity", func() { - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/missing", nil).WithContext(ctxUser()) - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("missing"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + code, _ := getItem(dto.EncodeID(testID("missing")), ctxUser()) + Expect(code).To(Equal(http.StatusNotFound)) }) It("returns 404 for an album in a library the user can't access", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxUser()) // only has access to library 1 - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 2}) + code, _ := getItem(dto.EncodeID(testID("a1")), ctxUser()) // only has access to library 1 + Expect(code).To(Equal(http.StatusNotFound)) }) It("returns 404 for a song in a library the user can't access", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1"), Title: "Song", LibraryID: 2}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("s1")), nil).WithContext(ctxUser()) // only has access to library 1 - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 2}) + code, _ := getItem(dto.EncodeID(testID("s1")), ctxUser()) // only has access to library 1 + Expect(code).To(Equal(http.StatusNotFound)) }) It("returns an album to an admin even when it's outside their (empty) Libraries", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 2}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("a1")), nil).WithContext(ctxAdmin()) // admin, Libraries: nil - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("a1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var item dto.BaseItemDto - Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 2}) + code, item := getItem(dto.EncodeID(testID("a1")), ctxAdmin()) // admin, Libraries: nil + Expect(code).To(Equal(http.StatusOK)) Expect(item.Id).To(Equal(dto.EncodeID(testID("a1")))) }) // Finamp fetches a /UserViews entry (Id=library id) as a plain item to resolve the // library node before it can load the home screen or any library tab. It("resolves a library-view id (from /UserViews) as a CollectionFolder item", func() { - w := httptest.NewRecorder() libs := model.Libraries{{ID: 1, Name: "Music Library"}} - ds.Library().(*tests.MockLibraryRepo).SetData(libs) - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeLibraryID(1), nil).WithContext(ctxUserWithLibraries(libs)) - r = withChiURLParam(r, "itemId", dto.EncodeLibraryID(1)) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var item dto.BaseItemDto - Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + putLibraries(ctx, ds, libs) + code, item := getItem(dto.EncodeLibraryID(1), ctxUserWithLibraries(libs)) + Expect(code).To(Equal(http.StatusOK)) Expect(item.Id).To(Equal(dto.EncodeLibraryID(1))) Expect(item.Name).To(Equal("Music Library")) Expect(item.Type).To(Equal("CollectionFolder")) @@ -1247,25 +1076,17 @@ var _ = Describe("Items", func() { }) It("does not resolve a library-view id the user has no access to", func() { - w := httptest.NewRecorder() libs := model.Libraries{{ID: 2, Name: "Other"}} // no access to library 1 - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeLibraryID(1), nil).WithContext(ctxUserWithLibraries(libs)) - r = withChiURLParam(r, "itemId", dto.EncodeLibraryID(1)) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + code, _ := getItem(dto.EncodeLibraryID(1), ctxUserWithLibraries(libs)) + Expect(code).To(Equal(http.StatusNotFound)) }) // Finamp's SyncBuffer fetches a playlist by id as a plain item; without this probe it // 404s with "Could not fetch BaseItemDto from server." It("resolves a playlist id via the playlists service", func() { fp.getByIDPls = &model.Playlist{ID: testID("p1"), Name: "My Mix", SongCount: 5} - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("p1")), nil).WithContext(ctxUser()) - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("p1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var item dto.BaseItemDto - Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + code, item := getItem(dto.EncodeID(testID("p1")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(item.Id).To(Equal(dto.EncodeID(testID("p1")))) Expect(item.Name).To(Equal("My Mix")) Expect(item.Type).To(Equal("Playlist")) @@ -1273,37 +1094,24 @@ var _ = Describe("Items", func() { It("returns 404 for a non-owned or absent playlist id", func() { fp.getByIDErr = model.ErrNotFound - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("p1")), nil).WithContext(ctxUser()) - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("p1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusNotFound)) + code, _ := getItem(dto.EncodeID(testID("p1")), ctxUser()) + Expect(code).To(Equal(http.StatusNotFound)) }) // Finamp's genre "See all" fetches the genre by id; a 404 white-screens it (see resolveItemByID). It("resolves a genre id as a MusicGenre item", func() { - Expect(ds.Genre().(*tests.MockedGenreRepo).Put(&model.Genre{ID: testID("g1"), Name: "Rock"})).To(Succeed()) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("g1")), nil).WithContext(ctxUser()) - r = withChiURLParam(r, "itemId", dto.EncodeID(testID("g1"))) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var item dto.BaseItemDto - Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + Expect(ds.Tag().Add(ctx, 1, model.Tag{ID: testID("g1"), TagName: model.TagGenre, TagValue: "Rock"})).To(Succeed()) + code, item := getItem(dto.EncodeID(testID("g1")), ctxUser()) + Expect(code).To(Equal(http.StatusOK)) Expect(item.Id).To(Equal(dto.EncodeID(testID("g1")))) Expect(item.Name).To(Equal("Rock")) Expect(item.Type).To(Equal("MusicGenre")) }) It("resolves a library-view id for an admin even though their Libraries slice is empty", func() { - ds.Library().(*tests.MockLibraryRepo).SetData(model.Libraries{{ID: 1, Name: "Music Library"}}) - w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeLibraryID(1), nil).WithContext(ctxAdmin()) - r = withChiURLParam(r, "itemId", dto.EncodeLibraryID(1)) - invoke(api.getItem, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - var item dto.BaseItemDto - Expect(json.Unmarshal(w.Body.Bytes(), &item)).To(Succeed()) + putLibraries(ctx, ds, model.Libraries{{ID: 1, Name: "Music Library"}}) + code, item := getItem(dto.EncodeLibraryID(1), ctxAdmin()) + Expect(code).To(Equal(http.StatusOK)) Expect(item.Id).To(Equal(dto.EncodeLibraryID(1))) Expect(item.Name).To(Equal("Music Library")) Expect(item.Type).To(Equal("CollectionFolder")) @@ -1311,30 +1119,27 @@ var _ = Describe("Items", func() { }) Describe("getLatest", func() { - It("returns a bare array of the newest albums", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) + latest := func(ctx context.Context) []dto.BaseItemDto { + GinkgoHelper() w := httptest.NewRecorder() - r := httptest.NewRequest(http.MethodGet, "/Users/u1/Items/Latest", nil).WithContext(ctxUser()) - invoke(api.getLatest, w, r) + invoke(api.getLatest, w, httptest.NewRequest(http.MethodGet, "/Users/u1/Items/Latest", nil).WithContext(ctx)) Expect(w.Code).To(Equal(http.StatusOK)) var items []dto.BaseItemDto Expect(json.Unmarshal(w.Body.Bytes(), &items)).To(Succeed()) + return items + } + + It("returns a bare array of the newest albums", func() { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("a1"), Name: "One", LibraryID: 1}) + items := latest(ctxUser()) Expect(items).To(HaveLen(1)) Expect(items[0].Id).To(Equal(dto.EncodeID(testID("a1")))) }) It("scopes to the user's accessible libraries", func() { - albumRepo := ds.Album().(*tests.MockAlbumRepo) - albumRepo.SetData(model.Albums{{ID: testID("a1"), Name: "One", LibraryID: 1}}) - w := httptest.NewRecorder() - libs := model.Libraries{{ID: 1}, {ID: 2}} - r := httptest.NewRequest(http.MethodGet, "/Users/u1/Items/Latest", nil).WithContext(ctxUserWithLibraries(libs)) - invoke(api.getLatest, w, r) - Expect(w.Code).To(Equal(http.StatusOK)) - sql, args, err := albumRepo.Options.Filters.ToSql() - Expect(err).NotTo(HaveOccurred()) - Expect(sql).To(ContainSubstring("library_id")) - Expect(args).To(ContainElements(1, 2)) + albumsPerLibrary() + items := latest(ctxUserWithLibraries(model.Libraries{{ID: 1}, {ID: 2}})) + Expect(itemNames(dto.QueryResult{Items: items})).To(ConsistOf("One", "Two")) }) }) diff --git a/server/jellyfin/jellyfin_suite_test.go b/server/jellyfin/jellyfin_suite_test.go index 530b55c36..2fe240f8b 100644 --- a/server/jellyfin/jellyfin_suite_test.go +++ b/server/jellyfin/jellyfin_suite_test.go @@ -1,12 +1,17 @@ package jellyfin import ( + "context" "net/http" + "strings" "testing" "github.com/navidrome/navidrome/conf/configtest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/id" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -15,11 +20,13 @@ import ( func TestJellyfinApi(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Jellyfin API Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() // testID maps a readable label to a deterministic canonical id, so fixtures exercise the same // id shape production uses. @@ -31,3 +38,76 @@ func testID(label string) string { return id.NewHash("jellyfin-test", label) } func invoke(h http.HandlerFunc, w http.ResponseWriter, r *http.Request) { normalizeQueryKeys(h).ServeHTTP(w, r) } + +// setTokenEpoch writes token_epoch directly: User().Put never stores it. +func setTokenEpoch(userID string, epoch int) { + GinkgoHelper() + _, err := db.Db().Exec("UPDATE user SET token_epoch = ? WHERE id = ?", epoch, userID) + Expect(err).ToNot(HaveOccurred()) +} + +type failingUserRepo struct { + model.UserRepository + err error +} + +func (f failingUserRepo) Get(context.Context, string) (*model.User, error) { return nil, f.err } + +type failingPropertyRepo struct { + model.PropertyRepository + err error +} + +func (f failingPropertyRepo) Get(context.Context, string) (string, error) { return "", f.err } + +// putUser stores u and returns it as the repository loads it, with the libraries it can access. +func putUser(ctx context.Context, ds model.DataStore, u model.User) model.User { + GinkgoHelper() + Expect(ds.User().Put(ctx, &u)).To(Succeed()) + stored, err := ds.User().Get(ctx, u.ID) + Expect(err).ToNot(HaveOccurred()) + return *stored +} + +// putArtists stores artists in library 1. +func putArtists(ctx context.Context, ds model.DataStore, artists ...model.Artist) { + GinkgoHelper() + putArtistsIn(ctx, ds, model.DefaultLibraryID, artists...) +} + +// putArtistsIn stores artists in libID, credited as artist and album artist so the role-filtered +// listings include them. +func putArtistsIn(ctx context.Context, ds model.DataStore, libID int, artists ...model.Artist) { + GinkgoHelper() + ids := make([]string, len(artists)) + inTx(ds, func(tx model.DataStore) { + for i, ar := range artists { + if ar.OrderArtistName == "" { + ar.OrderArtistName = strings.ToLower(ar.Name) + } + persistencetest.PutArtists(ctx, tx, libID, ar) + ids[i] = ar.ID + } + }) + persistencetest.SetArtistStats(ctx, libID, map[model.Role]model.ArtistStats{ + model.RoleArtist: {SongCount: 1}, model.RoleAlbumArtist: {SongCount: 1}, + }, ids...) +} + +// inTx runs seed in one transaction, which makes seeding thousands of rows fast. +func inTx(ds model.DataStore, seed func(tx model.DataStore)) { + GinkgoHelper() + Expect(ds.WithTx(func(tx model.DataStore) error { + seed(tx) + return nil + })).To(Succeed()) +} + +// credits names the stored artists artistIDs in role. +func credits(role model.Role, artistIDs ...string) model.Participants { + p := model.Participants{} + for _, id := range artistIDs { + p.Add(role, model.Artist{ID: id}) + } + return p +} diff --git a/server/jellyfin/lyrics_test.go b/server/jellyfin/lyrics_test.go index 6f0c19778..72825a431 100644 --- a/server/jellyfin/lyrics_test.go +++ b/server/jellyfin/lyrics_test.go @@ -6,10 +6,13 @@ import ( "net/http" "net/http/httptest" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -50,16 +53,16 @@ func (f *fakeLyricsService) GetLyricsByArtistTitle(context.Context, string, stri var _ = Describe("getLyrics", func() { var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore var fake *fakeLyricsService BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", LibraryID: 1}, - {ID: testID("s2"), Title: "Silent Song", LibraryID: 1}, - }) + ds = persistence.New(db.Db()) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", LibraryID: 1}, + model.MediaFile{ID: testID("s2"), Title: "Silent Song", LibraryID: 1}, + ) fake = &fakeLyricsService{lyrics: map[string]model.LyricList{}} api = &Router{ ds: ds, diff --git a/server/jellyfin/middlewares_test.go b/server/jellyfin/middlewares_test.go index 82e0c6f14..d109d0e2c 100644 --- a/server/jellyfin/middlewares_test.go +++ b/server/jellyfin/middlewares_test.go @@ -8,11 +8,13 @@ import ( "sync/atomic" "time" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" + "github.com/go-chi/chi/v5" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -20,13 +22,12 @@ import ( var _ = Describe("authenticate middleware", func() { var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - ur := ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) + Expect(ds.User().Put(ctx, &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) api = &Router{ds: ds} }) @@ -102,9 +103,9 @@ var _ = Describe("authenticate middleware", func() { var usr *model.User BeforeEach(func() { - ur := ds.User().(*tests.MockedUserRepo) usr = &model.User{ID: testID("u2"), UserName: "bob", NewPassword: "secret", TokenEpoch: 3} - Expect(ur.Put(ctx, usr)).To(Succeed()) + Expect(ds.User().Put(ctx, usr)).To(Succeed()) + setTokenEpoch(usr.ID, 3) }) serve := func(token string) *httptest.ResponseRecorder { @@ -127,7 +128,7 @@ var _ = Describe("authenticate middleware", func() { It("rejects a token whose epoch is stale", func() { tokenStr, err := auth.CreateAPIToken(usr, auth.AudienceJellyfin) Expect(err).ToNot(HaveOccurred()) - usr.TokenEpoch = 4 + setTokenEpoch(usr.ID, 4) Expect(serve(tokenStr).Code).To(Equal(http.StatusUnauthorized)) }) @@ -151,7 +152,7 @@ var _ = Describe("withPlayer middleware", func() { BeforeEach(func() { players = &fakePlayers{} - api = &Router{ds: &tests.MockDataStore{}, players: players} + api = &Router{ds: struct{ model.DataStore }{}, players: players} }) callWith := func() (model.Player, model.Transcoding, bool) { diff --git a/server/jellyfin/playlists_test.go b/server/jellyfin/playlists_test.go index 5af1303a0..1ff50ab8b 100644 --- a/server/jellyfin/playlists_test.go +++ b/server/jellyfin/playlists_test.go @@ -11,17 +11,17 @@ import ( "net/http" "net/http/httptest" "slices" - "strconv" "strings" "github.com/go-chi/chi/v5" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/server/filter" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -35,9 +35,9 @@ type fakePlaylists struct { createdIds []string createErr error - getPls *model.Playlist - getErr error - tracksRepo *tests.MockPlaylistTrackRepo + // ds backs the track reads, which the real service also leaves to the playlist repository. + ds model.DataStore + tracksRepo *spyTrackRepo getByIDPls *model.Playlist getByIDErr error @@ -99,30 +99,65 @@ func (f *fakePlaylists) Get(_ context.Context, _ string) (*model.Playlist, error return f.getByIDPls, nil } -func (f *fakePlaylists) GetWithTracks(_ context.Context, _ string) (*model.Playlist, error) { - if f.getErr != nil { - return nil, f.getErr - } - if f.getPls == nil { - return nil, model.ErrNotFound // mirror the real repo: never (nil, nil) - } - return f.getPls, nil +func (f *fakePlaylists) GetWithTracks(ctx context.Context, id string) (*model.Playlist, error) { + return f.ds.Playlist().GetWithTracks(ctx, id, true, false) } -// Tracks serves the same getPls fixture as GetWithTracks. tracksRepo is kept so tests can assert -// what was pushed down to the query. -func (f *fakePlaylists) Tracks(_ context.Context, _ string) (model.PlaylistTrackRepository, error) { - if f.getErr != nil { - return nil, f.getErr +// Tracks keeps the repository it returns so tests can assert what was pushed down to the query. +func (f *fakePlaylists) Tracks(ctx context.Context, id string) (model.PlaylistTrackRepository, error) { + if _, err := f.ds.Playlist().Get(ctx, id); err != nil { + return nil, err } - if f.getPls == nil { - return nil, model.ErrNotFound - } - f.tracksRepo = &tests.MockPlaylistTrackRepo{} - f.tracksRepo.SetData(f.getPls.Tracks) + f.tracksRepo = &spyTrackRepo{PlaylistTrackRepository: f.ds.Playlist().Tracks(ctx, id, true)} return f.tracksRepo, nil } +// spyTrackRepo records the options of the last track read: paging in the query and paging in +// memory return the same rows. +type spyTrackRepo struct { + model.PlaylistTrackRepository + Options model.QueryOptions +} + +func (s *spyTrackRepo) record(options []model.QueryOptions) { + s.Options = model.QueryOptions{} + if len(options) > 0 { + s.Options = options[0] + } +} + +func (s *spyTrackRepo) GetAll(ctx context.Context, options ...model.QueryOptions) (model.PlaylistTracks, error) { + s.record(options) + return s.PlaylistTrackRepository.GetAll(ctx, options...) +} + +func (s *spyTrackRepo) GetCursor(ctx context.Context, options ...model.QueryOptions) (model.PlaylistTrackCursor, error) { + s.record(options) + return s.PlaylistTrackRepository.GetCursor(ctx, options...) +} + +func (s *spyTrackRepo) GetMediaFileIDs(ctx context.Context, options ...model.QueryOptions) ([]string, error) { + s.record(options) + return s.PlaylistTrackRepository.GetMediaFileIDs(ctx, options...) +} + +// putPlaylist stores a public playlist holding the stored songs songIDs, in order, as entries 1, 2, ... +func putPlaylist(ctx context.Context, ds model.DataStore, id string, songIDs ...string) { + GinkgoHelper() + owner := putUser(ctx, ds, model.User{ID: testID("pl-owner"), UserName: "pl-owner"}) + pls := &model.Playlist{ID: id, Name: id, OwnerID: owner.ID, Public: true} + pls.AddMediaFilesByID(songIDs) + Expect(ds.Playlist().Put(request.WithUser(ctx, owner), pls)).To(Succeed()) +} + +// putSongsByID stores one song per id, titled after its position. +func putSongsByID(ctx context.Context, ds model.DataStore, ids ...string) { + GinkgoHelper() + for i, id := range ids { + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: id, Title: fmt.Sprintf("Song %d", i+1)}) + } +} + func (f *fakePlaylists) AddTracks(_ context.Context, playlistID string, ids []string) (int, error) { f.addPlaylistID = playlistID f.addIds = ids @@ -163,12 +198,14 @@ var _ = DescribeTable("insertPosition", var _ = Describe("Playlists", func() { var ctx context.Context var api *Router + var ds model.DataStore var fp *fakePlaylists BeforeEach(func() { ctx = GinkgoT().Context() - fp = &fakePlaylists{} - api = &Router{ds: &tests.MockDataStore{}, playlists: fp} + ds = persistence.New(db.Db()) + fp = &fakePlaylists{ds: ds} + api = &Router{ds: ds, playlists: fp} }) Describe("createPlaylist", func() { @@ -230,13 +267,8 @@ var _ = Describe("Playlists", func() { Describe("getPlaylistItems", func() { It("maps playlist tracks to Audio BaseItemDtos, tagging each with its PlaylistItemId", func() { - fp.getPls = &model.Playlist{ - ID: testID("pl1"), - Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1"), Title: "Song One"}}, - {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2"), Title: "Song Two"}}, - }, - } + putSongsByID(ctx, ds, testID("s1"), testID("s2")) + putPlaylist(ctx, ds, testID("pl1"), testID("s1"), testID("s2")) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Playlists/"+testID("pl1")+"/Items", nil).WithContext(ctx) r = withChiURLParam(r, "playlistId", dto.EncodeID(testID("pl1"))) @@ -254,14 +286,8 @@ var _ = Describe("Playlists", func() { }) It("pages with StartIndex/Limit, pushing them down to the query", func() { - fp.getPls = &model.Playlist{ - ID: testID("pl1"), - Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}}, - {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}}, - {ID: "3", MediaFileID: testID("s3"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s3")}}, - }, - } + putSongsByID(ctx, ds, testID("s1"), testID("s2"), testID("s3")) + putPlaylist(ctx, ds, testID("pl1"), testID("s1"), testID("s2"), testID("s3")) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Playlists/"+testID("pl1")+"/Items?StartIndex=1&Limit=1", nil). WithContext(ctx) @@ -278,13 +304,8 @@ var _ = Describe("Playlists", func() { }) It("clamps a negative StartIndex to 0", func() { - fp.getPls = &model.Playlist{ - ID: testID("pl1"), - Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}}, - {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}}, - }, - } + putSongsByID(ctx, ds, testID("s1"), testID("s2")) + putPlaylist(ctx, ds, testID("pl1"), testID("s1"), testID("s2")) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Playlists/"+testID("pl1")+"/Items?StartIndex=-1&Limit=1", nil). WithContext(ctx) @@ -299,7 +320,6 @@ var _ = Describe("Playlists", func() { }) It("returns 404 for a non-owned or absent playlist", func() { - fp.getErr = model.ErrNotFound w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Playlists/missing/Items", nil).WithContext(ctx) r = withChiURLParam(r, "playlistId", dto.EncodeID(testID("missing"))) @@ -309,13 +329,6 @@ var _ = Describe("Playlists", func() { }) Describe("container id expansion", func() { - var ds *tests.MockDataStore - - BeforeEach(func() { - ds = &tests.MockDataStore{} - api = &Router{ds: ds, playlists: fp} - }) - createWith := func(id string) { w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Playlists", strings.NewReader(`{"Name":"Mix","Ids":["`+dto.EncodeID(id)+`"]}`)). @@ -325,59 +338,57 @@ var _ = Describe("Playlists", func() { } It("passes a bare song id through unchanged", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}}) + putSongsByID(ctx, ds, testID("s1")) createWith(testID("s1")) Expect(fp.createdIds).To(Equal([]string{testID("s1")})) }) It("expands an album id into its songs, filtered by album", func() { - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{{ID: testID("al1")}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), AlbumID: testID("al1")}, {ID: testID("s2"), AlbumID: testID("al1")}, - }) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("al1"), Name: "One"}, model.Album{ID: testID("al2"), Name: "Two"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), AlbumID: testID("al1"), TrackNumber: 1}, + model.MediaFile{ID: testID("s2"), AlbumID: testID("al1"), TrackNumber: 2}, + model.MediaFile{ID: testID("s3"), AlbumID: testID("al2"), TrackNumber: 1}, + ) createWith(testID("al1")) Expect(fp.createdIds).To(Equal([]string{testID("s1"), testID("s2")})) - Expect(ds.MediaFile().(*tests.MockMediaFileRepo).Options.Filters).To(Equal(filter.SongsByAlbum(testID("al1")).Filters)) }) It("expands an artist id into its songs", func() { - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1")}}) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}, {ID: testID("s2")}}) + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "One"}, model.Artist{ID: testID("ar2"), Name: "Two"}) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), TrackNumber: 1, Participants: credits(model.RoleArtist, testID("ar1"))}, + model.MediaFile{ID: testID("s2"), TrackNumber: 2, Participants: credits(model.RoleAlbumArtist, testID("ar1"))}, + model.MediaFile{ID: testID("s3"), TrackNumber: 3, Participants: credits(model.RoleArtist, testID("ar2"))}, + ) createWith(testID("ar1")) Expect(fp.createdIds).To(Equal([]string{testID("s1"), testID("s2")})) - Expect(ds.MediaFile().(*tests.MockMediaFileRepo).Options.Filters).To(Equal(filter.SongsByArtistID(testID("ar1")).Filters)) }) It("expands a playlist id into its tracks' media file ids", func() { - fp.getPls = &model.Playlist{ID: testID("pl9"), Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s3")}, {ID: "2", MediaFileID: testID("s4")}, - }} + putSongsByID(ctx, ds, testID("s3"), testID("s4")) + putPlaylist(ctx, ds, testID("pl9"), testID("s3"), testID("s4")) createWith(testID("pl9")) Expect(fp.createdIds).To(Equal([]string{testID("s3"), testID("s4")})) }) }) Describe("request limits", func() { - var ds *tests.MockDataStore song := dto.EncodeID(testID("s1")) artist := dto.EncodeID(testID("ar1")) BeforeEach(func() { - ds = &tests.MockDataStore{} - api = &Router{ds: ds, playlists: fp} - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{{ID: testID("s1")}}) + putSongsByID(ctx, ds, testID("s1")) }) repeat := func(id string, n int) []string { return slices.Repeat([]string{id}, n) } // An artist whose expansion alone is just over a per-request track limit of 5. withHugeArtist := func() { conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) - ds.Artist().(*tests.MockArtistRepo).SetData(model.Artists{{ID: testID("ar1")}}) - songs := make(model.MediaFiles, 6) - for i := range songs { - songs[i] = model.MediaFile{ID: testID(fmt.Sprintf("big-%d", i))} + putArtists(ctx, ds, model.Artist{ID: testID("ar1"), Name: "Huge"}) + for i := range 6 { + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID(fmt.Sprintf("big-%d", i)), Participants: credits(model.RoleArtist, testID("ar1"))}) } - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) } create := func(body any) *httptest.ResponseRecorder { b, err := json.Marshal(body) @@ -426,11 +437,12 @@ var _ = Describe("Playlists", func() { It("asks a playlist container for at most one track past the limit", func() { conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 5 }) - tracks := make(model.PlaylistTracks, 6) - for i := range tracks { - tracks[i] = model.PlaylistTrack{ID: strconv.Itoa(i + 1), MediaFileID: testID(fmt.Sprintf("pl-%d", i))} + ids := make([]string, 6) + for i := range ids { + ids[i] = testID(fmt.Sprintf("pl-%d", i)) } - fp.getPls = &model.Playlist{ID: testID("pl9"), Tracks: tracks} + putSongsByID(ctx, ds, ids...) + putPlaylist(ctx, ds, testID("pl9"), ids...) w := create(map[string]any{"Name": "Mix", "Ids": []string{dto.EncodeID(testID("pl9"))}}) @@ -495,15 +507,9 @@ var _ = Describe("Playlists", func() { Describe("getPlaylist", func() { It("returns OpenAccess from Public and item ids (encoded media file ids, not entry ids)", func() { - pls := &model.Playlist{ - ID: testID("pl1"), - Public: true, - Tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: testID("s1"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s1")}}, - {ID: "2", MediaFileID: testID("s2"), PlaylistID: testID("pl1"), MediaFile: model.MediaFile{ID: testID("s2")}}, - }, - } - fp.getPls, fp.getByIDPls = pls, pls + putSongsByID(ctx, ds, testID("s1"), testID("s2")) + putPlaylist(ctx, ds, testID("pl1"), testID("s1"), testID("s2")) + fp.getByIDPls = &model.Playlist{ID: testID("pl1"), Public: true} w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Playlists/"+testID("pl1"), nil).WithContext(ctx) r = withChiURLParam(r, "playlistId", dto.EncodeID(testID("pl1"))) @@ -517,7 +523,6 @@ var _ = Describe("Playlists", func() { }) It("returns 404 for a non-owned or absent playlist", func() { - fp.getErr = model.ErrNotFound w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Playlists/missing", nil).WithContext(ctx) r = withChiURLParam(r, "playlistId", dto.EncodeID(testID("missing"))) diff --git a/server/jellyfin/quickconnect_test.go b/server/jellyfin/quickconnect_test.go index 9ac2e2a84..3c8511b4b 100644 --- a/server/jellyfin/quickconnect_test.go +++ b/server/jellyfin/quickconnect_test.go @@ -7,13 +7,16 @@ import ( "net/http/httptest" "strings" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/quickconnect" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -28,7 +31,7 @@ var _ = Describe("QuickConnect", func() { const finamp = `MediaBrowser Client="Finamp", Device="Pixel 7", DeviceId="dev-1", Version="1.0.0"` var ( api *Router - ds *tests.MockDataStore + ds model.DataStore qc quickconnect.QuickConnect alice = model.User{ID: testID("alice"), UserName: "alice"} bob = model.User{ID: testID("bob"), UserName: "bob"} @@ -37,11 +40,10 @@ var _ = Describe("QuickConnect", func() { BeforeEach(func() { conf.Update(func(c *conf.Options) { c.Jellyfin.QuickConnect = true }) - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - ur := ds.User().(*tests.MockedUserRepo) for _, u := range []model.User{alice, bob, admin} { - Expect(ur.Put(GinkgoT().Context(), &u)).To(Succeed()) + Expect(ds.User().Put(GinkgoT().Context(), &u)).To(Succeed()) } qc = quickconnect.New() api = &Router{ds: ds, quickConnect: qc} @@ -291,7 +293,9 @@ var _ = Describe("QuickConnect", func() { It("returns 500 when the user lookup fails", func() { req := initiate() _, _ = qc.Authorize(req.Code, alice.ID) - ds.User().(*tests.MockedUserRepo).Error = errors.New("db down") + api.ds = persistencetest.Stub(ds, persistencetest.Repos{User: func(r model.UserRepository) model.UserRepository { + return failingUserRepo{UserRepository: r, err: errors.New("db down")} + }}) Expect(redeemSecret(req.Secret).Code).To(Equal(http.StatusInternalServerError)) }) }) diff --git a/server/jellyfin/routing_test.go b/server/jellyfin/routing_test.go index 79522cf8f..24a626b1f 100644 --- a/server/jellyfin/routing_test.go +++ b/server/jellyfin/routing_test.go @@ -4,8 +4,10 @@ import ( "net/http" "net/http/httptest" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" + "github.com/go-chi/chi/v5" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -19,7 +21,7 @@ var _ = Describe("Case-insensitive routing", func() { var api *Router BeforeEach(func() { - api = New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + api = New(persistence.New(db.Db()), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) }) It("serves a fully lowercase path directly", func() { @@ -40,7 +42,7 @@ var _ = Describe("Case-insensitive routing", func() { w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/users/authenticatebyname", nil) api.ServeHTTP(w, r) - // MockDataStore has no users, so authentication itself may fail downstream, but the + // The database has no users, so authentication itself may fail downstream, but the // route must be found (not a 404) to prove case-insensitive matching worked. Expect(w.Code).ToNot(Equal(http.StatusNotFound)) }) diff --git a/server/jellyfin/sessions_test.go b/server/jellyfin/sessions_test.go index 1966349ab..bf28db9f9 100644 --- a/server/jellyfin/sessions_test.go +++ b/server/jellyfin/sessions_test.go @@ -12,7 +12,6 @@ import ( "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -67,7 +66,7 @@ var _ = Describe("Sessions", func() { BeforeEach(func() { ctx = GinkgoT().Context() pt = &fakePlayTracker{} - api = &Router{ds: &tests.MockDataStore{}, scrobbler: pt} + api = &Router{ds: struct{ model.DataStore }{}, scrobbler: pt} }) Describe("reportPlaybackStart", func() { @@ -186,7 +185,7 @@ var _ = Describe("withPlayer middleware", func() { BeforeEach(func() { fp = &fakePlayers{} - api = &Router{ds: &tests.MockDataStore{}, players: fp} + api = &Router{ds: struct{ model.DataStore }{}, players: fp} }) It("registers a player from the Emby device info and injects it into the context", func() { diff --git a/server/jellyfin/similar_test.go b/server/jellyfin/similar_test.go index 2abdf1daf..4c05b9946 100644 --- a/server/jellyfin/similar_test.go +++ b/server/jellyfin/similar_test.go @@ -10,11 +10,14 @@ import ( "sync/atomic" "time" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/core/external" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -129,10 +132,8 @@ var _ = Describe("getInstantMix", func() { similarWait = 20 * time.Millisecond DeferCleanup(func() { similarWait = old }) - ds := &tests.MockDataStore{} - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Seed Song", LibraryID: 1}, - }) + ds := persistence.New(db.Db()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: testID("s1"), Title: "Seed Song", LibraryID: 1}) release := make(chan struct{}) DeferCleanup(func() { close(release) }) api := &Router{ds: ds, provider: &blockingProvider{release: release}} @@ -157,8 +158,8 @@ var _ = Describe("getInstantMix", func() { for i := range want + 50 { // more than requested, so only the limit bounds the result songs = append(songs, model.MediaFile{ID: testID(fmt.Sprintf("t%d", i)), Title: fmt.Sprintf("Track %d", i), LibraryID: 1}) } - ds := &tests.MockDataStore{} - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(songs) + ds := persistence.New(db.Db()) + persistencetest.PutMediaFiles(ctx, ds, songs[0]) api := &Router{ds: ds, provider: &fakeSimilarProvider{songs: songs[1:]}} w := httptest.NewRecorder() @@ -174,7 +175,7 @@ var _ = Describe("getInstantMix", func() { }) It("returns a mix for a genre id, which GetEntityByID can't resolve", func() { - ds := &tests.MockDataStore{} + ds := persistence.New(db.Db()) songs := model.MediaFiles{ {ID: testID("m1"), Title: "Track 1", LibraryID: 1}, {ID: testID("m2"), Title: "Track 2", LibraryID: 1}, @@ -203,10 +204,8 @@ var _ = Describe("getSimilarAlbums", func() { It("does not return the seed album as its own similar album", func() { // With no external agent the provider falls back to the album's own tracks, which map // straight back to the requested album. - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: testID("al-1"), Name: "Seed Album", LibraryID: 1}, - }) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("al-1"), Name: "Seed Album", LibraryID: 1}) api := &Router{ds: ds, provider: &fakeSimilarProvider{ songs: model.MediaFiles{{ID: testID("m1"), AlbumID: testID("al-1"), LibraryID: 1}}, }} @@ -224,10 +223,8 @@ var _ = Describe("getSimilarAlbums", func() { }) It("returns albums derived from the provider's similar songs", func() { - ds := &tests.MockDataStore{} - ds.Album().(*tests.MockAlbumRepo).SetData(model.Albums{ - {ID: testID("al-2"), Name: "Other", LibraryID: 1}, - }) + ds := persistence.New(db.Db()) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: testID("al-2"), Name: "Other", LibraryID: 1}) api := &Router{ds: ds, provider: &fakeSimilarProvider{ songs: model.MediaFiles{{ID: testID("m1"), AlbumID: testID("al-2"), LibraryID: 1}}, }} diff --git a/server/jellyfin/socket_test.go b/server/jellyfin/socket_test.go index 79098aafd..2dd21a99f 100644 --- a/server/jellyfin/socket_test.go +++ b/server/jellyfin/socket_test.go @@ -6,10 +6,12 @@ import ( "strings" "time" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" + "github.com/gorilla/websocket" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -80,14 +82,13 @@ var _ = Describe("handleSocket", func() { // wrapper + chi mux + auth middleware) with a real network listener, exactly as Finamp // hits it in production with ?api_key=. Context("mounted behind the full router and auth middleware", func() { - var ds *tests.MockDataStore + var ds model.DataStore var token string BeforeEach(func() { - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - ur := ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(GinkgoT().Context(), &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) + Expect(ds.User().Put(GinkgoT().Context(), &model.User{ID: testID("u1"), UserName: "alice", NewPassword: "secret"})).To(Succeed()) t, err := auth.CreateToken(&model.User{ID: testID("u1"), UserName: "alice"}) Expect(err).ToNot(HaveOccurred()) diff --git a/server/jellyfin/stream_test.go b/server/jellyfin/stream_test.go index a73b7404f..9f680d208 100644 --- a/server/jellyfin/stream_test.go +++ b/server/jellyfin/stream_test.go @@ -11,10 +11,12 @@ import ( "time" "github.com/navidrome/navidrome/core/stream" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -22,7 +24,7 @@ import ( var _ = Describe("Stream", func() { var ctx context.Context var api *Router - var ds *tests.MockDataStore + var ds model.DataStore var streamer *fakeMediaStreamer var decider *fakeTranscodeDecider @@ -33,7 +35,10 @@ var _ = Describe("Stream", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) + putUser(ctx, ds, model.User{ID: testID("u1"), UserName: "alice"}) + persistencetest.SetLibraries(ctx, ds, "/music1", "/music2") + Expect(ds.User().SetUserLibraries(ctx, testID("u1"), []int{1})).To(Succeed()) streamer = &fakeMediaStreamer{} decider = &fakeTranscodeDecider{} api = &Router{ @@ -44,9 +49,9 @@ var _ = Describe("Stream", func() { Describe("getPlaybackInfo", func() { It("returns a media source for an accessible track", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Items/"+dto.EncodeID(testID("s1"))+"/PlaybackInfo", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -63,9 +68,9 @@ var _ = Describe("Stream", func() { }) It("returns 404 for a track in a library the user can't access", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodPost, "/Items/"+dto.EncodeID(testID("s1"))+"/PlaybackInfo", nil).WithContext(ctxUser()) // only has access to library 1 r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -104,9 +109,9 @@ var _ = Describe("Stream", func() { } It("advertises a Lyric stream for plugin/sidecar-sourced lyrics not embedded in the file", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, + ) api.lyrics = &fakeLyricsService{lyrics: map[string]model.LyricList{ testID("s1"): {{Kind: "main", Synced: true, Line: []model.Line{{Value: "hello"}}}}, }} @@ -115,17 +120,17 @@ var _ = Describe("Stream", func() { }) It("advertises no Lyric stream when the pipeline finds nothing", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, + ) Expect(lyricStreams(playbackInfo())).To(BeEmpty()) }) It("advertises no Lyric stream when the lyrics endpoint would 404 (main lyric has no lines)", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, + ) api.lyrics = &fakeLyricsService{lyrics: map[string]model.LyricList{ testID("s1"): {{Kind: "main", Lang: "eng"}}, }} @@ -134,9 +139,9 @@ var _ = Describe("Stream", func() { }) It("doesn't duplicate the Lyric stream when lyrics are already embedded", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1, Lyrics: `[{"lang":"xxx","line":[]}]`}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1, Lyrics: `[{"lang":"xxx","line":[]}]`}, + ) api.lyrics = &fakeLyricsService{lyrics: map[string]model.LyricList{ testID("s1"): {{Kind: "main", Synced: true, Line: []model.Line{{Value: "hello"}}}}, }} @@ -147,9 +152,9 @@ var _ = Describe("Stream", func() { It("still returns 200 with a valid MediaSource and no Lyric stream when the lyrics pipeline errors", func() { // Own ID: an erroring loader isn't cached, but a shared ID could still pick up // another test's cached (non-error) result and mask this assertion. - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s-err"), Title: "Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s-err"), Title: "Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, + ) api.lyrics = &fakeLyricsService{err: errors.New("boom")} w := httptest.NewRecorder() @@ -177,9 +182,9 @@ var _ = Describe("Stream", func() { Eventually(doneCh).Should(BeClosed()) }) - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Slow Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Slow Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, + ) api.lyrics = &fakeLyricsService{ lyrics: map[string]model.LyricList{ testID("s1"): {{Kind: "main", Synced: true, Line: []model.Line{{Value: "delayed"}}}}, @@ -197,9 +202,9 @@ var _ = Describe("Stream", func() { }) It("recovers panics in detached lyrics lookup and returns 200 without Lyric stream", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s-panic"), Title: "Panic Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s-panic"), Title: "Panic Song", Suffix: "mp3", Duration: 100, Size: 1000, LibraryID: 1}, + ) api.lyrics = &fakeLyricsService{panicVal: "lyrics plugin crash"} w := httptest.NewRecorder() @@ -217,9 +222,9 @@ var _ = Describe("Stream", func() { Describe("streamAudio", func() { It("invokes the transcode decider and streamer for an accessible track", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, + ) streamer.content = "audio-bytes" w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Audio/"+dto.EncodeID(testID("s1"))+"/stream", nil).WithContext(ctxUser()) @@ -233,9 +238,9 @@ var _ = Describe("Stream", func() { }) It("returns 404 for a track in a library the user can't access, without invoking the streamer or decider", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Audio/"+dto.EncodeID(testID("s1"))+"/stream", nil).WithContext(ctxUser()) // only has access to library 1 r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -258,9 +263,9 @@ var _ = Describe("Stream", func() { }) It("converts the bps audioBitRate param to kbps", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Audio/"+dto.EncodeID(testID("s1"))+"/stream?audiobitrate=320000", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -270,9 +275,9 @@ var _ = Describe("Stream", func() { }) It("uses the audioCodec param as target format when no container is given", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Audio/"+dto.EncodeID(testID("s1"))+"/stream?audiocodec=aac", nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -282,9 +287,9 @@ var _ = Describe("Stream", func() { }) It("returns 500 and logs when the streamer fails", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, + ) streamer.err = errors.New("boom") w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Audio/"+dto.EncodeID(testID("s1"))+"/stream", nil).WithContext(ctxUser()) @@ -297,9 +302,9 @@ var _ = Describe("Stream", func() { Describe("HEAD requests", func() { head := func(query string) *httptest.ResponseRecorder { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "flac", LibraryID: 1}, + ) streamer.content = "audio-bytes" w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodHead, "/Audio/"+dto.EncodeID(testID("s1"))+"/stream?"+query, nil).WithContext(ctxUser()) @@ -327,9 +332,9 @@ var _ = Describe("Stream", func() { Describe("streamUniversal", func() { universal := func(query string) { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Suffix: "mp3", LibraryID: 1}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Audio/"+dto.EncodeID(testID("s1"))+"/universal?"+query, nil).WithContext(ctxUser()) r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) @@ -374,9 +379,9 @@ var _ = Describe("Stream", func() { Describe("streamHls", func() { BeforeEach(func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "dsf", Duration: 100.5, LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "dsf", Duration: 100.5, LibraryID: 1}, + ) }) hls := func(query string, ctx context.Context) *httptest.ResponseRecorder { @@ -429,23 +434,23 @@ var _ = Describe("Stream", func() { }) It("returns 404 for a track in a library the user can't access", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "dsf", LibraryID: 2}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "dsf", LibraryID: 2}, + ) Expect(hls("", ctxUser()).Code).To(Equal(http.StatusNotFound)) }) It("returns 404 when the id doesn't match any media file", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{}) + Expect(ds.MediaFile().Delete(ctx, testID("s1"))).To(Succeed()) Expect(hls("", ctxUser()).Code).To(Equal(http.StatusNotFound)) }) }) Describe("streamFile", func() { It("invokes the decider with a raw/direct-play request and the streamer for an accessible track", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 1}, + ) streamer.content = "audio-bytes" w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("s1"))+"/File", nil).WithContext(ctxUser()) @@ -460,9 +465,9 @@ var _ = Describe("Stream", func() { }) It("returns 404 for a track in a library the user can't access, without invoking the streamer or decider", func() { - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(model.MediaFiles{ - {ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: testID("s1"), Title: "Song", Suffix: "mp3", LibraryID: 2}, + ) w := httptest.NewRecorder() r := httptest.NewRequest(http.MethodGet, "/Items/"+dto.EncodeID(testID("s1"))+"/File", nil).WithContext(ctxUser()) // only has access to library 1 r = withChiURLParam(r, "itemId", dto.EncodeID(testID("s1"))) diff --git a/server/jellyfin/system_test.go b/server/jellyfin/system_test.go index 9df5f780b..ef7f99168 100644 --- a/server/jellyfin/system_test.go +++ b/server/jellyfin/system_test.go @@ -9,10 +9,14 @@ import ( "net/http/httptest" "sync" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -142,11 +146,11 @@ var _ = Describe("System", func() { Context("serverID with a real DataStore", func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) }) It("persists the generated id so it can be read back by another Router sharing the same DataStore", func() { @@ -179,13 +183,13 @@ var _ = Describe("System", func() { It("does not overwrite or pin over a stored id when the property read fails transiently", func() { Expect(ds.Property().Put(ctx, consts.JellyfinServerIDKey, "6ba7b8109dad11d180b400c04fd430c8")).To(Succeed()) - r := &Router{ds: ds} - props := ds.Property().(*tests.MockedPropertyRepo) - props.Error = errors.New("database is locked") + r := &Router{ds: persistencetest.Stub(ds, persistencetest.Repos{Property: func(r model.PropertyRepository) model.PropertyRepository { + return failingPropertyRepo{PropertyRepository: r, err: errors.New("database is locked")} + }})} degraded := r.serverID(ctx) Expect(degraded).ToNot(BeEmpty()) Expect(degraded).ToNot(Equal("6ba7b8109dad11d180b400c04fd430c8")) // temporary value, not the (unreadable) stored one - props.Error = nil + r.ds = ds // Once the DB recovers, the stored id is intact and served again. Expect(r.serverID(ctx)).To(Equal("6ba7b8109dad11d180b400c04fd430c8")) diff --git a/server/jellyfin/users_test.go b/server/jellyfin/users_test.go index 355686667..9c11efaa9 100644 --- a/server/jellyfin/users_test.go +++ b/server/jellyfin/users_test.go @@ -8,10 +8,11 @@ import ( "time" "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/jellyfin/dto" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -19,9 +20,9 @@ import ( var _ = Describe("Users", func() { var ctx context.Context var api *Router - // The repo holds the full rows; the user carries the id/name-only copy its projection returns. + // The DB holds the full rows; the user carries the id/name-only copy its projection returns. authedWithLibraries := func(r *http.Request, libs model.Libraries) *http.Request { - api.ds.Library().(*tests.MockLibraryRepo).SetData(libs) + putLibraries(ctx, api.ds, libs) stripped := make(model.Libraries, len(libs)) for i, lib := range libs { stripped[i] = model.Library{ID: lib.ID, Name: lib.Name} @@ -30,7 +31,7 @@ var _ = Describe("Users", func() { } BeforeEach(func() { ctx = GinkgoT().Context() - api = &Router{ds: &tests.MockDataStore{}} + api = &Router{ds: persistence.New(db.Db())} }) Describe("getUserViews", func() { @@ -107,7 +108,6 @@ var _ = Describe("Users", func() { }) Describe("getPublicUsers", func() { - var ur *tests.MockedUserRepo publicUsers := func() []dto.UserDto { w := httptest.NewRecorder() api.getPublicUsers(w, httptest.NewRequest(http.MethodGet, "/Users/Public", nil)) @@ -118,9 +118,8 @@ var _ = Describe("Users", func() { } BeforeEach(func() { - ur = api.ds.User().(*tests.MockedUserRepo) - Expect(ur.Put(ctx, &model.User{ID: testID("u1"), UserName: "alice"})).To(Succeed()) - Expect(ur.Put(ctx, &model.User{ID: testID("u2"), UserName: "bob"})).To(Succeed()) + Expect(api.ds.User().Put(ctx, &model.User{ID: testID("u1"), UserName: "alice"})).To(Succeed()) + Expect(api.ds.User().Put(ctx, &model.User{ID: testID("u2"), UserName: "bob"})).To(Succeed()) }) It("returns an empty list when the config is unset", func() { @@ -155,3 +154,19 @@ var _ = Describe("Users", func() { }) }) }) + +// putLibraries stores libs with their stats and creation dates, which Library().Put does not store. +func putLibraries(ctx context.Context, ds model.DataStore, libs model.Libraries) { + GinkgoHelper() + for _, lib := range libs { + if lib.Path == "" { + lib.Path = "/" + lib.Name + } + if lib.ID != model.DefaultLibraryID { + Expect(ds.Library().Put(ctx, &lib)).To(Succeed()) + } + _, err := db.Db().Exec("UPDATE library SET name = ?, path = ?, total_albums = ?, created_at = ? WHERE id = ?", + lib.Name, lib.Path, lib.TotalAlbums, lib.CreatedAt, lib.ID) + Expect(err).ToNot(HaveOccurred()) + } +} diff --git a/server/middlewares_test.go b/server/middlewares_test.go index 3a844249d..ee20b1146 100644 --- a/server/middlewares_test.go +++ b/server/middlewares_test.go @@ -15,9 +15,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/publicurl" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -365,7 +366,7 @@ var _ = Describe("middlewares", func() { middleware func(next http.Handler) http.Handler req *http.Request ctx context.Context - ds *tests.MockDataStore + ds model.DataStore id string lastAccessTime time.Time ) @@ -377,8 +378,8 @@ var _ = Describe("middlewares", func() { BeforeEach(func() { ctx = GinkgoT().Context() id = uuid.NewString() - ds = &tests.MockDataStore{} - lastAccessTime = time.Now() + ds = persistence.New(db.Db()) + lastAccessTime = time.Now().Add(-time.Hour) Expect(ds.User().Put(ctx, &model.User{ID: id, UserName: "johndoe", LastAccessAt: &lastAccessTime})). To(Succeed()) @@ -401,14 +402,14 @@ var _ = Describe("middlewares", func() { callMiddleware(req) - user, _ := ds.MockedUser.FindByUsername(ctx, "johndoe") + user, _ := ds.User().FindByUsername(ctx, "johndoe") Expect(*user.LastAccessAt).To(BeTemporally(">", lastAccessTime, time.Second)) }) It("skip fast successive requests", func() { // First request callMiddleware(req) - user, _ := ds.MockedUser.FindByUsername(ctx, "johndoe") + user, _ := ds.User().FindByUsername(ctx, "johndoe") lastAccessTime = *user.LastAccessAt // Store the last access time // Second request @@ -416,8 +417,8 @@ var _ = Describe("middlewares", func() { callMiddleware(req) // The second request should not have changed the last access time - user, _ = ds.MockedUser.FindByUsername(ctx, "johndoe") - Expect(user.LastAccessAt).To(Equal(&lastAccessTime)) + user, _ = ds.User().FindByUsername(ctx, "johndoe") + Expect(*user.LastAccessAt).To(BeTemporally("==", lastAccessTime)) }) }) Context("when the request has no user", func() { @@ -425,8 +426,8 @@ var _ = Describe("middlewares", func() { req = req.WithContext(ctx) callMiddleware(req) - usr, _ := ds.MockedUser.FindByUsername(ctx, "johndoe") - Expect(usr.LastAccessAt).To(Equal(&lastAccessTime)) + usr, _ := ds.User().FindByUsername(ctx, "johndoe") + Expect(*usr.LastAccessAt).To(BeTemporally("==", lastAccessTime)) }) }) Context("when the request is an internal call (e.g. from a plugin)", func() { @@ -447,8 +448,8 @@ var _ = Describe("middlewares", func() { callMiddleware(req) - usr, _ := ds.MockedUser.FindByUsername(ctx, "johndoe") - Expect(usr.LastAccessAt).To(Equal(&lastAccessTime)) + usr, _ := ds.User().FindByUsername(ctx, "johndoe") + Expect(*usr.LastAccessAt).To(BeTemporally("==", lastAccessTime)) }) }) }) diff --git a/server/nativeapi/config_test.go b/server/nativeapi/config_test.go index aefa507b1..0c5987843 100644 --- a/server/nativeapi/config_test.go +++ b/server/nativeapi/config_test.go @@ -10,10 +10,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" - "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -30,9 +30,9 @@ var _ = Describe("Config API", func() { c.EnableSharing = false c.DevUIShowConfig = true }) // Enable config endpoint for tests - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil) + nativeRouter := newTestRouter(ds, nil, nil, nil) router = server.JWTVerifier(nativeRouter) // Create test users @@ -51,9 +51,7 @@ var _ = Describe("Config API", func() { NewPassword: "userpass", } - // Store in mock datastore - Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) - Expect(ds.User().Put(ctx, ®ularUser)).To(Succeed()) + putUsers(ctx, ds, &adminUser, ®ularUser) }) Describe("GET /api/config", func() { diff --git a/server/nativeapi/library_test.go b/server/nativeapi/library_test.go index 3bc8a243b..f0c555828 100644 --- a/server/nativeapi/library_test.go +++ b/server/nativeapi/library_test.go @@ -7,15 +7,17 @@ import ( "fmt" "net/http" "net/http/httptest" + "strconv" "strings" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" - "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -26,13 +28,14 @@ var _ = Describe("Library API", func() { var router http.Handler var adminUser, regularUser model.User var library1, library2 model.Library + var library1Path, library2Path string BeforeEach(func() { ctx = GinkgoT().Context() conf.Update(func(c *conf.Options) { c.EnableSharing = false }) - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil) + nativeRouter := newTestRouter(ds, nil, nil, nil) router = server.JWTVerifier(nativeRouter) // Create test users @@ -51,21 +54,11 @@ var _ = Describe("Library API", func() { NewPassword: "userpass", } - // Create test libraries - library1 = model.Library{ - ID: 1, - Name: "Test Library 1", - Path: "/music/library1", - } - library2 = model.Library{ - ID: 2, - Name: "Test Library 2", - Path: "/music/library2", - } - - // Store in mock datastore - Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) - Expect(ds.User().Put(ctx, ®ularUser)).To(Succeed()) + putUsers(ctx, ds, &adminUser, ®ularUser) + library1Path, library2Path = GinkgoT().TempDir(), GinkgoT().TempDir() + persistencetest.SetLibraries(ctx, ds, library1Path, library2Path) + library1 = model.Library{ID: 1, Name: "Test Library 1", Path: library1Path} + library2 = model.Library{ID: 2, Name: "Test Library 2", Path: library2Path} Expect(ds.Library().Put(ctx, &library1)).To(Succeed()) Expect(ds.Library().Put(ctx, &library2)).To(Succeed()) }) @@ -111,7 +104,7 @@ var _ = Describe("Library API", func() { err := json.Unmarshal(w.Body.Bytes(), &library) Expect(err).ToNot(HaveOccurred()) Expect(library.Name).To(Equal("Test Library 1")) - Expect(library.Path).To(Equal("/music/library1")) + Expect(library.Path).To(Equal(library1Path)) }) It("returns 404 for non-existent library", func() { @@ -137,7 +130,7 @@ var _ = Describe("Library API", func() { It("creates a new library", func() { newLibrary := model.Library{ Name: "New Library", - Path: "/music/new", + Path: GinkgoT().TempDir(), } body, _ := json.Marshal(newLibrary) req := createAuthenticatedRequest("POST", "/library", bytes.NewBuffer(body), adminToken) @@ -145,13 +138,21 @@ var _ = Describe("Library API", func() { router.ServeHTTP(w, req) - Expect(w.Code).To(Equal(http.StatusOK)) + Expect(w.Code).To(Equal(http.StatusOK), w.Body.String()) + var created struct{ ID string } + Expect(json.Unmarshal(w.Body.Bytes(), &created)).To(Succeed()) + id, err := strconv.Atoi(created.ID) + Expect(err).ToNot(HaveOccurred()) + stored, err := ds.Library().Get(ctx, id) + Expect(err).ToNot(HaveOccurred()) + Expect(stored.Name).To(Equal("New Library")) + Expect(stored.Path).To(Equal(newLibrary.Path)) }) It("validates required fields", func() { invalidLibrary := model.Library{ Name: "", // Missing name - Path: "/music/invalid", + Path: GinkgoT().TempDir(), } body, _ := json.Marshal(invalidLibrary) req := createAuthenticatedRequest("POST", "/library", bytes.NewBuffer(body), adminToken) @@ -160,7 +161,7 @@ var _ = Describe("Library API", func() { router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusBadRequest)) - Expect(w.Body.String()).To(ContainSubstring("library name is required")) + Expect(w.Body.String()).To(ContainSubstring(`"name":"ra.validation.required"`)) }) It("validates path field", func() { @@ -175,18 +176,18 @@ var _ = Describe("Library API", func() { router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusBadRequest)) - Expect(w.Body.String()).To(ContainSubstring("library path is required")) + Expect(w.Body.String()).To(ContainSubstring(`"path":"ra.validation.required"`)) }) }) Describe("PUT /api/library/{id}", func() { It("updates an existing library", func() { updatedLibrary := model.Library{ - Name: "Updated Library 1", - Path: "/music/updated", + Name: "Updated Library 2", + Path: GinkgoT().TempDir(), } body, _ := json.Marshal(updatedLibrary) - req := createAuthenticatedRequest("PUT", "/library/1", bytes.NewBuffer(body), adminToken) + req := createAuthenticatedRequest("PUT", "/library/2", bytes.NewBuffer(body), adminToken) w := httptest.NewRecorder() router.ServeHTTP(w, req) @@ -196,34 +197,43 @@ var _ = Describe("Library API", func() { var updated model.Library err := json.Unmarshal(w.Body.Bytes(), &updated) Expect(err).ToNot(HaveOccurred()) - Expect(updated.ID).To(Equal(1)) - Expect(updated.Name).To(Equal("Updated Library 1")) - Expect(updated.Path).To(Equal("/music/updated")) + Expect(updated.ID).To(Equal(2)) + Expect(updated.Name).To(Equal("Updated Library 2")) + Expect(updated.Path).To(Equal(updatedLibrary.Path)) + stored, err := ds.Library().Get(ctx, 2) + Expect(err).ToNot(HaveOccurred()) + Expect(stored.Name).To(Equal("Updated Library 2")) + Expect(stored.Path).To(Equal(updatedLibrary.Path)) }) It("validates required fields on update", func() { invalidLibrary := model.Library{ Name: "", - Path: "/music/path", + Path: library2Path, } body, _ := json.Marshal(invalidLibrary) - req := createAuthenticatedRequest("PUT", "/library/1", bytes.NewBuffer(body), adminToken) + req := createAuthenticatedRequest("PUT", "/library/2", bytes.NewBuffer(body), adminToken) w := httptest.NewRecorder() router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusBadRequest)) + stored, err := ds.Library().Get(ctx, 2) + Expect(err).ToNot(HaveOccurred()) + Expect(stored.Name).To(Equal("Test Library 2")) }) }) Describe("DELETE /api/library/{id}", func() { It("deletes an existing library", func() { - req := createAuthenticatedRequest("DELETE", "/library/1", nil, adminToken) + req := createAuthenticatedRequest("DELETE", "/library/2", nil, adminToken) w := httptest.NewRecorder() router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) + _, err := ds.Library().Get(ctx, 2) + Expect(err).To(MatchError(model.ErrNotFound)) }) It("returns 404 for non-existent library", func() { @@ -332,6 +342,7 @@ var _ = Describe("Library API", func() { }) It("sets user's libraries", func() { + Expect(ds.User().SetUserLibraries(ctx, regularUser.ID, []int{1})).To(Succeed()) request := map[string][]int{ "libraryIds": {1, 2}, } @@ -347,6 +358,9 @@ var _ = Describe("Library API", func() { err := json.Unmarshal(w.Body.Bytes(), &libraries) Expect(err).ToNot(HaveOccurred()) Expect(libraries).To(HaveLen(2)) + stored, err := ds.User().GetUserLibraries(ctx, regularUser.ID) + Expect(err).ToNot(HaveOccurred()) + Expect(stored).To(HaveLen(2)) }) It("validates library IDs exist", func() { @@ -360,7 +374,7 @@ var _ = Describe("Library API", func() { router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusBadRequest)) - Expect(w.Body.String()).To(ContainSubstring("library ID 999 does not exist")) + Expect(w.Body.String()).To(ContainSubstring("one or more library IDs are invalid")) }) It("requires at least one library for regular users", func() { diff --git a/server/nativeapi/metadata_test.go b/server/nativeapi/metadata_test.go index 42add6667..812582695 100644 --- a/server/nativeapi/metadata_test.go +++ b/server/nativeapi/metadata_test.go @@ -2,18 +2,22 @@ package nativeapi import ( "context" + "errors" "net/http" "net/http/httptest" "slices" "sync" + "time" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/external" - "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -37,43 +41,39 @@ func (f *fakeProvider) calls() []string { return slices.Clone(f.called) } +type failingAlbumGet struct{ model.AlbumRepository } + +func (failingAlbumGet) Get(context.Context, string) (*model.Album, error) { + return nil, errors.New("db unavailable") +} + var _ = Describe("Metadata API", func() { var ctx context.Context - var ds *tests.MockDataStore - var artRepo *tests.MockArtworkRepo - var queueRepo *tests.MockArtworkQueueRepo - var albumRepo *tests.MockAlbumRepo + var ds model.DataStore var provider *fakeProvider var router http.Handler var adminToken, userToken string + newRouter := func(ds model.DataStore) http.Handler { + return server.JWTVerifier(newTestRouter(ds, nil, nil, provider)) + } + BeforeEach(func() { ctx = GinkgoT().Context() conf.Update(func(c *conf.Options) { c.EnableSharing = false }) - artRepo = tests.CreateMockArtworkRepo() - queueRepo = tests.CreateMockArtworkQueueRepo() - albumRepo = tests.CreateMockAlbumRepo() - artistRepo := tests.CreateMockArtistRepo() - playlistRepo := tests.CreateMockPlaylistRepo() - Expect(albumRepo.Put(ctx, &model.Album{ID: "al-1", Name: "Kid A"})).To(Succeed()) - Expect(artistRepo.Put(ctx, &model.Artist{ID: "ar-1", Name: "Radiohead"})).To(Succeed()) - Expect(playlistRepo.Put(ctx, &model.Playlist{ID: "pl-1", Name: "My Playlist"})).To(Succeed()) - ds = &tests.MockDataStore{ - MockedArtwork: artRepo, - MockedArtworkQueue: queueRepo, - MockedAlbum: albumRepo, - MockedArtist: artistRepo, - MockedPlaylist: playlistRepo, - } + ds = persistence.New(db.Db()) auth.Init(ds) provider = &fakeProvider{} - nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, provider, nil) - router = server.JWTVerifier(nativeRouter) + router = newRouter(ds) adminUser := model.User{ID: "admin-1", UserName: "admin", IsAdmin: true, NewPassword: "adminpass"} regularUser := model.User{ID: "user-1", UserName: "regular", IsAdmin: false, NewPassword: "userpass"} - Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) - Expect(ds.User().Put(ctx, ®ularUser)).To(Succeed()) + putUsers(ctx, ds, &adminUser, ®ularUser) + + adminCtx := request.WithUser(ctx, adminUser) + Expect(ds.Album().Put(ctx, &model.Album{ID: "al-1", Name: "Kid A", LibraryID: model.DefaultLibraryID})).To(Succeed()) + persistencetest.PutArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Radiohead"}) + Expect(ds.Playlist().Put(adminCtx, &model.Playlist{ID: "pl-1", Name: "My Playlist", OwnerID: adminUser.ID})).To(Succeed()) var err error adminToken, err = auth.CreateToken(&adminUser) @@ -84,9 +84,12 @@ var _ = Describe("Metadata API", func() { Describe("POST /api/metadata/{kind}/{id}/refresh", func() { It("clears state and enqueues a Bump for admins", func() { - Expect(artRepo.PutItemArtwork(ctx, &model.ItemArtwork{ - ItemKind: "al", ItemID: "al-1", Hash: "oldhash", Source: "external", + Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ + ItemKind: "al", ItemID: "al-1", ImageType: model.ImageTypePrimary, Hash: "oldhash", Source: "external", + AttemptedAt: time.Now(), UpdatedAt: time.Now(), })).To(Succeed()) + _, err := ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary) + Expect(err).ToNot(HaveOccurred()) req := createAuthenticatedRequest("POST", "/metadata/al/al-1/refresh", nil, adminToken) w := httptest.NewRecorder() @@ -94,16 +97,12 @@ var _ = Describe("Metadata API", func() { Expect(w.Code).To(Equal(http.StatusNoContent)) - _, err := artRepo.GetItemArtwork(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary) + _, err = ds.Artwork().GetItemArtwork(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary) Expect(err).To(MatchError(model.ErrNotFound)) - queued, err := queueRepo.DequeueBatch(ctx, 1000) + queued, err := ds.ArtworkQueue().Get(ctx, model.KindAlbumArtwork, "al-1", model.ImageTypePrimary) Expect(err).ToNot(HaveOccurred()) - Expect(queued).To(ContainElement(SatisfyAll( - HaveField("ItemKind", "al"), - HaveField("ItemID", "al-1"), - HaveField("Priority", model.ArtworkPriorityBump), - ))) + Expect(queued.Priority).To(Equal(model.ArtworkPriorityBump)) }) It("returns 400 for an invalid kind", func() { @@ -166,7 +165,9 @@ var _ = Describe("Metadata API", func() { }) It("returns 500 when the lookup fails for a reason other than not-found", func() { - albumRepo.SetError(true) + router = newRouter(persistencetest.Stub(ds, persistencetest.Repos{ + Album: func(r model.AlbumRepository) model.AlbumRepository { return failingAlbumGet{r} }, + })) req := createAuthenticatedRequest("POST", "/metadata/al/al-1/refresh", nil, adminToken) w := httptest.NewRecorder() diff --git a/server/nativeapi/missing_test.go b/server/nativeapi/missing_test.go index b41dd4b5c..5b5ada141 100644 --- a/server/nativeapi/missing_test.go +++ b/server/nativeapi/missing_test.go @@ -8,10 +8,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" - "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -26,22 +26,19 @@ var _ = Describe("Missing Files Endpoint", func() { c.EnableSharing = false }) - mfRepo := tests.CreateMockMediaFileRepo() - mfRepo.SetData(model.MediaFiles{ - {ID: "missing-1", Title: "Gone", Missing: true}, - {ID: "present-1", Title: "Here"}, - }) - userRepo := tests.CreateMockUserRepo() - ds := &tests.MockDataStore{MockedMediaFile: mfRepo, MockedUser: userRepo, MockedProperty: &tests.MockedPropertyRepo{}} + ctx := GinkgoT().Context() + ds := persistence.New(db.Db()) auth.Init(ds) user := model.User{ID: "user-1", UserName: "user", NewPassword: "pass"} - Expect(userRepo.Put(GinkgoT().Context(), &user)).To(Succeed()) + putUsers(ctx, ds, &user) + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: "missing-1", LibraryID: 1, Path: "gone.mp3", Title: "Gone", Missing: true})).To(Succeed()) + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: "present-1", LibraryID: 1, Path: "here.mp3", Title: "Here"})).To(Succeed()) var err error token, err = auth.CreateToken(&user) Expect(err).ToNot(HaveOccurred()) - router = server.JWTVerifier(New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil)) + router = server.JWTVerifier(newTestRouter(ds, nil, nil, nil)) }) DescribeTable("GET /missing/{id}", diff --git a/server/nativeapi/native_api_song_test.go b/server/nativeapi/native_api_song_test.go index e3be64214..3715310b8 100644 --- a/server/nativeapi/native_api_song_test.go +++ b/server/nativeapi/native_api_song_test.go @@ -4,34 +4,57 @@ import ( "bytes" "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "net/url" "time" + "github.com/deluan/rest" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" - "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) +type failingMediaFileReads struct{ model.MediaFileRepository } + +var errMediaFileReads = errors.New("db unavailable") + +func (failingMediaFileReads) Count(context.Context, ...rest.QueryOptions) (int64, error) { + return 0, errMediaFileReads +} + +func (failingMediaFileReads) ReadAll(context.Context, ...rest.QueryOptions) ([]model.MediaFile, error) { + return nil, errMediaFileReads +} + +func (failingMediaFileReads) Read(context.Context, string) (*model.MediaFile, error) { + return nil, errMediaFileReads +} + var _ = Describe("Song Endpoints", func() { var ( ctx context.Context router http.Handler - ds *tests.MockDataStore - mfRepo *tests.MockMediaFileRepo - userRepo *tests.MockedUserRepo + ds model.DataStore w *httptest.ResponseRecorder testUser model.User testSongs model.MediaFiles ) + useFailingMediaFiles := func() { + router = server.JWTVerifier(newTestRouter(persistencetest.Stub(ds, persistencetest.Repos{ + MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { return failingMediaFileReads{r} }, + }), nil, nil, nil)) + } + BeforeEach(func() { ctx = GinkgoT().Context() conf.Update(func(c *conf.Options) { @@ -39,17 +62,7 @@ var _ = Describe("Song Endpoints", func() { c.SessionTimeout = time.Minute }) - // Setup mock repositories - mfRepo = tests.CreateMockMediaFileRepo() - userRepo = tests.CreateMockUserRepo() - - ds = &tests.MockDataStore{ - MockedMediaFile: mfRepo, - MockedUser: userRepo, - MockedProperty: &tests.MockedPropertyRepo{}, - } - - // Initialize auth system + ds = persistence.New(db.Db()) auth.Init(ds) // Create test user @@ -60,47 +73,50 @@ var _ = Describe("Song Endpoints", func() { IsAdmin: false, NewPassword: "testpass", } - err := userRepo.Put(ctx, &testUser) - Expect(err).ToNot(HaveOccurred()) + putUsers(ctx, ds, &testUser) // Create test songs testSongs = model.MediaFiles{ { - ID: "song-1", - Title: "Test Song 1", - Artist: "Test Artist 1", - Album: "Test Album 1", - AlbumID: "album-1", - ArtistID: "artist-1", - Duration: 180.5, - BitRate: 320, - Path: "/music/song1.mp3", - Suffix: "mp3", - Size: 5242880, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + ID: "song-1", + LibraryID: model.DefaultLibraryID, + Title: "Test Song 1", + OrderTitle: "test song 1", + Artist: "Test Artist 1", + Album: "Test Album 1", + AlbumID: "album-1", + ArtistID: "artist-1", + Duration: 180.5, + BitRate: 320, + Path: "/music/song1.mp3", + Suffix: "mp3", + Size: 5242880, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), }, { - ID: "song-2", - Title: "Test Song 2", - Artist: "Test Artist 2", - Album: "Test Album 2", - AlbumID: "album-2", - ArtistID: "artist-2", - Duration: 240.0, - BitRate: 256, - Path: "/music/song2.mp3", - Suffix: "mp3", - Size: 7340032, - CreatedAt: time.Now(), - UpdatedAt: time.Now(), + ID: "song-2", + LibraryID: model.DefaultLibraryID, + Title: "Test Song 2", + OrderTitle: "test song 2", + Artist: "Test Artist 2", + Album: "Test Album 2", + AlbumID: "album-2", + ArtistID: "artist-2", + Duration: 240.0, + BitRate: 256, + Path: "/music/song2.mp3", + Suffix: "mp3", + Size: 7340032, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), }, } - mfRepo.SetData(testSongs) + for i := range testSongs { + Expect(ds.MediaFile().Put(ctx, &testSongs[i])).To(Succeed()) + } - // Create the native API router and wrap it with the JWTVerifier middleware - nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil) - router = server.JWTVerifier(nativeRouter) + router = server.JWTVerifier(newTestRouter(ds, nil, nil, nil)) w = httptest.NewRecorder() }) @@ -150,7 +166,7 @@ var _ = Describe("Song Endpoints", func() { }) It("handles repository errors gracefully", func() { - mfRepo.SetError(true) + useFailingMediaFiles() req := createAuthenticatedRequest("GET", "/song", nil) router.ServeHTTP(w, req) @@ -194,7 +210,7 @@ var _ = Describe("Song Endpoints", func() { }) It("handles repository errors gracefully", func() { - mfRepo.SetError(true) + useFailingMediaFiles() req := createAuthenticatedRequest("GET", "/song/song-1", nil) router.ServeHTTP(w, req) @@ -274,13 +290,11 @@ var _ = Describe("Song Endpoints", func() { err := json.Unmarshal(w.Body.Bytes(), &response) Expect(err).ToNot(HaveOccurred()) - // Should still return all songs since our mock doesn't implement pagination - // but the request should be processed successfully - Expect(response).ToNot(BeEmpty()) + Expect(response).To(HaveLen(1)) }) It("handles sort parameters", func() { - req := createAuthenticatedRequest("GET", "/song?_sort=title&_order=ASC", nil) + req := createAuthenticatedRequest("GET", "/song?_sort=title&_order=DESC", nil) router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) @@ -290,6 +304,8 @@ var _ = Describe("Song Endpoints", func() { Expect(err).ToNot(HaveOccurred()) Expect(response).To(HaveLen(2)) + Expect(response[0].ID).To(Equal("song-2")) + Expect(response[1].ID).To(Equal("song-1")) }) It("handles filter parameters", func() { @@ -308,8 +324,8 @@ var _ = Describe("Song Endpoints", func() { err := json.Unmarshal(w.Body.Bytes(), &response) Expect(err).ToNot(HaveOccurred()) - // Mock doesn't implement filtering, but request should be processed - Expect(response).ToNot(BeEmpty()) + Expect(response).To(HaveLen(1)) + Expect(response[0].ID).To(Equal("song-1")) }) }) }) @@ -328,15 +344,14 @@ var _ = Describe("Song Endpoints", func() { router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) - // The X-Total-Count header might be set by the REST framework - // We just verify the request is processed successfully + Expect(w.Header().Get("X-Total-Count")).To(Equal("2")) }) }) Describe("Edge cases and error handling", func() { Context("when repository is unavailable", func() { It("handles database connection errors", func() { - mfRepo.SetError(true) + useFailingMediaFiles() req := createAuthenticatedRequest("GET", "/song", nil) router.ServeHTTP(w, req) @@ -347,7 +362,9 @@ var _ = Describe("Song Endpoints", func() { Context("when no songs exist", func() { It("returns empty array when no songs are found", func() { - mfRepo.SetData(model.MediaFiles{}) // Empty dataset + for _, song := range testSongs { + Expect(ds.MediaFile().Delete(ctx, song.ID)).To(Succeed()) + } req := createAuthenticatedRequest("GET", "/song", nil) router.ServeHTTP(w, req) @@ -373,8 +390,7 @@ var _ = Describe("Song Endpoints", func() { IsAdmin: true, NewPassword: "adminpass", } - err := userRepo.Put(ctx, &adminUser) - Expect(err).ToNot(HaveOccurred()) + putUsers(ctx, ds, &adminUser) // Create JWT token for admin user token, err := auth.CreateToken(&adminUser) @@ -396,8 +412,7 @@ var _ = Describe("Song Endpoints", func() { IsAdmin: false, NewPassword: "userpass", } - err := userRepo.Put(ctx, ®ularUser) - Expect(err).ToNot(HaveOccurred()) + putUsers(ctx, ds, ®ularUser) // Create JWT token for regular user token, err := auth.CreateToken(®ularUser) diff --git a/server/nativeapi/native_api_suite_test.go b/server/nativeapi/native_api_suite_test.go index 3ea5a1701..7066c8be5 100644 --- a/server/nativeapi/native_api_suite_test.go +++ b/server/nativeapi/native_api_suite_test.go @@ -1,10 +1,19 @@ package nativeapi import ( + "context" "testing" + _ "github.com/navidrome/navidrome/adapters/gotaglib" "github.com/navidrome/navidrome/conf/configtest" + "github.com/navidrome/navidrome/core" + "github.com/navidrome/navidrome/core/external" + "github.com/navidrome/navidrome/core/playlists" + _ "github.com/navidrome/navidrome/core/storage/local" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +22,31 @@ import ( func TestNativeApi(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Native RESTful API Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() + +type noopPluginUnloader struct{} + +func (noopPluginUnloader) UnloadDisabledPlugins(context.Context) {} + +// newTestRouter builds the native API router with the real library, user and playlist services on ds. +func newTestRouter(ds model.DataStore, pls playlists.Playlists, pluginManager PluginManager, provider external.Provider) *Router { + if pls == nil { + pls = playlists.NewPlaylists(ds, nil) + } + libs := core.NewLibrary(ds, nil, nil, events.NoopBroker(), noopPluginUnloader{}) + users := core.NewUser(ds, noopPluginUnloader{}) + return New(ds, nil, pls, nil, libs, users, nil, pluginManager, nil, provider, nil) +} + +func putUsers(ctx context.Context, ds model.DataStore, users ...*model.User) { + GinkgoHelper() + for _, u := range users { + Expect(ds.User().Put(ctx, u)).To(Succeed()) + } +} diff --git a/server/nativeapi/playlists_test.go b/server/nativeapi/playlists_test.go index c42d256d5..662efd776 100644 --- a/server/nativeapi/playlists_test.go +++ b/server/nativeapi/playlists_test.go @@ -19,10 +19,11 @@ import ( "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -70,43 +71,51 @@ var _ = Describe("Playlist Image Endpoints", func() { var _ = Describe("Playlist Tracks Endpoint", func() { var ( + ctx context.Context + ds model.DataStore router http.Handler - plsSvc *mockPlaylistsService - userRepo *tests.MockedUserRepo + testUser model.User w *httptest.ResponseRecorder ) BeforeEach(func() { + ctx = GinkgoT().Context() conf.Update(func(c *conf.Options) { c.EnableSharing = false c.SessionTimeout = time.Minute }) - plsSvc = &mockPlaylistsService{repo: &mockPlaylistRestRepo{}} - userRepo = tests.CreateMockUserRepo() - - ds := &tests.MockDataStore{ - MockedUser: userRepo, - MockedProperty: &tests.MockedPropertyRepo{}, - } - + ds = persistence.New(db.Db()) auth.Init(ds) - testUser := model.User{ + testUser = model.User{ ID: "user-1", UserName: "testuser", Name: "Test User", IsAdmin: false, NewPassword: "testpass", } - err := userRepo.Put(GinkgoT().Context(), &testUser) - Expect(err).ToNot(HaveOccurred()) + putUsers(ctx, ds, &testUser) + for _, id := range []string{"mf-1", "mf-2"} { + Expect(ds.MediaFile().Put(ctx, &model.MediaFile{ID: id, LibraryID: model.DefaultLibraryID, Path: id + ".mp3"})).To(Succeed()) + } - nativeRouter := New(ds, nil, plsSvc, nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, nil, nil, nil, nil) - router = server.JWTVerifier(nativeRouter) + router = server.JWTVerifier(newTestRouter(ds, nil, nil, nil)) w = httptest.NewRecorder() }) + userPlaylists := func() model.Playlists { + GinkgoHelper() + pls, err := ds.Playlist().GetAll(request.WithUser(ctx, testUser)) + Expect(err).ToNot(HaveOccurred()) + return pls + } + putPlaylist := func(pls *model.Playlist) { + GinkgoHelper() + pls.OwnerID = testUser.ID + Expect(ds.Playlist().Put(request.WithUser(ctx, testUser), pls)).To(Succeed()) + } + createAuthenticatedRequestWithBody := func(method, path string, body io.Reader) *http.Request { req := httptest.NewRequest(method, path, body) if body != nil { @@ -130,6 +139,13 @@ var _ = Describe("Playlist Tracks Endpoint", func() { } Describe("POST /playlist/{playlistId}/tracks", func() { + var plsSvc *mockPlaylistsService + + BeforeEach(func() { + plsSvc = &mockPlaylistsService{} + router = server.JWTVerifier(newTestRouter(ds, plsSvc, nil, nil)) + }) + DescribeTable("adds ids up to DevMaxPlaylistTracksPerRequest", func(limit, sent int) { conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = limit }) @@ -178,13 +194,12 @@ var _ = Describe("Playlist Tracks Endpoint", func() { Describe("POST /playlist", func() { It("treats JSON with a charset as JSON, not as an M3U upload", func() { - plsSvc.importM3UFn = func(context.Context, io.Reader) (*model.Playlist, error) { return &model.Playlist{}, nil } req := createAuthenticatedRequestWithBody("POST", "/playlist", jsonBody(map[string]any{"name": "Mix"})) req.Header.Set("Content-Type", "application/json; charset=utf-8") router.ServeHTTP(w, req) - Expect(w.Code).To(Equal(http.StatusOK)) - Expect(plsSvc.repo.(*mockPlaylistRestRepo).saved).To(HaveExactElements(HaveField("Name", "Mix"))) + Expect(w.Code).To(Equal(http.StatusOK), w.Body.String()) + Expect(userPlaylists()).To(HaveExactElements(HaveField("Name", "Mix"))) }) It("accepts a JSON body larger than 4 MiB when the track limit is raised", func() { @@ -194,7 +209,7 @@ var _ = Describe("Playlist Tracks Endpoint", func() { router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusOK)) - Expect(plsSvc.repo.(*mockPlaylistRestRepo).saved).To(HaveLen(1)) + Expect(userPlaylists()).To(HaveLen(1)) }) It("rejects a JSON body over the size limit with 413", func() { @@ -203,18 +218,19 @@ var _ = Describe("Playlist Tracks Endpoint", func() { router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) - Expect(plsSvc.repo.(*mockPlaylistRestRepo).saved).To(BeEmpty()) + Expect(userPlaylists()).To(BeEmpty()) }) }) Describe("PUT /playlist/{id}", func() { It("rejects a JSON body over the size limit with 413", func() { + putPlaylist(&model.Playlist{ID: "pls-1", Name: "Mine", Comment: "original"}) body := jsonBody(map[string]any{"comment": strings.Repeat("x", int(maxPlaylistJSONBody()))}) req := createAuthenticatedRequestWithBody("PUT", "/playlist/pls-1", body) router.ServeHTTP(w, req) Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) - Expect(plsSvc.repo.(*mockPlaylistRestRepo).updated).To(BeZero()) + Expect(userPlaylists()).To(HaveExactElements(HaveField("Comment", "original"))) }) }) @@ -248,12 +264,9 @@ var _ = Describe("Playlist Tracks Endpoint", func() { }) It("returns tracks when playlist exists", func() { - plsSvc.tracksRepo = &mockPlaylistTrackRepo{ - tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: "mf-1", PlaylistID: "pls-1"}, - {ID: "2", MediaFileID: "mf-2", PlaylistID: "pls-1"}, - }, - } + pls := &model.Playlist{ID: "pls-1", Name: "Mine"} + pls.AddMediaFilesByID([]string{"mf-1", "mf-2"}) + putPlaylist(pls) req := createAuthenticatedRequest("GET", "/playlist/pls-1/tracks") router.ServeHTTP(w, req) @@ -265,7 +278,9 @@ var _ = Describe("Playlist Tracks Endpoint", func() { Expect(err).ToNot(HaveOccurred()) Expect(response).To(HaveLen(2)) Expect(response[0].ID).To(Equal("1")) + Expect(response[0].MediaFileID).To(Equal("mf-1")) Expect(response[1].ID).To(Equal("2")) + Expect(response[1].MediaFileID).To(Equal("mf-2")) }) }) @@ -278,11 +293,9 @@ var _ = Describe("Playlist Tracks Endpoint", func() { }) It("returns the track when playlist exists", func() { - plsSvc.tracksRepo = &mockPlaylistTrackRepo{ - tracks: model.PlaylistTracks{ - {ID: "1", MediaFileID: "mf-1", PlaylistID: "pls-1"}, - }, - } + pls := &model.Playlist{ID: "pls-1", Name: "Mine"} + pls.AddMediaFilesByID([]string{"mf-1"}) + putPlaylist(pls) req := createAuthenticatedRequest("GET", "/playlist/pls-1/tracks/1") router.ServeHTTP(w, req) @@ -297,9 +310,7 @@ var _ = Describe("Playlist Tracks Endpoint", func() { }) It("returns 404 when track does not exist in playlist", func() { - plsSvc.tracksRepo = &mockPlaylistTrackRepo{ - tracks: model.PlaylistTracks{}, - } + putPlaylist(&model.Playlist{ID: "pls-1", Name: "Mine"}) req := createAuthenticatedRequest("GET", "/playlist/pls-1/tracks/999") router.ServeHTTP(w, req) @@ -408,32 +419,8 @@ var _ = Describe("writePlaylistError", func() { ) }) -type mockPlaylistTrackRepo struct { - model.PlaylistTrackRepository - tracks model.PlaylistTracks -} - -func (m *mockPlaylistTrackRepo) Count(context.Context, ...rest.QueryOptions) (int64, error) { - return int64(len(m.tracks)), nil -} - -func (m *mockPlaylistTrackRepo) ReadAll(context.Context, ...rest.QueryOptions) ([]model.PlaylistTrack, error) { - return m.tracks, nil -} - -func (m *mockPlaylistTrackRepo) Read(_ context.Context, id string) (*model.PlaylistTrack, error) { - for _, t := range m.tracks { - if t.ID == id { - return &t, nil - } - } - return nil, rest.ErrNotFound -} - type mockPlaylistsService struct { playlists.Playlists - repo rest.Repository[model.Playlist] - tracksRepo rest.Repository[model.PlaylistTrack] playlist *model.Playlist addCalls int addedIds []string @@ -461,7 +448,7 @@ func (m *mockPlaylistsService) SetImage(ctx context.Context, id string, reader i } func (m *mockPlaylistsService) Repository() rest.Repository[model.Playlist] { - return m.repo + return nil } func (m *mockPlaylistsService) GetWithTracks(_ context.Context, _ string) (*model.Playlist, error) { @@ -471,10 +458,6 @@ func (m *mockPlaylistsService) GetWithTracks(_ context.Context, _ string) (*mode return m.playlist, nil } -func (m *mockPlaylistsService) TracksRepository(_ context.Context, _ string, _ bool) rest.Repository[model.PlaylistTrack] { - return m.tracksRepo -} - func (m *mockPlaylistsService) AddTracks(_ context.Context, _ string, ids []string) (int, error) { m.addCalls++ m.addedIds = append(m.addedIds, ids...) @@ -495,35 +478,3 @@ func (m *mockPlaylistsService) AddDiscs(_ context.Context, _ string, discs []mod m.addCalls++ return len(discs), nil } - -// mockPlaylistRestRepo records what rest.Post and rest.Put hand to the playlist repository. -type mockPlaylistRestRepo struct { - saved []model.Playlist - updated int -} - -func (m *mockPlaylistRestRepo) Count(context.Context, ...rest.QueryOptions) (int64, error) { - return 0, nil -} - -func (m *mockPlaylistRestRepo) Read(_ context.Context, id string) (*model.Playlist, error) { - return &model.Playlist{ID: id}, nil -} - -func (m *mockPlaylistRestRepo) ReadAll(context.Context, ...rest.QueryOptions) ([]model.Playlist, error) { - return nil, nil -} - -func (m *mockPlaylistRestRepo) Save(_ context.Context, entity *model.Playlist) (string, error) { - m.saved = append(m.saved, *entity) - return "new-id", nil -} - -func (m *mockPlaylistRestRepo) Update(context.Context, string, model.Playlist, ...string) error { - m.updated++ - return nil -} - -func (m *mockPlaylistRestRepo) Delete(context.Context, ...string) error { - return nil -} diff --git a/server/nativeapi/plugin_test.go b/server/nativeapi/plugin_test.go index 87da2e5d4..4c8bb2a0a 100644 --- a/server/nativeapi/plugin_test.go +++ b/server/nativeapi/plugin_test.go @@ -12,9 +12,10 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/auth" - "github.com/navidrome/navidrome/core/playlists" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" @@ -23,7 +24,7 @@ import ( var _ = Describe("Plugin API", func() { var ctx context.Context - var ds *tests.MockDataStore + var ds model.DataStore var mockManager *tests.MockPluginManager var router http.Handler var adminUser, regularUser model.User @@ -35,10 +36,10 @@ var _ = Describe("Plugin API", func() { c.EnableSharing = false c.Plugins.Enabled = true }) - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) mockManager = &tests.MockPluginManager{} auth.Init(ds) - nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), tests.NewMockUserService(), nil, mockManager, nil, nil, nil) + nativeRouter := newTestRouter(ds, nil, mockManager, nil) router = server.JWTVerifier(nativeRouter) // Create test users @@ -74,9 +75,7 @@ var _ = Describe("Plugin API", func() { Enabled: true, } - // Store users in mock datastore - Expect(ds.User().Put(ctx, &adminUser)).To(Succeed()) - Expect(ds.User().Put(ctx, ®ularUser)).To(Succeed()) + putUsers(ctx, ds, &adminUser, ®ularUser) }) Context("when plugins are disabled", func() { diff --git a/server/nativeapi/queue_test.go b/server/nativeapi/queue_test.go index 165c71021..24bb164f9 100644 --- a/server/nativeapi/queue_test.go +++ b/server/nativeapi/queue_test.go @@ -2,34 +2,103 @@ package nativeapi import ( "bytes" + "context" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" "strings" "github.com/navidrome/navidrome/conf" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) +// queueFaults makes the play queue repository fail on demand, and records the columns of the last Store. +type queueFaults struct { + lastCols []string + storeErr error + retrieveErr error + withMediaFilesErr error + clearErr error +} + +type faultyPlayQueue struct { + model.PlayQueueRepository + *queueFaults +} + +func (q faultyPlayQueue) Store(ctx context.Context, pq *model.PlayQueue, cols ...string) error { + if q.storeErr != nil { + return q.storeErr + } + q.lastCols = cols + return q.PlayQueueRepository.Store(ctx, pq, cols...) +} + +func (q faultyPlayQueue) RetrieveWithMediaFiles(ctx context.Context, userID string) (*model.PlayQueue, error) { + if q.retrieveErr != nil { + return nil, q.retrieveErr + } + pq, err := q.PlayQueueRepository.RetrieveWithMediaFiles(ctx, userID) + if err == nil { + err = q.withMediaFilesErr + } + return pq, err +} + +func (q faultyPlayQueue) Clear(ctx context.Context, userID string) error { + if q.clearErr != nil { + return q.clearErr + } + return q.PlayQueueRepository.Clear(ctx, userID) +} + var _ = Describe("Queue Endpoints", func() { var ( - ds *tests.MockDataStore - repo *tests.MockPlayQueueRepo - user model.User - userRepo *tests.MockedUserRepo + ctx context.Context + realDS model.DataStore + ds model.DataStore + faults *queueFaults + user model.User ) + seed := func(pq *model.PlayQueue) { + GinkgoHelper() + pq.UserID = user.ID + Expect(realDS.PlayQueue().Store(ctx, pq, "current", "position", "items")).To(Succeed()) + } + stored := func() *model.PlayQueue { + GinkgoHelper() + pq, err := realDS.PlayQueue().Retrieve(ctx, user.ID) + Expect(err).ToNot(HaveOccurred()) + return pq + } + expectNoQueue := func() { + GinkgoHelper() + _, err := realDS.PlayQueue().Retrieve(ctx, user.ID) + Expect(err).To(MatchError(model.ErrNotFound)) + } + BeforeEach(func() { - repo = &tests.MockPlayQueueRepo{} + ctx = GinkgoT().Context() + realDS = persistence.New(db.Db()) + faults = &queueFaults{} + ds = persistencetest.Stub(realDS, persistencetest.Repos{PlayQueue: func(r model.PlayQueueRepository) model.PlayQueueRepository { + return faultyPlayQueue{r, faults} + }}) user = model.User{ID: "u1", UserName: "user"} - userRepo = tests.CreateMockUserRepo() - _ = userRepo.Put(GinkgoT().Context(), &user) - ds = &tests.MockDataStore{MockedPlayQueue: repo, MockedUser: userRepo, MockedProperty: &tests.MockedPropertyRepo{}} + putUsers(ctx, realDS, &user) + for _, id := range []string{"s1", "s2", "s3", "s4", "track1", "track2", "track3"} { + mf := &model.MediaFile{ID: id, LibraryID: model.DefaultLibraryID, Path: id + ".mp3", Title: id} + Expect(realDS.MediaFile().Put(ctx, mf)).To(Succeed()) + } }) DescribeTable("rejects a body over the size limit with 413 without saving", @@ -41,7 +110,7 @@ var _ = Describe("Queue Endpoints", func() { handler(ds)(w, req) Expect(w.Code).To(Equal(http.StatusRequestEntityTooLarge)) - Expect(repo.Queue).To(BeNil()) + expectNoQueue() }, Entry("POST", http.MethodPost, saveQueue), Entry("PUT", http.MethodPut, updateQueue), @@ -56,7 +125,7 @@ var _ = Describe("Queue Endpoints", func() { saveQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Items).To(HaveLen(1)) + Expect(stored().Items).To(HaveLen(1)) }) Describe("POST /queue", func() { @@ -71,14 +140,15 @@ var _ = Describe("Queue Endpoints", func() { saveQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue).ToNot(BeNil()) - Expect(repo.Queue.Current).To(Equal(1)) - Expect(repo.Queue.Items).To(HaveLen(2)) - Expect(repo.Queue.Items[1].ID).To(Equal("s2")) - Expect(repo.Queue.ChangedBy).To(Equal("TestClient")) + pq := stored() + Expect(pq.Current).To(Equal(1)) + Expect(pq.Items).To(HaveLen(2)) + Expect(pq.Items[1].ID).To(Equal("s2")) + Expect(pq.ChangedBy).To(Equal("TestClient")) }) It("saves an empty queue", func() { + seed(&model.PlayQueue{Items: model.MediaFiles{{ID: "s1"}}}) payload := updateQueuePayload{Ids: new([]string{}), Current: new(0), Position: new(int64(0))} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPost, "/queue", bytes.NewReader(body)) @@ -87,8 +157,7 @@ var _ = Describe("Queue Endpoints", func() { saveQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue).ToNot(BeNil()) - Expect(repo.Queue.Items).To(BeEmpty()) + expectNoQueue() }) It("returns bad request for invalid current index (negative)", func() { @@ -125,7 +194,7 @@ var _ = Describe("Queue Endpoints", func() { }) It("returns internal server error when store fails", func() { - repo.Err = true + faults.storeErr = errors.New("db unavailable") payload := updateQueuePayload{Ids: new([]string{"s1"}), Current: new(0), Position: new(int64(10))} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPost, "/queue", bytes.NewReader(body)) @@ -139,17 +208,11 @@ var _ = Describe("Queue Endpoints", func() { Describe("GET /queue", func() { It("returns the queue", func() { - queue := &model.PlayQueue{ - UserID: user.ID, + seed(&model.PlayQueue{ Current: 1, Position: 55, - Items: model.MediaFiles{ - {ID: "track1", Title: "Song 1"}, - {ID: "track2", Title: "Song 2"}, - {ID: "track3", Title: "Song 3"}, - }, - } - repo.Queue = queue + Items: model.MediaFiles{{ID: "track1"}, {ID: "track2"}, {ID: "track3"}}, + }) req := httptest.NewRequest(http.MethodGet, "/queue", nil) req = req.WithContext(request.WithUser(req.Context(), user)) w := httptest.NewRecorder() @@ -163,6 +226,7 @@ var _ = Describe("Queue Endpoints", func() { Expect(resp.Position).To(Equal(int64(55))) Expect(resp.Items).To(HaveLen(3)) Expect(resp.Items[0].ID).To(Equal("track1")) + Expect(resp.Items[0].Title).To(Equal("track1")) Expect(resp.Items[1].ID).To(Equal("track2")) Expect(resp.Items[2].ID).To(Equal("track3")) }) @@ -182,8 +246,8 @@ var _ = Describe("Queue Endpoints", func() { }) It("returns the loaded tracks when some of them fail to load", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Items: model.MediaFiles{{ID: "track1"}}} - repo.WithMediaFilesErr = fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) + seed(&model.PlayQueue{Items: model.MediaFiles{{ID: "track1"}}}) + faults.withMediaFilesErr = fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) req := httptest.NewRequest(http.MethodGet, "/queue", nil) req = req.WithContext(request.WithUser(req.Context(), user)) w := httptest.NewRecorder() @@ -196,7 +260,7 @@ var _ = Describe("Queue Endpoints", func() { }) It("returns internal server error when retrieve fails", func() { - repo.Err = true + faults.retrieveErr = errors.New("db unavailable") req := httptest.NewRequest(http.MethodGet, "/queue", nil) req = req.WithContext(request.WithUser(req.Context(), user)) w := httptest.NewRecorder() @@ -207,8 +271,9 @@ var _ = Describe("Queue Endpoints", func() { }) Describe("PUT /queue", func() { - It("updates the queue fields", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Items: model.MediaFiles{{ID: "s1"}, {ID: "s2"}, {ID: "s3"}}} + updateFieldsAsTestClient := func() { + GinkgoHelper() + seed(&model.PlayQueue{Items: model.MediaFiles{{ID: "s1"}, {ID: "s2"}, {ID: "s3"}}}) payload := updateQueuePayload{Current: new(2), Position: new(int64(20))} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) @@ -219,14 +284,21 @@ var _ = Describe("Queue Endpoints", func() { updateQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue).ToNot(BeNil()) - Expect(repo.Queue.Current).To(Equal(2)) - Expect(repo.Queue.Position).To(Equal(int64(20))) - Expect(repo.Queue.ChangedBy).To(Equal("TestClient")) + } + + It("updates the queue fields", func() { + updateFieldsAsTestClient() + Expect(stored().Current).To(Equal(2)) + Expect(stored().Position).To(Equal(int64(20))) + }) + + PIt("records the client that updated the queue", func() { + updateFieldsAsTestClient() + Expect(stored().ChangedBy).To(Equal("TestClient")) }) It("updates only ids", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Current: 1} + seed(&model.PlayQueue{Current: 1}) payload := updateQueuePayload{Ids: new([]string{"s1", "s2"})} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) @@ -235,16 +307,14 @@ var _ = Describe("Queue Endpoints", func() { updateQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Items).To(HaveLen(2)) - Expect(repo.LastCols).To(ConsistOf("items")) + Expect(stored().Items).To(HaveLen(2)) + Expect(faults.lastCols).To(ConsistOf("items")) }) It("updates only ids when some tracks fail to load", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Current: 1, Position: 45, - Items: model.MediaFiles{{ID: "s1"}, {ID: "s2"}, {ID: "s3"}}} - repo.QueueWithMediaFiles = &model.PlayQueue{UserID: user.ID, Current: 1, Position: 45, - Items: model.MediaFiles{{ID: "s1"}, {ID: "s2"}}} - repo.WithMediaFilesErr = fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) + seed(&model.PlayQueue{Current: 1, Position: 45, + Items: model.MediaFiles{{ID: "s1"}, {ID: "s2"}, {ID: "s3"}}}) + faults.withMediaFilesErr = fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) body, _ := json.Marshal(updateQueuePayload{Ids: new([]string{"s1", "s2", "s3", "s4"})}) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) req = req.WithContext(request.WithUser(req.Context(), user)) @@ -252,17 +322,15 @@ var _ = Describe("Queue Endpoints", func() { updateQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Items).To(HaveLen(4)) - Expect(repo.LastCols).To(ConsistOf("items")) + Expect(stored().Items).To(HaveLen(4)) + Expect(faults.lastCols).To(ConsistOf("items")) }) Context("when the stored queue has tracks the user can't see", func() { + storedItems := model.MediaFiles{{ID: "gone1"}, {ID: "s1"}, {ID: "gone2"}, {ID: "s2"}} + BeforeEach(func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Current: 2, Position: 45, - Items: model.MediaFiles{{ID: "gone1"}, {ID: "s1"}, {ID: "gone2"}, {ID: "s2"}}} - repo.QueueWithMediaFiles = &model.PlayQueue{UserID: user.ID, Current: 1, Position: 0, - Items: model.MediaFiles{{ID: "s1"}, {ID: "s2"}}} - ds.MediaFile().(*tests.MockMediaFileRepo).SetData(repo.QueueWithMediaFiles.Items) + seed(&model.PlayQueue{Current: 2, Position: 45, Items: storedItems}) }) put := func(payload updateQueuePayload) int { @@ -276,8 +344,8 @@ var _ = Describe("Queue Endpoints", func() { It("stores current as the index of the same track in the stored queue", func() { Expect(put(updateQueuePayload{Current: new(1)})).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Current).To(Equal(3)) - Expect(repo.LastCols).To(ConsistOf("current")) + Expect(stored().Current).To(Equal(3)) + Expect(faults.lastCols).To(ConsistOf("current")) }) It("rejects a current that is only valid for the stored queue", func() { @@ -286,50 +354,49 @@ var _ = Describe("Queue Endpoints", func() { It("moves current to the track the client saw when only position changes", func() { Expect(put(updateQueuePayload{Position: new(int64(30))})).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Current).To(Equal(3)) - Expect(repo.Queue.Position).To(Equal(int64(30))) - Expect(repo.LastCols).To(ConsistOf("current", "position")) + Expect(stored().Current).To(Equal(3)) + Expect(stored().Position).To(Equal(int64(30))) + Expect(faults.lastCols).To(ConsistOf("current", "position")) }) It("writes only position when the stored current track is visible", func() { - repo.Queue.Current = 1 - repo.QueueWithMediaFiles.Current = 0 + seed(&model.PlayQueue{Current: 1, Position: 45, Items: storedItems}) Expect(put(updateQueuePayload{Position: new(int64(30))})).To(Equal(http.StatusNoContent)) - Expect(repo.LastCols).To(ConsistOf("position")) + Expect(stored().Current).To(Equal(1)) + Expect(faults.lastCols).To(ConsistOf("position")) }) It("refuses to update current when the tracks fail to load", func() { - repo.WithMediaFilesErr = fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) + faults.withMediaFilesErr = fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) Expect(put(updateQueuePayload{Current: new(0)})).To(Equal(http.StatusInternalServerError)) - Expect(repo.LastCols).To(BeNil()) - Expect(repo.Queue.Current).To(Equal(2)) + Expect(faults.lastCols).To(BeNil()) + Expect(stored().Current).To(Equal(2)) }) It("keeps the current track and position the client saw when only ids change", func() { Expect(put(updateQueuePayload{Ids: new([]string{"s1", "s2", "s3"})})).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Current).To(Equal(1)) - Expect(repo.Queue.Position).To(BeZero()) - Expect(repo.LastCols).To(ConsistOf("items", "current", "position")) + Expect(stored().Current).To(Equal(1)) + Expect(stored().Position).To(BeZero()) + Expect(faults.lastCols).To(ConsistOf("items", "current", "position")) }) It("writes only the current index when the current track is visible and only ids change", func() { - repo.Queue.Current = 1 - repo.QueueWithMediaFiles.Current = 0 - repo.QueueWithMediaFiles.Position = 45 + seed(&model.PlayQueue{Current: 1, Position: 45, Items: storedItems}) Expect(put(updateQueuePayload{Ids: new([]string{"s1", "s2"})})).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Current).To(BeZero()) - Expect(repo.LastCols).To(ConsistOf("items", "current")) + Expect(stored().Current).To(BeZero()) + Expect(stored().Position).To(Equal(int64(45))) + Expect(faults.lastCols).To(ConsistOf("items", "current")) }) It("uses the position from the request when ids and position change", func() { Expect(put(updateQueuePayload{Ids: new([]string{"s1", "s2"}), Position: new(int64(10))})).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Current).To(Equal(1)) - Expect(repo.Queue.Position).To(Equal(int64(10))) + Expect(stored().Current).To(Equal(1)) + Expect(stored().Position).To(Equal(int64(10))) }) }) It("updates ids and current", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID} + seed(&model.PlayQueue{}) payload := updateQueuePayload{Ids: new([]string{"s1", "s2"}), Current: new(1)} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) @@ -338,13 +405,13 @@ var _ = Describe("Queue Endpoints", func() { updateQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue.Items).To(HaveLen(2)) - Expect(repo.Queue.Current).To(Equal(1)) - Expect(repo.LastCols).To(ConsistOf("items", "current")) + Expect(stored().Items).To(HaveLen(2)) + Expect(stored().Current).To(Equal(1)) + Expect(faults.lastCols).To(ConsistOf("items", "current")) }) It("returns bad request when new ids invalidate current", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Current: 2} + seed(&model.PlayQueue{Current: 2}) payload := updateQueuePayload{Ids: new([]string{"s1", "s2"})} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) @@ -356,7 +423,7 @@ var _ = Describe("Queue Endpoints", func() { }) It("returns bad request when current out of bounds", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Items: model.MediaFiles{{ID: "s1"}}} + seed(&model.PlayQueue{Items: model.MediaFiles{{ID: "s1"}}}) payload := updateQueuePayload{Current: new(3)} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) @@ -377,7 +444,8 @@ var _ = Describe("Queue Endpoints", func() { }) It("returns internal server error when store fails", func() { - repo.Err = true + seed(&model.PlayQueue{Items: model.MediaFiles{{ID: "s1"}}}) + faults.storeErr = errors.New("db unavailable") payload := updateQueuePayload{Position: new(int64(10))} body, _ := json.Marshal(payload) req := httptest.NewRequest(http.MethodPut, "/queue", bytes.NewReader(body)) @@ -391,18 +459,18 @@ var _ = Describe("Queue Endpoints", func() { Describe("DELETE /queue", func() { It("clears the queue", func() { - repo.Queue = &model.PlayQueue{UserID: user.ID, Items: model.MediaFiles{{ID: "s1"}}} + seed(&model.PlayQueue{Items: model.MediaFiles{{ID: "s1"}}}) req := httptest.NewRequest(http.MethodDelete, "/queue", nil) req = req.WithContext(request.WithUser(req.Context(), user)) w := httptest.NewRecorder() clearQueue(ds)(w, req) Expect(w.Code).To(Equal(http.StatusNoContent)) - Expect(repo.Queue).To(BeNil()) + expectNoQueue() }) It("returns internal server error when clear fails", func() { - repo.Err = true + faults.clearErr = errors.New("db unavailable") req := httptest.NewRequest(http.MethodDelete, "/queue", nil) req = req.WithContext(request.WithUser(req.Context(), user)) w := httptest.NewRecorder() diff --git a/server/nativeapi/user_password_token_refresh_test.go b/server/nativeapi/user_password_token_refresh_test.go index ddd19f49c..3138b6b58 100644 --- a/server/nativeapi/user_password_token_refresh_test.go +++ b/server/nativeapi/user_password_token_refresh_test.go @@ -6,27 +6,19 @@ import ( "encoding/json" "net/http" "net/http/httptest" - "path/filepath" "time" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/consts" - "github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core/auth" - "github.com/navidrome/navidrome/core/playlists" "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) -type noopPluginUnloader struct{} - -func (noopPluginUnloader) UnloadDisabledPlugins(context.Context) {} - // Pins that the token-epoch handoff survives a real request through the real middleware chain. var _ = Describe("PUT /user/{id}: token refresh on self password change", func() { var ctx context.Context @@ -39,17 +31,10 @@ var _ = Describe("PUT /user/{id}: token refresh on self password change", func() c.EnableUserEditing = true c.EnableSharing = false c.SessionTimeout = time.Hour - c.DbPath = filepath.Join(GinkgoT().TempDir(), "nativeapi-user-refresh.db") + "?_journal_mode=WAL" }) - // db.Db() is a process-wide singleton that this DeferCleanup closes for the whole binary; keep this the only real-DB spec in this package. - DeferCleanup(db.Init(GinkgoT().Context())) - - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds = persistence.New(db.Db()) auth.Init(ds) - - userService := core.NewUser(ds, noopPluginUnloader{}) - nativeRouter := New(ds, nil, playlists.NewPlaylists(ds, nil), nil, tests.NewMockLibraryService(), userService, nil, nil, nil, nil, nil) - router = server.JWTVerifier(nativeRouter) + router = server.JWTVerifier(newTestRouter(ds, nil, nil, nil)) }) It("carries the bumped epoch in the refreshed token, not the epoch the token was minted with", func() { diff --git a/server/public/handle_downloads_test.go b/server/public/handle_downloads_test.go index 98304a31d..2c499118e 100644 --- a/server/public/handle_downloads_test.go +++ b/server/public/handle_downloads_test.go @@ -10,8 +10,9 @@ import ( "time" "github.com/navidrome/navidrome/core" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -43,22 +44,20 @@ func (m *mockArchiver) ZipShare(_ context.Context, _ *model.Share, w io.Writer) } var _ = Describe("handleDownloads", func() { - var ds *tests.MockDataStore - var shareRepo *tests.MockShareRepo + var ctx context.Context + var ds model.DataStore var archiver *mockArchiver var pub *Router BeforeEach(func() { - ds = &tests.MockDataStore{} - shareRepo = &tests.MockShareRepo{} - ds.MockedShare = shareRepo + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) archiver = &mockArchiver{} pub = &Router{ds: ds, archiver: archiver, share: core.NewShare(ds)} }) - shareIs := func(s *model.Share) { - shareRepo.ID = s.ID - shareRepo.Entity = s + shareIs := func(s model.Share) { + putShare(ctx, ds, s) } makeRequest := func(id string) *httptest.ResponseRecorder { @@ -69,7 +68,7 @@ var _ = Describe("handleDownloads", func() { } It("sets a Content-Disposition filename from the share description", func() { - shareIs(&model.Share{ID: "abc123", Description: "My Mixtape", Downloadable: true}) + shareIs(model.Share{ID: "abc123", Description: "My Mixtape", Downloadable: true}) w := makeRequest("abc123") @@ -81,7 +80,7 @@ var _ = Describe("handleDownloads", func() { }) It("falls back to the share ID when there is no description", func() { - shareIs(&model.Share{ID: "abc123", Downloadable: true}) + shareIs(model.Share{ID: "abc123", Downloadable: true}) w := makeRequest("abc123") @@ -89,7 +88,7 @@ var _ = Describe("handleDownloads", func() { }) It("sanitizes characters that are unsafe in a filename", func() { - shareIs(&model.Share{ID: "abc123", Description: `AC/DC: Live, 1979`, Downloadable: true}) + shareIs(model.Share{ID: "abc123", Description: `AC/DC: Live, 1979`, Downloadable: true}) w := makeRequest("abc123") @@ -97,7 +96,7 @@ var _ = Describe("handleDownloads", func() { }) It("sanitizes the UTF-8 filename* as well", func() { - shareIs(&model.Share{ID: "abc123", Description: "Sigur Rós/Live", Downloadable: true}) + shareIs(model.Share{ID: "abc123", Description: "Sigur Rós/Live", Downloadable: true}) w := makeRequest("abc123") @@ -105,7 +104,7 @@ var _ = Describe("handleDownloads", func() { }) It("does not let the share description inject a second filename parameter", func() { - shareIs(&model.Share{ID: "abc123", Description: `mix"; filename="evil.html`, Downloadable: true}) + shareIs(model.Share{ID: "abc123", Description: `mix"; filename="evil.html`, Downloadable: true}) w := makeRequest("abc123") @@ -117,7 +116,7 @@ var _ = Describe("handleDownloads", func() { }) It("returns 403 without invoking the archiver when the share is not downloadable", func() { - shareIs(&model.Share{ID: "abc123", Description: "No Download", Downloadable: false}) + shareIs(model.Share{ID: "abc123", Description: "No Download", Downloadable: false}) w := makeRequest("abc123") @@ -127,7 +126,7 @@ var _ = Describe("handleDownloads", func() { }) It("returns 404 when the share does not exist", func() { - shareIs(&model.Share{ID: "other", Downloadable: true}) + shareIs(model.Share{ID: "other", Downloadable: true}) w := makeRequest("missing") @@ -136,7 +135,7 @@ var _ = Describe("handleDownloads", func() { }) It("returns 410 when the share has expired", func() { - shareIs(&model.Share{ID: "abc123", Downloadable: true, ExpiresAt: new(time.Now().Add(-time.Hour))}) + shareIs(model.Share{ID: "abc123", Downloadable: true, ExpiresAt: new(time.Now().Add(-time.Hour))}) w := makeRequest("abc123") @@ -145,7 +144,8 @@ var _ = Describe("handleDownloads", func() { }) It("returns 500 when the share lookup fails", func() { - shareRepo.Error = errors.New("db error") + ds = withShareGetError(ds, errors.New("db error")) + pub = &Router{ds: ds, archiver: archiver, share: core.NewShare(ds)} w := makeRequest("abc123") diff --git a/server/public/handle_images_test.go b/server/public/handle_images_test.go index 2ef9ee0e0..1b3f56a38 100644 --- a/server/public/handle_images_test.go +++ b/server/public/handle_images_test.go @@ -12,7 +12,6 @@ import ( "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -53,24 +52,18 @@ var _ = Describe("handleImages", func() { return httptest.NewRequest(http.MethodGet, "/img?:id="+url.QueryEscape(token), nil) } - // The handler re-checks that the entity behind the token still exists, so "1" must be live. - var ds *tests.MockDataStore - BeforeEach(func() { w = httptest.NewRecorder() - albumRepo := tests.CreateMockAlbumRepo() - albumRepo.SetData(model.Albums{{ID: "1"}}) - ds = &tests.MockDataStore{MockedAlbum: albumRepo} }) It("returns 404 when the artwork is unavailable", func() { - pub := &Router{ds: ds, artwork: &fakeArtwork{err: artwork.ErrUnavailable}} + pub := &Router{artwork: &fakeArtwork{err: artwork.ErrUnavailable}} pub.handleImages(w, newImageRequest("al-1")) Expect(w.Code).To(Equal(http.StatusNotFound)) }) It("returns 404 when the artwork is not found", func() { - pub := &Router{ds: ds, artwork: &fakeArtwork{err: model.ErrNotFound}} + pub := &Router{artwork: &fakeArtwork{err: model.ErrNotFound}} pub.handleImages(w, newImageRequest("al-1")) Expect(w.Code).To(Equal(http.StatusNotFound)) }) @@ -78,7 +71,7 @@ var _ = Describe("handleImages", func() { It("serves the image immutable when the token asserts the current hash", func() { const hash = "0123456789abcdef" img := &artwork.Image{ReadCloser: io.NopCloser(bytes.NewReader([]byte("IMG"))), Hash: hash} - pub := &Router{ds: ds, artwork: &fakeArtwork{img: img}} + pub := &Router{artwork: &fakeArtwork{img: img}} pub.handleImages(w, newImageRequest("al-1_"+hash)) Expect(w.Code).To(Equal(http.StatusOK)) Expect(w.Header().Get("Cache-Control")).To(Equal("public, max-age=31536000, immutable")) diff --git a/server/public/handle_shares_test.go b/server/public/handle_shares_test.go index 70d84dc61..51963d5a5 100644 --- a/server/public/handle_shares_test.go +++ b/server/public/handle_shares_test.go @@ -1,28 +1,30 @@ package public import ( + "context" "net/http" "net/http/httptest" "github.com/go-chi/jwtauth/v5" "github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("handleM3U", func() { - var ds *tests.MockDataStore - var shareRepo *tests.MockShareRepo + var ctx context.Context + var ds model.DataStore var pub *Router BeforeEach(func() { + ctx = GinkgoT().Context() auth.PublicTokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil) - ds = &tests.MockDataStore{} - shareRepo = &tests.MockShareRepo{} - ds.MockedShare = shareRepo + ds = persistence.New(db.Db()) pub = &Router{ds: ds, share: core.NewShare(ds)} }) @@ -34,9 +36,8 @@ var _ = Describe("handleM3U", func() { } It("sets the M3U content type", func() { - share := &model.Share{ID: "abc123", Tracks: model.MediaFiles{{ID: "t1", Title: "Track 1"}}} - shareRepo.ID = share.ID - shareRepo.Entity = share + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "t1", Title: "Track 1"}) + putShare(ctx, ds, model.Share{ID: "abc123", ResourceType: "media_file", ResourceIDs: "t1"}) w := makeRequest("abc123") @@ -47,8 +48,7 @@ var _ = Describe("handleM3U", func() { }) It("returns 404 when the share does not exist", func() { - shareRepo.ID = "other" - shareRepo.Entity = &model.Share{ID: "other"} + putShare(ctx, ds, model.Share{ID: "other"}) Expect(makeRequest("missing").Code).To(Equal(http.StatusNotFound)) }) diff --git a/server/public/handle_streams_test.go b/server/public/handle_streams_test.go index f802026b8..7d4cc3338 100644 --- a/server/public/handle_streams_test.go +++ b/server/public/handle_streams_test.go @@ -12,7 +12,10 @@ import ( "github.com/go-chi/jwtauth/v5" "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/stream" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -114,17 +117,14 @@ var _ = Describe("encodeMediafileShare", func() { var _ = Describe("handleStream", func() { var ctx context.Context - var ds *tests.MockDataStore - var shareRepo *tests.MockShareRepo + var ds model.DataStore var streamer *mockStreamer var pub *Router BeforeEach(func() { ctx = GinkgoT().Context() auth.PublicTokenAuth = jwtauth.New("HS256", []byte("test-secret"), nil) - ds = &tests.MockDataStore{MockedTranscoding: &tests.MockTranscodingRepo{}} - shareRepo = &tests.MockShareRepo{} - ds.MockedShare = shareRepo + ds = persistence.New(db.Db()) streamer = &mockStreamer{} pub = &Router{ds: ds, streamer: streamer, decider: stream.NewTranscodeDecider(ds, tests.NewMockFFmpeg(""))} }) @@ -137,14 +137,10 @@ var _ = Describe("handleStream", func() { } shareOwnedBy := func(owner model.User, mf model.MediaFile) { - shareRepo.ID = "share123" - shareRepo.Entity = &model.Share{ID: "share123", UserID: owner.ID, Tracks: model.MediaFiles{mf}} - userRepo := tests.CreateMockUserRepo() - Expect(userRepo.Put(ctx, &owner)).To(Succeed()) - ds.MockedUser = userRepo - mfRepo := tests.CreateMockMediaFileRepo() - mfRepo.SetData(model.MediaFiles{mf}) - ds.MockedMediaFile = mfRepo + GinkgoHelper() + Expect(ds.User().Put(ctx, &owner)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, mf) + putShare(ctx, ds, model.Share{ID: "share123", UserID: owner.ID, ResourceType: "media_file", ResourceIDs: mf.ID}) } It("passes all validation and reaches the streamer for a valid token", func() { @@ -172,10 +168,13 @@ var _ = Describe("handleStream", func() { }) It("returns 404 when the track is outside the share owner's libraries", func() { - shareOwnedBy( - model.User{ID: "owner1", UserName: "owner1", Libraries: model.Libraries{{ID: 1}}}, - model.MediaFile{ID: "mf-restricted", Title: "Other Lib Track", LibraryID: 2}, - ) + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Library 2", Path: "/music2"})).To(Succeed()) + restricted := model.MediaFile{ID: "mf-restricted", Title: "Other Lib Track", LibraryID: 2} + shareOwnedBy(model.User{ID: "owner1", UserName: "owner1"}, restricted) + // Loading the share already drops tracks the owner cannot see; put it back to reach the handler's own check. + pub.ds = persistencetest.Stub(ds, persistencetest.Repos{Share: func(r model.ShareRepository) model.ShareRepository { + return &extraShareTracksRepo{ShareRepository: r, extra: model.MediaFiles{restricted}} + }}) claims := auth.Claims{ID: "mf-restricted", ShareID: "share123"} token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims) @@ -186,15 +185,8 @@ var _ = Describe("handleStream", func() { }) It("returns 404 when the track is not a member of the share", func() { - owner := model.User{ID: "owner1", UserName: "owner1", IsAdmin: true} - userRepo := tests.CreateMockUserRepo() - Expect(userRepo.Put(ctx, &owner)).To(Succeed()) - ds.MockedUser = userRepo - mfRepo := tests.CreateMockMediaFileRepo() - mfRepo.SetData(model.MediaFiles{{ID: "mf-shared"}, {ID: "mf-other"}}) - ds.MockedMediaFile = mfRepo - shareRepo.ID = "share123" - shareRepo.Entity = &model.Share{ID: "share123", UserID: owner.ID, Tracks: model.MediaFiles{{ID: "mf-shared"}}} + shareOwnedBy(model.User{ID: "owner1", UserName: "owner1", IsAdmin: true}, model.MediaFile{ID: "mf-shared"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf-other"}) claims := auth.Claims{ID: "mf-other", ShareID: "share123"} token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims) @@ -206,7 +198,7 @@ var _ = Describe("handleStream", func() { It("streams a track inside the share owner's libraries", func() { shareOwnedBy( - model.User{ID: "owner1", UserName: "owner1", Libraries: model.Libraries{{ID: 1}}}, + model.User{ID: "owner1", UserName: "owner1"}, model.MediaFile{ID: "mf-ok", Title: "OK", LibraryID: 1}, ) @@ -243,7 +235,7 @@ var _ = Describe("handleStream", func() { }) It("returns 404 when share has been deleted", func() { - shareRepo.ID = "other-share" + putShare(ctx, ds, model.Share{ID: "other-share"}) claims := auth.Claims{ID: "mf-123", ShareID: "deleted-share"} token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims) w := makeRequest(token) @@ -251,8 +243,7 @@ var _ = Describe("handleStream", func() { }) It("returns 410 when share has been set to expired", func() { - shareRepo.ID = "share123" - shareRepo.Entity = &model.Share{ID: "share123", ExpiresAt: new(time.Now().Add(-time.Hour))} + putShare(ctx, ds, model.Share{ID: "share123", ExpiresAt: new(time.Now().Add(-time.Hour))}) claims := auth.Claims{ID: "mf-123", ShareID: "share123"} token, _ := auth.CreatePublicToken(claims) @@ -261,7 +252,8 @@ var _ = Describe("handleStream", func() { }) It("returns 500 when share lookup fails", func() { - shareRepo.Error = errors.New("db error") + ds = withShareGetError(ds, errors.New("db error")) + pub.ds = ds claims := auth.Claims{ID: "mf-123", ShareID: "share123"} token, _ := auth.CreateExpiringPublicToken(time.Now().Add(time.Hour), claims) w := makeRequest(token) @@ -281,3 +273,16 @@ var _ = Describe("handleStream", func() { Expect(w.Code).To(Equal(http.StatusBadRequest)) }) }) + +type extraShareTracksRepo struct { + model.ShareRepository + extra model.MediaFiles +} + +func (r *extraShareTracksRepo) Get(ctx context.Context, id string) (*model.Share, error) { + s, err := r.ShareRepository.Get(ctx, id) + if err == nil { + s.Tracks = append(s.Tracks, r.extra...) + } + return s, err +} diff --git a/server/public/public_suite_test.go b/server/public/public_suite_test.go index ea6029f29..e2ca663aa 100644 --- a/server/public/public_suite_test.go +++ b/server/public/public_suite_test.go @@ -1,9 +1,12 @@ package public import ( + "context" "testing" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -12,6 +15,38 @@ import ( func TestPublicEndpoints(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Public Endpoints Suite") } + +var _ = persistencetest.ResetBeforeEachSpec() + +var defaultShareOwner = model.User{ID: "owner1", UserName: "owner1", IsAdmin: true} + +// putShare stores the share, owned by defaultShareOwner (created here) unless it names an owner. +func putShare(ctx context.Context, ds model.DataStore, s model.Share) { + GinkgoHelper() + if s.UserID == "" { + owner := defaultShareOwner + Expect(ds.User().Put(ctx, &owner)).To(Succeed()) + s.UserID = owner.ID + } + _, err := ds.Share().Save(ctx, &s) + Expect(err).ToNot(HaveOccurred()) +} + +func withShareGetError(ds model.DataStore, err error) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{Share: func(r model.ShareRepository) model.ShareRepository { + return &shareGetErrorRepo{ShareRepository: r, err: err} + }}) +} + +type shareGetErrorRepo struct { + model.ShareRepository + err error +} + +func (r *shareGetErrorRepo) Get(context.Context, string) (*model.Share, error) { + return nil, r.err +} diff --git a/server/serve_index_test.go b/server/serve_index_test.go index 719159189..c0fa60acf 100644 --- a/server/serve_index_test.go +++ b/server/serve_index_test.go @@ -14,19 +14,21 @@ import ( "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/conf/mime" "github.com/navidrome/navidrome/consts" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("serveIndex", func() { var ds model.DataStore - mockUser := &mockedUserRepo{} + var ctx context.Context fs := os.DirFS("tests/fixtures") BeforeEach(func() { - ds = &tests.MockDataStore{MockedUser: mockUser} + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) }) It("adds app_config to index.html", func() { @@ -41,7 +43,6 @@ var _ = Describe("serveIndex", func() { }) It("sets firstTime = true when User table is empty", func() { - mockUser.empty = true r := httptest.NewRequest(http.MethodGet, "/index.html", nil) w := httptest.NewRecorder() @@ -52,7 +53,7 @@ var _ = Describe("serveIndex", func() { }) It("sets firstTime = false when User table is not empty", func() { - mockUser.empty = false + Expect(ds.User().Put(ctx, &model.User{UserName: "johndoe"})).To(Succeed()) r := httptest.NewRequest(http.MethodGet, "/index.html", nil) w := httptest.NewRecorder() @@ -335,15 +336,3 @@ func extractAppConfig(body string) map[string]any { Expect(json.Unmarshal([]byte(str), &config)).To(Succeed()) return config } - -type mockedUserRepo struct { - model.UserRepository - empty bool -} - -func (u *mockedUserRepo) CountAll(context.Context, ...model.QueryOptions) (int64, error) { - if u.empty { - return 0, nil - } - return 1, nil -} diff --git a/server/server_suite_test.go b/server/server_suite_test.go index b72905b32..3f7378001 100644 --- a/server/server_suite_test.go +++ b/server/server_suite_test.go @@ -5,6 +5,7 @@ import ( "github.com/navidrome/navidrome/conf/configtest" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -13,8 +14,10 @@ import ( func TestServer(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Server Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() diff --git a/server/server_test.go b/server/server_test.go index c2ee31ec8..39ae9b9f9 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -11,6 +11,8 @@ import ( "path/filepath" "time" + "github.com/navidrome/navidrome/db" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -145,9 +147,7 @@ var _ = Describe("TLS support", func() { When("server is started with valid TLS certificates", func() { It("accepts HTTPS connections", func() { - // Create server with mock dependencies - ds := &tests.MockDataStore{} - server := New(ds, nil, nil) + server := New(persistence.New(db.Db()), nil, nil) // Load the test certificate to create a trusted CA pool certFile := filepath.Join(testDataDir, "test_cert.pem") diff --git a/server/subsonic/album_lists_test.go b/server/subsonic/album_lists_test.go index 1e7482a36..1033182f9 100644 --- a/server/subsonic/album_lists_test.go +++ b/server/subsonic/album_lists_test.go @@ -3,14 +3,20 @@ package subsonic import ( "context" "errors" + "fmt" "net/http/httptest" + "strconv" + "time" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/subsonic/responses" - "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/utils/req" + "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -19,32 +25,72 @@ var _ = Describe("Album Lists", func() { var ctx context.Context var router *Router var ds model.DataStore - var mockRepo *tests.MockAlbumRepo var w *httptest.ResponseRecorder + childIDs := func(children []responses.Child) []string { + return slice.Map(children, func(c responses.Child) string { return c.Id }) + } + albumID3IDs := func(albums []responses.AlbumID3) []string { + return slice.Map(albums, func(a responses.AlbumID3) string { return a.Id }) + } + starredUser := model.User{ID: "test-user", UserName: "test-user"} + + // putTwelveAlbums stores al-01 (oldest) to al-12 (newest) in library 1. + putTwelveAlbums := func() { + GinkgoHelper() + base := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC) + for i := 1; i <= 12; i++ { + persistencetest.PutAlbums(ctx, ds, model.Album{ID: fmt.Sprintf("al-%02d", i), Name: fmt.Sprintf("Album %02d", i), + CreatedAt: base.Add(time.Duration(i) * time.Hour)}) + } + } + + // putLibraryContent stores artist ar-N, album al-N and rock song mf-N in each library N of 1-4, + // all starred by test-user, who can read libraries 1-3 only. + putLibraryContent := func() { + GinkgoHelper() + putUsers(ctx, ds, starredUser) + libIDs := persistencetest.SetLibraries(ctx, ds, "/lib1", "/lib2", "/lib3", "/lib4") + userCtx := request.WithUser(ctx, starredUser) + rock := model.NewTag(model.TagGenre, "rock") + for _, id := range libIDs { + n := strconv.Itoa(id) + Expect(ds.Tag().Add(ctx, id, rock)).To(Succeed()) + putAlbumArtists(ctx, ds, id, model.Artist{ID: "ar-" + n, Name: "Artist " + n}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-" + n, Name: "Album " + n, LibraryID: id}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf-" + n, Title: "Song " + n, LibraryID: id, + Tags: model.Tags{model.TagGenre: {"rock"}}}) + Expect(ds.Artist().SetStar(userCtx, true, "ar-"+n)).To(Succeed()) + Expect(ds.Album().SetStar(userCtx, true, "al-"+n)).To(Succeed()) + Expect(ds.MediaFile().SetStar(userCtx, true, "mf-"+n)).To(Succeed()) + } + Expect(ds.User().SetUserLibraries(ctx, starredUser.ID, libIDs[:3])).To(Succeed()) + } + BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) - mockRepo = ds.Album().(*tests.MockAlbumRepo) router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) w = httptest.NewRecorder() }) + failingAlbumsRouter := func() *Router { + return New(persistencetest.Stub(ds, persistencetest.Repos{Album: func(r model.AlbumRepository) model.AlbumRepository { + return failingAlbumGetAllRepo{r} + }}), + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) + } + Describe("GetAlbumList", func() { It("should return list of the type specified", func() { + putTwelveAlbums() r := newGetRequest("type=newest", "offset=10", "size=20") - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList.Album[0].Id).To(Equal("1")) - Expect(resp.AlbumList.Album[1].Id).To(Equal("2")) - Expect(w.Header().Get("x-total-count")).To(Equal("2")) - Expect(mockRepo.Options.Offset).To(Equal(10)) - Expect(mockRepo.Options.Max).To(Equal(20)) + Expect(childIDs(resp.AlbumList.Album)).To(Equal([]string{"al-02", "al-01"})) + Expect(w.Header().Get("x-total-count")).To(Equal("12")) }) It("should fail if missing type parameter", func() { @@ -55,10 +101,9 @@ var _ = Describe("Album Lists", func() { }) It("should return error if call fails", func() { - mockRepo.SetError(true) r := newGetRequest("type=newest") - _, err := router.GetAlbumList(w, r) + _, err := failingAlbumsRouter().GetAlbumList(w, r) Expect(err).To(MatchError(errSubsonic)) var subErr subError @@ -70,6 +115,7 @@ var _ = Describe("Album Lists", func() { var user model.User BeforeEach(func() { + putLibraryContent() user = model.User{ ID: "test-user", Libraries: []model.Library{ @@ -84,70 +130,44 @@ var _ = Describe("Album Lists", func() { It("should filter albums by specific library when musicFolderId is provided", func() { r := newGetRequest("type=newest", "musicFolderId=1") r = r.WithContext(ctx) - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList.Album).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?)")) - Expect(args).To(ContainElement(1)) + Expect(childIDs(resp.AlbumList.Album)).To(ConsistOf("al-1")) }) It("should filter albums by multiple libraries when multiple musicFolderId are provided", func() { r := newGetRequest("type=newest", "musicFolderId=1", "musicFolderId=2") r = r.WithContext(ctx) - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList.Album).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?,?)")) - Expect(args).To(ContainElements(1, 2)) + Expect(childIDs(resp.AlbumList.Album)).To(ConsistOf("al-1", "al-2")) }) It("should return all accessible albums when no musicFolderId is provided", func() { r := newGetRequest("type=newest") r = r.WithContext(ctx) - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList.Album).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?,?,?)")) - Expect(args).To(ContainElements(1, 2, 3)) + Expect(childIDs(resp.AlbumList.Album)).To(ConsistOf("al-1", "al-2", "al-3")) }) }) }) Describe("GetAlbumList2", func() { It("should return list of the type specified", func() { + putTwelveAlbums() r := newGetRequest("type=newest", "offset=10", "size=20") - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList2(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList2.Album[0].Id).To(Equal("1")) - Expect(resp.AlbumList2.Album[1].Id).To(Equal("2")) - Expect(w.Header().Get("x-total-count")).To(Equal("2")) - Expect(mockRepo.Options.Offset).To(Equal(10)) - Expect(mockRepo.Options.Max).To(Equal(20)) + Expect(albumID3IDs(resp.AlbumList2.Album)).To(Equal([]string{"al-02", "al-01"})) + Expect(w.Header().Get("x-total-count")).To(Equal("12")) }) It("should fail if missing type parameter", func() { @@ -159,10 +179,9 @@ var _ = Describe("Album Lists", func() { }) It("should return error if call fails", func() { - mockRepo.SetError(true) r := newGetRequest("type=newest") - _, err := router.GetAlbumList2(w, r) + _, err := failingAlbumsRouter().GetAlbumList2(w, r) Expect(err).To(MatchError(errSubsonic)) var subErr subError @@ -174,6 +193,7 @@ var _ = Describe("Album Lists", func() { var user model.User BeforeEach(func() { + putLibraryContent() user = model.User{ ID: "test-user", Libraries: []model.Library{ @@ -188,72 +208,54 @@ var _ = Describe("Album Lists", func() { It("should filter albums by specific library when musicFolderId is provided", func() { r := newGetRequest("type=newest", "musicFolderId=1") r = r.WithContext(ctx) - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList2(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList2.Album).To(HaveLen(2)) - // Verify that library filter was applied - Expect(mockRepo.Options.Filters).ToNot(BeNil()) + Expect(albumID3IDs(resp.AlbumList2.Album)).To(ConsistOf("al-1")) }) It("should filter albums by multiple libraries when multiple musicFolderId are provided", func() { r := newGetRequest("type=newest", "musicFolderId=1", "musicFolderId=2") r = r.WithContext(ctx) - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList2(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList2.Album).To(HaveLen(2)) - // Verify that library filter was applied - Expect(mockRepo.Options.Filters).ToNot(BeNil()) + Expect(albumID3IDs(resp.AlbumList2.Album)).To(ConsistOf("al-1", "al-2")) }) It("should return all accessible albums when no musicFolderId is provided", func() { r := newGetRequest("type=newest") r = r.WithContext(ctx) - mockRepo.SetData(model.Albums{ - {ID: "1"}, {ID: "2"}, - }) resp, err := router.GetAlbumList2(w, r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.AlbumList2.Album).To(HaveLen(2)) + Expect(albumID3IDs(resp.AlbumList2.Album)).To(ConsistOf("al-1", "al-2", "al-3")) }) }) }) Describe("GetRandomSongs", func() { - var mockMediaFileRepo *tests.MockMediaFileRepo - - BeforeEach(func() { - mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo) - }) - It("should return random songs", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "1", Title: "Song 1"}, + model.MediaFile{ID: "2", Title: "Song 2"}, + ) r := newGetRequest("size=2") resp, err := router.GetRandomSongs(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.RandomSongs.Songs).To(HaveLen(2)) + Expect(childIDs(resp.RandomSongs.Songs)).To(ConsistOf("1", "2")) }) Context("with musicFolderId parameter", func() { var user model.User BeforeEach(func() { + putLibraryContent() user = model.User{ ID: "test-user", Libraries: []model.Library{ @@ -266,85 +268,60 @@ var _ = Describe("Album Lists", func() { }) It("should filter songs by specific library when musicFolderId is provided", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) r := newGetRequest("size=2", "musicFolderId=1") r = r.WithContext(ctx) resp, err := router.GetRandomSongs(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.RandomSongs.Songs).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockMediaFileRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?)")) - Expect(args).To(ContainElement(1)) + Expect(childIDs(resp.RandomSongs.Songs)).To(ConsistOf("mf-1")) }) It("should filter songs by multiple libraries when multiple musicFolderId are provided", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) r := newGetRequest("size=2", "musicFolderId=1", "musicFolderId=2") r = r.WithContext(ctx) resp, err := router.GetRandomSongs(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.RandomSongs.Songs).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockMediaFileRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?,?)")) - Expect(args).To(ContainElements(1, 2)) + Expect(childIDs(resp.RandomSongs.Songs)).To(ConsistOf("mf-1", "mf-2")) }) It("should return all accessible songs when no musicFolderId is provided", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) - r := newGetRequest("size=2") + r := newGetRequest("size=10") r = r.WithContext(ctx) resp, err := router.GetRandomSongs(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.RandomSongs.Songs).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockMediaFileRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?,?,?)")) - Expect(args).To(ContainElements(1, 2, 3)) + Expect(childIDs(resp.RandomSongs.Songs)).To(ConsistOf("mf-1", "mf-2", "mf-3")) }) }) }) Describe("GetSongsByGenre", func() { - var mockMediaFileRepo *tests.MockMediaFileRepo - - BeforeEach(func() { - mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo) - }) - It("should return songs by genre", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) - r := newGetRequest("count=2", "genre=rock") + rock := model.NewTag(model.TagGenre, "rock") + jazz := model.NewTag(model.TagGenre, "jazz") + Expect(ds.Tag().Add(ctx, model.DefaultLibraryID, rock, jazz)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, + model.MediaFile{ID: "1", Title: "Song 1", Tags: model.Tags{model.TagGenre: {"rock"}}}, + model.MediaFile{ID: "2", Title: "Song 2", Tags: model.Tags{model.TagGenre: {"rock"}}}, + model.MediaFile{ID: "3", Title: "Song 3", Tags: model.Tags{model.TagGenre: {"jazz"}}}, + ) + r := newGetRequest("count=10", "genre=rock") resp, err := router.GetSongsByGenre(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.SongsByGenre.Songs).To(HaveLen(2)) + Expect(childIDs(resp.SongsByGenre.Songs)).To(ConsistOf("1", "2")) }) Context("with musicFolderId parameter", func() { var user model.User BeforeEach(func() { + putLibraryContent() user = model.User{ ID: "test-user", Libraries: []model.Library{ @@ -357,90 +334,69 @@ var _ = Describe("Album Lists", func() { }) It("should filter songs by specific library when musicFolderId is provided", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) r := newGetRequest("count=2", "genre=rock", "musicFolderId=1") r = r.WithContext(ctx) resp, err := router.GetSongsByGenre(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.SongsByGenre.Songs).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockMediaFileRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?)")) - Expect(args).To(ContainElement(1)) + Expect(childIDs(resp.SongsByGenre.Songs)).To(ConsistOf("mf-1")) }) It("should filter songs by multiple libraries when multiple musicFolderId are provided", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) r := newGetRequest("count=2", "genre=rock", "musicFolderId=1", "musicFolderId=2") r = r.WithContext(ctx) resp, err := router.GetSongsByGenre(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.SongsByGenre.Songs).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockMediaFileRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?,?)")) - Expect(args).To(ContainElements(1, 2)) + Expect(childIDs(resp.SongsByGenre.Songs)).To(ConsistOf("mf-1", "mf-2")) }) It("should return all accessible songs when no musicFolderId is provided", func() { - mockMediaFileRepo.SetData(model.MediaFiles{ - {ID: "1", Title: "Song 1"}, - {ID: "2", Title: "Song 2"}, - }) - r := newGetRequest("count=2", "genre=rock") + r := newGetRequest("count=10", "genre=rock") r = r.WithContext(ctx) resp, err := router.GetSongsByGenre(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.SongsByGenre.Songs).To(HaveLen(2)) - // Verify that library filter was applied - query, args, _ := mockMediaFileRepo.Options.Filters.ToSql() - Expect(query).To(ContainSubstring("library_id IN (?,?,?)")) - Expect(args).To(ContainElements(1, 2, 3)) + Expect(childIDs(resp.SongsByGenre.Songs)).To(ConsistOf("mf-1", "mf-2", "mf-3")) }) }) }) + // putStarredAndPlain stores ar-1, al-1 and mf-1 starred by test-user, and unstarred ar-2, al-2 and mf-2. + putStarredAndPlain := func() { + GinkgoHelper() + putUsers(ctx, ds, starredUser) + putAlbumArtists(ctx, ds, model.DefaultLibraryID, + model.Artist{ID: "ar-1", Name: "Artist 1"}, model.Artist{ID: "ar-2", Name: "Artist 2"}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-1", Name: "Album 1"}, model.Album{ID: "al-2", Name: "Album 2"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf-1", Title: "Song 1"}, model.MediaFile{ID: "mf-2", Title: "Song 2"}) + userCtx := request.WithUser(ctx, starredUser) + Expect(ds.Artist().SetStar(userCtx, true, "ar-1")).To(Succeed()) + Expect(ds.Album().SetStar(userCtx, true, "al-1")).To(Succeed()) + Expect(ds.MediaFile().SetStar(userCtx, true, "mf-1")).To(Succeed()) + } + Describe("GetStarred", func() { - var mockArtistRepo *tests.MockArtistRepo - var mockAlbumRepo *tests.MockAlbumRepo - var mockMediaFileRepo *tests.MockMediaFileRepo - - BeforeEach(func() { - mockArtistRepo = ds.Artist().(*tests.MockArtistRepo) - mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo) - mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo) - }) - It("should return starred items", func() { - mockArtistRepo.SetData(model.Artists{{ID: "1", Name: "Artist 1"}}) - mockAlbumRepo.SetData(model.Albums{{ID: "1", Name: "Album 1"}}) - mockMediaFileRepo.SetData(model.MediaFiles{{ID: "1", Title: "Song 1"}}) - r := newGetRequest() + putStarredAndPlain() + r := newGetRequest().WithContext(request.WithUser(ctx, starredUser)) resp, err := router.GetStarred(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.Starred.Artist).To(HaveLen(1)) - Expect(resp.Starred.Album).To(HaveLen(1)) - Expect(resp.Starred.Song).To(HaveLen(1)) + Expect(slice.Map(resp.Starred.Artist, func(a responses.Artist) string { return a.Id })).To(ConsistOf("ar-1")) + Expect(childIDs(resp.Starred.Album)).To(ConsistOf("al-1")) + Expect(childIDs(resp.Starred.Song)).To(ConsistOf("mf-1")) }) Context("with musicFolderId parameter", func() { var user model.User BeforeEach(func() { + putLibraryContent() user = model.User{ ID: "test-user", Libraries: []model.Library{ @@ -453,55 +409,37 @@ var _ = Describe("Album Lists", func() { }) It("should filter starred items by specific library when musicFolderId is provided", func() { - mockArtistRepo.SetData(model.Artists{{ID: "1", Name: "Artist 1"}}) - mockAlbumRepo.SetData(model.Albums{{ID: "1", Name: "Album 1"}}) - mockMediaFileRepo.SetData(model.MediaFiles{{ID: "1", Title: "Song 1"}}) r := newGetRequest("musicFolderId=1") r = r.WithContext(ctx) resp, err := router.GetStarred(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.Starred.Artist).To(HaveLen(1)) - Expect(resp.Starred.Album).To(HaveLen(1)) - Expect(resp.Starred.Song).To(HaveLen(1)) - // Verify that library filter was applied to all types - artistQuery, artistArgs, _ := mockArtistRepo.Options.Filters.ToSql() - Expect(artistQuery).To(ContainSubstring("library_id IN (?)")) - Expect(artistArgs).To(ContainElement(1)) + Expect(slice.Map(resp.Starred.Artist, func(a responses.Artist) string { return a.Id })).To(ConsistOf("ar-1")) + Expect(childIDs(resp.Starred.Album)).To(ConsistOf("al-1")) + Expect(childIDs(resp.Starred.Song)).To(ConsistOf("mf-1")) }) }) }) Describe("GetStarred2", func() { - var mockArtistRepo *tests.MockArtistRepo - var mockAlbumRepo *tests.MockAlbumRepo - var mockMediaFileRepo *tests.MockMediaFileRepo - - BeforeEach(func() { - mockArtistRepo = ds.Artist().(*tests.MockArtistRepo) - mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo) - mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo) - }) - It("should return starred items in ID3 format", func() { - mockArtistRepo.SetData(model.Artists{{ID: "1", Name: "Artist 1"}}) - mockAlbumRepo.SetData(model.Albums{{ID: "1", Name: "Album 1"}}) - mockMediaFileRepo.SetData(model.MediaFiles{{ID: "1", Title: "Song 1"}}) - r := newGetRequest() + putStarredAndPlain() + r := newGetRequest().WithContext(request.WithUser(ctx, starredUser)) resp, err := router.GetStarred2(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.Starred2.Artist).To(HaveLen(1)) - Expect(resp.Starred2.Album).To(HaveLen(1)) - Expect(resp.Starred2.Song).To(HaveLen(1)) + Expect(slice.Map(resp.Starred2.Artist, func(a responses.ArtistID3) string { return a.Id })).To(ConsistOf("ar-1")) + Expect(albumID3IDs(resp.Starred2.Album)).To(ConsistOf("al-1")) + Expect(childIDs(resp.Starred2.Song)).To(ConsistOf("mf-1")) }) Context("with musicFolderId parameter", func() { var user model.User BeforeEach(func() { + putLibraryContent() user = model.User{ ID: "test-user", Libraries: []model.Library{ @@ -514,23 +452,22 @@ var _ = Describe("Album Lists", func() { }) It("should filter starred items by specific library when musicFolderId is provided", func() { - mockArtistRepo.SetData(model.Artists{{ID: "1", Name: "Artist 1"}}) - mockAlbumRepo.SetData(model.Albums{{ID: "1", Name: "Album 1"}}) - mockMediaFileRepo.SetData(model.MediaFiles{{ID: "1", Title: "Song 1"}}) r := newGetRequest("musicFolderId=1") r = r.WithContext(ctx) resp, err := router.GetStarred2(r) Expect(err).ToNot(HaveOccurred()) - Expect(resp.Starred2.Artist).To(HaveLen(1)) - Expect(resp.Starred2.Album).To(HaveLen(1)) - Expect(resp.Starred2.Song).To(HaveLen(1)) - // Verify that library filter was applied to all types - artistQuery, artistArgs, _ := mockArtistRepo.Options.Filters.ToSql() - Expect(artistQuery).To(ContainSubstring("library_id IN (?)")) - Expect(artistArgs).To(ContainElement(1)) + Expect(slice.Map(resp.Starred2.Artist, func(a responses.ArtistID3) string { return a.Id })).To(ConsistOf("ar-1")) + Expect(albumID3IDs(resp.Starred2.Album)).To(ConsistOf("al-1")) + Expect(childIDs(resp.Starred2.Song)).To(ConsistOf("mf-1")) }) }) }) }) + +type failingAlbumGetAllRepo struct{ model.AlbumRepository } + +func (failingAlbumGetAllRepo) GetAll(context.Context, ...model.QueryOptions) (model.Albums, error) { + return nil, errors.New("db error") +} diff --git a/server/subsonic/api_suite_test.go b/server/subsonic/api_suite_test.go index 92d6f26fd..86ba52c59 100644 --- a/server/subsonic/api_suite_test.go +++ b/server/subsonic/api_suite_test.go @@ -1,6 +1,7 @@ package subsonic import ( + "context" "io/fs" "testing" @@ -8,8 +9,11 @@ import ( "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core/storage/local" "github.com/navidrome/navidrome/log" + "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/metadata" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -17,11 +21,13 @@ import ( func TestSubsonicApi(t *testing.T) { tests.Init(t, false) log.SetLevel(log.LevelFatal) + persistencetest.Init(t) RegisterFailHandler(Fail) RunSpecs(t, "Subsonic API Suite") } var _ = configtest.RestoreAfterEachSpec() +var _ = persistencetest.ResetBeforeEachSpec() // newLocalStorage fatals if the default extractor is not registered. // Register a no-op so storage.For works in sidecar-lyrics tests. @@ -35,3 +41,29 @@ type subsonicNoopExtractor struct{} func (e *subsonicNoopExtractor) Parse(_ ...string) (map[string]metadata.Info, error) { return nil, nil } func (e *subsonicNoopExtractor) Version() string { return "noop" } + +func putUsers(ctx context.Context, ds model.DataStore, users ...model.User) { + GinkgoHelper() + for i := range users { + Expect(ds.User().Put(ctx, &users[i])).To(Succeed()) + } +} + +// putAlbumArtists stores the artists as album artists of library libID, the role artist indexes list. +func putAlbumArtists(ctx context.Context, ds model.DataStore, libID int, artists ...model.Artist) { + GinkgoHelper() + persistencetest.PutArtists(ctx, ds, libID, artists...) + persistencetest.SetArtistStats(ctx, libID, map[model.Role]model.ArtistStats{ + model.RoleAlbumArtist: {SongCount: 1, AlbumCount: 1}, + }, slice.Map(artists, func(a model.Artist) string { return a.ID })...) +} + +// putItemArtwork records the resolved artwork of an item; an empty hash marks it known absent. +func putItemArtwork(ctx context.Context, ds model.DataStore, kind model.Kind, id, hash string) { + GinkgoHelper() + if hash != "" { + Expect(ds.Artwork().PutImage(ctx, &model.Artwork{Hash: hash, Mime: "image/jpeg"})).To(Succeed()) + } + Expect(ds.Artwork().PutItemArtwork(ctx, &model.ItemArtwork{ItemKind: kind.Prefix(), ItemID: id, + ImageType: model.ImageTypePrimary, Hash: hash, Source: "external"})).To(Succeed()) +} diff --git a/server/subsonic/bookmarks_test.go b/server/subsonic/bookmarks_test.go index d58424397..97be37537 100644 --- a/server/subsonic/bookmarks_test.go +++ b/server/subsonic/bookmarks_test.go @@ -4,26 +4,39 @@ import ( "context" "fmt" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/subsonic/responses" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Bookmarks", func() { var router *Router - var ds *tests.MockDataStore - var mfRepo *tests.MockMediaFileRepo + var ds model.DataStore var ctx context.Context + bookmarkedIDs := func() []string { + GinkgoHelper() + bookmarks, err := ds.MediaFile().GetBookmarks(ctx) + Expect(err).ToNot(HaveOccurred()) + ids := make([]string, len(bookmarks)) + for i, b := range bookmarks { + ids[i] = b.Item.ID + } + return ids + } + BeforeEach(func() { ctx = request.WithUser(GinkgoT().Context(), model.User{ID: "u1", UserName: "u1"}) - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: "Private", Path: "/private"})).To(Succeed()) + putUsers(ctx, ds, model.User{ID: "u1", UserName: "u1"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "visible"}, model.MediaFile{ID: "hidden", LibraryID: 2}) router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) - mfRepo = ds.MediaFile().(*tests.MockMediaFileRepo) - mfRepo.SetData(model.MediaFiles{{ID: "visible"}}) }) Describe("CreateBookmark", func() { @@ -34,7 +47,7 @@ var _ = Describe("Bookmarks", func() { Expect(err).To(HaveOccurred()) Expect(mapToSubsonicError(err).code).To(Equal(responses.ErrorDataNotFound)) - Expect(mfRepo.BookmarksAdded).To(BeEmpty()) + Expect(bookmarkedIDs()).To(BeEmpty()) }) It("accepts an id the user can read", func() { @@ -43,16 +56,17 @@ var _ = Describe("Bookmarks", func() { _, err := router.CreateBookmark(r) Expect(err).ToNot(HaveOccurred()) - Expect(mfRepo.BookmarksAdded).To(ConsistOf("visible")) + Expect(bookmarkedIDs()).To(ConsistOf("visible")) }) }) Context("when some queued tracks fail to load", func() { BeforeEach(func() { - ds.MockedPlayQueue = &tests.MockPlayQueueRepo{ - Queue: &model.PlayQueue{UserID: "u1", Items: model.MediaFiles{{ID: "visible"}}}, - WithMediaFilesErr: fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue), - } + Expect(ds.PlayQueue().Store(ctx, &model.PlayQueue{UserID: "u1", Items: model.MediaFiles{{ID: "visible"}}})).To(Succeed()) + router = New(persistencetest.Stub(ds, persistencetest.Repos{PlayQueue: func(r model.PlayQueueRepository) model.PlayQueueRepository { + return incompletePlayQueueRepo{r} + }}), + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) }) It("getPlayQueue returns the loaded tracks", func() { @@ -70,3 +84,13 @@ var _ = Describe("Bookmarks", func() { }) }) }) + +type incompletePlayQueueRepo struct{ model.PlayQueueRepository } + +func (r incompletePlayQueueRepo) RetrieveWithMediaFiles(ctx context.Context, userId string) (*model.PlayQueue, error) { + pq, err := r.PlayQueueRepository.RetrieveWithMediaFiles(ctx, userId) + if err != nil { + return pq, err + } + return pq, fmt.Errorf("%w: chunk failed", model.ErrIncompleteQueue) +} diff --git a/server/subsonic/browsing_test.go b/server/subsonic/browsing_test.go index f2202b5e8..0724ce4c7 100644 --- a/server/subsonic/browsing_test.go +++ b/server/subsonic/browsing_test.go @@ -8,9 +8,12 @@ import ( "github.com/navidrome/navidrome/core/auth" "github.com/navidrome/navidrome/core/external" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/server/subsonic/responses" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -32,9 +35,36 @@ var _ = Describe("Browsing", func() { var ctx context.Context var ds model.DataStore + // putArtistPerLibrary stores album artist ar-N in each library N, all granted to user-id. + putArtistPerLibrary := func() { + GinkgoHelper() + putUsers(ctx, ds, model.User{ID: "user-id", UserName: "user-id"}) + for _, id := range persistencetest.SetLibraries(ctx, ds, "/music/library1", "/music/library2", "/music/library3") { + putAlbumArtists(ctx, ds, id, model.Artist{ID: fmt.Sprintf("ar-%d", id), Name: fmt.Sprintf("Test Artist %d", id)}) + } + } + indexedArtistIDs := func(indexes []responses.Index) []string { + var ids []string + for _, idx := range indexes { + for _, a := range idx.Artists { + ids = append(ids, a.Id) + } + } + return ids + } + indexedArtistID3IDs := func(indexes []responses.IndexID3) []string { + var ids []string + for _, idx := range indexes { + for _, a := range idx.Artists { + ids = append(ids, a.Id) + } + } + return ids + } + BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) api = &Router{ds: ds} }) @@ -64,6 +94,7 @@ var _ = Describe("Browsing", func() { Describe("GetIndexes", func() { It("should validate user access to the specified musicFolderId", func() { + putArtistPerLibrary() // Create mock user with access to library 1 only ctx = contextWithUser(ctx, "user-id", 1) @@ -80,23 +111,10 @@ var _ = Describe("Browsing", func() { }) It("should default to first accessible library when no musicFolderId specified", func() { + putArtistPerLibrary() // Create mock user with access to libraries 2 and 3 ctx = contextWithUser(ctx, "user-id", 2, 3) - // Setup minimal mock library data for working tests - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(model.Libraries{ - {ID: 2, Name: "Test Library 2", Path: "/music/library2"}, - {ID: 3, Name: "Test Library 3", Path: "/music/library3"}, - }) - - // Setup mock artist data - mockArtistRepo := ds.Artist().(*tests.MockArtistRepo) - mockArtistRepo.SetData(model.Artists{ - {ID: "1", Name: "Test Artist 1"}, - {ID: "2", Name: "Test Artist 2"}, - }) - // Create request without musicFolderId r := httptest.NewRequest(http.MethodGet, "/rest/getIndexes", nil) r = r.WithContext(ctx) @@ -108,11 +126,13 @@ var _ = Describe("Browsing", func() { Expect(err).ToNot(HaveOccurred()) Expect(response).ToNot(BeNil()) Expect(response.Indexes).ToNot(BeNil()) + Expect(indexedArtistIDs(response.Indexes.Index)).To(ConsistOf("ar-2", "ar-3")) }) }) Describe("GetArtists", func() { It("should validate user access to the specified musicFolderId", func() { + putArtistPerLibrary() // Create mock user with access to library 1 only ctx = contextWithUser(ctx, "user-id", 1) @@ -129,23 +149,10 @@ var _ = Describe("Browsing", func() { }) It("should default to first accessible library when no musicFolderId specified", func() { + putArtistPerLibrary() // Create mock user with access to libraries 1 and 2 ctx = contextWithUser(ctx, "user-id", 1, 2) - // Setup minimal mock library data for working tests - mockLibRepo := ds.Library().(*tests.MockLibraryRepo) - mockLibRepo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library 1", Path: "/music/library1"}, - {ID: 2, Name: "Test Library 2", Path: "/music/library2"}, - }) - - // Setup mock artist data - mockArtistRepo := ds.Artist().(*tests.MockArtistRepo) - mockArtistRepo.SetData(model.Artists{ - {ID: "1", Name: "Test Artist 1"}, - {ID: "2", Name: "Test Artist 2"}, - }) - // Create request without musicFolderId r := httptest.NewRequest(http.MethodGet, "/rest/getArtists", nil) r = r.WithContext(ctx) @@ -157,6 +164,7 @@ var _ = Describe("Browsing", func() { Expect(err).ToNot(HaveOccurred()) Expect(response).ToNot(BeNil()) Expect(response.Artist).ToNot(BeNil()) + Expect(indexedArtistID3IDs(response.Artist.Index)).To(ConsistOf("ar-1", "ar-2")) }) }) diff --git a/server/subsonic/e2e/e2e_suite_test.go b/server/subsonic/e2e/e2e_suite_test.go index a2bca1ea6..7fa3f3dbb 100644 --- a/server/subsonic/e2e/e2e_suite_test.go +++ b/server/subsonic/e2e/e2e_suite_test.go @@ -87,7 +87,7 @@ const firstFixtureLine = "Should auld acquaintance be forgot," // Shared test state var ( ctx context.Context - ds *tests.MockDataStore + ds model.DataStore router *subsonic.Router streamerSpy *harness.SpyStreamer goldenDB *harness.DB @@ -428,7 +428,7 @@ func setupTestDB() { // Restore DB to golden state (no scan needed) goldenDB.Restore() - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds = persistence.New(db.Db()) auth.Init(ds) streamerSpy = &harness.SpyStreamer{} diff --git a/server/subsonic/e2e/subsonic_artwork_test.go b/server/subsonic/e2e/subsonic_artwork_test.go index d0c7af581..97eea0603 100644 --- a/server/subsonic/e2e/subsonic_artwork_test.go +++ b/server/subsonic/e2e/subsonic_artwork_test.go @@ -34,7 +34,6 @@ import ( "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/public" "github.com/navidrome/navidrome/server/subsonic" - "github.com/navidrome/navidrome/tests" "github.com/navidrome/navidrome/tests/harness" "github.com/navidrome/navidrome/utils/cache" . "github.com/onsi/ginkgo/v2" @@ -102,7 +101,7 @@ var _ = Describe("Artwork Serving", Ordered, func() { }) goldenDB.Restore() - ds = &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds = persistence.New(db.Db()) auth.Init(ds) // Re-scanning already-populated data deadlocks the parallel album-refresh phase at the diff --git a/server/subsonic/helpers_test.go b/server/subsonic/helpers_test.go index 1eb4e1b39..979c5dcab 100644 --- a/server/subsonic/helpers_test.go +++ b/server/subsonic/helpers_test.go @@ -30,10 +30,7 @@ var _ = Describe("helpers", func() { Describe("fakePath", func() { var mf model.MediaFile BeforeEach(func() { - mf.AlbumArtist = "Brock Berrigan" - mf.Album = "Point Pleasant" - mf.Title = "Split Decision" - mf.Suffix = "flac" + mf = model.MediaFile{AlbumArtist: "Brock Berrigan", Album: "Point Pleasant", Title: "Split Decision", Suffix: "flac"} }) When("TrackNumber is not available", func() { It("does not add any number to the filename", func() { diff --git a/server/subsonic/library_scanning_test.go b/server/subsonic/library_scanning_test.go index bafa2f029..81a9e4af8 100644 --- a/server/subsonic/library_scanning_test.go +++ b/server/subsonic/library_scanning_test.go @@ -6,8 +6,10 @@ import ( "net/http" "net/http/httptest" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/subsonic/responses" "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" @@ -18,11 +20,19 @@ var _ = Describe("LibraryScanning", func() { var ctx context.Context var api *Router var ms *tests.MockScanner + var ds model.DataStore + + putSecondLibrary := func(name, path string) { + GinkgoHelper() + Expect(ds.Library().Put(ctx, &model.Library{ID: 2, Name: name, Path: path})).To(Succeed()) + } BeforeEach(func() { ctx = GinkgoT().Context() ms = tests.NewMockScanner() - api = &Router{scanner: ms} + ds = persistence.New(db.Db()) + putUsers(ctx, ds, model.User{ID: "admin-id", UserName: "admin", IsAdmin: true}) + api = &Router{scanner: ms, ds: ds} }) Describe("StartScan", func() { @@ -81,11 +91,7 @@ var _ = Describe("LibraryScanning", func() { }) It("triggers a selective scan with single target parameter", func() { - // Setup mocks - mockUserRepo := tests.CreateMockUserRepo() - _ = mockUserRepo.SetUserLibraries(GinkgoT().Context(), "admin-id", []int{1, 2}) - mockDS := &tests.MockDataStore{MockedUser: mockUserRepo} - api.ds = mockDS + putSecondLibrary("Library 2", "/music2") // Create admin user userCtx := request.WithUser(ctx, model.User{ @@ -117,11 +123,7 @@ var _ = Describe("LibraryScanning", func() { }) It("triggers a selective scan with multiple target parameters", func() { - // Setup mocks - mockUserRepo := tests.CreateMockUserRepo() - _ = mockUserRepo.SetUserLibraries(GinkgoT().Context(), "admin-id", []int{1, 2}) - mockDS := &tests.MockDataStore{MockedUser: mockUserRepo} - api.ds = mockDS + putSecondLibrary("Library 2", "/music2") // Create admin user userCtx := request.WithUser(ctx, model.User{ @@ -155,12 +157,6 @@ var _ = Describe("LibraryScanning", func() { }) It("triggers a selective full scan with target and fullScan parameters", func() { - // Setup mocks - mockUserRepo := tests.CreateMockUserRepo() - _ = mockUserRepo.SetUserLibraries(GinkgoT().Context(), "admin-id", []int{1}) - mockDS := &tests.MockDataStore{MockedUser: mockUserRepo} - api.ds = mockDS - // Create admin user userCtx := request.WithUser(ctx, model.User{ ID: "admin-id", @@ -236,11 +232,8 @@ var _ = Describe("LibraryScanning", func() { }) It("returns error when library does not exist", func() { - // Setup mocks - user has access to library 1 and 2 only - mockUserRepo := tests.CreateMockUserRepo() - _ = mockUserRepo.SetUserLibraries(GinkgoT().Context(), "admin-id", []int{1, 2}) - mockDS := &tests.MockDataStore{MockedUser: mockUserRepo} - api.ds = mockDS + // User has access to library 1 and 2 only + putSecondLibrary("Library 2", "/music2") // Create admin user userCtx := request.WithUser(ctx, model.User{ @@ -265,19 +258,6 @@ var _ = Describe("LibraryScanning", func() { }) It("calls ScanAll when single library with empty path and only one library exists", func() { - // Setup mocks - single library in DB - mockUserRepo := tests.CreateMockUserRepo() - _ = mockUserRepo.SetUserLibraries(GinkgoT().Context(), "admin-id", []int{1}) - mockLibraryRepo := &tests.MockLibraryRepo{} - mockLibraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Music Library", Path: "/music"}, - }) - mockDS := &tests.MockDataStore{ - MockedUser: mockUserRepo, - MockedLibrary: mockLibraryRepo, - } - api.ds = mockDS - // Create admin user userCtx := request.WithUser(ctx, model.User{ ID: "admin-id", @@ -303,19 +283,7 @@ var _ = Describe("LibraryScanning", func() { }) It("calls ScanFolders when single library with empty path but multiple libraries exist", func() { - // Setup mocks - multiple libraries in DB - mockUserRepo := tests.CreateMockUserRepo() - _ = mockUserRepo.SetUserLibraries(GinkgoT().Context(), "admin-id", []int{1, 2}) - mockLibraryRepo := &tests.MockLibraryRepo{} - mockLibraryRepo.SetData(model.Libraries{ - {ID: 1, Name: "Music Library", Path: "/music"}, - {ID: 2, Name: "Audiobooks", Path: "/audiobooks"}, - }) - mockDS := &tests.MockDataStore{ - MockedUser: mockUserRepo, - MockedLibrary: mockLibraryRepo, - } - api.ds = mockDS + putSecondLibrary("Audiobooks", "/audiobooks") // Create admin user userCtx := request.WithUser(ctx, model.User{ diff --git a/server/subsonic/lyrics_test.go b/server/subsonic/lyrics_test.go index 993502273..f7284a040 100644 --- a/server/subsonic/lyrics_test.go +++ b/server/subsonic/lyrics_test.go @@ -1,14 +1,15 @@ package subsonic import ( + "context" "encoding/json" - "path/filepath" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/lyrics" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" + "github.com/navidrome/navidrome/persistence" "github.com/navidrome/navidrome/server/subsonic/responses" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -16,12 +17,12 @@ import ( var _ = Describe("GetLyricsBySongId", func() { var router *Router var ds model.DataStore - mockRepo := &mockedMediaFile{MockMediaFileRepo: tests.MockMediaFileRepo{}} + var ctx context.Context BeforeEach(func() { - ds = &tests.MockDataStore{ - MockedMediaFile: mockRepo, - } + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + useRepoRootAsLibrary(ctx, ds) router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, lyrics.NewLyrics(ds, nil), nil, nil) conf.Update(func(c *conf.Options) { c.LyricsPriority = "embedded,.lrc" }) }) @@ -107,14 +108,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJson), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJson)) response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -162,14 +156,7 @@ var _ = Describe("GetLyricsBySongId", func() { synced, }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJson), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJson)) response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -201,18 +188,7 @@ var _ = Describe("GetLyricsBySongId", func() { conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" }) r := newGetRequest("id=1") - fixturesDir, err := filepath.Abs("tests/fixtures") - Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - LibraryPath: fixturesDir, - Path: "test.mp3", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: "[]", - }, - }) + putRickAstleySong(ctx, ds, "tests/fixtures/test.mp3", "[]") response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -257,18 +233,7 @@ var _ = Describe("GetLyricsBySongId", func() { conf.Update(func(c *conf.Options) { c.LyricsPriority = ".ttml,embedded" }) r := newGetRequest("id=1&enhanced=true") - fixturesDir, err := filepath.Abs("tests/fixtures") - Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - LibraryPath: fixturesDir, - Path: "test-metadata.mp3", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: "[]", - }, - }) + putRickAstleySong(ctx, ds, "tests/fixtures/test-metadata.mp3", "[]") response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -395,14 +360,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJson), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJson)) response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -595,14 +553,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJSON), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON)) response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -698,14 +649,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJSON), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON)) response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) @@ -784,14 +728,7 @@ var _ = Describe("GetLyricsBySongId", func() { }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJSON), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON)) response, err := router.GetLyricsBySongId(r) Expect(err).ToNot(HaveOccurred()) diff --git a/server/subsonic/media_annotation_test.go b/server/subsonic/media_annotation_test.go index 02b767d6f..30e344927 100644 --- a/server/subsonic/media_annotation_test.go +++ b/server/subsonic/media_annotation_test.go @@ -8,11 +8,13 @@ import ( "time" "github.com/navidrome/navidrome/core/scrobbler" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/events" "github.com/navidrome/navidrome/server/subsonic/responses" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -24,9 +26,26 @@ var _ = Describe("MediaAnnotationController", func() { var eventBroker *fakeEventBroker var ctx context.Context + var userCtx context.Context + + // putOwnedPlaylist stores u1's playlist pl-1, which the specs annotate as u1. + putOwnedPlaylist := func() { + GinkgoHelper() + owner := model.User{ID: "u1", UserName: "u1"} + putUsers(ctx, ds, owner) + userCtx = request.WithUser(ctx, owner) + Expect(ds.Playlist().Put(userCtx, &model.Playlist{ID: "pl-1", Name: "My Playlist", OwnerID: "u1"})).To(Succeed()) + } + storedPlaylist := func() *model.Playlist { + GinkgoHelper() + pls, err := ds.Playlist().Get(userCtx, "pl-1") + Expect(err).ToNot(HaveOccurred()) + return pls + } + BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) playTracker = &fakePlayTracker{} eventBroker = &fakeEventBroker{} router = New(ds, nil, nil, nil, nil, nil, nil, eventBroker, nil, playTracker, nil, nil, nil, nil, nil, nil) @@ -78,7 +97,7 @@ var _ = Describe("MediaAnnotationController", func() { Context("submission=false", func() { var req *http.Request BeforeEach(func() { - _ = ds.MediaFile().Put(ctx, &model.MediaFile{ID: "12"}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "12"}) ctx = request.WithPlayer(ctx, model.Player{ID: "player-1"}) req = newGetRequest("id=12", "submission=false") req = req.WithContext(ctx) @@ -188,67 +207,56 @@ var _ = Describe("MediaAnnotationController", func() { }) Describe("Star/Unstar playlists", func() { - var plRepo *tests.MockPlaylistRepo - BeforeEach(func() { - plRepo = tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl-1", Name: "My Playlist", OwnerID: "u1"}}) - ds.(*tests.MockDataStore).MockedPlaylist = plRepo + putOwnedPlaylist() }) It("stars a playlist by dispatching to the Playlist repo", func() { - r := newGetRequest("id=pl-1") + r := newGetRequest("id=pl-1").WithContext(userCtx) _, err := router.Star(r) Expect(err).ToNot(HaveOccurred()) - Expect(plRepo.Starred).To(HaveKeyWithValue("pl-1", true)) + Expect(storedPlaylist().Starred).To(BeTrue()) }) It("unstars a playlist by dispatching to the Playlist repo", func() { - r := newGetRequest("id=pl-1") + Expect(ds.Playlist().SetStar(userCtx, true, "pl-1")).To(Succeed()) + r := newGetRequest("id=pl-1").WithContext(userCtx) _, err := router.Unstar(r) Expect(err).ToNot(HaveOccurred()) - Expect(plRepo.Starred).To(HaveKeyWithValue("pl-1", false)) + Expect(storedPlaylist().Starred).To(BeFalse()) }) }) Describe("SetRating playlists", func() { - var plRepo *tests.MockPlaylistRepo - BeforeEach(func() { - plRepo = tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl-1", Name: "My Playlist", OwnerID: "u1"}}) - ds.(*tests.MockDataStore).MockedPlaylist = plRepo + putOwnedPlaylist() }) It("rates a playlist by dispatching to the Playlist repo", func() { - r := newGetRequest("id=pl-1", "rating=4") + r := newGetRequest("id=pl-1", "rating=4").WithContext(userCtx) _, err := router.SetRating(r) Expect(err).ToNot(HaveOccurred()) - Expect(plRepo.Ratings).To(HaveKeyWithValue("pl-1", 4)) + Expect(storedPlaylist().Rating).To(Equal(4)) }) }) Describe("SetRating range validation", func() { - var plRepo *tests.MockPlaylistRepo - BeforeEach(func() { - plRepo = tests.CreateMockPlaylistRepo() - plRepo.SetData(model.Playlists{{ID: "pl-1", Name: "My Playlist", OwnerID: "u1"}}) - ds.(*tests.MockDataStore).MockedPlaylist = plRepo + putOwnedPlaylist() }) DescribeTable("rejects ratings outside the 0-5 range allowed by the Subsonic spec", func(rating string) { - _, err := router.SetRating(newGetRequest("id=pl-1", "rating=4")) + _, err := router.SetRating(newGetRequest("id=pl-1", "rating=4").WithContext(userCtx)) Expect(err).ToNot(HaveOccurred()) - r := newGetRequest("id=pl-1", "rating="+rating) + r := newGetRequest("id=pl-1", "rating="+rating).WithContext(userCtx) _, err = router.SetRating(r) @@ -256,7 +264,7 @@ var _ = Describe("MediaAnnotationController", func() { var subErr subError Expect(errors.As(err, &subErr)).To(BeTrue()) Expect(subErr.code).To(Equal(responses.ErrorGeneric)) - Expect(plRepo.Ratings).To(HaveKeyWithValue("pl-1", 4)) + Expect(storedPlaylist().Rating).To(Equal(4)) }, Entry("above maximum", "6"), Entry("well above maximum", "1000"), @@ -268,12 +276,15 @@ var _ = Describe("MediaAnnotationController", func() { DescribeTable("accepts ratings inside the 0-5 range", func(rating int) { - r := newGetRequest("id=pl-1", fmt.Sprintf("rating=%d", rating)) + if rating == 0 { + Expect(ds.Playlist().SetRating(userCtx, 4, "pl-1")).To(Succeed()) + } + r := newGetRequest("id=pl-1", fmt.Sprintf("rating=%d", rating)).WithContext(userCtx) _, err := router.SetRating(r) Expect(err).ToNot(HaveOccurred()) - Expect(plRepo.Ratings).To(HaveKeyWithValue("pl-1", rating)) + Expect(storedPlaylist().Rating).To(Equal(rating)) }, Entry("zero clears the rating", 0), Entry("middle of the range", 3), diff --git a/server/subsonic/media_retrieval_test.go b/server/subsonic/media_retrieval_test.go index 80649e7d0..7532aea0b 100644 --- a/server/subsonic/media_retrieval_test.go +++ b/server/subsonic/media_retrieval_test.go @@ -2,22 +2,22 @@ package subsonic import ( "bytes" - "cmp" "context" "encoding/json" "errors" "io" "net/http/httptest" - "path/filepath" - "slices" + "os" "time" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/artwork" "github.com/navidrome/navidrome/core/lyrics" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -25,20 +25,14 @@ import ( var _ = Describe("MediaRetrievalController", func() { var router *Router var ds model.DataStore - mockRepo := &mockedMediaFile{MockMediaFileRepo: tests.MockMediaFileRepo{}} + var ctx context.Context var artwork *fakeArtwork var w *httptest.ResponseRecorder BeforeEach(func() { - albumRepo := &tests.MockAlbumRepo{} - albumRepo.SetData(model.Albums{{ID: "34"}}) // the id the specs request, made accessible - radioRepo := tests.CreateMockedRadioRepo() - Expect(radioRepo.Put(GinkgoT().Context(), &model.Radio{ID: "rd1", Name: "Radio"})).To(Succeed()) - ds = &tests.MockDataStore{ - MockedMediaFile: mockRepo, - MockedAlbum: albumRepo, - MockedRadio: radioRepo, - } + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) + useRepoRootAsLibrary(ctx, ds) artwork = &fakeArtwork{data: "image data"} router = New(ds, artwork, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, lyrics.NewLyrics(ds, nil), nil, nil) w = httptest.NewRecorder() @@ -188,14 +182,7 @@ var _ = Describe("MediaRetrievalController", func() { }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJson), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJson)) response, err := router.GetLyrics(r) Expect(err).ToNot(HaveOccurred()) Expect(response.Lyrics.Artist).To(Equal("Rick Astley")) @@ -210,21 +197,19 @@ var _ = Describe("MediaRetrievalController", func() { {Kind: model.LyricKindMain, Lang: "eng", Line: []model.Line{{Start: &start, Value: "Never gonna let you down"}}}, }) Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - Lyrics: string(lyricsJSON), - }, - }) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON)) response, err := router.GetLyrics(r) Expect(err).ToNot(HaveOccurred()) Expect(response.Lyrics.Value).To(Equal("Never gonna let you down\n")) }) It("should return empty subsonic response if the record corresponding to the given artist & title is not found", func() { r := newGetRequest("artist=Dheeraj", "title=Rinkiya+Ke+Papa") - mockRepo.SetData(model.MediaFiles{}) + start := int64(0) + lyricsJSON, err := json.Marshal(model.LyricList{ + {Kind: model.LyricKindMain, Lang: "eng", Line: []model.Line{{Start: &start, Value: "Never gonna give you up"}}}, + }) + Expect(err).ToNot(HaveOccurred()) + putRickAstleySong(ctx, ds, "song.mp3", string(lyricsJSON)) response, err := router.GetLyrics(r) Expect(err).ToNot(HaveOccurred()) Expect(response.Lyrics.Artist).To(Equal("")) @@ -233,17 +218,7 @@ var _ = Describe("MediaRetrievalController", func() { }) It("should return lyric file when finding mediafile with no embedded lyrics but present on filesystem", func() { r := newGetRequest("artist=Rick+Astley", "title=Never+Gonna+Give+You+Up") - fixturesDir, err := filepath.Abs("tests/fixtures") - Expect(err).ToNot(HaveOccurred()) - mockRepo.SetData(model.MediaFiles{ - { - LibraryPath: fixturesDir, - Path: "test.mp3", - ID: "1", - Artist: "Rick Astley", - Title: "Never Gonna Give You Up", - }, - }) + putRickAstleySong(ctx, ds, "tests/fixtures/test.mp3", "") response, err := router.GetLyrics(r) Expect(err).ToNot(HaveOccurred()) Expect(response.Lyrics.Artist).To(Equal("Rick Astley")) @@ -287,29 +262,24 @@ func (c *fakeArtwork) GetOrPlaceholder(ctx context.Context, id string, size int, }, nil } -type mockedMediaFile struct { - tests.MockMediaFileRepo +func useRepoRootAsLibrary(ctx context.Context, ds model.DataStore) { + GinkgoHelper() + root, err := os.Getwd() + Expect(err).ToNot(HaveOccurred()) + persistencetest.SetLibraries(ctx, ds, root) } -func (m *mockedMediaFile) GetAll(ctx context.Context, opts ...model.QueryOptions) (model.MediaFiles, error) { - data, err := m.MockMediaFileRepo.GetAll(ctx, opts...) - if err != nil { - return nil, err - } - if len(opts) == 0 || opts[0].Sort != "lyrics, updated_at" { - return data, nil - } - - result := slices.Clone(data) - slices.SortFunc(result, func(a, b model.MediaFile) int { - diff := cmp.Or( - cmp.Compare(a.Lyrics, b.Lyrics), - cmp.Compare(a.UpdatedAt.Unix(), b.UpdatedAt.Unix()), - ) - if opts[0].Order == "desc" { - return -diff - } - return diff +// putRickAstleySong stores "Never Gonna Give You Up" by Rick Astley with ID "1" at path, relative to library 1. +func putRickAstleySong(ctx context.Context, ds model.DataStore, path, lyrics string) { + GinkgoHelper() + artist := model.Artist{ID: "ar-rick", Name: "Rick Astley"} + Expect(ds.Artist().Put(ctx, &artist)).To(Succeed()) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ + ID: "1", + Path: path, + Artist: "Rick Astley", + Title: "Never Gonna Give You Up", + Lyrics: lyrics, + Participants: model.Participants{model.RoleArtist: {{Artist: artist}}}, }) - return result, nil } diff --git a/server/subsonic/middlewares_test.go b/server/subsonic/middlewares_test.go index 37ee12fd9..469acc05d 100644 --- a/server/subsonic/middlewares_test.go +++ b/server/subsonic/middlewares_test.go @@ -18,10 +18,12 @@ import ( "github.com/navidrome/navidrome/consts" "github.com/navidrome/navidrome/core" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/log" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -51,7 +53,7 @@ var _ = Describe("Middlewares", func() { ctx = GinkgoT().Context() next = &mockHandler{} w = httptest.NewRecorder() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) }) Describe("ParsePostForm", func() { @@ -332,7 +334,7 @@ var _ = Describe("Middlewares", func() { Expect(err).ToNot(HaveOccurred()) Expect(ds.Player().Put(ctx, &model.Player{ID: "player-1", Name: "My Phone", UserId: usr.ID, Client: "Symfonium"})).To(Succeed()) key = "nds_0123456789abcdefghijkl" - Expect(ds.Player().SetAPIKey(ctx, "player-1", key)).To(Succeed()) + Expect(ds.Player().SetAPIKey(request.WithUser(ctx, *usr), "player-1", key)).To(Succeed()) }) It("authenticates the owner and binds the key's player", func() { @@ -473,10 +475,11 @@ var _ = Describe("Middlewares", func() { }) It("does not count server errors", func() { - userRepo := ds.User().(*tests.MockedUserRepo) - userRepo.Error = errors.New("db down") + store := &failingAuthStore{} + cp = authenticate(store.stub(ds))(next) + store.userErr = errors.New("db down") failTimes(5, "u=admin", "p=wordpass") - userRepo.Error = nil + store.userErr = nil serve(newGetRequest("u=admin", "p=wordpass")) Expect(next.called).To(BeTrue()) @@ -484,14 +487,15 @@ var _ = Describe("Middlewares", func() { It("does not count server errors when a key is sent as the password", func() { usr, _ := ds.User().FindByUsername(ctx, "admin") - playerRepo := ds.Player().(*tests.MockPlayerRepo) - Expect(playerRepo.Put(ctx, &model.Player{ID: "player-1", UserId: usr.ID})).To(Succeed()) + Expect(ds.Player().Put(ctx, &model.Player{ID: "player-1", UserId: usr.ID})).To(Succeed()) key := "nds_0123456789abcdefghijkl" - Expect(playerRepo.SetAPIKey(ctx, "player-1", key)).To(Succeed()) + Expect(ds.Player().SetAPIKey(request.WithUser(ctx, *usr), "player-1", key)).To(Succeed()) + store := &failingAuthStore{} + cp = authenticate(store.stub(ds))(next) - playerRepo.Error = errors.New("db down") + store.playerErr = errors.New("db down") failTimes(5, "u=admin", "p="+key) - playerRepo.Error = nil + store.playerErr = nil serve(newGetRequest("u=admin", "p="+key)) Expect(next.called).To(BeTrue()) @@ -530,16 +534,18 @@ var _ = Describe("Middlewares", func() { It("throttles a repeated bad key without locking out valid keys from the same IP", func() { usr, _ := ds.User().FindByUsername(ctx, "admin") - playerRepo := ds.Player().(*tests.MockPlayerRepo) - Expect(playerRepo.Put(ctx, &model.Player{ID: "player-1", UserId: usr.ID})).To(Succeed()) + ownerCtx := request.WithUser(ctx, *usr) + Expect(ds.Player().Put(ctx, &model.Player{ID: "player-1", UserId: usr.ID})).To(Succeed()) key := "nds_0123456789abcdefghijkl" - Expect(playerRepo.SetAPIKey(ctx, "player-1", key)).To(Succeed()) + Expect(ds.Player().SetAPIKey(ownerCtx, "player-1", key)).To(Succeed()) + badKey := "nds_bad0000000000000000000" for range 3 { - Expect(serve(newGetRequest("apiKey=nds_bad")).Body.String()).To(ContainSubstring(`code="44"`)) + Expect(serve(newGetRequest("apiKey=" + badKey)).Body.String()).To(ContainSubstring(`code="44"`)) } - playerRepo.APIKeys["nds_bad"] = "player-1" - rec := serve(newGetRequest("apiKey=nds_bad")) + Expect(ds.Player().Put(ctx, &model.Player{ID: "player-2", UserId: usr.ID})).To(Succeed()) + Expect(ds.Player().SetAPIKey(ownerCtx, "player-2", badKey)).To(Succeed()) + rec := serve(newGetRequest("apiKey=" + badKey)) Expect(next.called).To(BeFalse()) Expect(rec.Body.String()).To(ContainSubstring(`code="44"`)) @@ -947,3 +953,41 @@ func (g *gatedUserRepo) FindByUsernameWithPassword(ctx context.Context, username type countingHandler struct{ calls atomic.Int32 } func (c *countingHandler) ServeHTTP(http.ResponseWriter, *http.Request) { c.calls.Add(1) } + +// failingAuthStore fails the credential lookups while userErr or playerErr is set. +type failingAuthStore struct { + userErr, playerErr error +} + +func (f *failingAuthStore) stub(ds model.DataStore) model.DataStore { + return persistencetest.Stub(ds, persistencetest.Repos{ + User: func(r model.UserRepository) model.UserRepository { return failingAuthUserRepo{UserRepository: r, f: f} }, + Player: func(r model.PlayerRepository) model.PlayerRepository { + return failingAuthPlayerRepo{PlayerRepository: r, f: f} + }, + }) +} + +type failingAuthUserRepo struct { + model.UserRepository + f *failingAuthStore +} + +func (r failingAuthUserRepo) FindByUsernameWithPassword(ctx context.Context, username string) (*model.User, error) { + if r.f.userErr != nil { + return nil, r.f.userErr + } + return r.UserRepository.FindByUsernameWithPassword(ctx, username) +} + +type failingAuthPlayerRepo struct { + model.PlayerRepository + f *failingAuthStore +} + +func (r failingAuthPlayerRepo) FindByAPIKey(ctx context.Context, key string) (*model.Player, error) { + if r.f.playerErr != nil { + return nil, r.f.playerErr + } + return r.PlayerRepository.FindByAPIKey(ctx, key) +} diff --git a/server/subsonic/playlists_test.go b/server/subsonic/playlists_test.go index 808dbe897..299423164 100644 --- a/server/subsonic/playlists_test.go +++ b/server/subsonic/playlists_test.go @@ -13,7 +13,6 @@ import ( "github.com/navidrome/navidrome/model/criteria" "github.com/navidrome/navidrome/model/request" "github.com/navidrome/navidrome/server/subsonic/responses" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -28,7 +27,7 @@ var _ = Describe("buildPlaylist", func() { BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = struct{ model.DataStore }{} router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) }) @@ -332,7 +331,7 @@ var _ = Describe("UpdatePlaylist", func() { var playlists *fakePlaylists BeforeEach(func() { - ds = &tests.MockDataStore{} + ds = struct{ model.DataStore }{} playlists = &fakePlaylists{} router = New(ds, nil, nil, nil, nil, nil, nil, nil, playlists, nil, nil, nil, nil, nil, nil, nil) }) @@ -387,7 +386,7 @@ var _ = Describe("playlist track limit", func() { BeforeEach(func() { fp = &fakePlaylists{} - router = New(&tests.MockDataStore{}, nil, nil, nil, nil, nil, nil, nil, fp, nil, nil, nil, nil, nil, nil, nil) + router = New(struct{ model.DataStore }{}, nil, nil, nil, nil, nil, nil, nil, fp, nil, nil, nil, nil, nil, nil, nil) conf.Update(func(c *conf.Options) { c.DevMaxPlaylistTracksPerRequest = 3 }) }) diff --git a/server/subsonic/radio_test.go b/server/subsonic/radio_test.go index 287f51195..d62120334 100644 --- a/server/subsonic/radio_test.go +++ b/server/subsonic/radio_test.go @@ -2,39 +2,47 @@ package subsonic import ( "context" + "errors" "net/http" "net/http/httptest" "github.com/navidrome/navidrome/conf" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Radio", func() { var api *Router - var ds *tests.MockDataStore + var ds model.DataStore var ctx context.Context - var radioRepo *tests.MockedRadioRepo + + putRadios := func(radios ...model.Radio) { + GinkgoHelper() + adminCtx := request.WithUser(ctx, model.User{ID: "admin-id", IsAdmin: true}) + for i := range radios { + Expect(ds.Radio().Put(adminCtx, &radios[i])).To(Succeed()) + } + } BeforeEach(func() { ctx = GinkgoT().Context() - ds = &tests.MockDataStore{} + ds = persistence.New(db.Db()) auth.Init(ds) api = &Router{ds: ds} - radioRepo = tests.CreateMockedRadioRepo() - ds.MockedRadio = radioRepo }) Describe("GetInternetRadios", func() { BeforeEach(func() { - radioRepo.All = model.Radios{ - {ID: "rd-1", Name: "Radio 1", StreamUrl: "http://stream1.example.com", HomePageUrl: "http://home1.example.com", UploadedImage: "rd-1_cover.jpg"}, - {ID: "rd-2", Name: "Radio 2", StreamUrl: "http://stream2.example.com"}, - } + putRadios( + model.Radio{ID: "rd-1", Name: "Radio 1", StreamUrl: "http://stream1.example.com", HomePageUrl: "http://home1.example.com", UploadedImage: "rd-1_cover.jpg"}, + model.Radio{ID: "rd-2", Name: "Radio 2", StreamUrl: "http://stream2.example.com"}, + ) }) It("returns all radios with basic fields", func() { @@ -76,10 +84,12 @@ var _ = Describe("Radio", func() { }) It("suffixes coverArt with the content hash when resolved and omits it when known absent", func() { - radioRepo.All = model.Radios{ - {ID: "rd-1", Name: "Radio 1", UploadedImage: "rd-1_cover.jpg", ImageHash: "0123456789abcdef"}, - {ID: "rd-2", Name: "Radio 2", UploadedImage: "rd-2_cover.jpg", ImageAbsent: true}, - } + putRadios( + model.Radio{ID: "rd-1", Name: "Radio 1", StreamUrl: "http://stream1.example.com", UploadedImage: "rd-1_cover.jpg"}, + model.Radio{ID: "rd-2", Name: "Radio 2", StreamUrl: "http://stream2.example.com", UploadedImage: "rd-2_cover.jpg"}, + ) + putItemArtwork(ctx, ds, model.KindRadioArtwork, "rd-1", "0123456789abcdef") + putItemArtwork(ctx, ds, model.KindRadioArtwork, "rd-2", "") r := httptest.NewRequest(http.MethodGet, "/rest/getInternetRadios", nil) r = r.WithContext(ctx) @@ -145,7 +155,9 @@ var _ = Describe("Radio", func() { }) It("returns error when repository fails", func() { - radioRepo.SetError(true) + api = &Router{ds: persistencetest.Stub(ds, persistencetest.Repos{Radio: func(r model.RadioRepository) model.RadioRepository { + return failingRadioRepo{r} + }})} r := httptest.NewRequest(http.MethodGet, "/rest/getInternetRadios", nil) r = r.WithContext(ctx) @@ -155,3 +167,9 @@ var _ = Describe("Radio", func() { }) }) }) + +type failingRadioRepo struct{ model.RadioRepository } + +func (failingRadioRepo) GetAll(context.Context, ...model.QueryOptions) (model.Radios, error) { + return nil, errors.New("db error") +} diff --git a/server/subsonic/searching_test.go b/server/subsonic/searching_test.go index d1226a520..cdbd9d8b5 100644 --- a/server/subsonic/searching_test.go +++ b/server/subsonic/searching_test.go @@ -1,13 +1,18 @@ package subsonic import ( + "context" "net/http" + "strconv" - "github.com/Masterminds/squirrel" "github.com/navidrome/navidrome/core/auth" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" - "github.com/navidrome/navidrome/tests" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" + "github.com/navidrome/navidrome/server/subsonic/responses" + "github.com/navidrome/navidrome/utils/slice" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) @@ -15,29 +20,49 @@ import ( var _ = Describe("Search", func() { var router *Router var ds model.DataStore - var mockAlbumRepo *tests.MockAlbumRepo - var mockArtistRepo *tests.MockArtistRepo - var mockMediaFileRepo *tests.MockMediaFileRepo + var ctx context.Context BeforeEach(func() { - ds = &tests.MockDataStore{} + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) auth.Init(ds) router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil) - - // Get references to the mock repositories so we can inspect their Options - mockAlbumRepo = ds.Album().(*tests.MockAlbumRepo) - mockArtistRepo = ds.Artist().(*tests.MockArtistRepo) - mockMediaFileRepo = ds.MediaFile().(*tests.MockMediaFileRepo) }) Context("musicFolderId parameter", func() { - assertQueryOptions := func(filter squirrel.Sqlizer, expectedQuery string, expectedArgs ...any) { + // Every library N holds artist ar-N, album al-N and song mf-N, all matching "test". + // user1 can read libraries 1-3; library 4 is someone else's. + BeforeEach(func() { + putUsers(ctx, ds, model.User{ID: "user1", UserName: "testuser"}) + libIDs := persistencetest.SetLibraries(ctx, ds, "/lib1", "/lib2", "/lib3", "/lib4") + Expect(ds.User().SetUserLibraries(ctx, "user1", libIDs[:3])).To(Succeed()) + for _, id := range libIDs { + n := strconv.Itoa(id) + putAlbumArtists(ctx, ds, id, model.Artist{ID: "ar-" + n, Name: "Test Artist " + n}) + persistencetest.PutAlbums(ctx, ds, model.Album{ID: "al-" + n, Name: "Test Album " + n, LibraryID: id}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "mf-" + n, Title: "Test Song " + n, LibraryID: id}) + } + }) + + idsFor := func(prefix string, libs []string) []string { + ids := make([]string, len(libs)) + for i, n := range libs { + ids[i] = prefix + n + } + return ids + } + expectResults2 := func(res *responses.SearchResult2, libs ...string) { GinkgoHelper() - query, args, err := filter.ToSql() - Expect(err).ToNot(HaveOccurred()) - Expect(query).To(ContainSubstring(expectedQuery)) - Expect(args).To(ContainElements(expectedArgs...)) + Expect(slice.Map(res.Artist, func(a responses.Artist) string { return a.Id })).To(ConsistOf(idsFor("ar-", libs))) + Expect(slice.Map(res.Album, func(c responses.Child) string { return c.Id })).To(ConsistOf(idsFor("al-", libs))) + Expect(slice.Map(res.Song, func(c responses.Child) string { return c.Id })).To(ConsistOf(idsFor("mf-", libs))) + } + expectResults3 := func(res *responses.SearchResult3, libs ...string) { + GinkgoHelper() + Expect(slice.Map(res.Artist, func(a responses.ArtistID3) string { return a.Id })).To(ConsistOf(idsFor("ar-", libs))) + Expect(slice.Map(res.Album, func(a responses.AlbumID3) string { return a.Id })).To(ConsistOf(idsFor("al-", libs))) + Expect(slice.Map(res.Song, func(c responses.Child) string { return c.Id })).To(ConsistOf(idsFor("mf-", libs))) } Describe("Search2", func() { @@ -61,9 +86,7 @@ var _ = Describe("Search", func() { Expect(resp).ToNot(BeNil()) Expect(resp.SearchResult2).ToNot(BeNil()) - assertQueryOptions(mockAlbumRepo.Options.Filters, "library_id IN (?)", 1) - assertQueryOptions(mockMediaFileRepo.Options.Filters, "library_id IN (?)", 1) - assertQueryOptions(mockArtistRepo.Options.Filters, "library_id IN (?)", 1) + expectResults2(resp.SearchResult2, "1") }) It("applies no library filter when musicFolderId is not provided", func() { @@ -85,9 +108,7 @@ var _ = Describe("Search", func() { Expect(resp).ToNot(BeNil()) Expect(resp.SearchResult2).ToNot(BeNil()) - assertQueryOptions(mockAlbumRepo.Options.Filters, "library_id IN (?,?,?)", 1, 2, 3) - assertQueryOptions(mockMediaFileRepo.Options.Filters, "library_id IN (?,?,?)", 1, 2, 3) - assertQueryOptions(mockArtistRepo.Options.Filters, "library_id IN (?,?,?)", 1, 2, 3) + expectResults2(resp.SearchResult2, "1", "2", "3") }) It("should return empty results when user has no accessible libraries", func() { @@ -97,6 +118,7 @@ var _ = Describe("Search", func() { UserName: "testuser", Libraries: []model.Library{}, // No libraries }) + Expect(ds.User().SetUserLibraries(ctx, "user1", nil)).To(Succeed()) r = r.WithContext(ctx) resp, err := router.Search2(r) @@ -104,9 +126,7 @@ var _ = Describe("Search", func() { Expect(err).ToNot(HaveOccurred()) Expect(resp).ToNot(BeNil()) Expect(resp.SearchResult2).ToNot(BeNil()) - Expect(mockAlbumRepo.Options.Filters).To(BeNil()) - Expect(mockArtistRepo.Options.Filters).To(BeNil()) - Expect(mockMediaFileRepo.Options.Filters).To(BeNil()) + expectResults2(resp.SearchResult2) }) It("should return error for inaccessible musicFolderId", func() { @@ -145,9 +165,7 @@ var _ = Describe("Search", func() { Expect(resp).ToNot(BeNil()) Expect(resp.SearchResult3).ToNot(BeNil()) - assertQueryOptions(mockAlbumRepo.Options.Filters, "library_id IN (?)", 1) - assertQueryOptions(mockMediaFileRepo.Options.Filters, "library_id IN (?)", 1) - assertQueryOptions(mockArtistRepo.Options.Filters, "library_id IN (?)", 1) + expectResults3(resp.SearchResult3, "1") }) It("applies no library filter when musicFolderId is not provided", func() { @@ -169,9 +187,7 @@ var _ = Describe("Search", func() { Expect(resp).ToNot(BeNil()) Expect(resp.SearchResult3).ToNot(BeNil()) - assertQueryOptions(mockAlbumRepo.Options.Filters, "library_id IN (?,?,?)", 1, 2, 3) - assertQueryOptions(mockMediaFileRepo.Options.Filters, "library_id IN (?,?,?)", 1, 2, 3) - assertQueryOptions(mockArtistRepo.Options.Filters, "library_id IN (?,?,?)", 1, 2, 3) + expectResults3(resp.SearchResult3, "1", "2", "3") }) It("should return empty results when user has no accessible libraries", func() { @@ -181,6 +197,7 @@ var _ = Describe("Search", func() { UserName: "testuser", Libraries: []model.Library{}, // No libraries }) + Expect(ds.User().SetUserLibraries(ctx, "user1", nil)).To(Succeed()) r = r.WithContext(ctx) resp, err := router.Search3(r) @@ -188,9 +205,7 @@ var _ = Describe("Search", func() { Expect(err).ToNot(HaveOccurred()) Expect(resp).ToNot(BeNil()) Expect(resp.SearchResult3).ToNot(BeNil()) - Expect(mockAlbumRepo.Options.Filters).To(BeNil()) - Expect(mockArtistRepo.Options.Filters).To(BeNil()) - Expect(mockMediaFileRepo.Options.Filters).To(BeNil()) + expectResults3(resp.SearchResult3) }) It("should return error for inaccessible musicFolderId", func() { @@ -219,10 +234,13 @@ var _ = Describe("Search", func() { return r.WithContext(ctx) } + BeforeEach(func() { + putUsers(ctx, ds, model.User{ID: "user1", UserName: "testuser"}) + }) + It("omits coverArt and imageUrl for a known-absent artist", func() { - mockArtistRepo.SetData(model.Artists{ - {ID: "ar-1", Name: "Absent Artist", ImageAbsent: true}, - }) + putAlbumArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Absent Test Artist"}) + putItemArtwork(ctx, ds, model.KindArtistArtwork, "ar-1", "") resp, err := router.Search2(newSearchRequest()) Expect(err).ToNot(HaveOccurred()) Expect(resp.SearchResult2.Artist).To(HaveLen(1)) @@ -231,7 +249,7 @@ var _ = Describe("Search", func() { }) It("emits coverArt and imageUrl for an unresolved artist", func() { - mockArtistRepo.SetData(model.Artists{{ID: "ar-1", Name: "Unresolved Artist"}}) + putAlbumArtists(ctx, ds, model.DefaultLibraryID, model.Artist{ID: "ar-1", Name: "Unresolved Test Artist"}) resp, err := router.Search2(newSearchRequest()) Expect(err).ToNot(HaveOccurred()) Expect(resp.SearchResult2.Artist).To(HaveLen(1)) diff --git a/server/subsonic/transcode_test.go b/server/subsonic/transcode_test.go index 29f9b720a..0849adfe6 100644 --- a/server/subsonic/transcode_test.go +++ b/server/subsonic/transcode_test.go @@ -13,26 +13,28 @@ import ( "github.com/navidrome/navidrome/core/ffmpeg" "github.com/navidrome/navidrome/core/stream" + "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/model/request" + "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/server/subsonic/responses" - "github.com/navidrome/navidrome/tests" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" ) var _ = Describe("Transcode endpoints", func() { var ( - router *Router - ds *tests.MockDataStore - mockTD *mockTranscodeDecision - w *httptest.ResponseRecorder - mockMFRepo *tests.MockMediaFileRepo + ctx context.Context + router *Router + ds model.DataStore + mockTD *mockTranscodeDecision + w *httptest.ResponseRecorder ) BeforeEach(func() { - mockMFRepo = &tests.MockMediaFileRepo{} - ds = &tests.MockDataStore{MockedMediaFile: mockMFRepo} + ctx = GinkgoT().Context() + ds = persistence.New(db.Db()) mockTD = &mockTranscodeDecision{} router = New(ds, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) w = httptest.NewRecorder() @@ -68,7 +70,6 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns ErrorDataNotFound when media file does not exist", func() { - // mockMFRepo has no data set, so Get() returns model.ErrNotFound r := newJSONPostRequest("mediaId=nonexistent&mediaType=song", "{}") _, err := router.GetTranscodeDecision(w, r) Expect(err).To(HaveOccurred()) @@ -76,7 +77,11 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns error when media file retrieval fails", func() { - mockMFRepo.SetError(true) + router = New(persistencetest.Stub(ds, persistencetest.Repos{MediaFile: func(r model.MediaFileRepository) model.MediaFileRepository { + return failingMediaFileGetRepo{r} + }}), + nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFile{ID: "song-1", Suffix: "flac"}) r := newJSONPostRequest("mediaId=song-1&mediaType=song", "{}") _, err := router.GetTranscodeDecision(w, r) Expect(err).To(HaveOccurred()) @@ -84,7 +89,7 @@ var _ = Describe("Transcode endpoints", func() { }) It("enriches the decision error with the reason, without leaking the file path", func() { - mockMFRepo.SetData(model.MediaFiles{{ID: "song-1", Suffix: "flac"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-1", Suffix: "flac"}}...) mockTD.decisionErr = fmt.Errorf("probing media file song-1: %w", &ffmpeg.ProbeError{Path: "/music/secret/foo.flac", Reason: "the file: Invalid data found when processing input"}) r := newJSONPostRequest("mediaId=song-1&mediaType=song", "{}") @@ -99,7 +104,7 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns ErrorDataNotFound when the source file is missing on disk", func() { - mockMFRepo.SetData(model.MediaFiles{{ID: "song-1", Suffix: "flac"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-1", Suffix: "flac"}}...) mockTD.decisionErr = fmt.Errorf("probing media file song-1: %w", &ffmpeg.ProbeError{Path: "/music/gone.flac", Reason: "file not found", NotFound: true}) r := newJSONPostRequest("mediaId=song-1&mediaType=song", "{}") @@ -112,7 +117,7 @@ var _ = Describe("Transcode endpoints", func() { }) It("keeps ErrorGeneric when ffprobe is missing, even though the cause wraps fs.ErrNotExist", func() { - mockMFRepo.SetData(model.MediaFiles{{ID: "song-1", Suffix: "flac"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-1", Suffix: "flac"}}...) pe := &ffmpeg.ProbeError{Path: "/music/song.flac", Reason: "could not read file"} mockTD.decisionErr = fmt.Errorf("probing media file song-1: %w (%w)", pe, fs.ErrNotExist) Expect(errors.Is(mockTD.decisionErr, fs.ErrNotExist)).To(BeTrue()) @@ -201,9 +206,9 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns a valid decision response", func() { - mockMFRepo.SetData(model.MediaFiles{ + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{ {ID: "song-1", Suffix: "mp3", Codec: "MP3", BitRate: 320, Channels: 2, SampleRate: 44100}, - }) + }...) mockTD.decision = &stream.TranscodeDecision{ MediaID: "song-1", CanDirectPlay: true, @@ -229,9 +234,9 @@ var _ = Describe("Transcode endpoints", func() { }) It("filters AAC from transcoding profiles", func() { - mockMFRepo.SetData(model.MediaFiles{ + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{ {ID: "song-1", Suffix: "opus", Codec: "opus", BitRate: 128, Channels: 2, SampleRate: 48000}, - }) + }...) mockTD.decision = &stream.TranscodeDecision{MediaID: "song-1", CanDirectPlay: true} mockTD.token = "token" @@ -252,9 +257,9 @@ var _ = Describe("Transcode endpoints", func() { }) It("includes transcode stream when transcoding", func() { - mockMFRepo.SetData(model.MediaFiles{ + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{ {ID: "song-2", Suffix: "flac", Codec: "FLAC", BitRate: 1000, Channels: 2, SampleRate: 96000, BitDepth: new(24)}, - }) + }...) mockTD.decision = &stream.TranscodeDecision{ MediaID: "song-2", CanDirectPlay: false, @@ -290,9 +295,9 @@ var _ = Describe("Transcode endpoints", func() { } BeforeEach(func() { - mockMFRepo.SetData(model.MediaFiles{ + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{ {ID: "song-1", Suffix: "flac", Codec: "FLAC", BitRate: 900, Channels: 2, SampleRate: 44100}, - }) + }...) mockTD.decision = &stream.TranscodeDecision{MediaID: "song-1", CanDirectPlay: true} mockTD.token = "token" }) @@ -364,9 +369,9 @@ var _ = Describe("Transcode endpoints", func() { } BeforeEach(func() { - mockMFRepo.SetData(model.MediaFiles{ + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{ {ID: "song-1", Suffix: "flac", Codec: "FLAC", BitRate: 900, Channels: 2, SampleRate: 44100}, - }) + }...) mockTD.decision = &stream.TranscodeDecision{MediaID: "song-1", CanTranscode: true} mockTD.token = "token" }) @@ -480,7 +485,7 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns 410 for invalid or mismatched token", func() { - mockMFRepo.SetData(model.MediaFiles{{ID: "123"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "123"}}...) mockTD.resolveErr = stream.ErrTokenInvalid r := newGetRequest("mediaId=123", "mediaType=song", "transcodeParams=bad-token") resp, err := router.GetTranscodeStream(w, r) @@ -490,7 +495,6 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns 404 when media file not found", func() { - // mockMFRepo has no data, so Get() returns ErrNotFound r := newGetRequest("mediaId=gone-id", "mediaType=song", "transcodeParams=valid-token") resp, err := router.GetTranscodeStream(w, r) Expect(err).ToNot(HaveOccurred()) @@ -499,7 +503,7 @@ var _ = Describe("Transcode endpoints", func() { }) It("returns 410 when media file has changed (stale token)", func() { - mockMFRepo.SetData(model.MediaFiles{{ID: "song-1"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-1"}}...) mockTD.resolveErr = stream.ErrTokenStale r := newGetRequest("mediaId=song-1", "mediaType=song", "transcodeParams=stale-token") resp, err := router.GetTranscodeStream(w, r) @@ -511,7 +515,7 @@ var _ = Describe("Transcode endpoints", func() { It("builds correct StreamRequest for direct play", func() { fakeStreamer := &fakeMediaStreamer{} router = New(ds, nil, fakeStreamer, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) - mockMFRepo.SetData(model.MediaFiles{{ID: "song-1"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-1"}}...) mockTD.resolvedReq = stream.Request{} r := newGetRequest("mediaId=song-1", "mediaType=song", "transcodeParams=valid-token") @@ -528,7 +532,7 @@ var _ = Describe("Transcode endpoints", func() { It("builds correct StreamRequest for transcoding", func() { fakeStreamer := &fakeMediaStreamer{} router = New(ds, nil, fakeStreamer, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) - mockMFRepo.SetData(model.MediaFiles{{ID: "song-2"}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-2"}}...) mockTD.resolvedReq = stream.Request{ Format: "mp3", BitRate: 256, @@ -554,7 +558,7 @@ var _ = Describe("Transcode endpoints", func() { serve := func(method string, newStream func(*model.MediaFile) *stream.Stream, params ...string) { router = New(ds, nil, &fakeMediaStreamer{newStream: newStream}, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, mockTD, nil) - mockMFRepo.SetData(model.MediaFiles{{ID: "song-1", Title: "Song", Duration: 10}}) + persistencetest.PutMediaFiles(ctx, ds, model.MediaFiles{{ID: "song-1", Title: "Song", Duration: 10}}...) mockTD.resolvedReq = stream.Request{Format: "mp3", BitRate: 128} r := newGetRequest(append([]string{"mediaId=song-1", "mediaType=song", "transcodeParams=valid-token"}, params...)...) r.Method = method @@ -715,3 +719,9 @@ func (f *fakeMediaStreamer) NewStream(_ context.Context, mf *model.MediaFile, re } return nil, errStreamCaptured } + +type failingMediaFileGetRepo struct{ model.MediaFileRepository } + +func (failingMediaFileGetRepo) Get(context.Context, string) (*model.MediaFile, error) { + return nil, errors.New("db error") +} diff --git a/tests/harness/harness.go b/tests/harness/harness.go index 52fe417a5..4025b1768 100644 --- a/tests/harness/harness.go +++ b/tests/harness/harness.go @@ -7,7 +7,6 @@ import ( "context" "errors" "io" - "os" "path/filepath" "strings" "testing/fstest" @@ -23,9 +22,9 @@ import ( "github.com/navidrome/navidrome/db" "github.com/navidrome/navidrome/model" "github.com/navidrome/navidrome/persistence" + "github.com/navidrome/navidrome/persistence/persistencetest" "github.com/navidrome/navidrome/scanner" "github.com/navidrome/navidrome/server/events" - "github.com/navidrome/navidrome/tests" "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" //nolint:staticcheck ) @@ -57,7 +56,7 @@ func SetupDB(ctx context.Context, users ...*model.User) *DB { db.Db().SetMaxOpenConns(1) db.Init(ctx) - ds := &tests.MockDataStore{RealDS: persistence.New(db.Db())} + ds := persistence.New(db.Db()) auth.Init(ds) h.Library = model.Library{ID: 1, Name: "Music Library", Path: "fake:///music"} @@ -78,30 +77,10 @@ func SetupDB(ctx context.Context, users ...*model.User) *DB { _, err := s.ScanAll(ctx, true) Expect(err).ToNot(HaveOccurred()) - _, err = db.Db().Exec("PRAGMA wal_checkpoint(TRUNCATE)") - Expect(err).ToNot(HaveOccurred()) - data, err := os.ReadFile(h.FilePath) - Expect(err).ToNot(HaveOccurred()) - Expect(os.WriteFile(h.SnapshotPath, data, 0o600)).To(Succeed()) //nolint:gosec // path derives from TempDir + Expect(persistencetest.Snapshot(h.SnapshotPath)).To(Succeed()) return h } -// ResettableTables lists the tables a per-spec reset may write. FTS shadow tables are excluded: -// their content tables' triggers keep them in sync, and writing them directly corrupts the index. -func ResettableTables() []string { - rows, err := db.Db().Query("SELECT name FROM main.sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '%_fts' AND name NOT LIKE '%_fts_%'") - Expect(err).ToNot(HaveOccurred()) - defer rows.Close() - var tables []string - for rows.Next() { - var name string - Expect(rows.Scan(&name)).To(Succeed()) - tables = append(tables, name) - } - Expect(rows.Err()).To(Succeed()) - return tables -} - // TruncateDB empties every resettable table, leaving the migrated schema in place — for suites // whose specs each build their own library, so the schema is not re-migrated per spec. func TruncateDB(tables []string) { @@ -117,27 +96,9 @@ func TruncateDB(tables []string) { } } -// Restore reloads every table from the golden snapshot via ATTACH DATABASE — much faster than a -// rescan. +// Restore reloads every table from the golden snapshot — much faster than a rescan. func (h *DB) Restore() { - sqlDB := db.Db() - _, err := sqlDB.Exec("PRAGMA foreign_keys = OFF") - Expect(err).ToNot(HaveOccurred()) - _, err = sqlDB.Exec("ATTACH DATABASE ? AS snapshot", h.SnapshotPath) - Expect(err).ToNot(HaveOccurred()) - - for _, table := range ResettableTables() { - // Table names come from sqlite_master, not user input. - _, err = sqlDB.Exec(`DELETE FROM main."` + table + `"`) //nolint:gosec - Expect(err).ToNot(HaveOccurred()) - _, err = sqlDB.Exec(`INSERT INTO main."` + table + `" SELECT * FROM snapshot."` + table + `"`) //nolint:gosec - Expect(err).ToNot(HaveOccurred()) - } - - _, err = sqlDB.Exec("DETACH DATABASE snapshot") - Expect(err).ToNot(HaveOccurred()) - _, err = sqlDB.Exec("PRAGMA foreign_keys = ON") - Expect(err).ToNot(HaveOccurred()) + Expect(persistencetest.RestoreFrom(h.SnapshotPath)).To(Succeed()) } // SpyStreamer captures the Request passed to NewStream and returns a minimal fake stream. diff --git a/tests/mock_album_repo.go b/tests/mock_album_repo.go deleted file mode 100644 index f8100c189..000000000 --- a/tests/mock_album_repo.go +++ /dev/null @@ -1,225 +0,0 @@ -package tests - -import ( - "context" - "errors" - "sync" - "time" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/id" -) - -func CreateMockAlbumRepo() *MockAlbumRepo { - return &MockAlbumRepo{ - Data: make(map[string]*model.Album), - } -} - -type MockAlbumRepo struct { - model.AlbumRepository - Data map[string]*model.Album - All model.Albums - Err bool - Options model.QueryOptions - optionsMu sync.Mutex - SearchQuery string // last query passed to Search - ReassignAnnotationCalls map[string]string // prevID -> newID - CopyAttributesCalls map[string]string // fromID -> toID -} - -func (m *MockAlbumRepo) SetError(err bool) { - m.Err = err -} - -func (m *MockAlbumRepo) SetData(albums model.Albums) { - m.Data = make(map[string]*model.Album, len(albums)) - m.All = albums - for i, a := range m.All { - m.Data[a.ID] = &m.All[i] - } -} - -func (m *MockAlbumRepo) Exists(_ context.Context, id string) (bool, error) { - if m.Err { - return false, errors.New("unexpected error") - } - _, found := m.Data[id] - return found, nil -} - -func (m *MockAlbumRepo) Get(_ context.Context, id string) (*model.Album, error) { - if m.Err { - return nil, errors.New("unexpected error") - } - if d, ok := m.Data[id]; ok { - return d, nil - } - return nil, model.ErrNotFound -} - -func (m *MockAlbumRepo) Put(_ context.Context, al *model.Album) error { - if m.Err { - return errors.New("unexpected error") - } - if al.ID == "" { - al.ID = id.NewRandom() - } - if m.Data == nil { - m.Data = make(map[string]*model.Album) - } - m.Data[al.ID] = al - return nil -} - -func (m *MockAlbumRepo) GetAll(_ context.Context, qo ...model.QueryOptions) (model.Albums, error) { - if len(qo) > 0 { - // Recording the last options is a read-path write, and callers resolve concurrently. - m.optionsMu.Lock() - m.Options = qo[0] - m.optionsMu.Unlock() - } - if m.Err { - return nil, errors.New("unexpected error") - } - return m.All, nil -} - -func (m *MockAlbumRepo) GetCursor(ctx context.Context, qo ...model.QueryOptions) (model.AlbumCursor, error) { - res, err := m.GetAll(ctx, qo...) - if err != nil { - return nil, err - } - return func(yield func(model.Album, error) bool) { - for _, a := range res { - if !yield(a, nil) { - return - } - } - }, nil -} - -func (m *MockAlbumRepo) IncPlayCount(_ context.Context, id string, timestamp time.Time) error { - if m.Err { - return errors.New("unexpected error") - } - if d, ok := m.Data[id]; ok { - d.PlayCount++ - d.PlayDate = ×tamp - return nil - } - return model.ErrNotFound -} -func (m *MockAlbumRepo) CountAll(_ context.Context, _ ...model.QueryOptions) (int64, error) { - return int64(len(m.All)), nil -} - -func (m *MockAlbumRepo) GetTouchedAlbums(_ context.Context, libID int) (model.AlbumCursor, error) { - if m.Err { - return nil, errors.New("unexpected error") - } - return func(yield func(model.Album, error) bool) { - for _, a := range m.Data { - if a.ID == "error" { - if !yield(*a, errors.New("error")) { - break - } - continue - } - if a.LibraryID != libID { - continue - } - if !yield(*a, nil) { - break - } - } - }, nil -} - -func (m *MockAlbumRepo) UpdateExternalInfo(ctx context.Context, album *model.Album) error { - return m.Put(ctx, album) -} - -func (m *MockAlbumRepo) Search(_ context.Context, q string, options ...model.QueryOptions) (model.Albums, error) { - m.SearchQuery = q - if len(options) > 0 { - m.Options = options[0] - } - if m.Err { - return nil, errors.New("unexpected error") - } - // Simple mock implementation - just return all albums for testing - return m.All, nil -} - -// ReassignAnnotation reassigns annotations from one album to another -func (m *MockAlbumRepo) ReassignAnnotation(_ context.Context, prevID string, newID string) error { - if m.Err { - return errors.New("unexpected error") - } - // Mock implementation - track the reassignment calls - if m.ReassignAnnotationCalls == nil { - m.ReassignAnnotationCalls = make(map[string]string) - } - m.ReassignAnnotationCalls[prevID] = newID - return nil -} - -// CopyAttributes copies attributes from one album to another -func (m *MockAlbumRepo) CopyAttributes(_ context.Context, fromID, toID string, columns ...string) error { - if m.Err { - return errors.New("unexpected error") - } - from, ok := m.Data[fromID] - if !ok { - return model.ErrNotFound - } - to, ok := m.Data[toID] - if !ok { - return model.ErrNotFound - } - for _, col := range columns { - switch col { - case "created_at": - to.CreatedAt = from.CreatedAt - } - } - if m.CopyAttributesCalls == nil { - m.CopyAttributesCalls = make(map[string]string) - } - m.CopyAttributesCalls[fromID] = toID - return nil -} - -// SetRating sets the rating for an album -func (m *MockAlbumRepo) SetRating(_ context.Context, rating int, itemID string) error { - if m.Err { - return errors.New("unexpected error") - } - if d, ok := m.Data[itemID]; ok { - d.Rating = rating - } - return nil -} - -// SetStar sets the starred status for albums -func (m *MockAlbumRepo) SetStar(_ context.Context, starred bool, itemIDs ...string) error { - if m.Err { - return errors.New("unexpected error") - } - for _, id := range itemIDs { - if d, ok := m.Data[id]; ok { - d.Starred = starred - } - } - return nil -} - -func (m *MockAlbumRepo) GetYears(_ context.Context, libraryIDs ...int) ([]int, error) { - if m.Err { - return nil, errors.New("error") - } - return []int{}, nil -} - -var _ model.AlbumRepository = (*MockAlbumRepo)(nil) diff --git a/tests/mock_artist_repo.go b/tests/mock_artist_repo.go deleted file mode 100644 index 0161279fd..000000000 --- a/tests/mock_artist_repo.go +++ /dev/null @@ -1,203 +0,0 @@ -package tests - -import ( - "context" - "errors" - "time" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/id" -) - -func CreateMockArtistRepo() *MockArtistRepo { - return &MockArtistRepo{ - Data: make(map[string]*model.Artist), - } -} - -type MockArtistRepo struct { - model.ArtistRepository - Data map[string]*model.Artist - Err bool - Options model.QueryOptions -} - -func (m *MockArtistRepo) SetError(err bool) { - m.Err = err -} - -func (m *MockArtistRepo) SetData(artists model.Artists) { - m.Data = make(map[string]*model.Artist) - for i, a := range artists { - m.Data[a.ID] = &artists[i] - } -} - -func (m *MockArtistRepo) Exists(_ context.Context, id string) (bool, error) { - if m.Err { - return false, errors.New("error") - } - _, found := m.Data[id] - return found, nil -} - -func (m *MockArtistRepo) Get(_ context.Context, id string) (*model.Artist, error) { - if m.Err { - return nil, errors.New("error") - } - if d, ok := m.Data[id]; ok { - return d, nil - } - return nil, model.ErrNotFound -} - -func (m *MockArtistRepo) Put(_ context.Context, ar *model.Artist, columsToUpdate ...string) error { - if m.Err { - return errors.New("error") - } - if ar.ID == "" { - ar.ID = id.NewRandom() - } - if m.Data == nil { - m.Data = make(map[string]*model.Artist) - } - m.Data[ar.ID] = ar - return nil -} - -func (m *MockArtistRepo) IncPlayCount(_ context.Context, id string, timestamp time.Time) error { - if m.Err { - return errors.New("error") - } - if d, ok := m.Data[id]; ok { - d.PlayCount++ - d.PlayDate = ×tamp - return nil - } - return model.ErrNotFound -} - -func (m *MockArtistRepo) SetStar(_ context.Context, starred bool, itemIDs ...string) error { - if m.Err { - return errors.New("error") - } - for _, id := range itemIDs { - if d, ok := m.Data[id]; ok { - d.Starred = starred - } - } - return nil -} - -func (m *MockArtistRepo) SetRating(_ context.Context, rating int, itemID string) error { - if m.Err { - return errors.New("error") - } - if d, ok := m.Data[itemID]; ok { - d.Rating = rating - } - return nil -} - -func (m *MockArtistRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Artists, error) { - if len(options) > 0 { - m.Options = options[0] - } - if m.Err { - return nil, errors.New("mock repo error") - } - var allArtists model.Artists - for _, artist := range m.Data { - allArtists = append(allArtists, *artist) - } - // Apply Max=1 if present (simple simulation for findArtistByName) - if len(options) > 0 && options[0].Max == 1 && len(allArtists) > 0 { - return allArtists[:1], nil - } - return allArtists, nil -} - -func (m *MockArtistRepo) GetCursor(ctx context.Context, options ...model.QueryOptions) (model.ArtistCursor, error) { - res, err := m.GetAll(ctx, options...) - if err != nil { - return nil, err - } - return func(yield func(model.Artist, error) bool) { - for _, a := range res { - if !yield(a, nil) { - return - } - } - }, nil -} - -func (m *MockArtistRepo) UpdateExternalInfo(ctx context.Context, artist *model.Artist) error { - return m.Put(ctx, artist) -} - -func (m *MockArtistRepo) RefreshStats(_ context.Context, allArtists bool) (int64, error) { - if m.Err { - return 0, errors.New("mock repo error") - } - return int64(len(m.Data)), nil -} - -func (m *MockArtistRepo) RefreshPlayCounts(_ context.Context) (int64, error) { - if m.Err { - return 0, errors.New("mock repo error") - } - return int64(len(m.Data)), nil -} - -func (m *MockArtistRepo) GetIndex(ctx context.Context, includeMissing bool, libraryIds []int, roles ...model.Role) (model.ArtistIndexes, error) { - if m.Err { - return nil, errors.New("mock repo error") - } - - artists, err := m.GetAll(ctx) - if err != nil { - return nil, err - } - - // For mock purposes, if no artists available, return empty result - if len(artists) == 0 { - return model.ArtistIndexes{}, nil - } - - // Simple index grouping by first letter (simplified implementation for mocks) - indexMap := make(map[string]model.Artists) - for _, artist := range artists { - key := "#" - if len(artist.Name) > 0 { - key = string(artist.Name[0]) - } - indexMap[key] = append(indexMap[key], artist) - } - - var result model.ArtistIndexes - for k, artists := range indexMap { - result = append(result, model.ArtistIndex{ID: k, Artists: artists}) - } - - return result, nil -} - -func (m *MockArtistRepo) CountAll(context.Context, ...model.QueryOptions) (int64, error) { - if m.Err { - return 0, errors.New("mock repo error") - } - return int64(len(m.Data)), nil -} - -func (m *MockArtistRepo) Search(ctx context.Context, q string, options ...model.QueryOptions) (model.Artists, error) { - if len(options) > 0 { - m.Options = options[0] - } - if m.Err { - return nil, errors.New("unexpected error") - } - // Simple mock implementation - just return all artists for testing - return m.GetAll(ctx) -} - -var _ model.ArtistRepository = (*MockArtistRepo)(nil) diff --git a/tests/mock_artwork_queue_repo.go b/tests/mock_artwork_queue_repo.go deleted file mode 100644 index c6a7917f0..000000000 --- a/tests/mock_artwork_queue_repo.go +++ /dev/null @@ -1,364 +0,0 @@ -package tests - -import ( - "cmp" - "context" - "slices" - "sync" - "time" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/utils/slice" -) - -type MockArtworkQueueRepo struct { - model.ArtworkQueueRepository - // mu guards Data: the worker drains this mock concurrently. - mu sync.Mutex - Data map[string]model.ArtworkQueueItem // keyed by iaKey(kind, id, imageType) - Err error - // ItemArtworkSource, when set, backs the set-difference insert with real item_artwork state. - ItemArtworkSource *MockArtworkRepo - // ExistingIDs is keyed by item_kind; a nil per-kind map means PurgeDangling keeps that kind. - ExistingIDs map[string]map[string]bool -} - -func CreateMockArtworkQueueRepo() *MockArtworkQueueRepo { - return &MockArtworkQueueRepo{Data: map[string]model.ArtworkQueueItem{}} -} - -func (m *MockArtworkQueueRepo) Get(_ context.Context, kind model.Kind, id, imageType string) (*model.ArtworkQueueItem, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - it, ok := m.Data[iaKey(kind.Prefix(), id, imageType)] - if !ok { - return nil, model.ErrNotFound - } - return &it, nil -} - -func (m *MockArtworkQueueRepo) Enqueue(_ context.Context, items ...model.ArtworkQueueItem) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - m.enqueueLocked(items) - return nil -} - -func (m *MockArtworkQueueRepo) enqueueLocked(items []model.ArtworkQueueItem) { - now := time.Now() - for _, it := range items { - if it.ImageType == "" { - it.ImageType = model.ImageTypePrimary - } - k := iaKey(it.ItemKind, it.ItemID, it.ImageType) - // Mirror the SQL: retry_at/enqueued_at are server-set, never taken from the caller. - if prev, ok := m.Data[k]; ok { - prev.Priority = max(prev.Priority, it.Priority) - prev.RetryAt = now - prev.Attempts = 0 - prev.EnqueuedAt = now - m.Data[k] = prev - continue - } - it.Attempts = 0 - it.RetryAt = now - it.EnqueuedAt = now - m.Data[k] = it - } -} - -// EnqueueIfMissing mirrors the SQL anti-join: skip anything that already has an item_artwork row. -func (m *MockArtworkQueueRepo) EnqueueIfMissing(_ context.Context, items ...model.ArtworkQueueItem) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - var fresh []model.ArtworkQueueItem - for _, it := range items { - k := iaKey(it.ItemKind, it.ItemID, cmp.Or(it.ImageType, model.ImageTypePrimary)) - if m.ItemArtworkSource != nil { - if _, ok := m.ItemArtworkSource.ItemData[k]; ok { - continue - } - } - if _, ok := m.Data[k]; ok { // DO NOTHING - continue - } - fresh = append(fresh, it) - } - m.enqueueLocked(fresh) - return nil -} - -func (m *MockArtworkQueueRepo) DequeueBatch(_ context.Context, n int, kinds ...string) ([]model.ArtworkQueueItem, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - var res []model.ArtworkQueueItem - now := time.Now() - for _, it := range m.Data { - if !it.RetryAt.After(now) && (len(kinds) == 0 || slices.Contains(kinds, it.ItemKind)) { - res = append(res, it) - } - } - slices.SortFunc(res, func(a, b model.ArtworkQueueItem) int { - return cmp.Or(cmp.Compare(b.Priority, a.Priority), a.EnqueuedAt.Compare(b.EnqueuedAt)) - }) - if len(res) > n { - res = res[:n] - } - return res, nil -} - -func (m *MockArtworkQueueRepo) MarkFailedIfUnchanged(_ context.Context, kind, id, imageType string, seenRetryAt, retryAt time.Time, trace string) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - k := iaKey(kind, id, imageType) - if it, ok := m.Data[k]; ok && it.RetryAt.Equal(seenRetryAt) { - it.Attempts++ - it.RetryAt = retryAt - it.Trace = trace - m.Data[k] = it - } - return nil -} - -func (m *MockArtworkQueueRepo) DeleteIfUnchanged(_ context.Context, kind, id, imageType string, retryAt time.Time) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - k := iaKey(kind, id, imageType) - if it, ok := m.Data[k]; ok && it.RetryAt.Equal(retryAt) { - delete(m.Data, k) - } - return nil -} - -func (m *MockArtworkQueueRepo) PurgeDangling(context.Context) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - var purged int64 - for k, it := range m.Data { - existing := m.ExistingIDs[it.ItemKind] - if existing == nil { - continue - } - if !existing[it.ItemID] { - delete(m.Data, k) - purged++ - } - } - return purged, nil -} - -// queueFilterMatches mirrors artworkQueueFilter, so the mock cannot let a preview and a delete disagree. -func queueFilterMatches(it model.ArtworkQueueItem, kinds []model.Kind, priorities []int) bool { - prefixes := model.KindPrefixes(kinds) - return (len(prefixes) == 0 || slices.Contains(prefixes, it.ItemKind)) && - (len(priorities) == 0 || slices.Contains(priorities, it.Priority)) -} - -func (m *MockArtworkQueueRepo) PurgeQueued(_ context.Context, kinds []model.Kind, priorities []int) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - var purged int64 - for k, it := range m.Data { - if !queueFilterMatches(it, kinds, priorities) { - continue - } - delete(m.Data, k) - purged++ - } - return purged, nil -} - -func (m *MockArtworkQueueRepo) Count(context.Context) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - return int64(len(m.Data)), nil -} - -func (m *MockArtworkQueueRepo) CountQueued(_ context.Context, kinds []model.Kind, priorities []int) ([]model.ArtworkQueueStat, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - var res []model.ArtworkQueueStat - for _, it := range m.Data { - if !queueFilterMatches(it, kinds, priorities) { - continue - } - i := slices.IndexFunc(res, func(s model.ArtworkQueueStat) bool { - return s.ItemKind == it.ItemKind && s.Priority == it.Priority - }) - if i < 0 { - res = append(res, model.ArtworkQueueStat{ItemKind: it.ItemKind, Priority: it.Priority, Count: 1}) - continue - } - res[i].Count++ - } - slices.SortFunc(res, func(a, b model.ArtworkQueueStat) int { - return cmp.Or(cmp.Compare(a.ItemKind, b.ItemKind), cmp.Compare(b.Priority, a.Priority)) - }) - return res, nil -} - -func (m *MockArtworkQueueRepo) EnqueuePreservingBackoff(_ context.Context, items ...model.ArtworkQueueItem) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - now := time.Now() - for _, it := range items { - if it.ImageType == "" { - it.ImageType = model.ImageTypePrimary - } - k := iaKey(it.ItemKind, it.ItemID, it.ImageType) - // Preserve an existing row's retry_at: a bump raises priority without resetting backoff. - if prev, ok := m.Data[k]; ok { - prev.Priority = max(prev.Priority, it.Priority) - m.Data[k] = prev - continue - } - it.Attempts = 0 - it.RetryAt = now - it.EnqueuedAt = now - m.Data[k] = it - } - return nil -} - -// matchingSource mirrors the SQL filter: no sources means every source, "" the absent state, and -// ArtworkSourceFailed the absent states that gave up. -func (m *MockArtworkQueueRepo) matchingSource(kind model.Kind, sources []string) []model.ItemArtwork { - if m.ItemArtworkSource == nil { - return nil - } - matches := func(ia model.ItemArtwork) bool { - if len(sources) == 0 { - return true - } - if slices.Contains(sources, ia.Source) { - return true - } - return slices.Contains(sources, model.ArtworkSourceFailed) && ia.Hash == "" && ia.LastFailure != "" - } - var res []model.ItemArtwork - for _, ia := range m.ItemArtworkSource.ItemData { - if ia.ItemKind == kind.Prefix() && matches(ia) { - res = append(res, ia) - } - } - return res -} - -func (m *MockArtworkQueueRepo) CountBySource(_ context.Context, kind model.Kind, sources []string) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - return int64(len(m.matchingSource(kind, sources))), nil -} - -func (m *MockArtworkQueueRepo) SourcesInUse(_ context.Context, kind model.Kind) ([]string, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - sources := slice.Map(m.matchingSource(kind, nil), func(ia model.ItemArtwork) string { return ia.Source }) - return slice.Unique(sources), nil -} - -func (m *MockArtworkQueueRepo) EnqueueBySource(_ context.Context, kind model.Kind, sources []string, priority int) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - now := time.Now() - var inserted int64 - for _, ia := range m.matchingSource(kind, sources) { - k := iaKey(ia.ItemKind, ia.ItemID, ia.ImageType) - if _, ok := m.Data[k]; ok { // DO NOTHING: never touch existing queue rows - continue - } - m.Data[k] = model.ArtworkQueueItem{ - ItemKind: ia.ItemKind, - ItemID: ia.ItemID, - ImageType: ia.ImageType, - Priority: priority, - RetryAt: now, - EnqueuedAt: now, - } - inserted++ - } - return inserted, nil -} - -// EnqueueAllMissing mirrors the SQL set-difference insert: ExistingIDs[kind] minus ItemArtworkSource. -func (m *MockArtworkQueueRepo) EnqueueAllMissing(_ context.Context, kind model.Kind, priority int) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - hasRow := func(id string) bool { - if m.ItemArtworkSource == nil { - return false - } - for _, ia := range m.ItemArtworkSource.ItemData { - if ia.ItemKind == kind.Prefix() && ia.ItemID == id { - return true - } - } - return false - } - now := time.Now() - var inserted int64 - for id := range m.ExistingIDs[kind.Prefix()] { - if hasRow(id) { - continue - } - k := iaKey(kind.Prefix(), id, model.ImageTypePrimary) - if _, ok := m.Data[k]; ok { // DO NOTHING: never touch existing queue rows - continue - } - m.Data[k] = model.ArtworkQueueItem{ - ItemKind: kind.Prefix(), - ItemID: id, - ImageType: model.ImageTypePrimary, - Priority: priority, - RetryAt: now, - EnqueuedAt: now, - } - inserted++ - } - return inserted, nil -} diff --git a/tests/mock_artwork_repo.go b/tests/mock_artwork_repo.go deleted file mode 100644 index 350c0e9f6..000000000 --- a/tests/mock_artwork_repo.go +++ /dev/null @@ -1,190 +0,0 @@ -package tests - -import ( - "context" - "maps" - "sync" - "time" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/utils/slice" -) - -type MockArtworkRepo struct { - model.ArtworkRepository - // mu guards the maps so the worker's concurrent drain can hit this mock race-free. - mu sync.Mutex - Data map[string]model.Artwork - ItemData map[string]model.ItemArtwork // keyed by iaKey(kind, id, imageType) - Err error - // ExistingIDs, keyed by item_kind, backs PurgeDanglingItems; nil map keeps everything. - ExistingIDs map[string]map[string]bool -} - -func CreateMockArtworkRepo() *MockArtworkRepo { - return &MockArtworkRepo{Data: map[string]model.Artwork{}, ItemData: map[string]model.ItemArtwork{}} -} - -func iaKey(kind, id, imageType string) string { return kind + "|" + id + "|" + imageType } - -func (m *MockArtworkRepo) GetImage(_ context.Context, hash string) (*model.Artwork, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - if a, ok := m.Data[hash]; ok { - return &a, nil - } - return nil, model.ErrNotFound -} - -func (m *MockArtworkRepo) PutImage(_ context.Context, a *model.Artwork) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - // Mirrors the SQL repository: every upsert refreshes created_at. Age fixtures via Data directly. - a.CreatedAt = time.Now() - m.Data[a.Hash] = *a - return nil -} - -func (m *MockArtworkRepo) GetMimeByHash(context.Context) (map[string]string, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - mimes := make(map[string]string, len(m.Data)) - for h, a := range m.Data { - mimes[h] = a.Mime - } - return mimes, nil -} - -func (m *MockArtworkRepo) PurgeDanglingItems(context.Context) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - var purged int64 - for k, ia := range m.ItemData { - // A nil per-kind map means that kind isn't tracked by the test, so keep it. - existing := m.ExistingIDs[ia.ItemKind] - if existing == nil { - continue - } - if !existing[ia.ItemID] { - delete(m.ItemData, k) - purged++ - } - } - return purged, nil -} - -func (m *MockArtworkRepo) PurgeOrphans(_ context.Context, createdBefore time.Time) (int64, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return 0, m.Err - } - var deleted int64 - for h, a := range m.Data { - if m.referenced(h) || !a.CreatedAt.Before(createdBefore) { - continue - } - delete(m.Data, h) - deleted++ - } - return deleted, nil -} - -func (m *MockArtworkRepo) referenced(hash string) bool { - for _, ia := range m.ItemData { - if ia.Hash == hash { - return true - } - } - return false -} - -func (m *MockArtworkRepo) GetItemArtwork(_ context.Context, kind model.Kind, id, imageType string) (*model.ItemArtwork, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - if ia, ok := m.ItemData[iaKey(kind.Prefix(), id, imageType)]; ok { - return &ia, nil - } - return nil, model.ErrNotFound -} - -func (m *MockArtworkRepo) PutLastFailure(_ context.Context, kind model.Kind, id, imageType, trace string) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - key := iaKey(kind.Prefix(), id, imageType) - if ia, ok := m.ItemData[key]; ok { - ia.LastFailure = trace - m.ItemData[key] = ia - } - return nil -} - -func (m *MockArtworkRepo) PutItemArtwork(_ context.Context, ia *model.ItemArtwork) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - if ia.ImageType == "" { - ia.ImageType = model.ImageTypePrimary - } - ia.UpdatedAt = time.Now() - if ia.AttemptedAt.IsZero() { - ia.AttemptedAt = ia.UpdatedAt - } - m.ItemData[iaKey(ia.ItemKind, ia.ItemID, ia.ImageType)] = *ia - return nil -} - -func (m *MockArtworkRepo) DeleteForItems(_ context.Context, kind model.Kind, ids []string) error { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return m.Err - } - idSet := slice.ToSet(ids) - maps.DeleteFunc(m.ItemData, func(_ string, ia model.ItemArtwork) bool { - _, ok := idSet[ia.ItemID] - return ok && ia.ItemKind == kind.Prefix() - }) - return nil -} - -func (m *MockArtworkRepo) GetInfoForItems(_ context.Context, kind model.Kind, ids []string) (map[string]model.ItemArtworkInfo, error) { - m.mu.Lock() - defer m.mu.Unlock() - if m.Err != nil { - return nil, m.Err - } - res := map[string]model.ItemArtworkInfo{} - for _, id := range ids { - if ia, ok := m.ItemData[iaKey(kind.Prefix(), id, model.ImageTypePrimary)]; ok { - info := model.ItemArtworkInfo{ItemID: id, Hash: ia.Hash} - if a, ok := m.Data[ia.Hash]; ok { - info.BlurHash, info.ThumbHash = a.BlurHash, a.ThumbHash - info.DominantColor = a.DominantColor - info.Width, info.Height = a.Width, a.Height - } - res[id] = info - } - } - return res, nil -} diff --git a/tests/mock_data_store.go b/tests/mock_data_store.go deleted file mode 100644 index a5e4126cf..000000000 --- a/tests/mock_data_store.go +++ /dev/null @@ -1,342 +0,0 @@ -package tests - -import ( - "context" - "sync" - - "github.com/navidrome/navidrome/model" -) - -type MockDataStore struct { - RealDS model.DataStore - MockedLibrary model.LibraryRepository - MockedFolder model.FolderRepository - MockedGenre model.GenreRepository - MockedAlbum model.AlbumRepository - MockedArtist model.ArtistRepository - MockedMediaFile model.MediaFileRepository - MockedTag model.TagRepository - MockedUser model.UserRepository - MockedProperty model.PropertyRepository - MockedPlayer model.PlayerRepository - MockedPlaylist model.PlaylistRepository - MockedPlayQueue model.PlayQueueRepository - MockedShare model.ShareRepository - MockedTranscoding model.TranscodingRepository - MockedUserProps model.UserPropsRepository - MockedScrobbleBuffer model.ScrobbleBufferRepository - MockedScrobble model.ScrobbleRepository - MockedRadio model.RadioRepository - MockedPlugin model.PluginRepository - MockedArtwork model.ArtworkRepository - MockedArtworkQueue model.ArtworkQueueRepository - scrobbleBufferMu sync.Mutex - repoMu sync.Mutex - - // GC tracking - GCCalled bool - GCError error -} - -func (db *MockDataStore) Library() model.LibraryRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedLibrary != nil { - return db.MockedLibrary - } - if db.RealDS != nil { - return db.RealDS.Library() - } - db.MockedLibrary = &MockLibraryRepo{} - return db.MockedLibrary -} - -func (db *MockDataStore) Folder() model.FolderRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedFolder != nil { - return db.MockedFolder - } - if db.RealDS != nil { - return db.RealDS.Folder() - } - db.MockedFolder = struct{ model.FolderRepository }{} - return db.MockedFolder -} - -func (db *MockDataStore) Tag() model.TagRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedTag != nil { - return db.MockedTag - } - if db.RealDS != nil { - return db.RealDS.Tag() - } - db.MockedTag = &MockTagRepo{} - return db.MockedTag -} - -func (db *MockDataStore) Album() model.AlbumRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedAlbum != nil { - return db.MockedAlbum - } - if db.RealDS != nil { - return db.RealDS.Album() - } - db.MockedAlbum = CreateMockAlbumRepo() - return db.MockedAlbum -} - -func (db *MockDataStore) Artist() model.ArtistRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedArtist != nil { - return db.MockedArtist - } - if db.RealDS != nil { - return db.RealDS.Artist() - } - db.MockedArtist = CreateMockArtistRepo() - return db.MockedArtist -} - -func (db *MockDataStore) MediaFile() model.MediaFileRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.RealDS != nil && db.MockedMediaFile == nil { - return db.RealDS.MediaFile() - } - if db.MockedMediaFile == nil { - db.MockedMediaFile = CreateMockMediaFileRepo() - } - return db.MockedMediaFile -} - -func (db *MockDataStore) Genre() model.GenreRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedGenre != nil { - return db.MockedGenre - } - if db.RealDS != nil { - return db.RealDS.Genre() - } - db.MockedGenre = &MockedGenreRepo{} - return db.MockedGenre -} - -func (db *MockDataStore) Playlist() model.PlaylistRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedPlaylist != nil { - return db.MockedPlaylist - } - if db.RealDS != nil { - return db.RealDS.Playlist() - } - db.MockedPlaylist = CreateMockPlaylistRepo() - return db.MockedPlaylist -} - -func (db *MockDataStore) PlayQueue() model.PlayQueueRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedPlayQueue != nil { - return db.MockedPlayQueue - } - if db.RealDS != nil { - return db.RealDS.PlayQueue() - } - db.MockedPlayQueue = &MockPlayQueueRepo{} - return db.MockedPlayQueue -} - -func (db *MockDataStore) UserProps() model.UserPropsRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedUserProps != nil { - return db.MockedUserProps - } - if db.RealDS != nil { - return db.RealDS.UserProps() - } - db.MockedUserProps = &MockedUserPropsRepo{} - return db.MockedUserProps -} - -func (db *MockDataStore) Property() model.PropertyRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedProperty != nil { - return db.MockedProperty - } - if db.RealDS != nil { - return db.RealDS.Property() - } - db.MockedProperty = &MockedPropertyRepo{} - return db.MockedProperty -} - -func (db *MockDataStore) Share() model.ShareRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedShare != nil { - return db.MockedShare - } - if db.RealDS != nil { - return db.RealDS.Share() - } - db.MockedShare = &MockShareRepo{} - return db.MockedShare -} - -func (db *MockDataStore) User() model.UserRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedUser != nil { - return db.MockedUser - } - if db.RealDS != nil { - return db.RealDS.User() - } - db.MockedUser = CreateMockUserRepo() - return db.MockedUser -} - -func (db *MockDataStore) Transcoding() model.TranscodingRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedTranscoding != nil { - return db.MockedTranscoding - } - if db.RealDS != nil { - return db.RealDS.Transcoding() - } - db.MockedTranscoding = struct{ model.TranscodingRepository }{} - return db.MockedTranscoding -} - -func (db *MockDataStore) Player() model.PlayerRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedPlayer != nil { - return db.MockedPlayer - } - if db.RealDS != nil { - return db.RealDS.Player() - } - db.MockedPlayer = CreateMockPlayerRepo() - return db.MockedPlayer -} - -func (db *MockDataStore) ScrobbleBuffer() model.ScrobbleBufferRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.RealDS != nil && db.MockedScrobbleBuffer == nil { - return db.RealDS.ScrobbleBuffer() - } - db.scrobbleBufferMu.Lock() - defer db.scrobbleBufferMu.Unlock() - if db.MockedScrobbleBuffer == nil { - db.MockedScrobbleBuffer = &MockedScrobbleBufferRepo{} - } - return db.MockedScrobbleBuffer -} - -func (db *MockDataStore) Scrobble() model.ScrobbleRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedScrobble != nil { - return db.MockedScrobble - } - if db.RealDS != nil { - return db.RealDS.Scrobble() - } - db.MockedScrobble = &MockScrobbleRepo{} - return db.MockedScrobble -} - -func (db *MockDataStore) Radio() model.RadioRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedRadio != nil { - return db.MockedRadio - } - if db.RealDS != nil { - return db.RealDS.Radio() - } - db.MockedRadio = CreateMockedRadioRepo() - return db.MockedRadio -} - -func (db *MockDataStore) Plugin() model.PluginRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedPlugin != nil { - return db.MockedPlugin - } - if db.RealDS != nil { - return db.RealDS.Plugin() - } - db.MockedPlugin = CreateMockPluginRepo() - return db.MockedPlugin -} - -func (db *MockDataStore) Artwork() model.ArtworkRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - return db.artworkLocked() -} - -// artworkLocked is the body of Artwork for callers already holding repoMu; repoMu is a plain -// Mutex, so re-entering through the exported method would deadlock. -func (db *MockDataStore) artworkLocked() model.ArtworkRepository { - if db.MockedArtwork != nil { - return db.MockedArtwork - } - if db.RealDS != nil { - return db.RealDS.Artwork() - } - db.MockedArtwork = CreateMockArtworkRepo() - return db.MockedArtwork -} - -func (db *MockDataStore) ArtworkQueue() model.ArtworkQueueRepository { - db.repoMu.Lock() - defer db.repoMu.Unlock() - if db.MockedArtworkQueue != nil { - return db.MockedArtworkQueue - } - if db.RealDS != nil { - return db.RealDS.ArtworkQueue() - } - q := CreateMockArtworkQueueRepo() - if aw, ok := db.artworkLocked().(*MockArtworkRepo); ok { - q.ItemArtworkSource = aw - } - db.MockedArtworkQueue = q - return db.MockedArtworkQueue -} - -func (db *MockDataStore) WithTx(block func(tx model.DataStore) error, label ...string) error { - return block(db) -} - -func (db *MockDataStore) WithTxImmediate(block func(tx model.DataStore) error, label ...string) error { - return block(db) -} - -func (db *MockDataStore) WithTxRetry(ctx context.Context, block func(ctx context.Context, tx model.DataStore) error, label ...string) error { - return block(ctx, db) -} - -func (db *MockDataStore) GC(context.Context, ...int) error { - db.GCCalled = true - if db.GCError != nil { - return db.GCError - } - return nil -} diff --git a/tests/mock_genre_repo.go b/tests/mock_genre_repo.go deleted file mode 100644 index 917e2c626..000000000 --- a/tests/mock_genre_repo.go +++ /dev/null @@ -1,74 +0,0 @@ -package tests - -import ( - "context" - - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" -) - -type MockedGenreRepo struct { - Error error - Data map[string]model.Genre - Options model.QueryOptions -} - -func (r *MockedGenreRepo) init() { - if r.Data == nil { - r.Data = make(map[string]model.Genre) - } -} - -func (r *MockedGenreRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Genres, error) { - if len(options) > 0 { - r.Options = options[0] - } - if r.Error != nil { - return nil, r.Error - } - r.init() - - var all model.Genres - for _, g := range r.Data { - all = append(all, g) - } - return all, nil -} - -func (r *MockedGenreRepo) Get(_ context.Context, id string) (*model.Genre, error) { - if r.Error != nil { - return nil, r.Error - } - r.init() - if g, ok := r.Data[id]; ok { - return &g, nil - } - return nil, model.ErrNotFound -} - -func (r *MockedGenreRepo) Put(g *model.Genre) error { - if r.Error != nil { - return r.Error - } - r.init() - r.Data[g.ID] = *g - return nil -} - -func (r *MockedGenreRepo) Count(context.Context, ...rest.QueryOptions) (int64, error) { - if r.Error != nil { - return 0, r.Error - } - r.init() - return int64(len(r.Data)), nil -} - -func (r *MockedGenreRepo) Read(ctx context.Context, id string) (*model.Genre, error) { - return r.Get(ctx, id) -} - -func (r *MockedGenreRepo) ReadAll(ctx context.Context, _ ...rest.QueryOptions) ([]model.Genre, error) { - return r.GetAll(ctx) -} - -var _ model.GenreRepository = (*MockedGenreRepo)(nil) diff --git a/tests/mock_library_repo.go b/tests/mock_library_repo.go deleted file mode 100644 index 6de2b9265..000000000 --- a/tests/mock_library_repo.go +++ /dev/null @@ -1,312 +0,0 @@ -package tests - -import ( - "context" - "errors" - "fmt" - "slices" - "strconv" - - "github.com/Masterminds/squirrel" - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" -) - -type MockLibraryRepo struct { - model.LibraryRepository - Data map[int]model.Library - Err error - PutFn func(*model.Library) error // Allow custom Put behavior for testing - PutCols []string -} - -func (m *MockLibraryRepo) SetData(data model.Libraries) { - m.Data = make(map[int]model.Library) - for _, d := range data { - m.Data[d.ID] = d - } -} - -func (m *MockLibraryRepo) GetAll(_ context.Context, _ ...model.QueryOptions) (model.Libraries, error) { - if m.Err != nil { - return nil, m.Err - } - var libraries model.Libraries - for _, lib := range m.Data { - libraries = append(libraries, lib) - } - // Sort by ID for predictable order - slices.SortFunc(libraries, func(a, b model.Library) int { - return a.ID - b.ID - }) - return libraries, nil -} - -func (m *MockLibraryRepo) CountAll(_ context.Context, qo ...model.QueryOptions) (int64, error) { - if m.Err != nil { - return 0, m.Err - } - - // If no query options, return total count - if len(qo) == 0 || qo[0].Filters == nil { - return int64(len(m.Data)), nil - } - - // Handle squirrel.Eq filter for ID validation - if eq, ok := qo[0].Filters.(squirrel.Eq); ok { - if idFilter, exists := eq["id"]; exists { - if ids, isSlice := idFilter.([]int); isSlice { - count := 0 - for _, id := range ids { - if _, exists := m.Data[id]; exists { - count++ - } - } - return int64(count), nil - } - } - } - - // Default to total count for other filters - return int64(len(m.Data)), nil -} - -func (m *MockLibraryRepo) Get(_ context.Context, id int) (*model.Library, error) { - if m.Err != nil { - return nil, m.Err - } - if lib, ok := m.Data[id]; ok { - return &lib, nil - } - return nil, model.ErrNotFound -} - -func (m *MockLibraryRepo) GetPath(_ context.Context, id int) (string, error) { - if m.Err != nil { - return "", m.Err - } - if lib, ok := m.Data[id]; ok { - return lib.Path, nil - } - return "", model.ErrNotFound -} - -func (m *MockLibraryRepo) Put(_ context.Context, library *model.Library, colsToUpdate ...string) error { - m.PutCols = colsToUpdate - if m.PutFn != nil { - return m.PutFn(library) - } - if m.Err != nil { - return m.Err - } - if m.Data == nil { - m.Data = make(map[int]model.Library) - } - m.Data[library.ID] = *library - return nil -} - -func (m *MockLibraryRepo) Delete(_ context.Context, id int) error { - if m.Err != nil { - return m.Err - } - if _, ok := m.Data[id]; !ok { - return model.ErrNotFound - } - delete(m.Data, id) - return nil -} - -func (m *MockLibraryRepo) StoreMusicFolder(_ context.Context) error { - if m.Err != nil { - return m.Err - } - return nil -} - -func (m *MockLibraryRepo) AddArtist(_ context.Context, id int, artistID string) error { - if m.Err != nil { - return m.Err - } - return nil -} - -func (m *MockLibraryRepo) ScanBegin(_ context.Context, id int, fullScan bool) error { - if m.Err != nil { - return m.Err - } - return nil -} - -func (m *MockLibraryRepo) ScanEnd(_ context.Context, id int) error { - if m.Err != nil { - return m.Err - } - return nil -} - -func (m *MockLibraryRepo) SetScannedPID(_ context.Context, id int, pid model.PIDConfig) error { - if m.Err != nil { - return m.Err - } - if lib, ok := m.Data[id]; ok { - lib.ScannedPIDAlbum, lib.ScannedPIDTrack = pid.Album, pid.Track - m.Data[id] = lib - } - return nil -} - -func (m *MockLibraryRepo) ScanInProgress(_ context.Context) (bool, error) { - if m.Err != nil { - return false, m.Err - } - return false, nil -} - -func (m *MockLibraryRepo) RefreshStats(_ context.Context, id int) error { - return nil -} - -// User-library association methods - mock implementations - -func (m *MockLibraryRepo) GetUsersWithLibraryAccess(_ context.Context, libraryID int) (model.Users, error) { - if m.Err != nil { - return nil, m.Err - } - // Mock: return empty users for now - return model.Users{}, nil -} - -func (m *MockLibraryRepo) Count(ctx context.Context, _ ...rest.QueryOptions) (int64, error) { - return m.CountAll(ctx) -} - -func (m *MockLibraryRepo) Read(ctx context.Context, id string) (*model.Library, error) { - idInt, _ := strconv.Atoi(id) - return m.Get(ctx, idInt) -} - -func (m *MockLibraryRepo) ReadAll(ctx context.Context, _ ...rest.QueryOptions) ([]model.Library, error) { - return m.GetAll(ctx) -} - -// REST Repository methods (string-based IDs) - -func (m *MockLibraryRepo) Save(_ context.Context, lib *model.Library) (string, error) { - if m.Err != nil { - return "", m.Err - } - - // Validate required fields - if lib.Name == "" { - return "", &rest.ValidationError{Errors: map[string]string{"name": "library name is required"}} - } - if lib.Path == "" { - return "", &rest.ValidationError{Errors: map[string]string{"path": "library path is required"}} - } - - // Generate ID if not set - if lib.ID == 0 { - lib.ID = len(m.Data) + 1 - } - if m.Data == nil { - m.Data = make(map[int]model.Library) - } - m.Data[lib.ID] = *lib - return strconv.Itoa(lib.ID), nil -} - -func (m *MockLibraryRepo) Update(_ context.Context, id string, entity model.Library, _ ...string) error { - lib := &entity - if m.Err != nil { - return m.Err - } - - // Validate required fields - if lib.Name == "" { - return &rest.ValidationError{Errors: map[string]string{"name": "library name is required"}} - } - if lib.Path == "" { - return &rest.ValidationError{Errors: map[string]string{"path": "library path is required"}} - } - - idInt, err := strconv.Atoi(id) - if err != nil { - return errors.New("invalid ID format") - } - if _, exists := m.Data[idInt]; !exists { - return rest.ErrNotFound - } - lib.ID = idInt - m.Data[idInt] = *lib - return nil -} - -func (m *MockLibraryRepo) DeleteByStringID(id string) error { - if m.Err != nil { - return m.Err - } - idInt, err := strconv.Atoi(id) - if err != nil { - return errors.New("invalid ID format") - } - if _, exists := m.Data[idInt]; !exists { - return rest.ErrNotFound - } - delete(m.Data, idInt) - return nil -} - -// Service-level methods for core.Library interface - -func (m *MockLibraryRepo) GetUserLibraries(ctx context.Context, userID string) (model.Libraries, error) { - if m.Err != nil { - return nil, m.Err - } - if userID == "non-existent" { - return nil, model.ErrNotFound - } - // Convert map to slice for return - var libraries model.Libraries - for _, lib := range m.Data { - libraries = append(libraries, lib) - } - // Sort by ID for predictable order - slices.SortFunc(libraries, func(a, b model.Library) int { - return a.ID - b.ID - }) - return libraries, nil -} - -func (m *MockLibraryRepo) SetUserLibraries(ctx context.Context, userID string, libraryIDs []int) error { - if m.Err != nil { - return m.Err - } - if userID == "non-existent" { - return model.ErrNotFound - } - if userID == "admin-1" { - return fmt.Errorf("%w: cannot manually assign libraries to admin users", model.ErrValidation) - } - if len(libraryIDs) == 0 { - return fmt.Errorf("%w: at least one library must be assigned to non-admin users", model.ErrValidation) - } - // Validate all library IDs exist - for _, id := range libraryIDs { - if _, exists := m.Data[id]; !exists { - return fmt.Errorf("%w: library ID %d does not exist", model.ErrValidation, id) - } - } - return nil -} - -func (m *MockLibraryRepo) ValidateLibraryAccess(ctx context.Context, userID string, libraryID int) error { - if m.Err != nil { - return m.Err - } - // For testing purposes, allow access to all libraries - return nil -} - -var _ model.LibraryRepository = (*MockLibraryRepo)(nil) -var _ rest.Repository[model.Library] = (*MockLibraryRepo)(nil) diff --git a/tests/mock_library_service.go b/tests/mock_library_service.go deleted file mode 100644 index f5e1f0387..000000000 --- a/tests/mock_library_service.go +++ /dev/null @@ -1,47 +0,0 @@ -package tests - -import ( - "context" - - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" -) - -// MockLibraryService provides a simple wrapper around MockLibraryRepo -// that implements the core.Library interface for testing. -// Returns concrete type to avoid import cycles - callers assign to core.Library. -type MockLibraryService struct { - *MockLibraryRepo -} - -// MockLibraryRestAdapter adapts MockLibraryRepo to the REST repository interface -type MockLibraryRestAdapter struct { - *MockLibraryRepo -} - -// NewMockLibraryService creates a new mock library service for testing. -// Returns concrete type - assign to core.Library at call site. -func NewMockLibraryService() *MockLibraryService { - repo := &MockLibraryRepo{ - Data: make(map[int]model.Library), - } - // Set up default test data - repo.SetData(model.Libraries{ - {ID: 1, Name: "Test Library 1", Path: "/music/library1"}, - {ID: 2, Name: "Test Library 2", Path: "/music/library2"}, - }) - return &MockLibraryService{MockLibraryRepo: repo} -} - -func (m *MockLibraryService) Repository() rest.Repository[model.Library] { - return &MockLibraryRestAdapter{MockLibraryRepo: m.MockLibraryRepo} -} - -func (a *MockLibraryRestAdapter) Delete(_ context.Context, ids ...string) error { - for _, id := range ids { - if err := a.DeleteByStringID(id); err != nil { - return err - } - } - return nil -} diff --git a/tests/mock_mediafile_repo.go b/tests/mock_mediafile_repo.go deleted file mode 100644 index 954587b92..000000000 --- a/tests/mock_mediafile_repo.go +++ /dev/null @@ -1,392 +0,0 @@ -package tests - -import ( - "cmp" - "context" - "errors" - "maps" - "slices" - "time" - - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/criteria" - "github.com/navidrome/navidrome/model/id" - "github.com/navidrome/navidrome/utils/slice" -) - -func CreateMockMediaFileRepo() *MockMediaFileRepo { - return &MockMediaFileRepo{ - Data: make(map[string]*model.MediaFile), - } -} - -type MockMediaFileRepo struct { - model.MediaFileRepository - Data map[string]*model.MediaFile - Err bool - // Add fields and methods for controlling CountAll and DeleteAllMissing in tests. - // A nil CountAllValue is unset, and CountAll falls back to counting rows in Data. - CountAllValue *int64 - CountAllOptions model.QueryOptions - DeleteAllMissingValue int64 - // ReassignReferencesCalls records prevID -> newID - ReassignReferencesCalls map[string]string - Options model.QueryOptions - // Add fields for cross-library move detection tests - FindRecentFilesByMBZTrackIDFunc func(missing model.MediaFile, since time.Time) (model.MediaFiles, error) - FindRecentFilesByPropertiesFunc func(missing model.MediaFile, since time.Time) (model.MediaFiles, error) - MatchesCriteriaValue bool - MatchesCriteriaErr error - BookmarksAdded []string -} - -func (m *MockMediaFileRepo) SetError(err bool) { - m.Err = err -} - -func (m *MockMediaFileRepo) SetCountAll(count int64) { - m.CountAllValue = &count -} - -func (m *MockMediaFileRepo) SetData(mfs model.MediaFiles) { - m.Data = make(map[string]*model.MediaFile) - for i, mf := range mfs { - m.Data[mf.ID] = &mfs[i] - } -} - -func (m *MockMediaFileRepo) Exists(_ context.Context, id string) (bool, error) { - if m.Err { - return false, errors.New("error") - } - _, found := m.Data[id] - return found, nil -} - -func (m *MockMediaFileRepo) Get(_ context.Context, id string) (*model.MediaFile, error) { - if m.Err { - return nil, errors.New("error") - } - if d, ok := m.Data[id]; ok { - // Intentionally clone the file and remove participants. This should - // catch any caller that actually means to call GetWithParticipants - res := *d - res.Participants = model.Participants{} - return &res, nil - } - return nil, model.ErrNotFound -} - -func (m *MockMediaFileRepo) AddBookmark(_ context.Context, id, _ string, _ int64) error { - if m.Err { - return errors.New("error") - } - m.BookmarksAdded = append(m.BookmarksAdded, id) - return nil -} - -func (m *MockMediaFileRepo) GetWithParticipants(_ context.Context, id string) (*model.MediaFile, error) { - if m.Err { - return nil, errors.New("error") - } - if d, ok := m.Data[id]; ok { - return d, nil - } - return nil, model.ErrNotFound -} - -func (m *MockMediaFileRepo) GetAllByTags(ctx context.Context, _ model.TagName, _ []string, options ...model.QueryOptions) (model.MediaFiles, error) { - return m.GetAll(ctx, options...) -} - -func (m *MockMediaFileRepo) GetAll(_ context.Context, qo ...model.QueryOptions) (model.MediaFiles, error) { - if len(qo) > 0 { - m.Options = qo[0] - } - if m.Err { - return nil, errors.New("error") - } - values := slices.Collect(maps.Values(m.Data)) - result := slice.Map(values, func(p *model.MediaFile) model.MediaFile { - return *p - }) - // Sort by ID to ensure deterministic ordering for tests - slices.SortFunc(result, func(a, b model.MediaFile) int { - return cmp.Compare(a.ID, b.ID) - }) - return result, nil -} - -func (m *MockMediaFileRepo) GetRandom(ctx context.Context, qo ...model.QueryOptions) (model.MediaFiles, error) { - res, err := m.GetAll(ctx, qo...) - if err != nil { - return nil, err - } - if len(qo) > 0 && qo[0].Max > 0 && len(res) > qo[0].Max { - res = res[:qo[0].Max] - } - return res, nil -} - -func (m *MockMediaFileRepo) GetCursor(ctx context.Context, qo ...model.QueryOptions) (model.MediaFileCursor, error) { - res, err := m.GetAll(ctx, qo...) - if err != nil { - return nil, err - } - return func(yield func(model.MediaFile, error) bool) { - for _, mf := range res { - if !yield(mf, nil) { - return - } - } - }, nil -} - -func (m *MockMediaFileRepo) GetCursorWithArtwork(ctx context.Context, qo ...model.QueryOptions) (model.MediaFileCursor, error) { - return m.GetCursor(ctx, qo...) -} - -func (m *MockMediaFileRepo) Put(_ context.Context, mf *model.MediaFile) error { - if m.Err { - return errors.New("error") - } - if mf.ID == "" { - mf.ID = id.NewRandom() - } - m.Data[mf.ID] = mf - return nil -} - -func (m *MockMediaFileRepo) UpdateProbeData(_ context.Context, id string, data string) error { - if m.Err { - return errors.New("error") - } - if d, ok := m.Data[id]; ok { - d.ProbeData = data - return nil - } - return model.ErrNotFound -} - -func (m *MockMediaFileRepo) Delete(_ context.Context, id string) error { - if m.Err { - return errors.New("error") - } - if _, ok := m.Data[id]; !ok { - return model.ErrNotFound - } - delete(m.Data, id) - return nil -} - -func (m *MockMediaFileRepo) ReassignReferences(_ context.Context, prevID, newID string) error { - if m.Err { - return errors.New("error") - } - if m.ReassignReferencesCalls == nil { - m.ReassignReferencesCalls = make(map[string]string) - } - m.ReassignReferencesCalls[prevID] = newID - return nil -} - -func (m *MockMediaFileRepo) IncPlayCount(_ context.Context, id string, timestamp time.Time) error { - if m.Err { - return errors.New("error") - } - if d, ok := m.Data[id]; ok { - d.PlayCount++ - d.PlayDate = ×tamp - return nil - } - return model.ErrNotFound -} - -func (m *MockMediaFileRepo) SetStar(_ context.Context, starred bool, itemIDs ...string) error { - if m.Err { - return errors.New("error") - } - for _, id := range itemIDs { - if d, ok := m.Data[id]; ok { - d.Starred = starred - } - } - return nil -} - -func (m *MockMediaFileRepo) SetRating(_ context.Context, rating int, itemID string) error { - if m.Err { - return errors.New("error") - } - if d, ok := m.Data[itemID]; ok { - d.Rating = rating - } - return nil -} - -func (m *MockMediaFileRepo) FindByAlbum(artistId string) (model.MediaFiles, error) { - if m.Err { - return nil, errors.New("error") - } - var res = make(model.MediaFiles, len(m.Data)) - i := 0 - for _, a := range m.Data { - if a.AlbumID == artistId { - res[i] = *a - i++ - } - } - - return res, nil -} - -func (m *MockMediaFileRepo) GetMissingAndMatching(_ context.Context, libId int) (model.MediaFileCursor, error) { - if m.Err { - return nil, errors.New("error") - } - var res model.MediaFiles - for _, a := range m.Data { - if a.LibraryID == libId && a.Missing { - res = append(res, *a) - } - } - - for _, a := range m.Data { - if a.LibraryID == libId && !(*a).Missing && slices.IndexFunc(res, func(mediaFile model.MediaFile) bool { - return mediaFile.PID == a.PID - }) != -1 { - res = append(res, *a) - } - } - slices.SortFunc(res, func(i, j model.MediaFile) int { - return cmp.Or( - cmp.Compare(i.PID, j.PID), - cmp.Compare(i.ID, j.ID), - ) - }) - - return func(yield func(model.MediaFile, error) bool) { - for _, a := range res { - if !yield(a, nil) { - break - } - } - }, nil -} - -func (m *MockMediaFileRepo) CountAll(_ context.Context, opts ...model.QueryOptions) (int64, error) { - if m.Err { - return 0, errors.New("error") - } - if len(opts) > 0 { - m.CountAllOptions = opts[0] - } - if m.CountAllValue != nil { - return *m.CountAllValue, nil - } - return int64(len(m.Data)), nil -} - -func (m *MockMediaFileRepo) DeleteAllMissing(_ context.Context) (int64, error) { - if m.Err { - return 0, errors.New("error") - } - if m.DeleteAllMissingValue != 0 { - return m.DeleteAllMissingValue, nil - } - // Remove all missing files from Data - var count int64 - for id, mf := range m.Data { - if mf.Missing { - delete(m.Data, id) - count++ - } - } - return count, nil -} - -// REST repository methods - -func (m *MockMediaFileRepo) Count(ctx context.Context, _ ...rest.QueryOptions) (int64, error) { - return m.CountAll(ctx) -} - -func (m *MockMediaFileRepo) Read(ctx context.Context, id string) (*model.MediaFile, error) { - return m.Get(ctx, id) -} - -func (m *MockMediaFileRepo) ReadAll(ctx context.Context, _ ...rest.QueryOptions) ([]model.MediaFile, error) { - return m.GetAll(ctx) -} - -func (m *MockMediaFileRepo) Search(ctx context.Context, q string, options ...model.QueryOptions) (model.MediaFiles, error) { - if len(options) > 0 { - m.Options = options[0] - } - if m.Err { - return nil, errors.New("unexpected error") - } - // Simple mock implementation - just return all media files for testing - return m.GetAll(ctx) -} - -// Cross-library move detection mock methods - -func (m *MockMediaFileRepo) FindRecentFilesByMBZTrackID(_ context.Context, missing model.MediaFile, since time.Time) (model.MediaFiles, error) { - if m.Err { - return nil, errors.New("error") - } - if m.FindRecentFilesByMBZTrackIDFunc != nil { - return m.FindRecentFilesByMBZTrackIDFunc(missing, since) - } - // Default implementation: find files with same MBZ Track ID in other libraries - var result model.MediaFiles - for _, mf := range m.Data { - if mf.LibraryID != missing.LibraryID && - mf.MbzReleaseTrackID == missing.MbzReleaseTrackID && - mf.MbzReleaseTrackID != "" && - mf.Suffix == missing.Suffix && - mf.CreatedAt.After(since) && - !mf.Missing { - result = append(result, *mf) - } - } - return result, nil -} - -func (m *MockMediaFileRepo) FindRecentFilesByProperties(_ context.Context, missing model.MediaFile, since time.Time) (model.MediaFiles, error) { - if m.Err { - return nil, errors.New("error") - } - if m.FindRecentFilesByPropertiesFunc != nil { - return m.FindRecentFilesByPropertiesFunc(missing, since) - } - // Default implementation: find files with same properties in other libraries - var result model.MediaFiles - for _, mf := range m.Data { - if mf.LibraryID != missing.LibraryID && - mf.Title == missing.Title && - mf.Size == missing.Size && - mf.Suffix == missing.Suffix && - mf.DiscNumber == missing.DiscNumber && - mf.TrackNumber == missing.TrackNumber && - mf.Album == missing.Album && - mf.MbzReleaseTrackID == "" && // Exclude files with MBZ Track ID - mf.CreatedAt.After(since) && - !mf.Missing { - result = append(result, *mf) - } - } - return result, nil -} - -func (m *MockMediaFileRepo) MatchesCriteria(context.Context, string, criteria.Criteria) (bool, error) { - if m.MatchesCriteriaErr != nil { - return false, m.MatchesCriteriaErr - } - return m.MatchesCriteriaValue, nil -} - -var _ model.MediaFileRepository = (*MockMediaFileRepo)(nil) -var _ rest.Repository[model.MediaFile] = (*MockMediaFileRepo)(nil) diff --git a/tests/mock_player_repo.go b/tests/mock_player_repo.go deleted file mode 100644 index 56835f0cc..000000000 --- a/tests/mock_player_repo.go +++ /dev/null @@ -1,75 +0,0 @@ -package tests - -import ( - "context" - "maps" - "slices" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/id" -) - -func CreateMockPlayerRepo() *MockPlayerRepo { - return &MockPlayerRepo{Data: map[string]*model.Player{}, APIKeys: map[string]string{}} -} - -// MockPlayerRepo keeps API keys in plaintext (key -> player ID); hashing belongs to the real repository. -type MockPlayerRepo struct { - model.PlayerRepository - Error error - Data map[string]*model.Player - APIKeys map[string]string -} - -func (m *MockPlayerRepo) Get(_ context.Context, id string) (*model.Player, error) { - if m.Error != nil { - return nil, m.Error - } - p, ok := m.Data[id] - if !ok { - return nil, model.ErrNotFound - } - cp := *p - cp.HasAPIKey = slices.Contains(slices.Collect(maps.Values(m.APIKeys)), id) - return &cp, nil -} - -func (m *MockPlayerRepo) Put(_ context.Context, p *model.Player) error { - if m.Error != nil { - return m.Error - } - if p.ID == "" { - p.ID = id.NewRandom() - } - cp := *p - m.Data[p.ID] = &cp - return nil -} - -func (m *MockPlayerRepo) FindByAPIKey(ctx context.Context, key string) (*model.Player, error) { - if m.Error != nil { - return nil, m.Error - } - if playerID, ok := m.APIKeys[key]; ok { - return m.Get(ctx, playerID) - } - return nil, model.ErrNotFound -} - -func (m *MockPlayerRepo) SetAPIKey(_ context.Context, playerID, key string) error { - if m.Error != nil { - return m.Error - } - if _, ok := m.Data[playerID]; !ok { - return model.ErrNotFound - } - m.removeKeys(playerID) - if key != "" { - m.APIKeys[key] = playerID - } - return nil -} - -func (m *MockPlayerRepo) removeKeys(playerID string) { - maps.DeleteFunc(m.APIKeys, func(_ string, v string) bool { return v == playerID }) -} diff --git a/tests/mock_playlist_repo.go b/tests/mock_playlist_repo.go deleted file mode 100644 index 824e701f6..000000000 --- a/tests/mock_playlist_repo.go +++ /dev/null @@ -1,189 +0,0 @@ -package tests - -import ( - "context" - "errors" - "time" - - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/id" -) - -func CreateMockPlaylistRepo() *MockPlaylistRepo { - return &MockPlaylistRepo{ - Data: make(map[string]*model.Playlist), - PathMap: make(map[string]*model.Playlist), - } -} - -type MockPlaylistRepo struct { - model.PlaylistRepository - Data map[string]*model.Playlist // keyed by ID - PathMap map[string]*model.Playlist // keyed by path - All model.Playlists - Options model.QueryOptions - Last *model.Playlist - Deleted []string - Starred map[string]bool // itemID -> starred - Ratings map[string]int // itemID -> rating - Err bool - TracksRepo model.PlaylistTrackRepository - TracksRefreshed bool -} - -func (m *MockPlaylistRepo) SetError(err bool) { - m.Err = err -} - -func (m *MockPlaylistRepo) SetData(playlists model.Playlists) { - m.Data = make(map[string]*model.Playlist, len(playlists)) - m.All = playlists - for i, p := range m.All { - m.Data[p.ID] = &m.All[i] - } -} - -func (m *MockPlaylistRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Playlists, error) { - if len(options) > 0 { - m.Options = options[0] - } - if m.Err { - return nil, errors.New("error") - } - return m.All, nil -} - -func (m *MockPlaylistRepo) GetCursor(ctx context.Context, options ...model.QueryOptions) (model.PlaylistCursor, error) { - res, err := m.GetAll(ctx, options...) - if err != nil { - return nil, err - } - return func(yield func(model.Playlist, error) bool) { - for _, p := range res { - if !yield(p, nil) { - return - } - } - }, nil -} - -func (m *MockPlaylistRepo) Get(_ context.Context, id string) (*model.Playlist, error) { - if m.Err { - return nil, errors.New("error") - } - if m.Data != nil { - if pls, ok := m.Data[id]; ok { - return pls, nil - } - } - return nil, model.ErrNotFound -} - -func (m *MockPlaylistRepo) GetWithTracks(ctx context.Context, id string, _, _ bool) (*model.Playlist, error) { - return m.Get(ctx, id) -} - -func (m *MockPlaylistRepo) Put(_ context.Context, pls *model.Playlist, _ ...string) error { - if m.Err { - return errors.New("error") - } - if pls.ID == "" { - pls.ID = id.NewRandom() - } - m.Last = pls - if m.Data != nil { - m.Data[pls.ID] = pls - } - return nil -} - -func (m *MockPlaylistRepo) FindByPath(_ context.Context, path string) (*model.Playlist, error) { - if m.Err { - return nil, errors.New("error") - } - if m.PathMap != nil { - if pls, ok := m.PathMap[path]; ok { - return pls, nil - } - } - return nil, model.ErrNotFound -} - -func (m *MockPlaylistRepo) Delete(_ context.Context, ids ...string) error { - if m.Err { - return errors.New("error") - } - m.Deleted = append(m.Deleted, ids...) - return nil -} - -func (m *MockPlaylistRepo) SetStar(_ context.Context, starred bool, ids ...string) error { - if m.Err { - return errors.New("error") - } - if m.Starred == nil { - m.Starred = map[string]bool{} - } - for _, id := range ids { - m.Starred[id] = starred - } - return nil -} - -func (m *MockPlaylistRepo) SetRating(_ context.Context, rating int, id string) error { - if m.Err { - return errors.New("error") - } - if m.Ratings == nil { - m.Ratings = map[string]int{} - } - m.Ratings[id] = rating - return nil -} - -func (m *MockPlaylistRepo) IncPlayCount(context.Context, string, time.Time) error { - if m.Err { - return errors.New("error") - } - return nil -} - -func (m *MockPlaylistRepo) ReassignAnnotation(context.Context, string, string) error { - if m.Err { - return errors.New("error") - } - return nil -} - -func (m *MockPlaylistRepo) Tracks(_ context.Context, _ string, refreshSmartPlaylist bool) model.PlaylistTrackRepository { - m.TracksRefreshed = refreshSmartPlaylist - return m.TracksRepo -} - -func (m *MockPlaylistRepo) Exists(_ context.Context, id string) (bool, error) { - if m.Err { - return false, errors.New("error") - } - if m.Data != nil { - _, found := m.Data[id] - return found, nil - } - return false, nil -} - -func (m *MockPlaylistRepo) Count(_ context.Context, _ ...rest.QueryOptions) (int64, error) { - if m.Err { - return 0, errors.New("error") - } - return int64(len(m.Data)), nil -} - -func (m *MockPlaylistRepo) CountAll(_ context.Context, _ ...model.QueryOptions) (int64, error) { - if m.Err { - return 0, errors.New("error") - } - return int64(len(m.Data)), nil -} - -var _ model.PlaylistRepository = (*MockPlaylistRepo)(nil) diff --git a/tests/mock_playlist_track_repo.go b/tests/mock_playlist_track_repo.go deleted file mode 100644 index 535d98af0..000000000 --- a/tests/mock_playlist_track_repo.go +++ /dev/null @@ -1,138 +0,0 @@ -package tests - -import ( - "context" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/utils/slice" -) - -type MockPlaylistTrackRepo struct { - model.PlaylistTrackRepository - Data model.PlaylistTracks - Options model.QueryOptions - AddedIds []string - DeletedIds []string - Reordered bool - AddCount int - InsertPos int - Err error - AlbumIDs []string // stubbed result for GetAlbumIDs, ignoring options -} - -func (m *MockPlaylistTrackRepo) SetData(tracks model.PlaylistTracks) { - m.Data = tracks -} - -// page applies Max/Offset as the real repository's SQL would. -func (m *MockPlaylistTrackRepo) page(options ...model.QueryOptions) model.PlaylistTracks { - var opts model.QueryOptions - if len(options) > 0 { - opts = options[0] - m.Options = opts - } - tracks := m.Data - if opts.Offset >= len(tracks) { - return nil - } - tracks = tracks[opts.Offset:] - if opts.Max > 0 && opts.Max < len(tracks) { - tracks = tracks[:opts.Max] - } - return tracks -} - -func (m *MockPlaylistTrackRepo) CountAll(_ context.Context, _ ...model.QueryOptions) (int64, error) { - if m.Err != nil { - return 0, m.Err - } - return int64(len(m.Data)), nil -} - -func (m *MockPlaylistTrackRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.PlaylistTracks, error) { - if m.Err != nil { - return nil, m.Err - } - return m.page(options...), nil -} - -func (m *MockPlaylistTrackRepo) GetCursor(_ context.Context, options ...model.QueryOptions) (model.PlaylistTrackCursor, error) { - if m.Err != nil { - return nil, m.Err - } - tracks := m.page(options...) - return func(yield func(model.PlaylistTrack, error) bool) { - for _, t := range tracks { - if !yield(t, nil) { - return - } - } - }, nil -} - -func (m *MockPlaylistTrackRepo) GetAlbumIDs(context.Context, ...model.QueryOptions) ([]string, error) { - if m.Err != nil { - return nil, m.Err - } - return m.AlbumIDs, nil -} - -func (m *MockPlaylistTrackRepo) GetMediaFileIDs(_ context.Context, options ...model.QueryOptions) ([]string, error) { - if m.Err != nil { - return nil, m.Err - } - return slice.Map(m.page(options...), func(t model.PlaylistTrack) string { return t.MediaFileID }), nil -} - -func (m *MockPlaylistTrackRepo) GetPositionIDs(_ context.Context, options ...model.QueryOptions) ([]string, error) { - if m.Err != nil { - return nil, m.Err - } - return slice.Map(m.page(options...), func(t model.PlaylistTrack) string { return t.ID }), nil -} - -func (m *MockPlaylistTrackRepo) Add(_ context.Context, ids []string) (int, error) { - m.AddedIds = append(m.AddedIds, ids...) - if m.Err != nil { - return 0, m.Err - } - return m.AddCount, nil -} - -func (m *MockPlaylistTrackRepo) Insert(ctx context.Context, ids []string, pos int) (int, error) { - m.InsertPos = pos - return m.Add(ctx, ids) -} - -func (m *MockPlaylistTrackRepo) AddAlbums(_ context.Context, _ []string) (int, error) { - if m.Err != nil { - return 0, m.Err - } - return m.AddCount, nil -} - -func (m *MockPlaylistTrackRepo) AddArtists(_ context.Context, _ []string) (int, error) { - if m.Err != nil { - return 0, m.Err - } - return m.AddCount, nil -} - -func (m *MockPlaylistTrackRepo) AddDiscs(_ context.Context, _ []model.DiscID) (int, error) { - if m.Err != nil { - return 0, m.Err - } - return m.AddCount, nil -} - -func (m *MockPlaylistTrackRepo) Delete(_ context.Context, ids ...string) error { - m.DeletedIds = append(m.DeletedIds, ids...) - return m.Err -} - -func (m *MockPlaylistTrackRepo) Reorder(_ context.Context, _, _ int) error { - m.Reordered = true - return m.Err -} - -var _ model.PlaylistTrackRepository = (*MockPlaylistTrackRepo)(nil) diff --git a/tests/mock_playqueue_repo.go b/tests/mock_playqueue_repo.go deleted file mode 100644 index ea44509b5..000000000 --- a/tests/mock_playqueue_repo.go +++ /dev/null @@ -1,74 +0,0 @@ -package tests - -import ( - "context" - "errors" - - "github.com/navidrome/navidrome/model" -) - -type MockPlayQueueRepo struct { - model.PlayQueueRepository - Queue *model.PlayQueue - // QueueWithMediaFiles, when set, is what RetrieveWithMediaFiles returns, to simulate tracks the user can't see - QueueWithMediaFiles *model.PlayQueue - // WithMediaFilesErr is returned by RetrieveWithMediaFiles together with the queue - WithMediaFilesErr error - Err bool - LastCols []string -} - -func (m *MockPlayQueueRepo) Store(_ context.Context, q *model.PlayQueue, cols ...string) error { - if m.Err { - return errors.New("error") - } - copyItems := make(model.MediaFiles, len(q.Items)) - copy(copyItems, q.Items) - qCopy := *q - qCopy.Items = copyItems - m.Queue = &qCopy - m.LastCols = cols - return nil -} - -func (m *MockPlayQueueRepo) RetrieveWithMediaFiles(_ context.Context, userId string) (*model.PlayQueue, error) { - if m.Err { - return nil, errors.New("error") - } - src := m.Queue - if m.QueueWithMediaFiles != nil { - src = m.QueueWithMediaFiles - } - if src == nil || src.UserID != userId { - return nil, model.ErrNotFound - } - copyItems := make(model.MediaFiles, len(src.Items)) - copy(copyItems, src.Items) - qCopy := *src - qCopy.Items = copyItems - return &qCopy, m.WithMediaFilesErr -} - -func (m *MockPlayQueueRepo) Retrieve(_ context.Context, userId string) (*model.PlayQueue, error) { - if m.Err { - return nil, errors.New("error") - } - if m.Queue == nil || m.Queue.UserID != userId { - return nil, model.ErrNotFound - } - copyItems := make(model.MediaFiles, len(m.Queue.Items)) - for i, t := range m.Queue.Items { - copyItems[i] = model.MediaFile{ID: t.ID} - } - qCopy := *m.Queue - qCopy.Items = copyItems - return &qCopy, nil -} - -func (m *MockPlayQueueRepo) Clear(_ context.Context, userId string) error { - if m.Err { - return errors.New("error") - } - m.Queue = nil - return nil -} diff --git a/tests/mock_plugin_repo.go b/tests/mock_plugin_repo.go deleted file mode 100644 index 9a14bde91..000000000 --- a/tests/mock_plugin_repo.go +++ /dev/null @@ -1,166 +0,0 @@ -package tests - -import ( - "context" - "errors" - "time" - - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" -) - -func CreateMockPluginRepo() *MockPluginRepo { - return &MockPluginRepo{ - Data: make(map[string]*model.Plugin), - IsAdmin: true, // Default to admin access - Permitted: true, - } -} - -type MockPluginRepo struct { - Data map[string]*model.Plugin - All model.Plugins - Err bool - Options model.QueryOptions - IsAdmin bool - Permitted bool -} - -func (m *MockPluginRepo) SetError(err bool) { - m.Err = err -} - -func (m *MockPluginRepo) ClearErrors(context.Context) error { - if m.Err { - return errors.New("unexpected error") - } - for i := range m.All { - m.All[i].LastError = "" - } - for k, p := range m.Data { - p.LastError = "" - m.Data[k] = p - } - return nil -} - -func (m *MockPluginRepo) SetData(plugins model.Plugins) { - m.Data = make(map[string]*model.Plugin, len(plugins)) - m.All = plugins - for i, p := range m.All { - m.Data[p.ID] = &m.All[i] - } -} - -func (m *MockPluginRepo) SetPermitted(permitted bool) { - m.Permitted = permitted -} - -func (m *MockPluginRepo) Get(_ context.Context, id string) (*model.Plugin, error) { - if !m.Permitted { - return nil, rest.ErrPermissionDenied - } - if m.Err { - return nil, errors.New("unexpected error") - } - if d, ok := m.Data[id]; ok { - return d, nil - } - return nil, model.ErrNotFound -} - -func (m *MockPluginRepo) Read(ctx context.Context, id string) (*model.Plugin, error) { - return m.Get(ctx, id) -} - -func (m *MockPluginRepo) Put(_ context.Context, p *model.Plugin) error { - if !m.Permitted { - return rest.ErrPermissionDenied - } - if m.Err { - return errors.New("unexpected error") - } - if p.ID == "" { - return errors.New("plugin ID cannot be empty") - } - now := time.Now() - if existing, ok := m.Data[p.ID]; ok { - p.CreatedAt = existing.CreatedAt - } else { - p.CreatedAt = now - } - p.UpdatedAt = now - m.Data[p.ID] = p - // Update All slice - found := false - for i, existing := range m.All { - if existing.ID == p.ID { - m.All[i] = *p - found = true - break - } - } - if !found { - m.All = append(m.All, *p) - } - return nil -} - -func (m *MockPluginRepo) Delete(_ context.Context, id string) error { - if !m.Permitted { - return rest.ErrPermissionDenied - } - if m.Err { - return errors.New("unexpected error") - } - delete(m.Data, id) - // Update All slice - for i, p := range m.All { - if p.ID == id { - m.All = append(m.All[:i], m.All[i+1:]...) - break - } - } - return nil -} - -func (m *MockPluginRepo) GetAll(_ context.Context, qo ...model.QueryOptions) (model.Plugins, error) { - if len(qo) > 0 { - m.Options = qo[0] - } - if !m.Permitted { - return nil, rest.ErrPermissionDenied - } - if m.Err { - return nil, errors.New("unexpected error") - } - return m.All, nil -} - -func (m *MockPluginRepo) CountAll(_ context.Context, qo ...model.QueryOptions) (int64, error) { - if len(qo) > 0 { - m.Options = qo[0] - } - if !m.Permitted { - return 0, rest.ErrPermissionDenied - } - if m.Err { - return 0, errors.New("unexpected error") - } - return int64(len(m.All)), nil -} - -// REST repository methods - -func (m *MockPluginRepo) Count(_ context.Context, _ ...rest.QueryOptions) (int64, error) { - if !m.Permitted { - return 0, rest.ErrPermissionDenied - } - return int64(len(m.All)), nil -} - -func (m *MockPluginRepo) ReadAll(ctx context.Context, _ ...rest.QueryOptions) ([]model.Plugin, error) { - return m.GetAll(ctx) -} - -var _ model.PluginRepository = (*MockPluginRepo)(nil) diff --git a/tests/mock_property_repo.go b/tests/mock_property_repo.go deleted file mode 100644 index 949f894c1..000000000 --- a/tests/mock_property_repo.go +++ /dev/null @@ -1,63 +0,0 @@ -package tests - -import ( - "context" - - "github.com/navidrome/navidrome/model" -) - -type MockedPropertyRepo struct { - model.PropertyRepository - Error error - Data map[string]string -} - -func (p *MockedPropertyRepo) init() { - if p.Data == nil { - p.Data = make(map[string]string) - } -} - -func (p *MockedPropertyRepo) Put(_ context.Context, id string, value string) error { - if p.Error != nil { - return p.Error - } - p.init() - p.Data[id] = value - return nil -} - -func (p *MockedPropertyRepo) Get(_ context.Context, id string) (string, error) { - if p.Error != nil { - return "", p.Error - } - p.init() - if v, ok := p.Data[id]; ok { - return v, nil - } - return "", model.ErrNotFound -} - -func (p *MockedPropertyRepo) Delete(_ context.Context, id string) error { - if p.Error != nil { - return p.Error - } - p.init() - if _, ok := p.Data[id]; ok { - delete(p.Data, id) - return nil - } - return model.ErrNotFound -} - -func (p *MockedPropertyRepo) DefaultGet(ctx context.Context, id string, defaultValue string) (string, error) { - if p.Error != nil { - return "", p.Error - } - p.init() - v, err := p.Get(ctx, id) - if err != nil { - return defaultValue, nil //nolint:nilerr - } - return v, nil -} diff --git a/tests/mock_radio_repository.go b/tests/mock_radio_repository.go deleted file mode 100644 index 14721e1b0..000000000 --- a/tests/mock_radio_repository.go +++ /dev/null @@ -1,84 +0,0 @@ -package tests - -import ( - "context" - "errors" - - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/id" -) - -type MockedRadioRepo struct { - model.RadioRepository - Data map[string]*model.Radio - All model.Radios - Err bool - Options model.QueryOptions -} - -func CreateMockedRadioRepo() *MockedRadioRepo { - return &MockedRadioRepo{Data: map[string]*model.Radio{}} -} - -func (m *MockedRadioRepo) SetError(err bool) { - m.Err = err -} - -func (m *MockedRadioRepo) CountAll(_ context.Context, options ...model.QueryOptions) (int64, error) { - if m.Err { - return 0, errors.New("error") - } - return int64(len(m.Data)), nil -} - -func (m *MockedRadioRepo) Delete(_ context.Context, ids ...string) error { - if m.Err { - return errors.New("error") - } - for _, id := range ids { - if _, found := m.Data[id]; !found { - return errors.New("not found") - } - delete(m.Data, id) - } - return nil -} - -func (m *MockedRadioRepo) Exists(_ context.Context, id string) (bool, error) { - if m.Err { - return false, errors.New("error") - } - _, found := m.Data[id] - return found, nil -} - -func (m *MockedRadioRepo) Get(_ context.Context, id string) (*model.Radio, error) { - if m.Err { - return nil, errors.New("error") - } - if d, ok := m.Data[id]; ok { - return d, nil - } - return nil, model.ErrNotFound -} - -func (m *MockedRadioRepo) GetAll(_ context.Context, qo ...model.QueryOptions) (model.Radios, error) { - if len(qo) > 0 { - m.Options = qo[0] - } - if m.Err { - return nil, errors.New("error") - } - return m.All, nil -} - -func (m *MockedRadioRepo) Put(_ context.Context, radio *model.Radio, _ ...string) error { - if m.Err { - return errors.New("error") - } - if radio.ID == "" { - radio.ID = id.NewRandom() - } - m.Data[radio.ID] = radio - return nil -} diff --git a/tests/mock_scrobble_buffer_repo.go b/tests/mock_scrobble_buffer_repo.go deleted file mode 100644 index 9831f9d07..000000000 --- a/tests/mock_scrobble_buffer_repo.go +++ /dev/null @@ -1,112 +0,0 @@ -package tests - -import ( - "context" - "sync" - "time" - - "github.com/navidrome/navidrome/model" -) - -type MockedScrobbleBufferRepo struct { - Error error - Data model.ScrobbleEntries - mu sync.RWMutex -} - -func CreateMockedScrobbleBufferRepo() *MockedScrobbleBufferRepo { - return &MockedScrobbleBufferRepo{} -} - -func (m *MockedScrobbleBufferRepo) UserIDs(_ context.Context, service string) ([]string, error) { - if m.Error != nil { - return nil, m.Error - } - m.mu.RLock() - defer m.mu.RUnlock() - userIds := make(map[string]struct{}) - for _, e := range m.Data { - if e.Service == service { - userIds[e.UserID] = struct{}{} - } - } - var result []string - for uid := range userIds { - result = append(result, uid) - } - return result, nil -} - -func (m *MockedScrobbleBufferRepo) Enqueue(_ context.Context, service, userId, mediaFileId string, playTime time.Time) error { - if m.Error != nil { - return m.Error - } - m.mu.Lock() - defer m.mu.Unlock() - m.Data = append(m.Data, model.ScrobbleEntry{ - MediaFile: model.MediaFile{ID: mediaFileId}, - Service: service, - UserID: userId, - PlayTime: playTime, - EnqueueTime: time.Now(), - }) - return nil -} - -func (m *MockedScrobbleBufferRepo) Next(_ context.Context, service, userId string) (*model.ScrobbleEntry, error) { - if m.Error != nil { - return nil, m.Error - } - m.mu.RLock() - defer m.mu.RUnlock() - for _, e := range m.Data { - if e.Service == service && e.UserID == userId { - return &e, nil - } - } - return nil, nil -} - -func (m *MockedScrobbleBufferRepo) Dequeue(_ context.Context, entry *model.ScrobbleEntry) error { - if m.Error != nil { - return m.Error - } - m.mu.Lock() - defer m.mu.Unlock() - newData := model.ScrobbleEntries{} - for _, e := range m.Data { - if e.Service == entry.Service && e.UserID == entry.UserID && e.PlayTime.Equal(entry.PlayTime) && e.MediaFile.ID == entry.MediaFile.ID { - continue - } - newData = append(newData, e) - } - m.Data = newData - return nil -} - -func (m *MockedScrobbleBufferRepo) Discard(_ context.Context, service string) error { - if m.Error != nil { - return m.Error - } - m.mu.Lock() - defer m.mu.Unlock() - newData := model.ScrobbleEntries{} - for _, e := range m.Data { - if e.Service != service { - newData = append(newData, e) - } - } - m.Data = newData - return nil -} - -func (m *MockedScrobbleBufferRepo) Length(context.Context) (int64, error) { - if m.Error != nil { - return 0, m.Error - } - m.mu.RLock() - defer m.mu.RUnlock() - return int64(len(m.Data)), nil -} - -var _ model.ScrobbleBufferRepository = (*MockedScrobbleBufferRepo)(nil) diff --git a/tests/mock_scrobble_repo.go b/tests/mock_scrobble_repo.go deleted file mode 100644 index a76bc5d59..000000000 --- a/tests/mock_scrobble_repo.go +++ /dev/null @@ -1,57 +0,0 @@ -package tests - -import ( - "context" - "strconv" - "time" - - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" - "github.com/navidrome/navidrome/model/request" -) - -type MockScrobbleRepo struct { - RecordedScrobbles []model.Scrobble -} - -func (m *MockScrobbleRepo) Get(_ context.Context, id string) (*model.Scrobble, error) { - for idx := range m.RecordedScrobbles { - if strconv.FormatInt(m.RecordedScrobbles[idx].ID, 10) == id { - return &m.RecordedScrobbles[idx], nil - } - } - - return nil, model.ErrNotFound -} - -func (m *MockScrobbleRepo) GetAll(_ context.Context, _ ...model.QueryOptions) (model.Scrobbles, error) { - return m.RecordedScrobbles, nil -} - -func (m *MockScrobbleRepo) CountAll(_ context.Context, _ ...model.QueryOptions) (int64, error) { - return int64(len(m.RecordedScrobbles)), nil -} - -func (m *MockScrobbleRepo) RecordScrobble(ctx context.Context, fileID string, submissionTime time.Time) error { - user, _ := request.UserFrom(ctx) - m.RecordedScrobbles = append(m.RecordedScrobbles, model.Scrobble{ - MediaFileID: fileID, - UserID: user.ID, - SubmissionTime: submissionTime.Unix(), - }) - return nil -} - -func (m *MockScrobbleRepo) Count(ctx context.Context, _ ...rest.QueryOptions) (int64, error) { - return m.CountAll(ctx) -} - -func (m *MockScrobbleRepo) Read(ctx context.Context, id string) (*model.Scrobble, error) { - return m.Get(ctx, id) -} - -func (m *MockScrobbleRepo) ReadAll(ctx context.Context, _ ...rest.QueryOptions) ([]model.Scrobble, error) { - return m.GetAll(ctx) -} - -var _ model.ScrobbleRepository = (*MockScrobbleRepo)(nil) diff --git a/tests/mock_share_repo.go b/tests/mock_share_repo.go deleted file mode 100644 index 0c872dc0d..000000000 --- a/tests/mock_share_repo.go +++ /dev/null @@ -1,57 +0,0 @@ -package tests - -import ( - "context" - - "github.com/navidrome/navidrome/model" -) - -type MockShareRepo struct { - model.ShareRepository - - Entity any - ID string - Cols []string - Error error -} - -func (m *MockShareRepo) Save(_ context.Context, s *model.Share) (string, error) { - if m.Error != nil { - return "", m.Error - } - if s.ID == "" { - s.ID = "id" - } - m.Entity = s - return s.ID, nil -} - -func (m *MockShareRepo) Update(_ context.Context, id string, entity model.Share, cols ...string) error { - if m.Error != nil { - return m.Error - } - m.ID = id - m.Entity = &entity - m.Cols = cols - return nil -} - -func (m *MockShareRepo) Exists(_ context.Context, id string) (bool, error) { - if m.Error != nil { - return false, m.Error - } - return id == m.ID, nil -} - -func (m *MockShareRepo) Get(_ context.Context, id string) (*model.Share, error) { - if m.Error != nil { - return nil, m.Error - } - if id != m.ID { - return nil, model.ErrNotFound - } - if s, ok := m.Entity.(*model.Share); ok { - return s, nil - } - return &model.Share{ID: id}, nil -} diff --git a/tests/mock_tag_repo.go b/tests/mock_tag_repo.go deleted file mode 100644 index f1f252efe..000000000 --- a/tests/mock_tag_repo.go +++ /dev/null @@ -1,26 +0,0 @@ -package tests - -import ( - "context" - - "github.com/navidrome/navidrome/model" -) - -// MockTagRepo records the QueryOptions passed to GetAll, mirroring MockArtistRepo, so tests can -// assert on which filters a caller attached (e.g. a library scope). -type MockTagRepo struct { - model.TagRepository - Data model.TagList - Options model.QueryOptions - Err error -} - -func (r *MockTagRepo) GetAll(_ context.Context, _ model.TagName, options ...model.QueryOptions) (model.TagList, error) { - if len(options) > 0 { - r.Options = options[0] - } - if r.Err != nil { - return nil, r.Err - } - return r.Data, nil -} diff --git a/tests/mock_transcoding_repo.go b/tests/mock_transcoding_repo.go deleted file mode 100644 index 52eb16eed..000000000 --- a/tests/mock_transcoding_repo.go +++ /dev/null @@ -1,32 +0,0 @@ -package tests - -import ( - "context" - - "github.com/navidrome/navidrome/model" -) - -type MockTranscodingRepo struct { - model.TranscodingRepository -} - -func (m *MockTranscodingRepo) Get(_ context.Context, id string) (*model.Transcoding, error) { - return &model.Transcoding{ID: id, TargetFormat: "mp3", DefaultBitRate: 160}, nil -} - -func (m *MockTranscodingRepo) FindByFormat(_ context.Context, format string) (*model.Transcoding, error) { - switch format { - case "mp3": - return &model.Transcoding{ID: "mp31", TargetFormat: "mp3", DefaultBitRate: 160}, nil - case "oga": - return &model.Transcoding{ID: "oga1", TargetFormat: "oga", DefaultBitRate: 128}, nil - case "opus": - return &model.Transcoding{ID: "opus1", TargetFormat: "opus", DefaultBitRate: 96}, nil - case "flac": - return &model.Transcoding{ID: "flac1", TargetFormat: "flac", DefaultBitRate: 0, Command: "ffmpeg -ss %t -i %s -map 0:a:0 -v 0 -c:a flac -f flac -"}, nil - case "aac": - return &model.Transcoding{ID: "aac1", TargetFormat: "aac", DefaultBitRate: 256, Command: "ffmpeg -ss %t -i %s -map 0:a:0 -b:a %bk -v 0 -c:a aac -f ipod -movflags frag_keyframe+empty_moov -"}, nil - default: - return nil, model.ErrNotFound - } -} diff --git a/tests/mock_user_props_repo.go b/tests/mock_user_props_repo.go deleted file mode 100644 index 278a68431..000000000 --- a/tests/mock_user_props_repo.go +++ /dev/null @@ -1,63 +0,0 @@ -package tests - -import ( - "context" - - "github.com/navidrome/navidrome/model" -) - -type MockedUserPropsRepo struct { - model.UserPropsRepository - Error error - Data map[string]string -} - -func (p *MockedUserPropsRepo) init() { - if p.Data == nil { - p.Data = make(map[string]string) - } -} - -func (p *MockedUserPropsRepo) Put(_ context.Context, userId, key string, value string) error { - if p.Error != nil { - return p.Error - } - p.init() - p.Data[userId+key] = value - return nil -} - -func (p *MockedUserPropsRepo) Get(_ context.Context, userId, key string) (string, error) { - if p.Error != nil { - return "", p.Error - } - p.init() - if v, ok := p.Data[userId+key]; ok { - return v, nil - } - return "", model.ErrNotFound -} - -func (p *MockedUserPropsRepo) Delete(_ context.Context, userId, key string) error { - if p.Error != nil { - return p.Error - } - p.init() - if _, ok := p.Data[userId+key]; ok { - delete(p.Data, userId+key) - return nil - } - return model.ErrNotFound -} - -func (p *MockedUserPropsRepo) DefaultGet(ctx context.Context, userId, key string, defaultValue string) (string, error) { - if p.Error != nil { - return "", p.Error - } - p.init() - v, err := p.Get(ctx, userId, key) - if err != nil { - return defaultValue, nil //nolint:nilerr - } - return v, nil -} diff --git a/tests/mock_user_repo.go b/tests/mock_user_repo.go deleted file mode 100644 index 58c985157..000000000 --- a/tests/mock_user_repo.go +++ /dev/null @@ -1,186 +0,0 @@ -package tests - -import ( - "context" - "encoding/base64" - "fmt" - "strings" - "time" - - "github.com/navidrome/navidrome/model" -) - -func CreateMockUserRepo() *MockedUserRepo { - return &MockedUserRepo{ - Data: map[string]*model.User{}, - UserLibraries: map[string][]int{}, - } -} - -type MockedUserRepo struct { - model.UserRepository - Error error - Data map[string]*model.User - UserLibraries map[string][]int // userID -> libraryIDs -} - -func (u *MockedUserRepo) CountAll(_ context.Context, qo ...model.QueryOptions) (int64, error) { - if u.Error != nil { - return 0, u.Error - } - return int64(len(u.Data)), nil -} - -func (u *MockedUserRepo) Put(_ context.Context, usr *model.User) error { - if u.Error != nil { - return u.Error - } - if usr.ID == "" { - usr.ID = base64.StdEncoding.EncodeToString([]byte(usr.UserName)) - } - usr.Password = usr.NewPassword - u.Data[strings.ToLower(usr.UserName)] = usr - return nil -} - -func (u *MockedUserRepo) FindByUsername(_ context.Context, username string) (*model.User, error) { - if u.Error != nil { - return nil, u.Error - } - usr, ok := u.Data[strings.ToLower(username)] - if !ok { - return nil, model.ErrNotFound - } - return usr, nil -} - -func (u *MockedUserRepo) FindByUsernameWithPassword(ctx context.Context, username string) (*model.User, error) { - return u.FindByUsername(ctx, username) -} - -func (u *MockedUserRepo) FindFirstAdmin(_ context.Context) (*model.User, error) { - if u.Error != nil { - return nil, u.Error - } - for _, usr := range u.Data { - if usr.IsAdmin { - return usr, nil - } - } - return nil, model.ErrNotFound -} - -func (u *MockedUserRepo) Get(_ context.Context, id string) (*model.User, error) { - if u.Error != nil { - return nil, u.Error - } - for _, usr := range u.Data { - if usr.ID == id { - return usr, nil - } - } - return nil, model.ErrNotFound -} - -func (u *MockedUserRepo) GetAll(_ context.Context, options ...model.QueryOptions) (model.Users, error) { - if u.Error != nil { - return nil, u.Error - } - var users model.Users - for _, usr := range u.Data { - users = append(users, *usr) - } - return users, nil -} - -func (u *MockedUserRepo) UpdateLastLoginAt(_ context.Context, id string) error { - for _, usr := range u.Data { - if usr.ID == id { - usr.LastLoginAt = new(time.Now()) - return nil - } - } - return u.Error -} - -func (u *MockedUserRepo) UpdateLastAccessAt(_ context.Context, id string) error { - for _, usr := range u.Data { - if usr.ID == id { - usr.LastAccessAt = new(time.Now()) - return nil - } - } - return u.Error -} - -// Library association methods - mock implementations - -func (u *MockedUserRepo) GetUserLibraries(_ context.Context, userID string) (model.Libraries, error) { - if u.Error != nil { - return nil, u.Error - } - libraryIDs, exists := u.UserLibraries[userID] - if !exists { - return model.Libraries{}, nil - } - - // Mock: Create libraries based on IDs - var libraries model.Libraries - for _, id := range libraryIDs { - libraries = append(libraries, model.Library{ - ID: id, - Name: fmt.Sprintf("Test Library %d", id), - Path: fmt.Sprintf("/music/library%d", id), - }) - } - return libraries, nil -} - -func (u *MockedUserRepo) SetUserLibraries(_ context.Context, userID string, libraryIDs []int) error { - if u.Error != nil { - return u.Error - } - if u.UserLibraries == nil { - u.UserLibraries = make(map[string][]int) - } - u.UserLibraries[userID] = libraryIDs - return nil -} - -func (u *MockedUserRepo) Delete(_ context.Context, ids ...string) error { - if u.Error != nil { - return u.Error - } - for _, id := range ids { - if err := u.deleteOne(id); err != nil { - return err - } - } - return nil -} - -func (u *MockedUserRepo) deleteOne(id string) error { - for key, usr := range u.Data { - if usr.ID == id { - delete(u.Data, key) - delete(u.UserLibraries, id) - return nil - } - } - return model.ErrNotFound -} - -func (u *MockedUserRepo) Save(ctx context.Context, usr *model.User) (string, error) { - if err := u.Put(ctx, usr); err != nil { - return "", err - } - return usr.ID, nil -} - -func (u *MockedUserRepo) Update(ctx context.Context, id string, entity model.User, _ ...string) error { - if u.Error != nil { - return u.Error - } - entity.ID = id - return u.Put(ctx, &entity) -} diff --git a/tests/mock_user_service.go b/tests/mock_user_service.go deleted file mode 100644 index bde843d1a..000000000 --- a/tests/mock_user_service.go +++ /dev/null @@ -1,29 +0,0 @@ -package tests - -import ( - "github.com/deluan/rest" - "github.com/navidrome/navidrome/model" -) - -// MockUserService provides a simple wrapper around MockedUserRepo -// that implements the core.User interface for testing. -// Returns concrete type to avoid import cycles - callers assign to core.User. -type MockUserService struct { - *MockedUserRepo -} - -// MockUserRestAdapter adapts MockedUserRepo to the REST repository interface -type MockUserRestAdapter struct { - *MockedUserRepo -} - -// NewMockUserService creates a new mock user service for testing. -// Returns concrete type - assign to core.User at call site. -func NewMockUserService() *MockUserService { - repo := CreateMockUserRepo() - return &MockUserService{MockedUserRepo: repo} -} - -func (m *MockUserService) Repository() rest.Repository[model.User] { - return &MockUserRestAdapter{MockedUserRepo: m.MockedUserRepo} -}