package backend import ( "context" "os" "path/filepath" "testing" "music-server/internal/db/repository" "music-server/internal/testutil/fakedb" "github.com/google/uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func writeFile(t *testing.T, path, content string) { t.Helper() require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) require.NoError(t, os.WriteFile(path, []byte(content), 0o644)) } // addSoundtrackWithSongs creates a soundtrack folder with song files and matching database rows. func addSoundtrackWithSongs(t *testing.T, store *fakedb.Store, musicDir, name string, timesPlayed int32, songs ...string) repository.Soundtrack { t.Helper() dir := musicDir + "/" + name + "/" st := store.AddSoundtrack(repository.Soundtrack{SoundtrackName: name, Path: dir, TimesPlayed: timesPlayed}) for _, song := range songs { fileName := song + ".mp3" writeFile(t, dir+fileName, song) store.AddTestSong(repository.Song{SoundtrackID: st.ID, SongName: song, Path: dir + fileName, FileName: &fileName}) } return st } // newQueue starts a queue for the tests. func newQueue(t *testing.T, m *MusicService) uuid.UUID { t.Helper() id, err := m.ResolveQueue(context.Background(), "") require.NoError(t, err) return id } // queueSong fetches a random song and adds it to the queue. func queueSong(t *testing.T, m *MusicService, queueID uuid.UUID) string { t.Helper() path, err := m.RandomSong(context.Background(), queueID) require.NoError(t, err) require.NoError(t, m.AddLatestToQueue(context.Background(), queueID)) return path } func TestMusicServiceEmptyQueue(t *testing.T) { m := NewMusicService(fakedb.New(), t.TempDir()) ctx := context.Background() q := newQueue(t, m) _, err := m.NextSong(ctx, q) assert.ErrorIs(t, err, ErrQueueEmpty) _, err = m.PreviousSong(ctx, q) assert.ErrorIs(t, err, ErrQueueEmpty) _, err = m.Song(ctx, q, 0) assert.ErrorIs(t, err, ErrQueueEmpty) info, err := m.SongInfo(ctx, q) require.NoError(t, err) assert.Equal(t, SongInfo{}, info) played, err := m.PlayedSongs(ctx, q) require.NoError(t, err) assert.Empty(t, played) assert.NotNil(t, played, "an empty queue is [] in JSON") assert.NoError(t, m.AddLatestPlayed(ctx, q)) assert.NoError(t, m.SetPlayed(ctx, q, -1)) } func TestMusicServiceNoSoundtracks(t *testing.T) { m := NewMusicService(fakedb.New(), t.TempDir()) ctx := context.Background() q := newQueue(t, m) _, err := m.RandomSong(ctx, q) assert.ErrorIs(t, err, ErrNoSongs) _, err = m.RandomSongLowChance(ctx, q) assert.ErrorIs(t, err, ErrNoSongs) _, err = m.RandomSongClassic(ctx, q) assert.ErrorIs(t, err, ErrNoSongs) } func TestMusicServiceSoundtracksWithoutSongs(t *testing.T) { store := fakedb.New() store.AddSoundtrack(repository.Soundtrack{SoundtrackName: "Empty"}) m := NewMusicService(store, t.TempDir()) _, err := m.RandomSong(context.Background(), newQueue(t, m)) assert.ErrorIs(t, err, ErrNoSongs) } func TestMusicServiceQueue(t *testing.T) { store := fakedb.New() musicDir := t.TempDir() addSoundtrackWithSongs(t, store, musicDir, "Game A", 0, "Song 1", "Song 2") m := NewMusicService(store, t.TempDir()) ctx := context.Background() q := newQueue(t, m) first := queueSong(t, m, q) second := queueSong(t, m, q) info, err := m.SongInfo(ctx, q) require.NoError(t, err) assert.Equal(t, "Game A", info.Soundtrack) soundtrack, _ := store.Soundtrack("Game A") assert.Equal(t, soundtrack.Uuid, info.SoundtrackUuid) assert.Equal(t, second, songPathByUUID(store, info.SongUuid)) assert.Equal(t, 1, info.SongNo) assert.True(t, info.CurrentlyPlaying) path, err := m.PreviousSong(ctx, q) require.NoError(t, err) assert.Equal(t, first, path) path, err = m.PreviousSong(ctx, q) require.NoError(t, err) assert.Equal(t, first, path, "previous stays on the first song") path, err = m.NextSong(ctx, q) require.NoError(t, err) assert.Equal(t, second, path) path, err = m.NextSong(ctx, q) require.NoError(t, err) assert.Equal(t, second, path, "next stays on the last song") path, err = m.Song(ctx, q, 99) require.NoError(t, err) assert.Equal(t, second, path, "song number is clamped") played, err := m.PlayedSongs(ctx, q) require.NoError(t, err) require.Len(t, played, 2) assert.False(t, played[0].CurrentlyPlaying) assert.True(t, played[1].CurrentlyPlaying) } func TestMusicServiceQueuesAreSeparate(t *testing.T) { store := fakedb.New() addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song 1") m := NewMusicService(store, t.TempDir()) ctx := context.Background() q1, q2 := newQueue(t, m), newQueue(t, m) require.NotEqual(t, q1, q2) queueSong(t, m, q1) queueSong(t, m, q1) queueSong(t, m, q2) played, err := m.PlayedSongs(ctx, q1) require.NoError(t, err) assert.Len(t, played, 2) played, err = m.PlayedSongs(ctx, q2) require.NoError(t, err) assert.Len(t, played, 1) } func TestMusicServiceQueueSurvivesRestart(t *testing.T) { store := fakedb.New() addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song 1") m := NewMusicService(store, t.TempDir()) q := newQueue(t, m) path := queueSong(t, m, q) restarted := NewMusicService(store, t.TempDir()) id, err := restarted.ResolveQueue(context.Background(), q.String()) require.NoError(t, err) assert.Equal(t, q, id) current, err := restarted.Song(context.Background(), q, 0) require.NoError(t, err) assert.Equal(t, path, current) } func TestMusicServiceNewQueue(t *testing.T) { store := fakedb.New() addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song 1") m := NewMusicService(store, t.TempDir()) ctx := context.Background() old := newQueue(t, m) queueSong(t, m, old) q, err := m.NewQueue(ctx, old) require.NoError(t, err) assert.NotEqual(t, old, q) _, err = m.NextSong(ctx, q) assert.ErrorIs(t, err, ErrQueueEmpty) resolved, err := m.ResolveQueue(ctx, old.String()) require.NoError(t, err) assert.NotEqual(t, old, resolved, "an ended queue is not used again") played, err := m.PlayedSongs(ctx, old) require.NoError(t, err) assert.Len(t, played, 1, "ended queues are kept") } func TestMusicServiceEndAllQueues(t *testing.T) { m := NewMusicService(fakedb.New(), t.TempDir()) ctx := context.Background() q1, q2 := newQueue(t, m), newQueue(t, m) require.NoError(t, m.EndAllQueues(ctx)) for _, q := range []uuid.UUID{q1, q2} { id, err := m.ResolveQueue(ctx, q.String()) require.NoError(t, err) assert.NotEqual(t, q, id) } } func TestMusicServiceResolveQueue(t *testing.T) { m := NewMusicService(fakedb.New(), t.TempDir()) ctx := context.Background() q := newQueue(t, m) id, err := m.ResolveQueue(ctx, q.String()) require.NoError(t, err) assert.Equal(t, q, id) for _, header := range []string{"", "not-a-uuid", uuid.NewString()} { id, err := m.ResolveQueue(ctx, header) require.NoError(t, err) assert.NotEqual(t, uuid.Nil, id, header) assert.NotEqual(t, q, id, header) } } func TestMusicServiceRemovedSongInQueue(t *testing.T) { store := fakedb.New() addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song 1") m := NewMusicService(store, t.TempDir()) ctx := context.Background() q := newQueue(t, m) queueSong(t, m, q) require.NoError(t, store.ClearSongs(ctx)) _, err := m.Song(ctx, q, 0) assert.ErrorIs(t, err, ErrNotFound) info, err := m.SongInfo(ctx, q) require.NoError(t, err) assert.Equal(t, "Game A", info.Soundtrack, "the stored names are kept") assert.Equal(t, "Song 1", info.Song) assert.NoError(t, m.AddLatestPlayed(ctx, q), "removed songs are not counted") } func TestMusicServiceAddLatestToQueueWithoutFetch(t *testing.T) { m := NewMusicService(fakedb.New(), t.TempDir()) q := newQueue(t, m) require.NoError(t, m.AddLatestToQueue(context.Background(), q)) _, err := m.NextSong(context.Background(), q) assert.ErrorIs(t, err, ErrQueueEmpty) } func TestMusicServiceAddLatestToQueueOnlyOnce(t *testing.T) { store := fakedb.New() addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song 1") m := NewMusicService(store, t.TempDir()) q := newQueue(t, m) queueSong(t, m, q) require.NoError(t, m.AddLatestToQueue(context.Background(), q)) played, err := m.PlayedSongs(context.Background(), q) require.NoError(t, err) assert.Len(t, played, 1) } func TestMusicServiceMarkPlayed(t *testing.T) { store := fakedb.New() st := addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song 1") m := NewMusicService(store, t.TempDir()) ctx := context.Background() q := newQueue(t, m) queueSong(t, m, q) require.NoError(t, m.AddLatestPlayed(ctx, q)) require.NoError(t, m.SetPlayed(ctx, q, 0)) require.NoError(t, m.SetPlayed(ctx, q, 5), "out of range is ignored") updated, _ := store.Soundtrack("Game A") assert.Equal(t, int32(2), updated.TimesPlayed) assert.Equal(t, int32(2), store.SongsOf(st.ID)[0].TimesPlayed) } func TestMusicServiceRemovesBrokenSongs(t *testing.T) { store := fakedb.New() musicDir := t.TempDir() st := addSoundtrackWithSongs(t, store, musicDir, "Game A", 0, "Good") missing := "Missing.mp3" store.AddTestSong(repository.Song{SoundtrackID: st.ID, SongName: "Missing", Path: st.Path + missing, FileName: &missing}) wav := "Wave.wav" writeFile(t, st.Path+wav, "wav") store.AddTestSong(repository.Song{SoundtrackID: st.ID, SongName: "Wave", Path: st.Path + wav, FileName: &wav}) m := NewMusicService(store, t.TempDir()) q := newQueue(t, m) for range 20 { path, err := m.RandomSong(context.Background(), q) require.NoError(t, err) assert.Equal(t, st.Path+"Good.mp3", path) } songs := store.SongsOf(st.ID) require.Len(t, songs, 1) assert.Equal(t, "Good", songs[0].SongName) } func TestMusicServiceRandomSongClassic(t *testing.T) { store := fakedb.New() st := addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Good") missing := "Missing.mp3" store.AddTestSong(repository.Song{SoundtrackID: st.ID, SongName: "Missing", Path: st.Path + missing, FileName: &missing}) m := NewMusicService(store, t.TempDir()) q := newQueue(t, m) for range 20 { path, err := m.RandomSongClassic(context.Background(), q) require.NoError(t, err) assert.Equal(t, st.Path+"Good.mp3", path) } assert.Len(t, store.SongsOf(st.ID), 1) } func TestLowChanceWeights(t *testing.T) { soundtracks := []repository.Soundtrack{ {SoundtrackName: "Often", TimesPlayed: 30}, {SoundtrackName: "Average", TimesPlayed: 20}, {SoundtrackName: "Rarely", TimesPlayed: 10}, } weights := lowChanceWeights(soundtracks) assert.Equal(t, []int{1, 1, 10}, []int{weights[0].weight, weights[1].weight, weights[2].weight}) } func TestAveragePlayed(t *testing.T) { assert.Equal(t, int32(0), averagePlayed(nil)) assert.Equal(t, int32(20), averagePlayed([]repository.Soundtrack{{TimesPlayed: 10}, {TimesPlayed: 30}})) } func TestSoundtrackNames(t *testing.T) { store := fakedb.New() store.AddSoundtrack(repository.Soundtrack{SoundtrackName: "B"}) store.AddSoundtrack(repository.Soundtrack{SoundtrackName: "A"}) m := NewMusicService(store, t.TempDir()) names, err := m.SoundtrackNames(context.Background()) require.NoError(t, err) assert.Equal(t, []string{"A", "B"}, names) random, err := m.SoundtrackNamesRandom(context.Background()) require.NoError(t, err) assert.ElementsMatch(t, []string{"A", "B"}, random) assert.Equal(t, []string{"A", "B"}, names, "shuffling must not change the cached order") } func TestSoundCheckSong(t *testing.T) { dir := t.TempDir() m := NewMusicService(fakedb.New(), dir) _, err := m.SoundCheckSong() assert.ErrorIs(t, err, ErrNoSongs) writeFile(t, filepath.Join(dir, "check.mp3"), "x") path, err := m.SoundCheckSong() require.NoError(t, err) assert.Equal(t, filepath.Join(dir, "check.mp3"), path) _, err = NewMusicService(fakedb.New(), filepath.Join(dir, "missing")).SoundCheckSong() assert.Error(t, err) } func songPathByUUID(store *fakedb.Store, id uuid.UUID) string { for _, song := range store.Songs { if song.Uuid == id { return song.Path } } return "" } func TestMarkPlayedUsesSongUUID(t *testing.T) { // Two songs with the same name in one soundtrack: only the played one is counted. store := fakedb.New() st := addSoundtrackWithSongs(t, store, t.TempDir(), "Game A", 0, "Song") fileName := "Song (copy).mp3" writeFile(t, st.Path+fileName, "copy") store.AddTestSong(repository.Song{SoundtrackID: st.ID, SongName: "Song", Path: st.Path + fileName, FileName: &fileName}) m := NewMusicService(store, t.TempDir()) q := newQueue(t, m) queueSong(t, m, q) require.NoError(t, m.AddLatestPlayed(context.Background(), q)) songs := store.SongsOf(st.ID) require.Len(t, songs, 2) assert.ElementsMatch(t, []int32{0, 1}, []int32{songs[0].TimesPlayed, songs[1].TimesPlayed}) }