test: replace shared repository fakes with a real per-suite database (#6519)

This commit is contained in:
Deluan Quintão authored and GitHub committed 2026-11-22 15:41:43 -05:00
1 parent 71553644ed
commit f78929da2e
195 files changed
+7059 -10969

No files matched your search

+4 -7
View File
@@ -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,
}
+5 -2
View File
@@ -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)
+8 -7
View File
@@ -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
}
+3
View File
@@ -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()
+6 -3
View File
@@ -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)
})
@@ -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()
+45 -32
View File
@@ -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 <kind> <id> 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
}
+3
View File
@@ -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()
+32 -13
View File
@@ -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"))
})
})
+4 -6
View File
@@ -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())
})
}
+14 -1
View File
@@ -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" })
})
+3
View File
@@ -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()
+18 -6
View File
@@ -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"}}))
})
+73 -36
View File
@@ -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...)
}
+22 -5
View File
@@ -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")
+79 -154
View File
@@ -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
+3 -2
View File
@@ -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() {
+110 -32
View File
@@ -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())
}
+82 -90
View File
@@ -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",
+52 -53
View File
@@ -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"))
-17
View File
@@ -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)
+6 -3
View File
@@ -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())
+87 -56
View File
@@ -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))
})
})
+24 -11
View File
@@ -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
}
+30 -39
View File
@@ -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() {
+7 -5
View File
@@ -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())
})
+61 -116
View File
@@ -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")
+20 -20
View File
@@ -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))
+86 -181
View File
@@ -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() {
+92 -147
View File
@@ -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")
+5 -6
View File
@@ -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)
})
+10 -19
View File
@@ -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" })
+168 -275
View File
@@ -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)
+4 -2
View File
@@ -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 {
+6 -5
View File
@@ -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() {
+6 -7
View File
@@ -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() {
+3
View File
@@ -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()
+24 -159
View File
@@ -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
+3
View File
@@ -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()
+21 -22
View File
@@ -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())
})
File diff suppressed because it is too large. Load diff
+88 -244
View File
@@ -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())
})
})
+38 -18
View File
@@ -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())
+29 -22
View File
@@ -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&amp;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{
+118 -189
View File
@@ -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())
+3
View File
@@ -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
+63 -24
View File
@@ -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
+316 -283
View File
@@ -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)
}
+6 -6
View File
@@ -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{
+3
View File
@@ -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()
+114 -266
View File
@@ -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
}
}
+55 -61
View File
@@ -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
}
+139 -328
View File
@@ -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())
}
+5 -12
View File
@@ -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)
+73
View File
@@ -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())
}
+133 -136
View File
@@ -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() {
+112 -103
View File
@@ -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())
})
})
})
+22 -26
View File
@@ -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,
+116 -99
View File
@@ -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}
+44
View File
@@ -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)
}
}
}
+35 -12
View File
@@ -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())
})
})
})
+4
View File
@@ -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()
+14 -17
View File
@@ -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"}
+21 -19
View File
@@ -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))
})
+6 -10
View File
@@ -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(""))
})
+10 -4
View File
@@ -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)
+3
View File
@@ -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()
+4 -5
View File
@@ -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)
+20 -11
View File
@@ -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")
}
+22 -10
View File
@@ -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 }
+3
View File
@@ -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()
+9 -46
View File
@@ -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())
}
+8
View File
@@ -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
+164
View File
@@ -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())
}
+144
View File
@@ -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)
})
@@ -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
}
@@ -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()
@@ -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()
}
}
+100
View File
@@ -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)
}
+17 -9
View File
@@ -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
}
+4 -14
View File
@@ -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{
+2 -7
View File
@@ -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{
+2 -7
View File
@@ -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{
+2 -7
View File
@@ -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{
+17 -97
View File
@@ -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{
+61 -115
View File
@@ -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...)
}
+2 -7
View File
@@ -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{
+5 -19
View File
@@ -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())
+7 -18
View File
@@ -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())
+24 -55
View File
@@ -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() {
+2 -7
View File
@@ -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{
+21 -82
View File
@@ -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{
+2 -7
View File
@@ -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{
+3 -6
View File
@@ -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(),
}
+6 -8
View File
@@ -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())
+18 -19
View File
@@ -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)
+1
View File
@@ -17,6 +17,7 @@ var _ = Describe("Manager", Ordered, func() {
BeforeAll(func() {
ctx = GinkgoT().Context()
newTestDataStore(testManagerPlugins...)
})
Describe("Plugin Loading", func() {
+2 -8
View File
@@ -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)
+72 -5
View File
@@ -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
}
+5 -8
View File
@@ -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())
Loaded 100 of 195 files, more files were not shown because too many files have changed in this diff. Show more