diff --git a/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowFixture.cs
new file mode 100644
index 00000000..d62ba7bb
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowFixture.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTrackRowFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the track.
+ /// Optional. The title of the track.
+ /// Optional. The duration of the track in seconds.
+ /// Optional. The Id of the album the track belongs to.
+ /// Optional. The title of the album the track belongs to.
+ /// Optional. The Id of the artist the album belongs to.
+ /// Optional. The path of the cover of the album.
+ /// Whether the cover path should be included, or forced to .
+ /// The created .
+ public ShuffleTrackRowDto Create(
+ Guid? trackId = null,
+ string? title = null,
+ int? durationInSeconds = null,
+ Guid? albumId = null,
+ string? albumTitle = null,
+ Guid? artistId = null,
+ string? coverPath = null,
+ bool includeCoverPath = true)
+ {
+ return new ShuffleTrackRowDto(
+ trackId ?? _faker.Random.Guid(),
+ title ?? _faker.Lorem.Sentence(),
+ durationInSeconds ?? _faker.Random.Int(1, 7200),
+ albumId ?? _faker.Random.Guid(),
+ albumTitle ?? _faker.Lorem.Sentence(),
+ artistId ?? _faker.Random.Guid(),
+ includeCoverPath ? (coverPath ?? _faker.System.FileName("jpg")) : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryFixture.cs
new file mode 100644
index 00000000..77474ee9
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryFixture.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksQueryFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the tracks are sampled from, taken from the route.
+ /// Optional. The maximum number of tracks to return.
+ /// Optional. The Id of the artist whose tracks are sampled.
+ /// Optional. The Id of the album whose tracks are sampled.
+ /// Optional. The tracks that must not be returned.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the excluded track Ids should be included, or forced to .
+ /// The created .
+ public ShuffleTracksQuery Create(
+ string? libraryId = null,
+ int? count = null,
+ Guid? artistId = null,
+ Guid? albumId = null,
+ IReadOnlyList? excludedTrackIds = null,
+ bool includeLibraryId = true,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeExcludedTrackIds = true)
+ {
+ return new ShuffleTracksQuery(
+ includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null,
+ count ?? Random.Shared.Next(1, 501),
+ includeArtistId ? (artistId ?? Guid.NewGuid()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid()) : null,
+ includeExcludedTrackIds
+ ? (excludedTrackIds ?? [.. Enumerable.Range(0, Random.Shared.Next(0, 3)).Select(_ => Guid.NewGuid())])
+ : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestFixture.cs
new file mode 100644
index 00000000..05e353d5
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestFixture.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The maximum number of tracks to return.
+ /// Optional. The Id of the artist whose tracks are sampled.
+ /// Optional. The Id of the album whose tracks are sampled.
+ /// Optional. The tracks that must not be returned.
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the excluded track Ids should be included, or forced to .
+ /// The created .
+ public ShuffleTracksRequest Create(
+ int? count = null,
+ Guid? artistId = null,
+ Guid? albumId = null,
+ List? excludedTrackIds = null,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeExcludedTrackIds = true)
+ {
+ return new ShuffleTracksRequest(
+ count ?? Random.Shared.Next(1, 501),
+ includeArtistId ? (artistId ?? Guid.NewGuid()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid()) : null,
+ includeExcludedTrackIds
+ ? (excludedTrackIds ?? [.. Enumerable.Range(0, Random.Shared.Next(0, 3)).Select(_ => Guid.NewGuid())])
+ : null);
+ }
+
+ ///
+ /// Creates a list of records with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured records.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackResponseFixture.cs
new file mode 100644
index 00000000..a2b4eff7
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackResponseFixture.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTrackResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the track.
+ /// Optional. The title of the track.
+ /// Optional. The duration of the track in seconds.
+ /// Optional. The Id of the album the track belongs to.
+ /// Optional. The title of the album the track belongs to.
+ /// Optional. The Id of the artist the album belongs to.
+ /// Optional. The path of the cover of the album.
+ /// Whether the cover path should be included, or forced to .
+ /// The created .
+ public ShuffleTrackResponse Create(
+ Guid? trackId = null,
+ string? title = null,
+ int? durationInSeconds = null,
+ Guid? albumId = null,
+ string? albumTitle = null,
+ Guid? artistId = null,
+ string? coverPath = null,
+ bool includeCoverPath = true)
+ {
+ return new ShuffleTrackResponse(
+ trackId ?? _faker.Random.Guid(),
+ title ?? _faker.Lorem.Sentence(),
+ durationInSeconds ?? _faker.Random.Int(1, 7200),
+ albumId ?? _faker.Random.Guid(),
+ albumTitle ?? _faker.Lorem.Sentence(),
+ artistId ?? _faker.Random.Guid(),
+ includeCoverPath ? (coverPath ?? _faker.System.FileName("jpg")) : null);
+ }
+
+ ///
+ /// Creates a list of records with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured records.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/MusicShuffleTrackDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/MusicShuffleTrackDtoFixture.cs
new file mode 100644
index 00000000..c48f55a4
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/AudioLibrary/MusicLibrary/MusicShuffleTrackDtoFixture.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicShuffleTrackDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The Id of the track.
+ /// Optional. The title of the track.
+ /// Optional. The duration of the track in seconds.
+ /// Optional. The Id of the album the track belongs to.
+ /// Optional. The title of the album the track belongs to.
+ /// Optional. The Id of the artist the album belongs to.
+ /// Optional. The path of the cover of the album.
+ /// Whether the cover path should be included, or forced to .
+ /// A configured instance.
+ public MusicShuffleTrackDto Create(
+ Guid? trackId = null,
+ string? title = null,
+ int? durationInSeconds = null,
+ Guid? albumId = null,
+ string? albumTitle = null,
+ Guid? artistId = null,
+ string? coverPath = null,
+ bool includeCoverPath = true)
+ {
+ return new MusicShuffleTrackDto
+ {
+ TrackId = trackId ?? _faker.Random.Guid(),
+ Title = title ?? _faker.Lorem.Sentence(),
+ DurationInSeconds = durationInSeconds ?? _faker.Random.Int(1, 7200),
+ AlbumId = albumId ?? _faker.Random.Guid(),
+ AlbumTitle = albumTitle ?? _faker.Lorem.Sentence(),
+ ArtistId = artistId ?? _faker.Random.Guid(),
+ CoverPath = includeCoverPath ? (coverPath ?? _faker.System.FileName("jpg")) : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestFixture.cs
new file mode 100644
index 00000000..ccafd0f9
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestFixture.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksRequestFixture
+{
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library the tracks are sampled from.
+ /// Optional. The maximum number of tracks to return.
+ /// Optional. The Id of the artist whose tracks are sampled.
+ /// Optional. The Id of the album whose tracks are sampled.
+ /// Optional. The tracks that must not be returned.
+ /// Whether the artist Id should be included, or forced to .
+ /// Whether the album Id should be included, or forced to .
+ /// Whether the excluded track Ids should be included, or forced to .
+ /// The created .
+ public ShuffleTracksRequest Create(
+ Guid? libraryId = null,
+ int? count = null,
+ Guid? artistId = null,
+ Guid? albumId = null,
+ List? excludedTrackIds = null,
+ bool includeArtistId = true,
+ bool includeAlbumId = true,
+ bool includeExcludedTrackIds = true)
+ {
+ return new ShuffleTracksRequest(
+ libraryId ?? Guid.NewGuid(),
+ count ?? Random.Shared.Next(1, 501),
+ includeArtistId ? (artistId ?? Guid.NewGuid()) : null,
+ includeAlbumId ? (albumId ?? Guid.NewGuid()) : null,
+ includeExcludedTrackIds
+ ? (excludedTrackIds ?? [.. Enumerable.Range(0, Random.Shared.Next(0, 3)).Select(_ => Guid.NewGuid())])
+ : null);
+ }
+
+ ///
+ /// Creates a list of records with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured records.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs
index 77e0b88b..37649e5c 100644
--- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs
+++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/Repositories/MusicLibrary/TrackRepositoryTests.cs
@@ -17,6 +17,7 @@ using Lumina.Domain.Common.Errors;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using NSubstitute;
@@ -46,6 +47,7 @@ public class TrackRepositoryTests
private readonly MediaContributorEntityFixture _mediaContributorEntityFixture = new();
private readonly AlbumEntityFixture _albumEntityFixture = new();
private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
private readonly PaginationDataDtoFixture _paginationDataDtoFixture = new();
[Fact]
@@ -932,6 +934,348 @@ public class TrackRepositoryTests
result.Value.Select(track => track.Id).OrderBy(id => id));
}
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenCalled_ShouldReturnOnlyTracksOfTheRequestedLibrary()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-library-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ List libraryTracks = await SeedShuffleTracksAsync(context, album, libraryId, 3);
+ Guid otherLibraryId = Guid.NewGuid();
+ ArtistEntity otherArtist = await SeedArtistAsync(context, otherLibraryId, "ABBA");
+ AlbumEntity otherAlbum = await SeedAlbumForArtistAsync(context, otherLibraryId, otherArtist.Id, "Arrival");
+ List otherLibraryTracks = await SeedShuffleTracksAsync(context, otherAlbum, otherLibraryId, 3);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, null, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(libraryTracks.Count, result.Value.Count);
+ Assert.All(result.Value, row => Assert.Contains(libraryTracks, track => track.Id == row.TrackId));
+ Assert.DoesNotContain(result.Value, row => otherLibraryTracks.Exists(track => track.Id == row.TrackId));
+ Assert.Equal(result.Value.Count, result.Value.Select(row => row.TrackId).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenArtistIdIsProvided_ShouldReturnOnlyTracksOfThatArtist()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-artist-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity artistAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ List artistTracks = await SeedShuffleTracksAsync(context, artistAlbum, libraryId, 2);
+ ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId, "David Bowie");
+ AlbumEntity otherArtistAlbum = await SeedAlbumForArtistAsync(context, libraryId, otherArtist.Id, "Heroes");
+ List otherArtistTracks = await SeedShuffleTracksAsync(context, otherArtistAlbum, libraryId, 2);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, artist.Id, null, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(artistTracks.Count, result.Value.Count);
+ Assert.All(result.Value, row => Assert.Contains(artistTracks, track => track.Id == row.TrackId));
+ Assert.All(result.Value, row => Assert.Equal(artist.Id, row.ArtistId));
+ Assert.DoesNotContain(result.Value, row => otherArtistTracks.Exists(track => track.Id == row.TrackId));
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenAlbumIdIsProvided_ShouldReturnOnlyTracksOfThatAlbum()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-album-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ List albumTracks = await SeedShuffleTracksAsync(context, album, libraryId, 2);
+ AlbumEntity otherAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "News of the World");
+ List otherAlbumTracks = await SeedShuffleTracksAsync(context, otherAlbum, libraryId, 2);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, album.Id, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(albumTracks.Count, result.Value.Count);
+ Assert.All(result.Value, row => Assert.Contains(albumTracks, track => track.Id == row.TrackId));
+ Assert.All(result.Value, row => Assert.Equal(album.Id, row.AlbumId));
+ Assert.DoesNotContain(result.Value, row => otherAlbumTracks.Exists(track => track.Id == row.TrackId));
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenArtistIdAndAlbumIdAreProvided_ShouldApplyBothFilters()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-bothfilters-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ List albumTracks = await SeedShuffleTracksAsync(context, album, libraryId, 2);
+ AlbumEntity otherAlbumOfArtist = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "News of the World");
+ List otherAlbumOfArtistTracks = await SeedShuffleTracksAsync(context, otherAlbumOfArtist, libraryId, 2);
+ ArtistEntity otherArtist = await SeedArtistAsync(context, libraryId, "David Bowie");
+ AlbumEntity otherArtistAlbum = await SeedAlbumForArtistAsync(context, libraryId, otherArtist.Id, "Heroes");
+ List otherArtistAlbumTracks = await SeedShuffleTracksAsync(context, otherArtistAlbum, libraryId, 2);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, artist.Id, album.Id, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(albumTracks.Count, result.Value.Count);
+ Assert.All(result.Value, row => Assert.Contains(albumTracks, track => track.Id == row.TrackId));
+ Assert.DoesNotContain(result.Value, row => otherAlbumOfArtistTracks.Exists(track => track.Id == row.TrackId));
+ Assert.DoesNotContain(result.Value, row => otherArtistAlbumTracks.Exists(track => track.Id == row.TrackId));
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenExcludedTrackIdsAreProvided_ShouldExcludeEveryOneOfThem()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-excluded-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ List tracks = await SeedShuffleTracksAsync(context, album, libraryId, 4);
+ Guid[] excludedTrackIds = [.. tracks.Take(3).Select(track => track.Id)];
+ TrackEntity expectedTrack = tracks[3];
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, null, excludedTrackIds, 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ShuffleTrackRowDto row = Assert.Single(result.Value);
+ Assert.Equal(expectedTrack.Id, row.TrackId);
+ Assert.DoesNotContain(result.Value, candidate => excludedTrackIds.Contains(candidate.TrackId));
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenCountIsLowerThanTheAvailableTracks_ShouldReturnAtMostCount()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-count-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ await SeedShuffleTracksAsync(context, album, libraryId, 5);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, null, [], 2, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(2, result.Value.Count);
+ Assert.Equal(result.Value.Count, result.Value.Select(row => row.TrackId).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenTheLibraryHasFewerTracksThanCount_ShouldReturnEveryAvailableTrack()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-fewertracks-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ List tracks = await SeedShuffleTracksAsync(context, album, libraryId, 2);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, null, [], 50, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(tracks.Count, result.Value.Count);
+ Assert.All(result.Value, row => Assert.Contains(tracks, track => track.Id == row.TrackId));
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenNothingMatches_ShouldReturnAnEmptyList()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nomatch-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ await SeedShuffleTracksAsync(context, album, libraryId, 2);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, Guid.NewGuid(), [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(result.Value);
+ Assert.Empty(result.Value);
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenCalled_ShouldProjectEveryField()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-projection-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ TrackEntity track = _trackEntityFixture.Create(
+ albumId: album.Id,
+ libraryId: libraryId,
+ path: "/music/queen/bohemian-rhapsody.flac",
+ title: "Bohemian Rhapsody",
+ includeMetadata: false);
+ track.DurationInSeconds = 355;
+ context.Tracks.Add(track);
+ await context.SaveChangesAsync();
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, null, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ShuffleTrackRowDto row = Assert.Single(result.Value);
+ Assert.Equal(track.Id, row.TrackId);
+ Assert.Equal("Bohemian Rhapsody", row.Title);
+ Assert.Equal(355, row.DurationInSeconds);
+ Assert.Equal(album.Id, row.AlbumId);
+ Assert.Equal("A Night at the Opera", row.AlbumTitle);
+ Assert.Equal(artist.Id, row.ArtistId);
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenTheAlbumHasACoverArtwork_ShouldProjectItsFileName()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-cover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ TrackEntity track = (await SeedShuffleTracksAsync(context, album, libraryId, 1))[0];
+ await AddArtworkAsync(context, album.Id, ArtworkType.Cover, "a-night-at-the-opera-cover.jpg");
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, album.Id, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ShuffleTrackRowDto row = Assert.Single(result.Value);
+ Assert.Equal(track.Id, row.TrackId);
+ Assert.Equal("a-night-at-the-opera-cover.jpg", row.CoverPath);
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenTheAlbumHasNoArtwork_ShouldProjectANullCoverPath()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-nocover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ await SeedShuffleTracksAsync(context, album, libraryId, 1);
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, album.Id, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ShuffleTrackRowDto row = Assert.Single(result.Value);
+ Assert.Null(row.CoverPath);
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenTheAlbumOnlyHasANonCoverArtwork_ShouldNotUseItAsTheCover()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-noncover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ await SeedShuffleTracksAsync(context, album, libraryId, 1);
+ await AddArtworkAsync(context, album.Id, ArtworkType.Booklet, "booklet-page.jpg");
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, album.Id, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ShuffleTrackRowDto row = Assert.Single(result.Value);
+ Assert.Null(row.CoverPath);
+ }
+
+ [Fact]
+ public async Task GetShuffleTracksLiteAsync_WhenOnlyAnotherAlbumHasACover_ShouldNotUseThatCover()
+ {
+ // Arrange
+ using SqliteConnection anchorConnection = new($"Data Source=luminadataccess-trackrepo-shuffle-othercover-{Guid.NewGuid()};Mode=Memory;Cache=Shared");
+ anchorConnection.Open();
+ using LuminaDbContext context = CreateContext(anchorConnection);
+ TrackRepository sut = new(context);
+ Guid libraryId = Guid.NewGuid();
+ ArtistEntity artist = await SeedArtistAsync(context, libraryId, "Queen");
+ AlbumEntity album = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "A Night at the Opera");
+ await SeedShuffleTracksAsync(context, album, libraryId, 1);
+ AlbumEntity otherAlbum = await SeedAlbumForArtistAsync(context, libraryId, artist.Id, "News of the World");
+ await AddArtworkAsync(context, otherAlbum.Id, ArtworkType.Cover, "news-of-the-world-cover.jpg");
+
+ // Act
+ Result> result = await sut.GetShuffleTracksLiteAsync(
+ libraryId, null, album.Id, [], 10, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ ShuffleTrackRowDto row = Assert.Single(result.Value);
+ Assert.Null(row.CoverPath);
+ }
+
///
/// Creates a list of tracks with distinct paths and empty metadata collections, so that the chunked lookup can be exercised without extra graph data.
///
@@ -1032,4 +1376,76 @@ public class TrackRepositoryTests
.Include(track => track.Isrcs)
.FirstAsync(track => track.Id == trackId);
}
+
+ ///
+ /// Seeds an artist of the library identified by .
+ ///
+ /// The context the artist is persisted through.
+ /// The Id of the library the artist belongs to.
+ /// The name of the artist.
+ /// The persisted artist.
+ private async Task SeedArtistAsync(LuminaDbContext context, Guid libraryId, string name)
+ {
+ ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false);
+ context.Artists.Add(artist);
+ await context.SaveChangesAsync();
+ return artist;
+ }
+
+ ///
+ /// Seeds an album of the artist identified by .
+ ///
+ /// The context the album is persisted through.
+ /// The Id of the library the album belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The title of the album.
+ /// The persisted album.
+ private async Task SeedAlbumForArtistAsync(LuminaDbContext context, Guid libraryId, Guid artistId, string title)
+ {
+ AlbumEntity album = _albumEntityFixture.Create(
+ artistId: artistId, libraryId: libraryId, title: title, includeTracks: false, includeMetadata: false);
+ context.Albums.Add(album);
+ await context.SaveChangesAsync();
+ return album;
+ }
+
+ ///
+ /// Seeds a number of tracks of the album identified by , with distinct paths and no metadata collections.
+ ///
+ /// The context the tracks are persisted through.
+ /// The album that owns the tracks.
+ /// The Id of the library that owns the tracks.
+ /// The number of tracks to seed.
+ /// The persisted tracks.
+ private async Task> SeedShuffleTracksAsync(LuminaDbContext context, AlbumEntity album, Guid libraryId, int count)
+ {
+ List tracks = [.. Enumerable.Range(0, count).Select(index => _trackEntityFixture.Create(
+ albumId: album.Id,
+ libraryId: libraryId,
+ path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
+ title: $"Shuffle Track {index}",
+ includeMetadata: false))];
+ context.Tracks.AddRange(tracks);
+ await context.SaveChangesAsync();
+ return tracks;
+ }
+
+ ///
+ /// Seeds a piece of artwork of the album identified by .
+ ///
+ /// The context the artwork is persisted through.
+ /// The Id of the album that owns the artwork.
+ /// The type of the artwork.
+ /// The relative file name of the stored artwork.
+ private async Task AddArtworkAsync(LuminaDbContext context, Guid albumId, ArtworkType artworkType, string fileName)
+ {
+ context.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
+ ownerType: MusicArtworkOwnerType.Album,
+ ownerId: albumId,
+ artworkType: artworkType,
+ ordinal: 0,
+ fileName: fileName,
+ status: ArtworkStatus.Enriched));
+ await context.SaveChangesAsync();
+ }
}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
new file mode 100644
index 00000000..b8dc750f
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
@@ -0,0 +1,483 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+using Lumina.Presentation.Api.IntegrationTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true,
+ Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly MusicArtworkEntityFixture _musicArtworkEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededLibraryIds = [];
+ private readonly List _seededUserIds = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public ShuffleTracksEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes the authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenLibraryHasTracks_ShouldReturnTheTracksWithAllTheirFields()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Queen Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ Guid trackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
+ Guid otherTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
+ await SeedAlbumCoverAsync(albumId, "a-night-at-the-opera-cover.jpg");
+ // A second library proves that the response is scoped to the library in the route.
+ Guid otherLibraryId = await SeedLibraryAsync(userId, "Other Library");
+ Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "ABBA");
+ Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Arrival");
+ Guid otherLibraryTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Dancing Queen", 231);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, 10);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Equal(2, tracks!.Count);
+ Assert.All(tracks, track => Assert.Contains(track.TrackId, new[] { trackId, otherTrackId }));
+ Assert.DoesNotContain(tracks, track => track.TrackId == otherLibraryTrackId);
+ ShuffleTrackResponse foundTrack = Assert.Single(tracks, track => track.TrackId == trackId);
+ Assert.Equal("Bohemian Rhapsody", foundTrack.Title);
+ Assert.Equal(355, foundTrack.DurationInSeconds);
+ Assert.Equal(albumId, foundTrack.AlbumId);
+ Assert.Equal("A Night at the Opera", foundTrack.AlbumTitle);
+ Assert.Equal(artistId, foundTrack.ArtistId);
+ Assert.Equal("a-night-at-the-opera-cover.jpg", foundTrack.CoverPath);
+ Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenArtistIdIsProvided_ShouldReturnOnlyTracksOfAlbumsOfThatArtist()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Two Artists Library");
+ Guid firstArtistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid firstAlbumId = await SeedAlbumAsync(libraryId, firstArtistId, "A Night at the Opera");
+ await SeedTrackAsync(libraryId, firstAlbumId, "Bohemian Rhapsody", 355);
+ await SeedTrackAsync(libraryId, firstAlbumId, "Love of My Life", 219);
+ Guid secondArtistId = await SeedArtistAsync(libraryId, "David Bowie");
+ Guid secondAlbumId = await SeedAlbumAsync(libraryId, secondArtistId, "Heroes");
+ await SeedTrackAsync(libraryId, secondAlbumId, "Heroes", 371);
+ await SeedTrackAsync(libraryId, secondAlbumId, "Beauty and the Beast", 212);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, 10, artistId: firstArtistId);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = JsonSerializer.Deserialize>(
+ await response.Content.ReadAsStringAsync(), _jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Equal(2, tracks!.Count);
+ Assert.All(tracks, track => Assert.Equal(firstArtistId, track.ArtistId));
+ Assert.All(tracks, track => Assert.Equal(firstAlbumId, track.AlbumId));
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenAlbumIdIsProvided_ShouldReturnOnlyTracksOfThatAlbum()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Two Albums Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
+ await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
+ Guid otherAlbumId = await SeedAlbumAsync(libraryId, artistId, "News of the World");
+ await SeedTrackAsync(libraryId, otherAlbumId, "We Are the Champions", 179);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, 10, albumId: albumId);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = JsonSerializer.Deserialize>(
+ await response.Content.ReadAsStringAsync(), _jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Equal(2, tracks!.Count);
+ Assert.All(tracks, track => Assert.Equal(albumId, track.AlbumId));
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenExcludedTrackIdsAreProvided_ShouldNeverReturnThem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Exclusion Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
+ Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
+ Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "The Prophet Song", 367);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(
+ libraryId, 10, excludedTrackIds: [firstTrackId, secondTrackId]);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = JsonSerializer.Deserialize>(
+ await response.Content.ReadAsStringAsync(), _jsonOptions);
+ Assert.NotNull(tracks);
+ ShuffleTrackResponse track = Assert.Single(tracks!);
+ Assert.Equal(thirdTrackId, track.TrackId);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenCountIsLowerThanTheAvailableTracks_ShouldReturnAtMostCountTracks()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Count Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ for (int index = 0; index < 5; index++)
+ await SeedTrackAsync(libraryId, albumId, $"Track {index}", 200 + index);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, 2);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = JsonSerializer.Deserialize>(
+ await response.Content.ReadAsStringAsync(), _jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Equal(2, tracks!.Count);
+ Assert.Equal(tracks.Count, tracks.Select(track => track.TrackId).Distinct().Count());
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenCountIsLargerThanTheAvailableTracks_ShouldReturnEveryAvailableTrack()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Small Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
+ Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, 50);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? tracks = JsonSerializer.Deserialize>(
+ await response.Content.ReadAsStringAsync(), _jsonOptions);
+ Assert.NotNull(tracks);
+ Assert.Equal(2, tracks!.Count);
+ Assert.Contains(tracks, track => track.TrackId == firstTrackId);
+ Assert.Contains(tracks, track => track.TrackId == secondTrackId);
+ }
+
+ [Theory]
+ [InlineData(0, "ShuffleTrackCountMustBeGreaterThanZero")] // no track is requested
+ [InlineData(-1, "ShuffleTrackCountMustBeGreaterThanZero")] // a negative selection size
+ [InlineData(501, "ShuffleTrackCountMustBeAtMost500")] // one more than the documented maximum
+ public async Task ShuffleTracks_WhenCountIsInvalid_ShouldReturnUnprocessableEntityWithTheValidationError(int count, string expectedError)
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, "Validation Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 355);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, count);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("General.Validation", problemDetails!["title"].GetString());
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails["status"].GetInt32());
+ JsonElement errors = problemDetails["errors"];
+ Assert.True(errors.TryGetProperty("General.Validation", out JsonElement validationErrors));
+ Assert.Contains(validationErrors.EnumerateArray(), error => error.GetString() == expectedError);
+ Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutTrackData()
+ {
+ // Arrange
+ (Guid otherUserId, string otherUsername) = await SeedOtherUserAsync();
+ Guid libraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ await SeedTrackAsync(libraryId, albumId, "Secret Song", 300);
+
+ // Act
+ HttpResponseMessage response = await PostShuffleAsync(libraryId, 10);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Secret Song", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.False(string.IsNullOrWhiteSpace(otherUsername));
+ }
+
+ ///
+ /// Posts a shuffle request for the library identified by .
+ ///
+ /// The Id of the library whose tracks are shuffled.
+ /// The maximum number of tracks to return.
+ /// Optional. The Id of the artist whose tracks are sampled.
+ /// Optional. The Id of the album whose tracks are sampled.
+ /// Optional. The tracks that must not be returned.
+ /// The response of the API.
+ private async Task PostShuffleAsync(
+ Guid libraryId,
+ int count,
+ Guid? artistId = null,
+ Guid? albumId = null,
+ IReadOnlyCollection? excludedTrackIds = null)
+ {
+ return await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{libraryId}/tracks/shuffle",
+ new { count, artistId, albumId, excludedTrackIds });
+ }
+
+ ///
+ /// Seeds a library owned by and tracks it for cleanup.
+ ///
+ /// The Id of the user that owns the library.
+ /// The title of the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(
+ id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ _seededLibraryIds.Add(libraryId);
+ return libraryId;
+ }
+
+ ///
+ /// Seeds an artist of the library identified by .
+ ///
+ /// The Id of the library the artist belongs to.
+ /// The name of the artist.
+ /// The Id of the seeded artist.
+ private async Task SeedArtistAsync(Guid libraryId, string name)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Artists.Add(_artistEntityFixture.Create(
+ id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return artistId;
+ }
+
+ ///
+ /// Seeds an album of the artist identified by .
+ ///
+ /// The Id of the library the album belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The title of the album.
+ /// The Id of the seeded album.
+ private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(
+ id: albumId,
+ artistId: artistId,
+ libraryId: libraryId,
+ title: title,
+ includeTracks: false,
+ includeMetadata: false,
+ includeBarcode: false,
+ includeOriginalReleaseDate: false,
+ includeOriginalReleaseYear: false,
+ includeReReleaseDate: false,
+ includeReReleaseYear: false);
+ dbContext.Albums.Add(album);
+ await dbContext.SaveChangesAsync();
+ return albumId;
+ }
+
+ ///
+ /// Seeds a track of the album identified by .
+ ///
+ /// The Id of the library the track belongs to.
+ /// The Id of the album the track belongs to.
+ /// The title of the track.
+ /// The duration of the track in seconds.
+ /// The Id of the seeded track.
+ private async Task SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid trackId = Guid.NewGuid();
+ TrackEntity track = _trackEntityFixture.Create(
+ id: trackId,
+ albumId: albumId,
+ libraryId: libraryId,
+ path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
+ title: title,
+ includeMetadata: false,
+ includeOriginalReleaseDate: false,
+ includeOriginalReleaseYear: false,
+ includeReReleaseDate: false,
+ includeReReleaseYear: false);
+ track.DurationInSeconds = durationInSeconds;
+ dbContext.Tracks.Add(track);
+ await dbContext.SaveChangesAsync();
+ return trackId;
+ }
+
+ ///
+ /// Seeds the cover artwork of the album identified by .
+ ///
+ /// The Id of the album that owns the artwork.
+ /// The file name of the stored cover.
+ private async Task SeedAlbumCoverAsync(Guid albumId, string fileName)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ dbContext.MusicArtwork.Add(_musicArtworkEntityFixture.Create(
+ ownerType: MusicArtworkOwnerType.Album,
+ ownerId: albumId,
+ artworkType: ArtworkType.Cover,
+ ordinal: 0,
+ fileName: fileName,
+ status: ArtworkStatus.Enriched));
+ await dbContext.SaveChangesAsync();
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user.
+ ///
+ /// The Id and the username of the seeded user.
+ private async Task<(Guid userId, string username)> SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUserIds.Add(userId);
+ return (userId, username);
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Removes the data seeded by the test and the API factory test user.
+ ///
+ public async Task DisposeAsync()
+ {
+ using (IServiceScope scope = _apiFactory.Services.CreateScope())
+ {
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ foreach (Guid libraryId in _seededLibraryIds)
+ {
+ List albumIds = await dbContext.Albums
+ .Where(album => album.LibraryId == libraryId)
+ .Select(album => album.Id)
+ .ToListAsync();
+ dbContext.MusicArtwork.RemoveRange(dbContext.MusicArtwork.Where(artwork => albumIds.Contains(artwork.OwnerId)));
+ dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => track.LibraryId == libraryId));
+ dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => album.LibraryId == libraryId));
+ dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => artist.LibraryId == libraryId));
+ dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => library.Id == libraryId));
+ }
+ dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id)));
+ await dbContext.SaveChangesAsync();
+ }
+ await _apiFactory.RemoveTestUserAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
new file mode 100644
index 00000000..8571fcb2
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
@@ -0,0 +1,202 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.AudioLibrary.MusicLibrary;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksEndpointTests : IClassFixture
+{
+ private const string SHUFFLE_TRACKS_PATH = "/en-us/library/audio-library/music-library/tracks/api-shuffle-tracks";
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
+ private readonly MusicShuffleTrackDtoFixture _musicShuffleTrackDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public ShuffleTracksEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenApiReturnsTracks_ShouldReturnTheMappedTracks()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid trackId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid excludedTrackId = Guid.NewGuid();
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
+ count: 25, excludedTrackIds: [excludedTrackId]);
+ MusicShuffleTrackDto expectedTrack = _musicShuffleTrackDtoFixture.Create(
+ trackId: trackId,
+ title: "Bohemian Rhapsody",
+ durationInSeconds: 355,
+ albumId: albumId,
+ albumTitle: "A Night at the Opera",
+ artistId: artistId,
+ coverPath: "a-night-at-the-opera-cover.jpg");
+ _apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List { expectedTrack });
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(1, data.GetArrayLength());
+ JsonElement track = data[0];
+ Assert.Equal(trackId, track.GetProperty("trackId").GetGuid());
+ Assert.Equal("Bohemian Rhapsody", track.GetProperty("title").GetString());
+ Assert.Equal(355, track.GetProperty("durationInSeconds").GetInt32());
+ Assert.Equal(albumId, track.GetProperty("albumId").GetGuid());
+ Assert.Equal("A Night at the Opera", track.GetProperty("albumTitle").GetString());
+ Assert.Equal(artistId, track.GetProperty("artistId").GetGuid());
+ Assert.Equal("a-night-at-the-opera-cover.jpg", track.GetProperty("coverPath").GetString());
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenCalled_ShouldForwardTheRequestToTheLibraryShuffleEndpoint()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid firstExcludedTrackId = Guid.NewGuid();
+ Guid secondExcludedTrackId = Guid.NewGuid();
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
+ count: 25,
+ artistId: artistId,
+ albumId: albumId,
+ excludedTrackIds: [firstExcludedTrackId, secondExcludedTrackId]);
+ _apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ (string Endpoint, object? Data) forwardedRequest = Assert.Single(
+ _apiFactory.ApiClientStub.PostRequests,
+ postRequest => postRequest.Endpoint == ExpectedEndpoint(request.LibraryId));
+ Assert.Equal($"libraries/{request.LibraryId}/tracks/shuffle", forwardedRequest.Endpoint);
+ ShuffleTracksRequest forwarded = Assert.IsType(forwardedRequest.Data);
+ Assert.Equal(request.LibraryId, forwarded.LibraryId);
+ Assert.Equal(25, forwarded.Count);
+ Assert.Equal(artistId, forwarded.ArtistId);
+ Assert.Equal(albumId, forwarded.AlbumId);
+ Assert.NotNull(forwarded.ExcludedTrackIds);
+ Assert.Equal(new[] { firstExcludedTrackId, secondExcludedTrackId }, forwarded.ExcludedTrackIds);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenApiReturnsNoTracks_ShouldReturnAnEmptyDataArray()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
+ _apiFactory.ApiClientStub.RegisterPostResponse(ExpectedEndpoint(request.LibraryId), new List());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(JsonValueKind.Array, data.ValueKind);
+ Assert.Equal(0, data.GetArrayLength());
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenBodyIsMalformed_ShouldNotLeakServerDetailsOrCallTheApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ StringContent body = new("{\"libraryId\": \"'; DROP TABLE Tracks; --\", \"count\": \"'; DROP TABLE Tracks; --\"}", Encoding.UTF8, "application/json");
+ HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
+ {
+ Content = body
+ };
+ shuffleRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
+ shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(shuffleRequest);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ // The unbound request is rejected before the upstream API is reached, and the JSON error is sanitized.
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.False(json.RootElement.GetProperty("success").GetBoolean());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint.EndsWith("/tracks/shuffle", StringComparison.Ordinal));
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("'; DROP TABLE Tracks; --", content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Builds the upstream API endpoint of the shuffle request for the library identified by .
+ ///
+ /// The Id of the media library the tracks are sampled from.
+ /// The upstream endpoint.
+ private static string ExpectedEndpoint(Guid libraryId)
+ {
+ return ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
+ }
+
+ ///
+ /// Builds the Web shuffle request that posts the given .
+ ///
+ /// The shuffle request to send.
+ /// The configured Web request.
+ private static HttpRequestMessage CreateShuffleRequest(ShuffleTracksRequest request)
+ {
+ HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
+ {
+ Content = JsonContent.Create(request)
+ };
+ shuffleRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
+ shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ return shuffleRequest;
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
new file mode 100644
index 00000000..764889c9
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
@@ -0,0 +1,353 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+using Lumina.Presentation.Api.SecurityTests.Common.Setup;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Json;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+
+///
+/// Contains security tests for the class.
+///
+///
+/// Rate limiting is not exercised because the shuffle route does not declare a rate limiter policy, unlike the authentication and track streaming routes,
+/// so there is no configured limit to exceed. Token and claim correctness does not apply, because the route issues no token. Timing attack resistance does not
+/// apply either, because the route performs no credential comparison.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksEndpointTests : IClassFixture, IDisposable
+{
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
+ private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly TrackEntityFixture _trackEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public ShuffleTracksEndpointTests(LuminaApiFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ _client = apiFactory.CreateClient();
+ // A unique X-Forwarded-For isolates rate limiting state per test.
+ _client.DefaultRequestHeaders.Add("X-Forwarded-For", LuminaApiFactory.GetUniqueTestIp());
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle";
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(url, new { count = 10 });
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal(url, problemDetails["instance"].GetProperty("value").GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; EXEC xp_cmdshell('dir'); --")] // command execution attempt
+ public async Task ShuffleTracks_WithSQLInjectionInLibraryId_ShouldNotCorruptOrLeakData(string maliciousLibraryId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{Uri.EscapeDataString(maliciousLibraryId)}/tracks/shuffle", new { count = 10 });
+
+ // Assert
+ // The route value is kept as a raw string, so the unparseable Id reaches the query validator, which reports a clean validation error instead of failing the request binding.
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("General.Validation", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Contains("LibraryIdCannotBeEmpty", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInCount_ShouldNotCorruptOrLeakData(string maliciousCount)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = maliciousCount });
+
+ // Assert
+ // The endpoint opts into DontCatchExceptions(), so a body value that cannot be bound is answered by the generic exception handler with the sanitized 500 problem.
+ Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
+ await AssertSanitizedProblemAsync(response, maliciousCount);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInArtistId_ShouldNotCorruptOrLeakData(string maliciousArtistId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, artistId = maliciousArtistId });
+
+ // Assert
+ Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
+ await AssertSanitizedProblemAsync(response, maliciousArtistId);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInAlbumId_ShouldNotCorruptOrLeakData(string maliciousAlbumId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, albumId = maliciousAlbumId });
+
+ // Assert
+ Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
+ await AssertSanitizedProblemAsync(response, maliciousAlbumId);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldNotCorruptOrLeakData(string maliciousTrackId)
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{Guid.NewGuid()}/tracks/shuffle", new { count = 10, excludedTrackIds = new[] { maliciousTrackId } });
+
+ // Assert
+ Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
+ await AssertSanitizedProblemAsync(response, maliciousTrackId);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenResult()
+ {
+ // Arrange
+ (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client);
+ _seededUsernames.Add(username);
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid libraryId = await SeedLibraryAsync(otherUserId, "Other User Library");
+ Guid artistId = await SeedArtistAsync(libraryId, "Queen");
+ Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera");
+ await SeedTrackAsync(libraryId, albumId, "Hidden Song");
+
+ // Act
+ HttpResponseMessage response = await _client.PostAsJsonAsync(
+ $"/api/v1/libraries/{libraryId}/tracks/shuffle", new { count = 10 });
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.DoesNotContain("Hidden Song", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Asserts that the response is the sanitized generic API problem and never echoes the payload or leaks database details.
+ ///
+ /// The response to inspect.
+ /// The malicious payload that must not be echoed.
+ /// A task representing the asynchronous operation.
+ private static async Task AssertSanitizedProblemAsync(HttpResponseMessage response, string payload)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("testuser_", content, StringComparison.OrdinalIgnoreCase);
+ using JsonDocument problemDetails = JsonDocument.Parse(content);
+ Assert.Equal("InternalServerError", problemDetails.RootElement.GetProperty("title").GetString());
+ Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.RootElement.GetProperty("status").GetInt32());
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded other user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Seeds a library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The title of the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(
+ id: libraryId, userId: userId, title: title, libraryType: LibraryType.Music, contentLocations: []));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds an artist of the library identified by .
+ ///
+ /// The Id of the library the artist belongs to.
+ /// The name of the artist.
+ /// The Id of the seeded artist.
+ private async Task SeedArtistAsync(Guid libraryId, string name)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid artistId = Guid.NewGuid();
+ dbContext.Artists.Add(_artistEntityFixture.Create(
+ id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
+ await dbContext.SaveChangesAsync();
+ return artistId;
+ }
+
+ ///
+ /// Seeds an album of the artist identified by .
+ ///
+ /// The Id of the library the album belongs to.
+ /// The Id of the artist the album belongs to.
+ /// The title of the album.
+ /// The Id of the seeded album.
+ private async Task SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid albumId = Guid.NewGuid();
+ AlbumEntity album = _albumEntityFixture.Create(
+ id: albumId,
+ artistId: artistId,
+ libraryId: libraryId,
+ title: title,
+ includeTracks: false,
+ includeMetadata: false,
+ includeBarcode: false,
+ includeOriginalReleaseDate: false,
+ includeOriginalReleaseYear: false,
+ includeReReleaseDate: false,
+ includeReReleaseYear: false);
+ dbContext.Albums.Add(album);
+ await dbContext.SaveChangesAsync();
+ return albumId;
+ }
+
+ ///
+ /// Seeds a track of the album identified by .
+ ///
+ /// The Id of the library the track belongs to.
+ /// The Id of the album the track belongs to.
+ /// The title of the track.
+ /// The Id of the seeded track.
+ private async Task SeedTrackAsync(Guid libraryId, Guid albumId, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid trackId = Guid.NewGuid();
+ TrackEntity track = _trackEntityFixture.Create(
+ id: trackId,
+ albumId: albumId,
+ libraryId: libraryId,
+ path: $"/music/shuffle-{Guid.NewGuid():N}.flac",
+ title: title,
+ includeMetadata: false,
+ includeOriginalReleaseDate: false,
+ includeOriginalReleaseYear: false,
+ includeReReleaseDate: false,
+ includeReReleaseYear: false);
+ dbContext.Tracks.Add(track);
+ await dbContext.SaveChangesAsync();
+ return trackId;
+ }
+
+ ///
+ /// Disposes the API factory resources.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
new file mode 100644
index 00000000..fdf0337b
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
@@ -0,0 +1,211 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Exceptions;
+using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
+using Lumina.Presentation.Web.SecurityTests.Common.Setup;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+
+///
+/// Contains security tests for the class.
+///
+///
+/// The shuffle route declares no rate limiter policy, so rate limiting is not exercised here. Token and claim correctness does not apply, because the Web
+/// layer issues no token for this route, and timing attack resistance does not apply either, because the route performs no credential comparison.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksEndpointTests : IClassFixture
+{
+ private const string SHUFFLE_TRACKS_PATH = "/en-us/library/audio-library/music-library/tracks/api-shuffle-tracks";
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
+ private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public ShuffleTracksEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
+
+ // Act
+ HttpResponseMessage response = await anonymousClient.SendAsync(CreateShuffleRequest(request));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("/en-us/auth/login", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => IsShuffleCall(postRequest.Endpoint));
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInLibraryId_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
+ $"{{\"libraryId\": {JsonSerializer.Serialize(payload)}, \"count\": 10}}"));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ AssertRejectedWithoutLeak(content, payload);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInCount_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
+ $"{{\"libraryId\": \"{Guid.NewGuid()}\", \"count\": {JsonSerializer.Serialize(payload)}}}"));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ AssertRejectedWithoutLeak(content, payload);
+ }
+
+ [Theory]
+ [InlineData("'; DROP TABLE Tracks; --")] // destructive injection
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ public async Task ShuffleTracks_WithInjectionInExcludedTrackIds_ShouldRejectTheRequestWithoutCallingTheApi(string payload)
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateRawShuffleRequest(
+ $"{{\"libraryId\": \"{Guid.NewGuid()}\", \"count\": 10, \"excludedTrackIds\": [{JsonSerializer.Serialize(payload)}]}}"));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ AssertRejectedWithoutLeak(content, payload);
+ }
+
+ [Fact]
+ public async Task ShuffleTracks_WhenApiRejectsTheRequest_ShouldReturnACleanErrorWithoutLeakingData()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ Guid libraryId = Guid.NewGuid();
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(libraryId: libraryId);
+ string expectedEndpoint = ApiRoutes.Music.SHUFFLE_TRACKS.Replace("{libraryId}", libraryId.ToString());
+ _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(
+ _problemDetailsDtoFixture.Create(title: "General.Unauthorized", detail: "NotAuthorized"),
+ HttpStatusCode.Forbidden,
+ expectedEndpoint));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(CreateShuffleRequest(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ // The Web layer answers programmatic callers with a sanitized JSON error instead of forwarding the upstream problem details verbatim.
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.False(json.RootElement.GetProperty("success").GetBoolean());
+ Assert.Contains("not authorized", content, StringComparison.OrdinalIgnoreCase);
+ Assert.Contains(_apiFactory.ApiClientStub.PostRequests, postRequest => postRequest.Endpoint == expectedEndpoint);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Asserts that a request rejected before reaching the API was answered with a sanitized JSON error that does not echo the payload.
+ ///
+ /// The body of the response.
+ /// The malicious payload that must not be echoed.
+ private void AssertRejectedWithoutLeak(string content, string payload)
+ {
+ // The Web layer reports binding failures to programmatic callers as a JSON error with the success flag cleared, and never forwards the request upstream.
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.False(json.RootElement.GetProperty("success").GetBoolean());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.PostRequests, postRequest => IsShuffleCall(postRequest.Endpoint));
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(AppContext.BaseDirectory, content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Checks whether the specified upstream endpoint is the shuffle endpoint.
+ ///
+ /// The upstream endpoint to check.
+ /// when the endpoint is the shuffle endpoint, otherwise.
+ private static bool IsShuffleCall(string endpoint)
+ {
+ return endpoint.EndsWith("/tracks/shuffle", StringComparison.Ordinal);
+ }
+
+ ///
+ /// Builds the Web shuffle request that posts the given .
+ ///
+ /// The shuffle request to send.
+ /// The configured Web request.
+ private static HttpRequestMessage CreateShuffleRequest(ShuffleTracksRequest request)
+ {
+ HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
+ {
+ Content = JsonContent.Create(request)
+ };
+ shuffleRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
+ shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ return shuffleRequest;
+ }
+
+ ///
+ /// Builds the Web shuffle request that posts the given raw JSON body.
+ ///
+ /// The raw JSON body to send.
+ /// The configured Web request.
+ private static HttpRequestMessage CreateRawShuffleRequest(string jsonBody)
+ {
+ HttpRequestMessage shuffleRequest = new(HttpMethod.Post, SHUFFLE_TRACKS_PATH)
+ {
+ Content = new StringContent(jsonBody, Encoding.UTF8, "application/json")
+ };
+ shuffleRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
+ shuffleRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ return shuffleRequest;
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs
index 35de8edf..8ad5b25e 100644
--- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Albums/AlbumEntityMappingTests.cs
@@ -27,6 +27,7 @@ namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.
public class AlbumEntityMappingTests
{
private readonly AlbumEntityFixture _albumEntityFixture = new();
+ private readonly ArtistEntityFixture _artistEntityFixture = new();
private readonly TrackEntityFixture _trackEntityFixture = new();
private readonly GenreEntityFixture _genreEntityFixture = new();
private readonly TagEntityFixture _tagEntityFixture = new();
@@ -252,6 +253,7 @@ public class AlbumEntityMappingTests
{
// Arrange
AlbumEntity entity = _albumEntityFixture.Create();
+ entity.Artist = _artistEntityFixture.Create(name: "Queen");
// Act
AlbumResponse result = entity.ToResponse();
@@ -260,6 +262,7 @@ public class AlbumEntityMappingTests
Assert.NotNull(result);
Assert.Equal(entity.Id, result.Id);
Assert.Equal(entity.ArtistId, result.ArtistId);
+ Assert.Equal("Queen", result.ArtistName);
Assert.Equal(entity.LibraryId, result.LibraryId);
// No cover path is supplied by default, so the response exposes none.
Assert.Null(result.CoverPath);
@@ -299,6 +302,21 @@ public class AlbumEntityMappingTests
Assert.Equal(entity.Tracks.Select(track => track.Id), result.Tracks!.Select(track => track.Id));
}
+ [Fact]
+ public void ToResponse_WhenAlbumHasNoArtist_ShouldMapAnEmptyArtistName()
+ {
+ // Arrange
+ AlbumEntity entity = _albumEntityFixture.Create();
+ entity.Artist = null;
+
+ // Act
+ AlbumResponse result = entity.ToResponse();
+
+ // Assert
+ // The response contract always carries an artist name, so an album loaded without its artist exposes an empty one instead of null.
+ Assert.Equal(string.Empty, result.ArtistName);
+ }
+
[Fact]
public void ToResponse_WhenLanguageSubpropertiesAreBlank_ShouldMapLanguagesToNull()
{
@@ -335,6 +353,8 @@ public class AlbumEntityMappingTests
{
// Arrange
List entities = _albumEntityFixture.CreateMany(2);
+ for (int i = 0; i < entities.Count; i++)
+ entities[i].Artist = _artistEntityFixture.Create(name: $"Artist {i}");
// Act
IReadOnlyList results = entities.ToResponses();
@@ -346,6 +366,7 @@ public class AlbumEntityMappingTests
{
Assert.Equal(entities[i].Id, results[i].Id);
Assert.Equal(entities[i].Title, results[i].Metadata.Title);
+ Assert.Equal($"Artist {i}", results[i].ArtistName);
}
}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDtoMappingTests.cs
new file mode 100644
index 00000000..9d984b34
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTrackRowDtoMappingTests.cs
@@ -0,0 +1,94 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTrackRowDtoMappingTests
+{
+ private readonly ShuffleTrackRowFixture _shuffleTrackRowFixture = new();
+
+ [Fact]
+ public void ToResponse_WhenMappingTrackWithCoverPath_ShouldMapAllPropertiesCorrectly()
+ {
+ // Arrange
+ ShuffleTrackRowDto readModel = _shuffleTrackRowFixture.Create(
+ title: "Bohemian Rhapsody",
+ durationInSeconds: 355,
+ albumTitle: "A Night at the Opera",
+ coverPath: "a-night-at-the-opera-cover.jpg");
+
+ // Act
+ ShuffleTrackResponse result = readModel.ToResponse();
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(readModel.TrackId, result.TrackId);
+ Assert.Equal(readModel.Title, result.Title);
+ Assert.Equal(readModel.DurationInSeconds, result.DurationInSeconds);
+ Assert.Equal(readModel.AlbumId, result.AlbumId);
+ Assert.Equal(readModel.AlbumTitle, result.AlbumTitle);
+ Assert.Equal(readModel.ArtistId, result.ArtistId);
+ Assert.Equal("a-night-at-the-opera-cover.jpg", result.CoverPath);
+ }
+
+ [Fact]
+ public void ToResponse_WhenCoverPathIsMissing_ShouldMapNullCoverPath()
+ {
+ // Arrange
+ ShuffleTrackRowDto readModel = _shuffleTrackRowFixture.Create(includeCoverPath: false);
+
+ // Act
+ ShuffleTrackResponse result = readModel.ToResponse();
+
+ // Assert
+ Assert.Null(result.CoverPath);
+ Assert.Equal(readModel.TrackId, result.TrackId);
+ }
+
+ [Fact]
+ public void ToResponses_WhenMappingMultipleRows_ShouldMapEveryRowAndPreserveTheOrder()
+ {
+ // Arrange
+ List readModels = _shuffleTrackRowFixture.CreateMany(4);
+
+ // Act
+ IReadOnlyList results = readModels.ToResponses();
+
+ // Assert
+ Assert.NotNull(results);
+ Assert.Equal(readModels.Count, results.Count);
+ Assert.Equal(readModels.Select(readModel => readModel.TrackId), results.Select(response => response.TrackId));
+ Assert.Equal(readModels.Select(readModel => readModel.Title), results.Select(response => response.Title));
+ Assert.Equal(readModels.Select(readModel => readModel.DurationInSeconds), results.Select(response => response.DurationInSeconds));
+ Assert.Equal(readModels.Select(readModel => readModel.AlbumId), results.Select(response => response.AlbumId));
+ Assert.Equal(readModels.Select(readModel => readModel.AlbumTitle), results.Select(response => response.AlbumTitle));
+ Assert.Equal(readModels.Select(readModel => readModel.ArtistId), results.Select(response => response.ArtistId));
+ Assert.Equal(readModels.Select(readModel => readModel.CoverPath), results.Select(response => response.CoverPath));
+ }
+
+ [Fact]
+ public void ToResponses_WhenInputIsEmpty_ShouldReturnAnEmptyCollection()
+ {
+ // Arrange
+ IEnumerable readModels = [];
+
+ // Act
+ IReadOnlyList results = readModels.ToResponses();
+
+ // Assert
+ Assert.NotNull(results);
+ Assert.Empty(results);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestMappingTests.cs
new file mode 100644
index 00000000..0aa7879e
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/ShuffleTracksRequestMappingTests.cs
@@ -0,0 +1,107 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksRequestMappingTests
+{
+ private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
+
+ [Fact]
+ public void ToQuery_WhenMappingCompleteRequest_ShouldMapAllPropertiesCorrectly()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid firstExcludedTrackId = Guid.NewGuid();
+ Guid secondExcludedTrackId = Guid.NewGuid();
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
+ count: 25,
+ artistId: artistId,
+ albumId: albumId,
+ excludedTrackIds: [firstExcludedTrackId, secondExcludedTrackId]);
+
+ // Act
+ ShuffleTracksQuery result = request.ToQuery(libraryId.ToString());
+
+ // Assert
+ Assert.NotNull(result);
+ Assert.Equal(libraryId.ToString(), result.LibraryId);
+ Assert.Equal(25, result.Count);
+ Assert.Equal(artistId, result.ArtistId);
+ Assert.Equal(albumId, result.AlbumId);
+ Assert.NotNull(result.ExcludedTrackIds);
+ Assert.Equal(new[] { firstExcludedTrackId, secondExcludedTrackId }, result.ExcludedTrackIds);
+ }
+
+ [Fact]
+ public void ToQuery_WhenExcludedTrackIdsAreNull_ShouldKeepThemNull()
+ {
+ // Arrange
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(includeExcludedTrackIds: false);
+
+ // Act
+ ShuffleTracksQuery result = request.ToQuery(Guid.NewGuid().ToString());
+
+ // Assert
+ Assert.Null(result.ExcludedTrackIds);
+ }
+
+ [Fact]
+ public void ToQuery_WhenOptionalScopeIsMissing_ShouldKeepTheScopeNull()
+ {
+ // Arrange
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(includeArtistId: false, includeAlbumId: false);
+
+ // Act
+ ShuffleTracksQuery result = request.ToQuery(Guid.NewGuid().ToString());
+
+ // Assert
+ Assert.Null(result.ArtistId);
+ Assert.Null(result.AlbumId);
+ }
+
+ [Fact]
+ public void ToQuery_WhenLibraryIdArgumentIsNull_ShouldKeepItNull()
+ {
+ // Arrange
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
+
+ // Act
+ ShuffleTracksQuery result = request.ToQuery(null);
+
+ // Assert
+ // The route value is forwarded untouched, so that the query validator reports the missing identifier.
+ Assert.Null(result.LibraryId);
+ }
+
+ [Theory]
+ [InlineData("not-a-guid")] // a value that cannot be parsed
+ [InlineData("' OR '1'='1")] // an injection payload
+ [InlineData("'; DROP TABLE Tracks; --")] // a destructive injection payload
+ public void ToQuery_WhenLibraryIdArgumentIsNotParseable_ShouldPassItVerbatim(string libraryId)
+ {
+ // Arrange
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create();
+
+ // Act
+ ShuffleTracksQuery result = request.ToQuery(libraryId);
+
+ // Assert
+ // The raw route value must reach the validator, which is the layer that decides it is not a valid identifier.
+ Assert.Equal(libraryId, result.LibraryId);
+ Assert.Equal(request.Count, result.Count);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryHandlerTests.cs
new file mode 100644
index 00000000..b40e42cc
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryHandlerTests.cs
@@ -0,0 +1,318 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksQueryHandlerTests
+{
+ private readonly IUnitOfWork _mockUnitOfWork;
+ private readonly ITrackRepository _mockTrackRepository;
+ private readonly IAuthorizationService _mockAuthorizationService;
+ private readonly ICurrentUserService _mockCurrentUserService;
+ private readonly IValidator _mockValidator;
+ private readonly ShuffleTracksQueryHandler _sut;
+ private readonly Guid _userId;
+ private readonly ShuffleTracksQueryFixture _shuffleTracksQueryFixture = new();
+ private readonly ShuffleTrackRowFixture _shuffleTrackRowFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ShuffleTracksQueryHandlerTests()
+ {
+ _mockTrackRepository = Substitute.For();
+ _mockUnitOfWork = Substitute.For();
+ _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
+ _mockAuthorizationService = Substitute.For();
+ _mockCurrentUserService = Substitute.For();
+ _mockValidator = Substitute.For>();
+ _userId = Guid.NewGuid();
+
+ // Default stubs: the current user is authenticated and the library ownership policy allows access.
+ _mockCurrentUserService.UserId.Returns(_userId);
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(true);
+ _mockValidator.Validate(Arg.Any()).Returns([]);
+
+ _sut = new ShuffleTracksQueryHandler(_mockUnitOfWork, _mockAuthorizationService, _mockCurrentUserService, _mockValidator);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenRepositoryReturnsTracks_ShouldReturnMappedResponses()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
+ Guid firstTrackId = Guid.NewGuid();
+ Guid secondTrackId = Guid.NewGuid();
+ Guid firstAlbumId = Guid.NewGuid();
+ Guid secondAlbumId = Guid.NewGuid();
+ Guid firstArtistId = Guid.NewGuid();
+ Guid secondArtistId = Guid.NewGuid();
+ List rows =
+ [
+ _shuffleTrackRowFixture.Create(
+ trackId: firstTrackId,
+ title: "Bohemian Rhapsody",
+ durationInSeconds: 355,
+ albumId: firstAlbumId,
+ albumTitle: "A Night at the Opera",
+ artistId: firstArtistId,
+ coverPath: "a-night-at-the-opera-cover.jpg"),
+ _shuffleTrackRowFixture.Create(
+ trackId: secondTrackId,
+ title: "Love of My Life",
+ durationInSeconds: 219,
+ albumId: secondAlbumId,
+ albumTitle: "A Night at the Opera",
+ artistId: secondArtistId,
+ includeCoverPath: false)
+ ];
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>(rows));
+
+ // Act
+ Result> result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.Equal(2, result.Value.Count);
+ Assert.Equal(firstTrackId, result.Value[0].TrackId);
+ Assert.Equal("Bohemian Rhapsody", result.Value[0].Title);
+ Assert.Equal(355, result.Value[0].DurationInSeconds);
+ Assert.Equal(firstAlbumId, result.Value[0].AlbumId);
+ Assert.Equal("A Night at the Opera", result.Value[0].AlbumTitle);
+ Assert.Equal(firstArtistId, result.Value[0].ArtistId);
+ Assert.Equal("a-night-at-the-opera-cover.jpg", result.Value[0].CoverPath);
+ Assert.Equal(secondTrackId, result.Value[1].TrackId);
+ Assert.Equal("Love of My Life", result.Value[1].Title);
+ Assert.Equal(219, result.Value[1].DurationInSeconds);
+ Assert.Equal(secondAlbumId, result.Value[1].AlbumId);
+ Assert.Equal("A Night at the Opera", result.Value[1].AlbumTitle);
+ Assert.Equal(secondArtistId, result.Value[1].ArtistId);
+ Assert.Null(result.Value[1].CoverPath);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenTracksAreRequested_ShouldQueryRepositoryWithParsedLibraryScopeAndCount()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(
+ libraryId: libraryId.ToString(),
+ count: 25,
+ artistId: artistId,
+ albumId: albumId,
+ excludedTrackIds: [Guid.NewGuid(), Guid.NewGuid()]);
+ CancellationToken cancellationToken = new();
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+
+ // Act
+ await _sut.HandleAsync(query, cancellationToken);
+
+ // Assert
+ await _mockTrackRepository.Received(1).GetShuffleTracksLiteAsync(
+ libraryId,
+ artistId,
+ albumId,
+ Arg.Is>(excludedIds => excludedIds.Count == 2),
+ query.Count,
+ Arg.Is(cancellationToken));
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenExcludedTrackIdsAreNull_ShouldQueryRepositoryWithAnEmptyCollection()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeExcludedTrackIds: false);
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+
+ // Act
+ await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ await _mockTrackRepository.Received(1).GetShuffleTracksLiteAsync(
+ Arg.Any(),
+ Arg.Any(),
+ Arg.Any(),
+ Arg.Is>(excludedIds => excludedIds.Count == 0),
+ Arg.Any(),
+ Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenExcludedTrackIdsContainEmptyAndRepeatedIds_ShouldQueryRepositoryWithTheDistinctNonEmptyIds()
+ {
+ // Arrange
+ Guid firstTrackId = Guid.NewGuid();
+ Guid secondTrackId = Guid.NewGuid();
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(
+ excludedTrackIds: [firstTrackId, Guid.Empty, secondTrackId, firstTrackId]);
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+
+ // Act
+ await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ await _mockTrackRepository.Received(1).GetShuffleTracksLiteAsync(
+ Arg.Any(),
+ Arg.Any(),
+ Arg.Any(),
+ Arg.Is>(excludedIds =>
+ excludedIds.Count == 2 &&
+ excludedIds.Contains(firstTrackId) &&
+ excludedIds.Contains(secondTrackId) &&
+ !excludedIds.Contains(Guid.Empty)),
+ Arg.Any(),
+ Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenLibraryIsEvaluated_ShouldUseTheParsedLibraryIdAndTheCurrentUser()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(libraryId: libraryId.ToString());
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+
+ // Act
+ await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ await _mockAuthorizationService.Received(1).EvaluatePolicyAsync(
+ _userId,
+ Arg.Is(context => context.LibraryId == libraryId),
+ Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutQuerying()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
+ _mockValidator.Validate(Arg.Any()).Returns([Errors.Music.ShuffleTrackCountMustBeGreaterThanZero]);
+
+ // Act
+ Result> result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero, result.FirstError);
+ await _mockTrackRepository.DidNotReceive().GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any());
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(
+ Arg.Any(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
+ _mockCurrentUserService.UserId.Returns((Guid?)null);
+
+ // Act
+ Result> result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(
+ Arg.Any(), Arg.Any(), Arg.Any());
+ await _mockTrackRepository.DidNotReceive().GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenPolicyDeniesAccess_ShouldReturnNotAuthorizedError()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(libraryId: libraryId.ToString());
+ _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any())
+ .Returns(false);
+
+ // Act
+ Result> result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
+ await _mockAuthorizationService.Received(1).EvaluatePolicyAsync(
+ _userId,
+ Arg.Is(context => context.LibraryId == libraryId),
+ Arg.Any());
+ await _mockTrackRepository.DidNotReceive().GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any());
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenRepositoryReturnsError_ShouldReturnFailureResult()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Act
+ Result> result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.True(result.IsFailure);
+ Assert.Equal(Errors.Library.LibraryIdCannotBeEmpty, result.FirstError);
+ }
+
+ [Fact]
+ public async Task HandleAsync_WhenRepositoryReturnsNoTracks_ShouldReturnAnEmptyList()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create();
+ _mockTrackRepository.GetShuffleTracksLiteAsync(
+ Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+
+ // Act
+ Result> result = await _sut.HandleAsync(query, CancellationToken.None);
+
+ // Assert
+ Assert.False(result.IsFailure);
+ Assert.NotNull(result.Value);
+ Assert.Empty(result.Value);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryValidatorTests.cs
new file mode 100644
index 00000000..fc853079
--- /dev/null
+++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/ShuffleTracks/ShuffleTracksQueryValidatorTests.cs
@@ -0,0 +1,193 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using Lumina.Application.UnitTests.Common.Setup;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Application.UnitTests.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksQueryValidatorTests
+{
+ private readonly ShuffleTracksQueryFixture _shuffleTracksQueryFixture = new();
+ private readonly ShuffleTracksQueryValidator _validator = new();
+
+ [Theory]
+ [InlineData(1)] // the smallest allowed selection
+ [InlineData(500)] // the largest allowed selection
+ public void Validate_WhenQueryIsValid_ShouldNotHaveValidationError(int count)
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(
+ count: count,
+ includeArtistId: false,
+ includeAlbumId: false,
+ includeExcludedTrackIds: false);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveAnyValidationErrors();
+ result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
+ result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero);
+ result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeAtMost500);
+ }
+
+ [Theory]
+ [InlineData(null)] // missing route value
+ [InlineData("")] // empty route value
+ [InlineData(" ")] // whitespace route value
+ [InlineData("not-a-guid")] // non-Guid route value
+ [InlineData("' OR '1'='1")] // injection payload that is not a Guid
+ [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value
+ public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string? libraryId)
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
+ }
+
+ [Theory]
+ [InlineData(0)] // no track is requested
+ [InlineData(-1)] // a negative selection size
+ [InlineData(-500)] // a large negative selection size
+ public void Validate_WhenCountIsNotPositive_ShouldHaveValidationError(int count)
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(count: count);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero);
+ result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeAtMost500);
+ }
+
+ [Theory]
+ [InlineData(501)] // one more than the documented maximum
+ [InlineData(1000)] // well above the documented maximum
+ [InlineData(int.MaxValue)] // the largest possible value
+ public void Validate_WhenCountExceedsMaximum_ShouldHaveValidationError(int count)
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(count: count);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.Music.ShuffleTrackCountMustBeAtMost500);
+ result.ShouldNotHaveValidationError(Errors.Music.ShuffleTrackCountMustBeGreaterThanZero);
+ }
+
+ [Fact]
+ public void Validate_WhenArtistIdIsEmpty_ShouldHaveValidationError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(artistId: Guid.Empty);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
+ }
+
+ [Fact]
+ public void Validate_WhenArtistIdIsNull_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeArtistId: false);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty);
+ result.ShouldNotHaveAnyValidationErrors();
+ }
+
+ [Fact]
+ public void Validate_WhenAlbumIdIsEmpty_ShouldHaveValidationError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(albumId: Guid.Empty);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
+ }
+
+ [Fact]
+ public void Validate_WhenAlbumIdIsNull_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeAlbumId: false);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty);
+ result.ShouldNotHaveAnyValidationErrors();
+ }
+
+ [Fact]
+ public void Validate_WhenExcludedTrackIdsAreNull_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(includeExcludedTrackIds: false);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ // The validator has no rule for the exclusion list, because excluding tracks can never make a valid selection invalid.
+ result.ShouldNotHaveAnyValidationErrors();
+ }
+
+ [Fact]
+ public void Validate_WhenExcludedTrackIdsAreEmpty_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(excludedTrackIds: []);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ result.ShouldNotHaveAnyValidationErrors();
+ }
+
+ [Fact]
+ public void Validate_WhenExcludedTrackIdsContainEmptyOrDuplicatedIds_ShouldNotHaveValidationError()
+ {
+ // Arrange
+ Guid trackId = Guid.NewGuid();
+ ShuffleTracksQuery query = _shuffleTracksQueryFixture.Create(excludedTrackIds: [trackId, Guid.Empty, trackId]);
+
+ // Act
+ List result = _validator.TestValidate(query);
+
+ // Assert
+ // The exclusion list is normalized by the handler instead, so the validator reports no error for empty or repeated entries.
+ result.ShouldNotHaveAnyValidationErrors();
+ }
+}
diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
new file mode 100644
index 00000000..2bec5a1e
--- /dev/null
+++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/ShuffleTracks/ShuffleTracksEndpointTests.cs
@@ -0,0 +1,236 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.ShuffleTracks;
+using Lumina.Contracts.Fixtures.Core.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Fixtures.Core.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Http.HttpResults;
+using Microsoft.AspNetCore.Mvc;
+using NSubstitute;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.ShuffleTracks;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ShuffleTracksEndpointTests
+{
+ private readonly IQueryHandler>> _mockHandler;
+ private readonly ShuffleTracksEndpoint _sut;
+ private readonly ShuffleTracksRequestFixture _shuffleTracksRequestFixture = new();
+ private readonly ShuffleTrackResponseFixture _shuffleTrackResponseFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ShuffleTracksEndpointTests()
+ {
+ _mockHandler = Substitute.For>>>();
+ _sut = FastEndpoints.Factory.Create(_mockHandler);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithTrackResponses()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ CancellationToken cancellationToken = CancellationToken.None;
+ List expectedResponse = _shuffleTrackResponseFixture.CreateMany(3);
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From>(expectedResponse));
+ _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
+
+ // Act
+ IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
+
+ // Assert
+ Ok> okResult = Assert.IsType>>(result);
+ Assert.Equal(expectedResponse, okResult.Value);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ CancellationToken cancellationToken = CancellationToken.None;
+ Error validationError = Errors.Music.ShuffleTrackCountMustBeAtMost500;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(validationError);
+ _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
+
+ // Act
+ IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
+
+ // Assert
+ ProblemHttpResult problemDetails = Assert.IsType(result);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails.StatusCode);
+ Assert.Equal("application/problem+json", problemDetails.ContentType);
+ HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemDetails.ProblemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
+ Assert.Equal("General.Validation", validationProblemDetails.Title);
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
+ Assert.Single(validationProblemDetails.Errors);
+ Assert.Equal(new[] { "ShuffleTrackCountMustBeAtMost500" }, validationProblemDetails.Errors["General.Validation"]);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenHandlerReturnsForbiddenError_ShouldReturnForbiddenProblemResult()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ CancellationToken cancellationToken = CancellationToken.None;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(ApplicationErrors.Authorization.NotAuthorized);
+ _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
+
+ // Act
+ IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
+
+ // Assert
+ ProblemHttpResult problemDetails = Assert.IsType(result);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.StatusCode);
+ Assert.Equal("application/problem+json", problemDetails.ContentType);
+ ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetailsBody.Status);
+ Assert.Equal("General.Unauthorized", problemDetailsBody.Title);
+ Assert.Equal("NotAuthorized", problemDetailsBody.Detail);
+ Assert.NotNull(problemDetailsBody.Extensions["traceId"]);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ CancellationToken cancellationToken = CancellationToken.None;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Error.NotFound("Library.NotFound", "LibraryNotFound"));
+ _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
+
+ // Act
+ IResult result = await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
+
+ // Assert
+ ProblemHttpResult problemDetails = Assert.IsType(result);
+ Assert.Equal(StatusCodes.Status404NotFound, problemDetails.StatusCode);
+ Assert.Equal("application/problem+json", problemDetails.ContentType);
+ ProblemDetails problemDetailsBody = Assert.IsType(problemDetails.ProblemDetails);
+ Assert.Equal(StatusCodes.Status404NotFound, problemDetailsBody.Status);
+ Assert.Equal("Library.NotFound", problemDetailsBody.Title);
+ Assert.Equal("LibraryNotFound", problemDetailsBody.Detail);
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenCalled_ShouldSendQueryWithTheRouteAndRequestValues()
+ {
+ // Arrange
+ Guid libraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid excludedTrackId = Guid.NewGuid();
+ CancellationToken cancellationToken = CancellationToken.None;
+ ShuffleTracksRequest request = _shuffleTracksRequestFixture.Create(
+ count: 25,
+ artistId: artistId,
+ albumId: albumId,
+ excludedTrackIds: [excludedTrackId]);
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+ _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId.ToString();
+
+ // Act
+ await _sut.ExecuteAsync(request, cancellationToken);
+
+ // Assert
+ await _mockHandler.Received(1).HandleAsync(
+ Arg.Is(query =>
+ query.LibraryId == libraryId.ToString() &&
+ query.Count == 25 &&
+ query.ArtistId == artistId &&
+ query.AlbumId == albumId &&
+ query.ExcludedTrackIds != null &&
+ query.ExcludedTrackIds.Count == 1 &&
+ query.ExcludedTrackIds[0] == excludedTrackId),
+ Arg.Is(cancellationToken));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullLibraryId()
+ {
+ // Arrange
+ CancellationToken cancellationToken = CancellationToken.None;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any())
+ .Returns(Result.From>([]));
+ _sut.HttpContext.Request.RouteValues.Remove("libraryId");
+
+ // Act
+ await _sut.ExecuteAsync(_shuffleTracksRequestFixture.Create(), cancellationToken);
+
+ // Assert
+ await _mockHandler.Received(1).HandleAsync(
+ Arg.Is(query => query.LibraryId == null),
+ Arg.Is(cancellationToken));
+ }
+
+ [Fact]
+ public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendQueryWithTheRawRouteValue()
+ {
+ // Arrange
+ CancellationToken cancellationToken = CancellationToken.None;
+ _mockHandler.HandleAsync(Arg.Any(), Arg.Any