diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs index dc09756a..356403e6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpoint.cs @@ -51,6 +51,10 @@ public class AddPlaylistEntriesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddPlaylistEntriesRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // The playlist is identified by the route value, not by any id posted in the body. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); Result result = await _addPlaylistEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs index dfadfa40..8c7a5143 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpoint.cs @@ -51,6 +51,10 @@ public class AddPlaylistEntryEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddPlaylistEntryRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // The playlist is identified by the route value, not by any id posted in the body. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); Result result = await _addPlaylistEntryCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs index b1d734cb..b6022976 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpoint.cs @@ -51,6 +51,10 @@ public class AddPlaylistScopeEntriesEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(AddPlaylistScopeEntriesRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // The playlist is identified by the route value, not by any id posted in the body. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); Result result = await _addPlaylistScopeEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs index 67518137..c75e5684 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpoint.cs @@ -51,6 +51,10 @@ public class CreatePlaylistEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(CreatePlaylistRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; Result result = await _createPlaylistCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false); return result.Match(success => TypedResults.Ok(success), Problem); } diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs index d66f2881..0911fd18 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpoint.cs @@ -48,6 +48,10 @@ public class DeletePlaylistEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // Take the unique identifier from the route. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); Result result = await _deletePlaylistCommandHandler.HandleAsync(new DeletePlaylistCommand(playlistId), cancellationToken).ConfigureAwait(false); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs index 86de9a8b..6086d177 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpoint.cs @@ -51,6 +51,10 @@ public class MovePlaylistEntryEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(MovePlaylistEntryRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // The playlist and the entry are identified by the route values, not by any id posted in the body. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); string? playlistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs index 2cbf9ff8..b8e200b6 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpoint.cs @@ -49,6 +49,10 @@ public class RemovePlaylistEntryEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // Take the unique identifiers from the route. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); string? playlistEntryId = HttpContext.Request.RouteValues["playlistEntryId"]?.ToString(); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs index 6f828fa4..5978e2ec 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpoint.cs @@ -51,6 +51,10 @@ public class UpdatePlaylistEndpoint : BaseEndpointCancellation token that can be used to stop the execution. public override async Task ExecuteAsync(UpdatePlaylistRequest request, CancellationToken cancellationToken) { + // The playlists belong to the authenticated user, so no intermediary may store any response of this route, including its problem + // responses, and every response varies by the bearer token that authorized it. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers["Vary"] = "Authorization"; // The playlist is identified by the route value, not by any id posted in the body, so that a mismatched id can never redirect the // update to another playlist. string? playlistId = HttpContext.Request.RouteValues["playlistId"]?.ToString(); diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs index 4d2c40ef..1848ec1a 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpoint.cs @@ -2,6 +2,7 @@ using FastEndpoints; using Lumina.Presentation.Web.Common.Api; using Lumina.Presentation.Web.Common.DependencyInjection; +using Lumina.Presentation.Web.Common.Exceptions; using Lumina.Presentation.Web.Common.Http; using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks; using Lumina.Presentation.Web.Common.Routes; @@ -11,6 +12,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using System; using System.Collections.Generic; +using System.Net; using System.Threading; using System.Threading.Tasks; #endregion @@ -75,10 +77,21 @@ public class StreamMusicTrackEndpoint : BaseEndpoint +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackAccessSummaryDtoFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The number of distinct requested tracks that exist. + /// Optional. The Ids of the media libraries that contain those tracks. Defaults to a single random library. + /// The created . + public TrackAccessSummaryDto Create( + int? trackCount = null, + IReadOnlyList? libraryIds = null) + { + return new TrackAccessSummaryDto( + trackCount ?? 1, + libraryIds ?? [Guid.NewGuid()]); + } + + /// + /// 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/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDtoFixture.cs new file mode 100644 index 00000000..b4cb752e --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDtoFixture.cs @@ -0,0 +1,80 @@ +#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.IO; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackStreamDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The file system path of the track. + /// Optional. The Id of the media library the track belongs to. + /// Optional. The Id of the album the track belongs to. + /// Optional. The Id of the artist that owns the album the track belongs to. + /// Optional. The container of the audio file of the track. + /// Optional. The audio codec used by the audio file of the track. + /// Optional. The duration of the audio of the track, in seconds. + /// Optional. The sample rate of the audio of the track, in Hz. + /// Optional. The number of audio channels of the track. + /// Optional. The bit depth of the audio of the track. + /// Optional. The bitrate of the audio of the track, in kbps. + /// Whether the container should be included, or forced to . + /// Whether the audio codec should be included, or forced to . + /// Whether the bit depth should be included, or forced to . + /// Whether the bitrate should be included, or forced to . + /// The created . + public TrackStreamDto Create( + string? path = null, + Guid? libraryId = null, + Guid? albumId = null, + Guid? artistId = null, + string? container = null, + string? audioCodec = null, + int? durationInSeconds = null, + int? sampleRate = null, + int? channels = null, + int? bitDepth = null, + int? bitrate = null, + bool includeContainer = true, + bool includeAudioCodec = true, + bool includeBitDepth = true, + bool includeBitrate = true) + { + return new TrackStreamDto( + path ?? Path.Combine(_faker.System.DirectoryPath(), _faker.System.FileName("flac")), + libraryId ?? Guid.NewGuid(), + albumId ?? Guid.NewGuid(), + artistId ?? Guid.NewGuid(), + includeContainer ? (container ?? _faker.PickRandom("FLAC", "MP3", "OGG", "MP4", "AAC", "WAV")) : null, + includeAudioCodec ? (audioCodec ?? _faker.PickRandom("FLAC", "MP3", "AAC", "ALAC", "PCM")) : null, + durationInSeconds ?? _faker.Random.Int(1, 3600), + sampleRate ?? _faker.PickRandom(44100, 48000, 96000), + channels ?? _faker.PickRandom(1, 2, 6), + includeBitDepth ? (bitDepth ?? _faker.Random.Int(8, 32)) : null, + includeBitrate ? (bitrate ?? _faker.Random.Int(96, 1411)) : 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/Common/DTO/Playlists/PlaylistBulkAddResultDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Playlists/PlaylistBulkAddResultDtoFixture.cs new file mode 100644 index 00000000..f5ec610e --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Playlists/PlaylistBulkAddResultDtoFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistBulkAddResultDtoFixture +{ + private const long MAXIMUM_RANDOM_POSITION = 1_000_000_000L; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The sparse order key of the first appended entry. Defaults to a bounded random key. + /// Optional. The number of entries appended. Defaults to a bounded random count. + /// The created . + public PlaylistBulkAddResultDto Create( + long? firstPosition = null, + int? addedCount = null) + { + return new PlaylistBulkAddResultDto( + firstPosition ?? _faker.Random.Long(0, MAXIMUM_RANDOM_POSITION), + addedCount ?? _faker.Random.Int(0, 1_000)); + } + + /// + /// 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/Common/DTO/Playlists/PlaylistSummaryDtoFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Playlists/PlaylistSummaryDtoFixture.cs new file mode 100644 index 00000000..9c35c2b1 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Common/DTO/Playlists/PlaylistSummaryDtoFixture.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistSummaryDtoFixture +{ + private const int MAXIMUM_ENTRY_COUNT = 10_000; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist. + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Optional. The kind of media the playlist holds. Defaults to the only supported kind. + /// Optional. The number of entries of the playlist. Defaults to a bounded random count. + /// Optional. The date and time when the playlist was created. + /// Optional. The date and time when the playlist was last updated. + /// Whether the description should be included, or forced to . + /// Whether the update date and time should be included, or forced to . + /// The created . + public PlaylistSummaryDto Create( + Guid? id = null, + string? name = null, + string? description = null, + PlaylistType? type = null, + int? entryCount = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + bool includeDescription = true, + bool includeUpdatedOnUtc = false) + { + return new PlaylistSummaryDto( + id ?? _faker.Random.Guid(), + name ?? _faker.Lorem.Sentence(3), + includeDescription ? (description ?? _faker.Lorem.Sentence()) : null, + type ?? PlaylistType.Music, + entryCount ?? _faker.Random.Int(0, MAXIMUM_ENTRY_COUNT), + createdOnUtc ?? _faker.Date.Past(), + includeUpdatedOnUtc ? (updatedOnUtc ?? _faker.Date.Recent()) : 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/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs index abd1b116..d41b6e5a 100644 --- a/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Common/DataAccess/Entities/MediaLibrary/AudioLibrary/MusicLibrary/TrackEntityFixture.cs @@ -39,6 +39,7 @@ public class TrackEntityFixture /// Optional. The title of the track. /// Optional. The container of the audio file of the track. /// Optional. The number of the track on its disc. + /// Optional. The number of the disc the track belongs to. /// Optional. The original release date of the track. /// Optional. The original release year of the track. /// Optional. The re-release date of the track. @@ -66,6 +67,7 @@ public class TrackEntityFixture string? title = null, string? container = null, int? trackNumber = null, + int? discNumber = null, DateOnly? originalReleaseDate = null, int? originalReleaseYear = null, DateOnly? reReleaseDate = null, @@ -136,7 +138,7 @@ public class TrackEntityFixture .RuleFor(x => x.ReplayGainAlbumPeak, f => includeReplayGain ? (replayGainAlbumPeak ?? f.Random.Decimal(0m, 1.5m)) : null) .RuleFor(x => x.Bitrate, Random.Shared.Next(96, 1411)) .RuleFor(x => x.TrackNumber, f => trackNumber ?? f.Random.Int(1, 20)) - .RuleFor(x => x.DiscNumber, Random.Shared.Next(1, 3)) + .RuleFor(x => x.DiscNumber, discNumber ?? Random.Shared.Next(1, 3)) .RuleFor(x => x.Script, f => f.Random.String2(f.Random.Number(1, 50))) .RuleFor(x => x.Key, f => f.PickRandom()) .RuleFor(x => x.Bpm, Random.Shared.Next(40, 240)) diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryFixture.cs new file mode 100644 index 00000000..cb45c0b6 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamQueryFixture +{ + /// + /// Creates a random valid query to get the audio file of a track, for streaming. + /// + /// Optional. The Id of the media library the track belongs to. + /// Optional. The Id of the artist the album of the track belongs to. + /// Optional. The Id of the album the track belongs to. + /// Optional. The Id of the track whose audio file is streamed. + /// 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 track Id should be included, or forced to . + /// The created . + public GetTrackStreamQuery Create( + string? libraryId = null, + string? artistId = null, + string? albumId = null, + string? trackId = null, + bool includeLibraryId = true, + bool includeArtistId = true, + bool includeAlbumId = true, + bool includeTrackId = true) + { + return new GetTrackStreamQuery( + includeLibraryId ? (libraryId ?? Guid.NewGuid().ToString()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid().ToString()) : null, + includeAlbumId ? (albumId ?? Guid.NewGuid().ToString()) : null, + includeTrackId ? (trackId ?? Guid.NewGuid().ToString()) : null); + } + + /// + /// Creates a list of instances. + /// + /// 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/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandFixture.cs new file mode 100644 index 00000000..951d45b8 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistEntries; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Optional. The Ids of the tracks to add, in order. + /// Optional. The number of random track Ids to generate when is not supplied. + /// Whether the playlist Id should be included, or forced to . + /// Whether the track Ids should be included, or forced to . + /// The created . + public AddPlaylistEntriesCommand Create( + string? playlistId = null, + List? trackIds = null, + int trackCount = 3, + bool includePlaylistId = true, + bool includeTrackIds = true) + { + return new AddPlaylistEntriesCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null, + includeTrackIds ? (trackIds ?? CreateRandomTrackIds(trackCount)) : 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())]; + } + + /// + /// Creates the requested number of distinct random track Ids. + /// + /// The number of track Ids to create. + /// The created track Ids. + private static List CreateRandomTrackIds(int count) + { + return [.. Enumerable.Range(0, count).Select(_ => Guid.NewGuid())]; + } +} diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandFixture.cs new file mode 100644 index 00000000..83a7b599 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistEntry; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Optional. The Id of the track to add. + /// Whether the playlist Id should be included, or forced to . + /// Whether the track Id should be included, or forced to . + /// The created . + public AddPlaylistEntryCommand Create( + string? playlistId = null, + Guid? trackId = null, + bool includePlaylistId = true, + bool includeTrackId = true) + { + return new AddPlaylistEntryCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null, + includeTrackId ? (trackId ?? 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.Application.Fixtures/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandFixture.cs new file mode 100644 index 00000000..082b21fa --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Optional. The Id of the music library the scope belongs to. + /// Optional. The Id of the artist the scope is limited to. + /// Optional. The Id of the album the scope is limited to. + /// Whether the playlist Id should be included, or forced to . + /// 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 . + /// The created . + public AddPlaylistScopeEntriesCommand Create( + string? playlistId = null, + Guid? libraryId = null, + Guid? artistId = null, + Guid? albumId = null, + bool includePlaylistId = true, + bool includeLibraryId = true, + bool includeArtistId = false, + bool includeAlbumId = false) + { + return new AddPlaylistScopeEntriesCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null, + includeLibraryId ? (libraryId ?? Guid.NewGuid()) : null, + includeArtistId ? (artistId ?? Guid.NewGuid()) : null, + includeAlbumId ? (albumId ?? 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.Application.Fixtures/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandFixture.cs index d5ea816e..7b39497d 100644 --- a/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandFixture.cs +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandFixture.cs @@ -25,16 +25,18 @@ public class CreatePlaylistCommandFixture /// Optional. The kind of media the playlist holds. Defaults to the only supported kind. /// Whether the description should be included, or forced to . /// Whether the media type should be included, or forced to . + /// Whether the name should be included, or forced to . /// The created . public CreatePlaylistCommand Create( string? name = null, string? description = null, PlaylistType? type = null, bool includeDescription = true, - bool includeType = true) + bool includeType = true, + bool includeName = true) { return new CreatePlaylistCommand( - name ?? _faker.Lorem.Sentence(3), + includeName ? (name ?? _faker.Lorem.Sentence(3)) : null, includeDescription ? (description ?? _faker.Lorem.Sentence()) : null, includeType ? (type ?? PlaylistType.Music) : null); } diff --git a/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandFixture.cs new file mode 100644 index 00000000..6c72076d --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.DeletePlaylist; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Whether the playlist Id should be included, or forced to . + /// The created . + public DeletePlaylistCommand Create( + string? playlistId = null, + bool includePlaylistId = true) + { + return new DeletePlaylistCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : 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/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandFixture.cs new file mode 100644 index 00000000..22319923 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Optional. The Id of the entry to move, taken from the route. + /// Optional. The new zero based position of the entry. + /// Whether the playlist Id should be included, or forced to . + /// Whether the entry Id should be included, or forced to . + /// Whether the target position should be included, or forced to . + /// The created . + public MovePlaylistEntryCommand Create( + string? playlistId = null, + string? playlistEntryId = null, + int? targetPosition = null, + bool includePlaylistId = true, + bool includePlaylistEntryId = true, + bool includeTargetPosition = true) + { + return new MovePlaylistEntryCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null, + includePlaylistEntryId ? (playlistEntryId ?? Guid.NewGuid().ToString()) : null, + includeTargetPosition ? (targetPosition ?? _faker.Random.Int(0, 1_000)) : 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/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandFixture.cs new file mode 100644 index 00000000..76328b91 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandFixture.cs @@ -0,0 +1,45 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryCommandFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Optional. The Id of the entry to remove, taken from the route. + /// Whether the playlist Id should be included, or forced to . + /// Whether the entry Id should be included, or forced to . + /// The created . + public RemovePlaylistEntryCommand Create( + string? playlistId = null, + string? playlistEntryId = null, + bool includePlaylistId = true, + bool includePlaylistEntryId = true) + { + return new RemovePlaylistEntryCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null, + includePlaylistEntryId ? (playlistEntryId ?? Guid.NewGuid().ToString()) : 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/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandFixture.cs new file mode 100644 index 00000000..126dc990 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist, taken from the route. + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Whether the playlist Id should be included, or forced to . + /// Whether the name should be included, or forced to . + /// Whether the description should be included, or forced to . + /// The created . + public UpdatePlaylistCommand Create( + string? playlistId = null, + string? name = null, + string? description = null, + bool includePlaylistId = true, + bool includeName = true, + bool includeDescription = true) + { + return new UpdatePlaylistCommand( + includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null, + includeName ? (name ?? _faker.Lorem.Sentence(3)) : null, + includeDescription ? (description ?? _faker.Lorem.Sentence()) : 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/Playlists/Queries/GetPlaylists/GetPlaylistsQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryFixture.cs new file mode 100644 index 00000000..89413ddb --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Queries.GetPlaylists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.Playlists.Queries.GetPlaylists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsQueryFixture +{ + /// + /// Creates a . + /// + /// The created . + /// + /// The query carries no members, because the current user is always taken from the authenticated request context. + /// + public GetPlaylistsQuery Create() + { + return new GetPlaylistsQuery(); + } + + /// + /// Creates a list of instances. + /// + /// 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/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandFixture.cs new file mode 100644 index 00000000..6e6d9376 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateCommandFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid command to update the playback state the player reports for the current user. + /// + /// Optional. The last volume the player reported, as a value between 0 and 1. + /// Optional. The last mute state the player reported. + /// Whether the volume should be included, or forced to . + /// Whether the mute state should be included, or forced to . + /// The created . + public UpdatePlaybackStateCommand Create( + double? volume = null, + bool? isMuted = null, + bool includeVolume = true, + bool includeIsMuted = true) + { + return new UpdatePlaybackStateCommand( + includeVolume ? volume ?? _faker.Random.Double(0, 1) : null, + includeIsMuted ? isMuted ?? _faker.Random.Bool() : null); + } + + /// + /// Creates a list of instances. + /// + /// 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/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryFixture.cs new file mode 100644 index 00000000..393e5208 --- /dev/null +++ b/tests/Common/Lumina.Application.Fixtures/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryFixture.cs @@ -0,0 +1,34 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetPlaybackState; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateQueryFixture +{ + /// + /// Creates a new instance. + /// + /// The created . + public GetPlaybackStateQuery Create() + { + return new GetPlaybackStateQuery(); + } + + /// + /// Creates a list of instances. + /// + /// 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/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDtoFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDtoFixture.cs new file mode 100644 index 00000000..ce55d759 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/DTO/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/TrackStreamDataDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class TrackStreamDataDtoFixture +{ + private static readonly AudioFileFormat[] s_audioFileFormats = [AudioFileFormat.MP3, AudioFileFormat.FLAC, AudioFileFormat.OGG, AudioFileFormat.WAV]; + + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The file system path of the audio file of the track. + /// Optional. The file format of the audio file of the track. + /// Optional. The length of the audio file of the track, in bytes. + /// Optional. The date and time when the audio file of the track was last modified. + /// The created . + public TrackStreamDataDto Create( + string? path = null, + AudioFileFormat? format = null, + long? length = null, + DateTimeOffset? lastModified = null) + { + return new TrackStreamDataDto( + path ?? Path.Combine(_faker.System.DirectoryPath(), _faker.System.FileName("mp3")), + format ?? _faker.PickRandom(s_audioFileFormats), + length ?? _faker.Random.Long(1, 10_000_000), + lastModified ?? _faker.Date.PastOffset()); + } + + /// + /// 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/Playlists/AddPlaylistEntriesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistEntriesRequestFixture.cs new file mode 100644 index 00000000..19cfea1a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistEntriesRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Ids of the tracks to add, in order. + /// Optional. The number of random track Ids to generate when is not supplied. + /// Whether the track Ids should be included, or forced to . + /// The created . + public AddPlaylistEntriesRequest Create( + List? trackIds = null, + int trackCount = 3, + bool includeTrackIds = true) + { + return new AddPlaylistEntriesRequest( + includeTrackIds ? (trackIds ?? CreateRandomTrackIds(trackCount)) : 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())]; + } + + /// + /// Creates the requested number of distinct random track Ids. + /// + /// The number of track Ids to create. + /// The created track Ids. + private static List CreateRandomTrackIds(int count) + { + return [.. Enumerable.Range(0, count).Select(_ => Guid.NewGuid())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistEntryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistEntryRequestFixture.cs new file mode 100644 index 00000000..5bf94e60 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistEntryRequestFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the track to add. + /// Whether the track Id should be included, or forced to . + /// The created . + public AddPlaylistEntryRequest Create( + Guid? trackId = null, + bool includeTrackId = true) + { + return new AddPlaylistEntryRequest( + includeTrackId ? (trackId ?? 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/Playlists/AddPlaylistScopeEntriesRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistScopeEntriesRequestFixture.cs new file mode 100644 index 00000000..b344622e --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/AddPlaylistScopeEntriesRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesRequestFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The Id of the music library the scope belongs to. + /// Optional. The Id of the artist the scope is limited to. + /// Optional. The Id of the album the scope is limited to. + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// The created . + public AddPlaylistScopeEntriesRequest Create( + Guid? libraryId = null, + Guid? artistId = null, + Guid? albumId = null, + bool includeArtistId = false, + bool includeAlbumId = false) + { + return new AddPlaylistScopeEntriesRequest( + libraryId ?? Guid.NewGuid(), + includeArtistId ? (artistId ?? Guid.NewGuid()) : null, + includeAlbumId ? (albumId ?? 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/Playlists/CreatePlaylistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/CreatePlaylistRequestFixture.cs new file mode 100644 index 00000000..63a0835d --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/CreatePlaylistRequestFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Optional. The kind of media the playlist holds. Defaults to the only supported kind. + /// Whether the name should be included, or forced to . + /// Whether the description should be included, or forced to . + /// Whether the media type should be included, or forced to . + /// The created . + public CreatePlaylistRequest Create( + string? name = null, + string? description = null, + PlaylistType? type = null, + bool includeName = true, + bool includeDescription = true, + bool includeType = true) + { + return new CreatePlaylistRequest( + includeName ? (name ?? _faker.Lorem.Sentence(3)) : null, + includeDescription ? (description ?? _faker.Lorem.Sentence()) : null, + includeType ? (type ?? PlaylistType.Music) : 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/Playlists/MovePlaylistEntryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/MovePlaylistEntryRequestFixture.cs new file mode 100644 index 00000000..4cfa52c0 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/MovePlaylistEntryRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The new zero based position of the entry. Defaults to a bounded random position. + /// Whether the target position should be included, or forced to . + /// The created . + public MovePlaylistEntryRequest Create( + int? targetPosition = null, + bool includeTargetPosition = true) + { + return new MovePlaylistEntryRequest( + includeTargetPosition ? (targetPosition ?? _faker.Random.Int(0, 1_000)) : 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/Playlists/UpdatePlaylistRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/UpdatePlaylistRequestFixture.cs new file mode 100644 index 00000000..22337a03 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/Playlists/UpdatePlaylistRequestFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Whether the name should be included, or forced to . + /// Whether the description should be included, or forced to . + /// The created . + public UpdatePlaylistRequest Create( + string? name = null, + string? description = null, + bool includeName = true, + bool includeDescription = true) + { + return new UpdatePlaylistRequest( + includeName ? (name ?? _faker.Lorem.Sentence(3)) : null, + includeDescription ? (description ?? _faker.Lorem.Sentence()) : 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/UsersManagement/Settings/UpdatePlaybackStateRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdatePlaybackStateRequestFixture.cs new file mode 100644 index 00000000..ee90a9fa --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/UsersManagement/Settings/UpdatePlaybackStateRequestFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The last volume the player reported, as a value between 0 and 1. + /// Optional. The last mute state the player reported. + /// Whether the volume should be included, or forced to . + /// Whether the mute state should be included, or forced to . + /// The created . + public UpdatePlaybackStateRequest Create( + double? volume = null, + bool? isMuted = null, + bool includeVolume = true, + bool includeIsMuted = true) + { + return new UpdatePlaybackStateRequest( + includeVolume ? volume ?? _faker.Random.Double(0, 1) : null, + includeIsMuted ? isMuted ?? _faker.Random.Bool() : null); + } + + /// + /// Creates a list of instances. + /// + /// Number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistDetailsResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistDetailsResponseFixture.cs new file mode 100644 index 00000000..85f24f25 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistDetailsResponseFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistDetailsResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist. + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Optional. The kind of media the playlist holds. + /// Optional. The date and time when the playlist was last updated. + /// Whether the description should be included, or forced to . + /// Whether the update time should be included, or forced to . + /// The created . + public PlaylistDetailsResponse Create( + Guid? id = null, + string? name = null, + string? description = null, + PlaylistType? type = null, + DateTime? updatedOnUtc = null, + bool includeDescription = true, + bool includeUpdatedOnUtc = true) + { + return new PlaylistDetailsResponse( + id ?? _faker.Random.Guid(), + name ?? _faker.Lorem.Sentence(3), + includeDescription ? (description ?? _faker.Lorem.Sentence()) : null, + type ?? PlaylistType.Music, + includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : 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/Responses/Playlists/PlaylistEntriesAddedResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntriesAddedResponseFixture.cs new file mode 100644 index 00000000..dfe461f5 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntriesAddedResponseFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntriesAddedResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist the entries were added to. + /// Optional. The number of entries that were appended. + /// Optional. The date and time when the playlist was last updated. + /// Whether the update time should be included, or forced to . + /// The created . + public PlaylistEntriesAddedResponse Create( + Guid? playlistId = null, + int? addedCount = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + return new PlaylistEntriesAddedResponse( + playlistId ?? _faker.Random.Guid(), + addedCount ?? _faker.Random.Int(0, 1_000), + includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : 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/Responses/Playlists/PlaylistEntryAddedResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntryAddedResponseFixture.cs new file mode 100644 index 00000000..196f19de --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntryAddedResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryAddedResponseFixture +{ + private readonly Faker _faker = new(); + private readonly PlaylistEntryResponseFixture _playlistEntryResponseFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist the entry was added to. + /// Optional. The added entry. + /// Optional. The date and time when the playlist was last updated. + /// Whether the update time should be included, or forced to . + /// The created . + public PlaylistEntryAddedResponse Create( + Guid? playlistId = null, + PlaylistEntryResponse? entry = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + return new PlaylistEntryAddedResponse( + playlistId ?? _faker.Random.Guid(), + entry ?? _playlistEntryResponseFixture.Create(), + includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : 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/Responses/Playlists/PlaylistEntryMovedResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntryMovedResponseFixture.cs new file mode 100644 index 00000000..c0325c3a --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntryMovedResponseFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryMovedResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist whose entry was moved. + /// Optional. The Id of the moved entry. + /// Optional. The new zero based position of the entry. + /// Optional. The date and time when the playlist was last updated. + /// Whether the update time should be included, or forced to . + /// The created . + public PlaylistEntryMovedResponse Create( + Guid? playlistId = null, + Guid? entryId = null, + int? position = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + return new PlaylistEntryMovedResponse( + playlistId ?? _faker.Random.Guid(), + entryId ?? _faker.Random.Guid(), + position ?? _faker.Random.Int(0, 1_000), + includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : 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/Responses/Playlists/PlaylistEntryRemovedResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntryRemovedResponseFixture.cs new file mode 100644 index 00000000..201e1771 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistEntryRemovedResponseFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryRemovedResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist the entry was removed from. + /// Optional. The Id of the removed entry. + /// Optional. The number of entries that were repositioned, which the contract always reports as zero. + /// Optional. The date and time when the playlist was last updated. + /// Whether the update time should be included, or forced to . + /// The created . + public PlaylistEntryRemovedResponse Create( + Guid? playlistId = null, + Guid? removedEntryId = null, + int? repositionedCount = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + return new PlaylistEntryRemovedResponse( + playlistId ?? _faker.Random.Guid(), + removedEntryId ?? _faker.Random.Guid(), + repositionedCount ?? 0, + includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : 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/Responses/Playlists/PlaylistSummaryResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistSummaryResponseFixture.cs new file mode 100644 index 00000000..6daf93c7 --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/Playlists/PlaylistSummaryResponseFixture.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistSummaryResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the playlist. + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Optional. The kind of media the playlist holds. + /// Optional. The number of entries of the playlist. + /// Optional. The date and time when the playlist was created. + /// Optional. The date and time when the playlist was last updated. + /// Whether the description should be included, or forced to . + /// Whether the update time should be included, or forced to . + /// The created . + public PlaylistSummaryResponse Create( + Guid? id = null, + string? name = null, + string? description = null, + PlaylistType? type = null, + int? entryCount = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + bool includeDescription = true, + bool includeUpdatedOnUtc = true) + { + return new PlaylistSummaryResponse( + id ?? _faker.Random.Guid(), + name ?? _faker.Lorem.Sentence(3), + includeDescription ? (description ?? _faker.Lorem.Sentence()) : null, + type ?? PlaylistType.Music, + entryCount ?? _faker.Random.Int(0, 1_000), + createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)), + includeUpdatedOnUtc ? (updatedOnUtc ?? DateTime.UtcNow.AddMinutes(-_faker.Random.Int(1, 1_440))) : 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/Responses/UsersManagement/Settings/PlaybackStateResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/PlaybackStateResponseFixture.cs new file mode 100644 index 00000000..71d9c1be --- /dev/null +++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/UsersManagement/Settings/PlaybackStateResponseFixture.cs @@ -0,0 +1,43 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaybackStateResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The last volume the player reported, as a value between 0 and 1. + /// Optional. The last mute state the player reported. + /// The created . + public PlaybackStateResponse Create( + double? volume = null, + bool? isMuted = null) + { + return new PlaybackStateResponse( + volume ?? _faker.Random.Double(0, 1), + isMuted ?? _faker.Random.Bool()); + } + + /// + /// Creates a list of instances. + /// + /// Number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemIdFixture.cs new file mode 100644 index 00000000..0427bf02 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/MediaLibraryBoundedContext/MediaItemAggregate/MediaItemIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class MediaItemIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the media item Id. + /// The created . + public MediaItemId Create( + Guid? value = null) + { + return MediaItemId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserIdFixture.cs new file mode 100644 index 00000000..44d24090 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/ExternalIdentifiers/UserManagementBoundedContext/UserAggregate/UserIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class UserIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the user Id. + /// The created . + public UserId Create( + Guid? value = null) + { + return UserId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntryFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntryFixture.cs new file mode 100644 index 00000000..66a1730d --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntryFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; + +/// +/// Fixture class for the entity. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryFixture +{ + private const long MAXIMUM_RANDOM_POSITION = 1_000_000_000L; + + private readonly Faker _faker = new(); + private readonly PlaylistEntryIdFixture _playlistEntryIdFixture = new(); + private readonly MediaItemIdFixture _mediaItemIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the entry. + /// Optional. The Id of the media item referenced by the entry. + /// Optional. The kind of media item referenced by the entry. Defaults to a music track, which is the kind a music playlist accepts. + /// Optional. The sparse order key of the entry. Defaults to a bounded random key. + /// The created . + public PlaylistEntry Create( + PlaylistEntryId? id = null, + MediaItemId? mediaItemId = null, + PlaylistMediaItemType? mediaItemType = null, + long? position = null) + { + return PlaylistEntry.Create( + id ?? _playlistEntryIdFixture.Create(), + mediaItemId ?? _mediaItemIdFixture.Create(), + mediaItemType ?? PlaylistMediaItemType.MusicTrack, + position ?? _faker.Random.Long(0, MAXIMUM_RANDOM_POSITION)).Value; + } + + /// + /// Creates multiple instances with randomized test data and distinct positions. + /// + /// + /// The positions are spaced apart and unique, so the created entries can be placed in the same playlist without violating the + /// uniqueness invariant of the sparse order keys. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + long firstPosition = _faker.Random.Long(0, MAXIMUM_RANDOM_POSITION); + return [.. Enumerable.Range(0, count).Select(index => Create(position: firstPosition + index))]; + } +} diff --git a/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEventFixture.cs new file mode 100644 index 00000000..ef97a336 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEventFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistCreatedDomainEventFixture +{ + private readonly Faker _faker = new(); + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the domain event. + /// Optional. The unique identifier of the playlist. + /// Optional. The unique identifier of the user that owns the playlist. + /// Optional. The name of the playlist. + /// Optional. The kind of media the playlist holds. Defaults to the only supported kind. + /// Optional. The date and time when the domain event occurred. + /// The created . + public PlaylistCreatedDomainEvent Create( + Guid? id = null, + PlaylistId? playlistId = null, + UserId? userId = null, + string? name = null, + PlaylistType? type = null, + DateTime? occurredOnUtc = null) + { + return new PlaylistCreatedDomainEvent( + id ?? Guid.NewGuid(), + playlistId ?? _playlistIdFixture.Create(), + userId ?? _userIdFixture.Create(), + name ?? _faker.Lorem.Sentence(3), + type ?? PlaylistType.Music, + occurredOnUtc ?? DateTime.UtcNow); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEventFixture.cs new file mode 100644 index 00000000..4b896d27 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEventFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistDeletedDomainEventFixture +{ + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the domain event. + /// Optional. The unique identifier of the playlist. + /// Optional. The unique identifier of the user that owned the playlist. + /// Optional. The date and time when the domain event occurred. + /// The created . + public PlaylistDeletedDomainEvent Create( + Guid? id = null, + PlaylistId? playlistId = null, + UserId? userId = null, + DateTime? occurredOnUtc = null) + { + return new PlaylistDeletedDomainEvent( + id ?? Guid.NewGuid(), + playlistId ?? _playlistIdFixture.Create(), + userId ?? _userIdFixture.Create(), + occurredOnUtc ?? DateTime.UtcNow); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEventFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEventFixture.cs new file mode 100644 index 00000000..8c512e4f --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEventFixture.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistDetailsUpdatedDomainEventFixture +{ + private readonly Faker _faker = new(); + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The Id of the domain event. + /// Optional. The unique identifier of the playlist. + /// Optional. The unique identifier of the user that owns the playlist. + /// Optional. The new name of the playlist. + /// Optional. The date and time when the domain event occurred. + /// The created . + public PlaylistDetailsUpdatedDomainEvent Create( + Guid? id = null, + PlaylistId? playlistId = null, + UserId? userId = null, + string? name = null, + DateTime? occurredOnUtc = null) + { + return new PlaylistDetailsUpdatedDomainEvent( + id ?? Guid.NewGuid(), + playlistId ?? _playlistIdFixture.Create(), + userId ?? _userIdFixture.Create(), + name ?? _faker.Lorem.Sentence(3), + occurredOnUtc ?? DateTime.UtcNow); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistFixture.cs new file mode 100644 index 00000000..9c1b8225 --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistFixture.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; + +/// +/// Fixture class for the domain aggregate. +/// +[ExcludeFromCodeCoverage] +public class PlaylistFixture +{ + private readonly Faker _faker = new(); + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + /// + /// Creates a random valid domain aggregate, with pre-existing data. + /// + /// Optional. The Id of the playlist. + /// Optional. The Id of the user that owns the playlist. + /// Optional. The name of the playlist. + /// Optional. The description of the playlist. + /// Optional. The kind of media the playlist holds. Defaults to the only supported kind. + /// Optional. The ordered entries of the playlist. Defaults to no entries. + /// Optional. The date and time when the playlist was created. Defaults to a few days in the past. + /// Optional. The date and time when the playlist was last updated. + /// Whether the description should be included, or forced to no value. + /// Whether the update date and time should be included, or forced to no value. + /// The created . + /// + /// The playlist is built through the rehydrating + /// overload, so it carries no domain events and is never marked as deleted. + /// + public Playlist Create( + PlaylistId? id = null, + UserId? userId = null, + string? name = null, + string? description = null, + PlaylistType? type = null, + IEnumerable? entries = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + bool includeDescription = true, + bool includeUpdatedOnUtc = false) + { + return Playlist.Create( + id ?? _playlistIdFixture.Create(), + userId ?? _userIdFixture.Create(), + name ?? _faker.Lorem.Sentence(3), + includeDescription ? Optional.FromNullable(description ?? _faker.Lorem.Sentence()) : Optional.None(), + type ?? PlaylistType.Music, + entries is null ? [] : [.. entries], + createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)).AddMinutes(-_faker.Random.Int(0, 59)), + includeUpdatedOnUtc ? Optional.Some(updatedOnUtc ?? DateTime.UtcNow) : Optional.None()).Value; + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryIdFixture.cs new file mode 100644 index 00000000..70db6a8c --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the playlist entry Id. + /// The created . + public PlaylistEntryId Create( + Guid? value = null) + { + return PlaylistEntryId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistIdFixture.cs b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistIdFixture.cs new file mode 100644 index 00000000..acd2bf5d --- /dev/null +++ b/tests/Common/Lumina.Domain.Fixtures/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistIdFixture.cs @@ -0,0 +1,37 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Fixture class for the value object. +/// +[ExcludeFromCodeCoverage] +public class PlaylistIdFixture +{ + /// + /// Creates a random valid . + /// + /// Optional. The raw value of the playlist Id. + /// The created . + public PlaylistId Create( + Guid? value = null) + { + return PlaylistId.Create(value ?? Guid.NewGuid()); + } + + /// + /// 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.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs index 601b9e36..17f147b6 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/StubApiHttpClient.cs @@ -28,6 +28,7 @@ public class StubApiHttpClient : IApiHttpClient private readonly Dictionary> _postResponseFactories = []; private readonly Dictionary> _putResponseFactories = []; private readonly HashSet _deleteSuccessEndpoints = []; + private readonly Dictionary _deleteExceptions = []; private BlobDataDto? _blobResponse; /// @@ -167,6 +168,16 @@ public class StubApiHttpClient : IApiHttpClient _deleteSuccessEndpoints.Add(endpoint); } + /// + /// Registers the exception thrown when the specified DELETE endpoint is called. + /// + /// The API endpoint for which to register the exception. + /// The exception to throw. + public void RegisterDeleteException(string endpoint, ApiException exception) + { + _deleteExceptions[endpoint] = exception; + } + /// /// Registers the blob response returned when a blob endpoint is called. /// @@ -185,6 +196,7 @@ public class StubApiHttpClient : IApiHttpClient _postResponseFactories.Clear(); _putResponseFactories.Clear(); _deleteSuccessEndpoints.Clear(); + _deleteExceptions.Clear(); _blobResponse = null; GetEndpointsCalled.Clear(); PostRequests.Clear(); @@ -245,6 +257,8 @@ public class StubApiHttpClient : IApiHttpClient public Task DeleteAsync(string endpoint, CancellationToken cancellationToken = default) { DeleteEndpointsCalled.Add(endpoint); + if (_deleteExceptions.TryGetValue(endpoint, out ApiException? exception)) + throw exception; if (_deleteSuccessEndpoints.Contains(endpoint)) return Task.CompletedTask; throw new ApiException(null, System.Net.HttpStatusCode.InternalServerError, endpoint); diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs index af327f97..39dcc45d 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TestApiHttpMessageHandler.cs @@ -15,7 +15,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Api; [ExcludeFromCodeCoverage] public class TestApiHttpMessageHandler : HttpMessageHandler { - private readonly Func _responseFactory; + private readonly Func> _responseFactory; /// /// Gets the list of requests that were sent through this handler. @@ -27,11 +27,25 @@ public class TestApiHttpMessageHandler : HttpMessageHandler /// public List RequestBodies { get; } = []; + /// + /// Gets the cancellation tokens the requests were sent with. + /// + public List CancellationTokens { get; } = []; + /// /// Initializes a new instance of the class. /// /// The factory that produces the response for a given request. public TestApiHttpMessageHandler(Func responseFactory) + { + _responseFactory = (request, cancellationToken) => Task.FromResult(responseFactory(request)); + } + + /// + /// Initializes a new instance of the class. + /// + /// The asynchronous factory that produces the response for a given request and cancellation token. + public TestApiHttpMessageHandler(Func> responseFactory) { _responseFactory = responseFactory; } @@ -45,7 +59,8 @@ public class TestApiHttpMessageHandler : HttpMessageHandler protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Requests.Add(request); + CancellationTokens.Add(cancellationToken); RequestBodies.Add(request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken)); - return await Task.FromResult(_responseFactory(request)); + return await _responseFactory(request, cancellationToken); } } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TrackingStreamContent.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TrackingStreamContent.cs new file mode 100644 index 00000000..f001d7a1 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Api/TrackingStreamContent.cs @@ -0,0 +1,100 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Api; + +/// +/// test double that exposes whether the client buffered the content before handing it to the caller, +/// whether the content was disposed, and whether obtaining its stream is allowed to fail. +/// +[ExcludeFromCodeCoverage] +public sealed class TrackingStreamContent : HttpContent +{ + private readonly byte[] _contentBytes; + private readonly MemoryStream _contentStream; + private readonly bool _shouldFailStreamCreation; + + /// + /// Gets a value indicating whether the content was buffered by the client before it was handed to the caller. + /// + public bool WasBufferedByClient { get; private set; } + + /// + /// Gets a value indicating whether the content was disposed. + /// + public bool IsDisposed { get; private set; } + + /// + /// Gets the stream the content hands over when it is read without being buffered first. + /// + public Stream ContentStream => _contentStream; + + /// + /// Initializes a new instance of the class. + /// + /// The bytes of the content. + /// The media type the content declares. + /// Whether obtaining the content stream should fail. + public TrackingStreamContent(byte[] contentBytes, string mediaType = "application/octet-stream", bool shouldFailStreamCreation = false) + { + _contentBytes = contentBytes; + _contentStream = new MemoryStream(contentBytes); + _shouldFailStreamCreation = shouldFailStreamCreation; + Headers.ContentType = new MediaTypeHeaderValue(mediaType); + } + + /// + /// Writes the content to the provided stream, recording that the client buffered it. + /// + /// The stream the content is written to. + /// The transport context of the serialization, if any. + /// A task that represents the asynchronous serialization. + protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) + { + WasBufferedByClient = true; + return stream.WriteAsync(_contentBytes, 0, _contentBytes.Length); + } + + /// + /// Hands over the known content stream without buffering the content first. + /// + /// Cancellation token that can be used to stop the execution. + /// The content stream. + /// Thrown when the content is configured to fail obtaining its stream. + protected override Task CreateContentReadStreamAsync(CancellationToken cancellationToken) + { + if (_shouldFailStreamCreation) + throw new InvalidOperationException("The content stream cannot be obtained."); + return Task.FromResult(_contentStream); + } + + /// + /// Computes the length of the content. + /// + /// The length of the content in bytes. + /// Always . + protected override bool TryComputeLength(out long length) + { + length = _contentBytes.Length; + return true; + } + + /// + /// Disposes the content, recording that it was disposed. + /// + /// Whether the content is being disposed. + protected override void Dispose(bool disposing) + { + if (disposing) + IsDisposed = true; + base.Dispose(disposing); + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistDetailsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistDetailsDtoFixture.cs new file mode 100644 index 00000000..c1b77f85 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistDetailsDtoFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistDetailsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the playlist. + /// Optional name of the playlist. + /// Optional description of the playlist. + /// Optional kind of media the playlist holds. + /// Optional date and time when the playlist was last updated. + /// Whether the description should be included, or forced to . + /// Whether the last update date should be included, or forced to . + /// A configured instance. + public PlaylistDetailsDto Create( + Guid? id = null, + string? name = null, + string? description = null, + PlaylistType? type = null, + DateTime? updatedOnUtc = null, + bool includeDescription = true, + bool includeUpdatedOnUtc = true) + { + DateTime resolvedUpdatedOnUtc = DateTime.SpecifyKind(updatedOnUtc ?? DateTime.UtcNow.AddHours(-_faker.Random.Int(1, 24)), DateTimeKind.Utc); + return new PlaylistDetailsDto( + Id: id ?? _faker.Random.Guid(), + Name: name ?? _faker.Lorem.Sentence(3), + Description: includeDescription ? (description ?? _faker.Lorem.Sentence(5)) : null, + Type: type ?? PlaylistType.Music, + UpdatedOnUtc: includeUpdatedOnUtc ? resolvedUpdatedOnUtc : 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/DTO/Playlists/PlaylistEntriesAddedDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistEntriesAddedDtoFixture.cs new file mode 100644 index 00000000..e0627c34 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistEntriesAddedDtoFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntriesAddedDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the playlist the entries were added to. + /// Optional number of entries that were appended. + /// Optional date and time when the playlist was last updated. + /// Whether the last update date should be included, or forced to . + /// A configured instance. + public PlaylistEntriesAddedDto Create( + Guid? playlistId = null, + int? addedCount = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + DateTime resolvedUpdatedOnUtc = DateTime.SpecifyKind(updatedOnUtc ?? DateTime.UtcNow.AddHours(-_faker.Random.Int(1, 24)), DateTimeKind.Utc); + return new PlaylistEntriesAddedDto( + PlaylistId: playlistId ?? _faker.Random.Guid(), + AddedCount: addedCount ?? _faker.Random.Int(0, 1_000), + UpdatedOnUtc: includeUpdatedOnUtc ? resolvedUpdatedOnUtc : 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/DTO/Playlists/PlaylistEntryAddedDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistEntryAddedDtoFixture.cs new file mode 100644 index 00000000..f6720df2 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistEntryAddedDtoFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryAddedDtoFixture +{ + private readonly Faker _faker = new(); + private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the playlist the entry was added to. + /// Optional added entry. + /// Optional date and time when the playlist was last updated. + /// Whether the last update date should be included, or forced to . + /// A configured instance. + public PlaylistEntryAddedDto Create( + Guid? playlistId = null, + PlaylistEntryDto? entry = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + DateTime resolvedUpdatedOnUtc = DateTime.SpecifyKind(updatedOnUtc ?? DateTime.UtcNow.AddHours(-_faker.Random.Int(1, 24)), DateTimeKind.Utc); + return new PlaylistEntryAddedDto( + PlaylistId: playlistId ?? _faker.Random.Guid(), + Entry: entry ?? _playlistEntryDtoFixture.Create(), + UpdatedOnUtc: includeUpdatedOnUtc ? resolvedUpdatedOnUtc : 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/DTO/Playlists/PlaylistEntryMovedDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistEntryMovedDtoFixture.cs new file mode 100644 index 00000000..736f0c06 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistEntryMovedDtoFixture.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryMovedDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the playlist whose entry was moved. + /// Optional Id of the moved entry. + /// Optional new zero based position of the entry. + /// Optional date and time when the playlist was last updated. + /// Whether the last update date should be included, or forced to . + /// A configured instance. + public PlaylistEntryMovedDto Create( + Guid? playlistId = null, + Guid? entryId = null, + int? position = null, + DateTime? updatedOnUtc = null, + bool includeUpdatedOnUtc = true) + { + DateTime resolvedUpdatedOnUtc = DateTime.SpecifyKind(updatedOnUtc ?? DateTime.UtcNow.AddHours(-_faker.Random.Int(1, 24)), DateTimeKind.Utc); + return new PlaylistEntryMovedDto( + PlaylistId: playlistId ?? _faker.Random.Guid(), + EntryId: entryId ?? _faker.Random.Guid(), + Position: position ?? _faker.Random.Int(0, 1_000), + UpdatedOnUtc: includeUpdatedOnUtc ? resolvedUpdatedOnUtc : 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/DTO/Playlists/PlaylistSummaryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistSummaryDtoFixture.cs new file mode 100644 index 00000000..a78847dc --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Playlists/PlaylistSummaryDtoFixture.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class PlaylistSummaryDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the playlist. + /// Optional name of the playlist. + /// Optional description of the playlist. + /// Optional kind of media the playlist holds. + /// Optional number of entries of the playlist. + /// Optional date and time when the playlist was created. + /// Optional date and time when the playlist was last updated. + /// Whether the description should be included, or forced to . + /// Whether the last update date should be included, or forced to . + /// A configured instance. + public PlaylistSummaryDto Create( + Guid? id = null, + string? name = null, + string? description = null, + PlaylistType? type = null, + int? entryCount = null, + DateTime? createdOnUtc = null, + DateTime? updatedOnUtc = null, + bool includeDescription = true, + bool includeUpdatedOnUtc = true) + { + DateTime resolvedCreatedOnUtc = DateTime.SpecifyKind(createdOnUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)), DateTimeKind.Utc); + DateTime resolvedUpdatedOnUtc = DateTime.SpecifyKind(updatedOnUtc ?? resolvedCreatedOnUtc.AddHours(_faker.Random.Int(1, 24)), DateTimeKind.Utc); + return new PlaylistSummaryDto( + Id: id ?? _faker.Random.Guid(), + Name: name ?? _faker.Lorem.Sentence(3), + Description: includeDescription ? (description ?? _faker.Lorem.Sentence(5)) : null, + Type: type ?? PlaylistType.Music, + EntryCount: entryCount ?? _faker.Random.Int(0, 1_000), + CreatedOnUtc: resolvedCreatedOnUtc, + UpdatedOnUtc: includeUpdatedOnUtc ? resolvedUpdatedOnUtc : 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/DTO/Themes/ThemeTemplateResponseDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs index c1972755..79132eab 100644 --- a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/Themes/ThemeTemplateResponseDtoFixture.cs @@ -22,14 +22,16 @@ public class ThemeTemplateResponseDtoFixture /// /// Optional theme the template belongs to. /// Optional sanitized template content. + /// Whether the template content should be included, or forced to . /// A configured instance. public ThemeTemplateResponseDto Create( ThemeResponseDto? theme = null, - string? template = null) + string? template = null, + bool includeTemplate = true) { return new ThemeTemplateResponseDto( Theme: theme ?? _themeResponseDtoFixture.Create(), - Template: template ?? _faker.Lorem.Paragraph() + Template: includeTemplate ? (template ?? _faker.Lorem.Paragraph()) : null! ); } diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/PlaybackStateDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/PlaybackStateDtoFixture.cs new file mode 100644 index 00000000..63ef2004 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/UsersManagement/PlaybackStateDtoFixture.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackStateDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a random valid . + /// + /// Optional. The last volume the player reported, as a value between 0 and 1. + /// Optional. The last mute state the player reported. + /// Whether the volume should be included, or forced to . + /// Whether the mute state should be included, or forced to . + /// The created . + public PlaybackStateDto Create( + double? volume = null, + bool? isMuted = null, + bool includeVolume = true, + bool includeIsMuted = true) + { + return new PlaybackStateDto + { + Volume = includeVolume ? volume ?? _faker.Random.Double(0, 1) : null, + IsMuted = includeIsMuted ? isMuted ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates a list of instances. + /// + /// Number of elements to create. + /// The created list. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistEntriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistEntriesRequestFixture.cs new file mode 100644 index 00000000..86eceed3 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistEntriesRequestFixture.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Ids of the tracks to add, in order. + /// Optional number of random track Ids to generate when is not supplied. + /// Whether the track Ids should be included, or forced to . + /// A configured instance. + public AddPlaylistEntriesRequest Create( + List? trackIds = null, + int trackCount = 3, + bool includeTrackIds = true) + { + return new AddPlaylistEntriesRequest( + TrackIds: includeTrackIds ? (trackIds ?? CreateRandomTrackIds(trackCount)) : 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())]; + } + + /// + /// Creates the requested number of distinct random track Ids. + /// + /// The number of track Ids to create. + /// The created track Ids. + private static List CreateRandomTrackIds(int count) + { + return [.. Enumerable.Range(0, count).Select(_ => Guid.NewGuid())]; + } +} diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistEntryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistEntryRequestFixture.cs new file mode 100644 index 00000000..63d7284b --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistEntryRequestFixture.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the track to add. + /// Whether the track Id should be included, or forced to . + /// A configured instance. + public AddPlaylistEntryRequest Create( + Guid? trackId = null, + bool includeTrackId = true) + { + return new AddPlaylistEntryRequest( + TrackId: includeTrackId ? (trackId ?? Guid.NewGuid()) : 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/Playlists/AddPlaylistScopeEntriesRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistScopeEntriesRequestFixture.cs new file mode 100644 index 00000000..548b8a23 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/AddPlaylistScopeEntriesRequestFixture.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesRequestFixture +{ + /// + /// Creates a new instance with randomized test data. + /// + /// Optional Id of the music library the scope belongs to. + /// Optional Id of the artist the scope is limited to. + /// Optional Id of the album the scope is limited to. + /// Whether the artist Id should be included, or forced to . + /// Whether the album Id should be included, or forced to . + /// A configured instance. + public AddPlaylistScopeEntriesRequest Create( + Guid? libraryId = null, + Guid? artistId = null, + Guid? albumId = null, + bool includeArtistId = true, + bool includeAlbumId = true) + { + return new AddPlaylistScopeEntriesRequest( + LibraryId: libraryId ?? Guid.NewGuid(), + ArtistId: includeArtistId ? (artistId ?? Guid.NewGuid()) : null, + AlbumId: includeAlbumId ? (albumId ?? Guid.NewGuid()) : 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/Playlists/CreatePlaylistRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/CreatePlaylistRequestFixture.cs new file mode 100644 index 00000000..673c9d69 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/CreatePlaylistRequestFixture.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional name of the playlist. + /// Optional description of the playlist. + /// Optional kind of media the playlist holds. + /// Whether the name should be included, or forced to . + /// Whether the description should be included, or forced to . + /// Whether the media type should be included, or forced to . + /// A configured instance. + public CreatePlaylistRequest Create( + string? name = null, + string? description = null, + PlaylistType? type = null, + bool includeName = true, + bool includeDescription = true, + bool includeType = true) + { + return new CreatePlaylistRequest( + Name: includeName ? (name ?? _faker.Lorem.Sentence(3)) : null, + Description: includeDescription ? (description ?? _faker.Lorem.Sentence(5)) : null, + Type: includeType ? (type ?? PlaylistType.Music) : 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/Playlists/MovePlaylistEntryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/MovePlaylistEntryRequestFixture.cs new file mode 100644 index 00000000..ff3ef85c --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/MovePlaylistEntryRequestFixture.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional new zero based position of the entry. + /// Whether the target position should be included, or forced to . + /// A configured instance. + public MovePlaylistEntryRequest Create( + int? targetPosition = null, + bool includeTargetPosition = true) + { + return new MovePlaylistEntryRequest( + TargetPosition: includeTargetPosition ? (targetPosition ?? _faker.Random.Int(0, 1_000)) : 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/Playlists/UpdatePlaylistRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/UpdatePlaylistRequestFixture.cs new file mode 100644 index 00000000..40067e70 --- /dev/null +++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Playlists/UpdatePlaylistRequestFixture.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistRequestFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional name of the playlist. + /// Optional description of the playlist. + /// Whether the name should be included, or forced to . + /// Whether the description should be included, or forced to . + /// A configured instance. + public UpdatePlaylistRequest Create( + string? name = null, + string? description = null, + bool includeName = true, + bool includeDescription = true) + { + return new UpdatePlaylistRequest( + Name: includeName ? (name ?? _faker.Lorem.Sentence(3)) : null, + Description: includeDescription ? (description ?? _faker.Lorem.Sentence(5)) : 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/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs new file mode 100644 index 00000000..3bcef3d5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs @@ -0,0 +1,586 @@ +#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.Playlists; +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.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Playlists.AddPlaylistEntries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + 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 PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddPlaylistEntriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task AddPlaylistEntries_WhenTheTracksExist_ShouldAppendEveryEntryInTheRequestedOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Innuendo"); + Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "Innuendo", 393); + Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "The Show Must Go On", 262); + Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "These Are the Days of Our Lives", 255); + Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [thirdTrackId, firstTrackId, secondTrackId]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(playlistId, addedEntries!.PlaylistId); + Assert.Equal(3, addedEntries.AddedCount); + Assert.NotEqual(default, addedEntries.UpdatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId); + Assert.Equal([thirdTrackId, firstTrackId, secondTrackId], storedTrackIds); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(3, playlist.EntryCount); + } + + [Fact] + public async Task AddPlaylistEntries_WhenTheSameTrackAppearsTwice_ShouldKeepOneEntryPerOccurrence() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "News of the World"); + Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "We Will Rock You", 122); + Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "We Are the Champions", 179); + Guid playlistId = await SeedPlaylistAsync(userId, "Repeats allowed", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [firstTrackId, secondTrackId, firstTrackId]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(3, addedEntries!.AddedCount); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId); + Assert.Equal([firstTrackId, secondTrackId, firstTrackId], storedTrackIds); + } + + [Fact] + public async Task AddPlaylistEntries_WhenThePlaylistAlreadyHasEntries_ShouldAppendAfterThem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Night at the Opera"); + Guid existingTrackId = await SeedTrackAsync(libraryId, albumId, "Bohemian Rhapsody", 354); + Guid firstNewTrackId = await SeedTrackAsync(libraryId, albumId, "Love of My Life", 219); + Guid secondNewTrackId = await SeedTrackAsync(libraryId, albumId, "You're My Best Friend", 170); + Guid playlistId = await SeedPlaylistAsync(userId, "Append after existing", entryCount: 1); + await SeedPlaylistEntryAsync(playlistId, existingTrackId, 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [firstNewTrackId, secondNewTrackId]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(2, addedEntries!.AddedCount); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId); + Assert.Equal([existingTrackId, firstNewTrackId, secondNewTrackId], storedTrackIds); + } + + [Fact] + public async Task AddPlaylistEntries_WhenTheTrackListIsMissing_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "No tracks", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(includeTrackIds: false); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistEntries_WhenTheTrackListIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty batch", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: []); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistEntries_WhenAnEntryIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty entry", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [Guid.NewGuid(), Guid.Empty]); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistEntries_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task AddPlaylistEntries_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundWithoutAddingEntries() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Someone Else"); + Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Private Album"); + Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Private Track", 200); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [otherTrackId]); + string url = $"{PATH}/{otherPlaylistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == otherPlaylistId)); + } + + [Fact] + public async Task AddPlaylistEntries_WhenOneTrackDoesNotExist_ShouldReturnTrackNotFoundAndAddNothing() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Jazz"); + Guid existingTrackId = await SeedTrackAsync(libraryId, albumId, "Bicycle Race", 184); + Guid playlistId = await SeedPlaylistAsync(userId, "Partial batch", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [existingTrackId, Guid.NewGuid()]); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + } + + [Fact] + public async Task AddPlaylistEntries_WhenATrackBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingTrack() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Only my library", entryCount: 0); + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Not Mine"); + Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Not Mine Either"); + Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Unreachable Track", 210); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [otherTrackId]); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + } + + [Fact] + public async Task AddPlaylistEntries_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + string url = $"{PATH}/not-a-guid/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + /// + /// Reads the media item Ids of the entries of , in stored order. + /// + /// The database context to read from. + /// The Id of the playlist whose entries are read. + /// The media item Ids in stored order. + private static async Task> GetOrderedTrackIdsAsync(LuminaDbContext dbContext, Guid playlistId) + { + return await dbContext.PlaylistEntries + .AsNoTracking() + .Where(candidate => candidate.PlaylistId == playlistId) + .OrderBy(candidate => candidate.Position) + .Select(candidate => candidate.MediaItemId) + .ToListAsync(); + } + + /// + /// Seeds a music library owned by and tracks it for cleanup. + /// + /// The Id of the user that owns the media library. + /// The Id of the seeded media library. + private async Task SeedLibraryAsync(Guid userId) + { + 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: $"Library-{Guid.NewGuid():N}", 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(); + dbContext.Albums.Add(_albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: title, + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + 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, + 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 a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist already holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The Id of the referenced track. + /// The sparse order key of the entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + playlistId: playlistId, + mediaItemId: mediaItemId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List libraryIds = [.. _seededLibraryIds]; + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId))); + dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId))); + dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId))); + dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..ef5af8d4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs @@ -0,0 +1,579 @@ +#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.Playlists; +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.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Playlists.AddPlaylistEntry; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + 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 PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddPlaylistEntryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task AddPlaylistEntry_WhenThePlaylistAndTrackExist_ShouldAppendTheEntryAndReturnIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Innuendo"); + Guid trackId = await SeedTrackAsync(libraryId, albumId, "Innuendo", 393); + Guid playlistId = await SeedPlaylistAsync(userId, "Evening listening", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistEntryAddedResponse? addedEntry = await DeserializeAsync(response); + Assert.NotNull(addedEntry); + Assert.Equal(playlistId, addedEntry!.PlaylistId); + Assert.NotEqual(default, addedEntry.UpdatedOnUtc); + PlaylistEntryResponse entry = addedEntry.Entry; + Assert.NotEqual(Guid.Empty, entry.Id); + Assert.Equal(trackId, entry.MediaItemId); + Assert.Equal(PlaylistMediaItemType.MusicTrack, entry.MediaItemType); + Assert.Equal(0, entry.Position); + Assert.Equal(libraryId, entry.LibraryId); + Assert.Equal(albumId, entry.CollectionId); + Assert.Equal(artistId, entry.CreatorId); + Assert.Equal("Innuendo", entry.MediaItemTitle); + Assert.Equal("Innuendo", entry.CollectionTitle); + Assert.Equal("Queen", entry.CreatorName); + Assert.Equal(393, entry.DurationInSeconds); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntryEntity? storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstOrDefaultAsync(candidate => candidate.Id == entry.Id); + Assert.NotNull(storedEntry); + Assert.Equal(playlistId, storedEntry!.PlaylistId); + Assert.Equal(trackId, storedEntry.MediaItemId); + Assert.Equal(0, storedEntry.Position); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(1, playlist.EntryCount); + } + + [Fact] + public async Task AddPlaylistEntry_WhenThePlaylistAlreadyHasEntries_ShouldAppendTheEntryAtTheNextDensePosition() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "A Kind of Magic"); + Guid firstTrackId = await SeedTrackAsync(libraryId, albumId, "One Vision", 308); + Guid secondTrackId = await SeedTrackAsync(libraryId, albumId, "A Kind of Magic", 262); + Guid thirdTrackId = await SeedTrackAsync(libraryId, albumId, "Friends Will Be Friends", 248); + Guid playlistId = await SeedPlaylistAsync(userId, "Ordered listening", entryCount: 2); + await SeedPlaylistEntryAsync(playlistId, firstTrackId, 0); + await SeedPlaylistEntryAsync(playlistId, secondTrackId, 1_000_000_000L); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: thirdTrackId); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntryAddedResponse? addedEntry = await DeserializeAsync(response); + Assert.NotNull(addedEntry); + // The stored order keys are sparse, so the appended entry reports the dense display position derived from the entry count. + Assert.Equal(2, addedEntry!.Entry.Position); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await dbContext.PlaylistEntries + .AsNoTracking() + .Where(candidate => candidate.PlaylistId == playlistId) + .OrderBy(candidate => candidate.Position) + .Select(candidate => candidate.MediaItemId) + .ToListAsync(); + Assert.Equal([firstTrackId, secondTrackId, thirdTrackId], storedTrackIds); + } + + [Fact] + public async Task AddPlaylistEntry_WhenTheSameTrackIsAddedTwice_ShouldKeepBothEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "News of the World"); + Guid trackId = await SeedTrackAsync(libraryId, albumId, "We Will Rock You", 122); + Guid playlistId = await SeedPlaylistAsync(userId, "Repeats allowed", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + + // Act + HttpResponseMessage firstResponse = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request); + HttpResponseMessage secondResponse = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode); + Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode); + PlaylistEntryAddedResponse? firstEntry = await DeserializeAsync(firstResponse); + PlaylistEntryAddedResponse? secondEntry = await DeserializeAsync(secondResponse); + Assert.NotNull(firstEntry); + Assert.NotNull(secondEntry); + Assert.NotEqual(firstEntry!.Entry.Id, secondEntry!.Entry.Id); + Assert.Equal(0, firstEntry.Entry.Position); + Assert.Equal(1, secondEntry.Entry.Position); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.Equal(2, await dbContext.PlaylistEntries.CountAsync(candidate => candidate.PlaylistId == playlistId && candidate.MediaItemId == trackId)); + } + + [Fact] + public async Task AddPlaylistEntry_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Queen"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Jazz"); + Guid trackId = await SeedTrackAsync(libraryId, albumId, "Bicycle Race", 184); + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + string url = $"{PATH}/{playlistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task AddPlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundWithoutAddingAnEntry() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Someone Else"); + Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Private Album"); + Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Private Track", 200); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: otherTrackId); + string url = $"{PATH}/{otherPlaylistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == otherPlaylistId)); + } + + [Fact] + public async Task AddPlaylistEntry_WhenTheTrackDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Missing track", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.NewGuid()); + string url = $"{PATH}/{playlistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + } + + [Fact] + public async Task AddPlaylistEntry_WhenTheTrackBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingTrack() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Only my library", entryCount: 0); + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Not Mine"); + Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Not Mine Either"); + Guid otherTrackId = await SeedTrackAsync(otherLibraryId, otherAlbumId, "Unreachable Track", 210); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: otherTrackId); + string url = $"{PATH}/{playlistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + // The unreachable track is reported exactly like a missing one, so the response cannot be used to probe another user's library. + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "TrackNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + } + + [Fact] + public async Task AddPlaylistEntry_WhenTheTrackIdIsMissing_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "No track", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(includeTrackId: false); + string url = $"{PATH}/{playlistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistEntry_WhenTheTrackIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty track id", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.Empty); + string url = $"{PATH}/{playlistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistEntry_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.NewGuid()); + string url = $"{PATH}/not-a-guid/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + /// + /// Seeds a music library owned by and tracks it for cleanup. + /// + /// The Id of the user that owns the media library. + /// The Id of the seeded media library. + private async Task SeedLibraryAsync(Guid userId) + { + 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: $"Library-{Guid.NewGuid():N}", 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(); + dbContext.Albums.Add(_albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: title, + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + 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, + 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 a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist already holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The Id of the referenced track. + /// The sparse order key of the entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + playlistId: playlistId, + mediaItemId: mediaItemId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List libraryIds = [.. _seededLibraryIds]; + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId))); + dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId))); + dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId))); + dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs new file mode 100644 index 00000000..e6a85a18 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs @@ -0,0 +1,610 @@ +#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.Playlists; +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.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Playlists.AddPlaylistScopeEntries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + 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 PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddPlaylistScopeEntriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheWholeLibraryIsScoped_ShouldAppendEveryTrackInCatalogueOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid alphaArtistId = await SeedArtistAsync(libraryId, "Alpha Artist"); + Guid alphaAlbumId = await SeedAlbumAsync(libraryId, alphaArtistId, "Alpha Album"); + Guid alphaFirstTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha One", 100, trackNumber: 1); + Guid alphaSecondTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha Two", 110, trackNumber: 2); + Guid betaArtistId = await SeedArtistAsync(libraryId, "Beta Artist"); + Guid betaAlbumId = await SeedAlbumAsync(libraryId, betaArtistId, "Beta Album"); + Guid betaTrackId = await SeedTrackAsync(libraryId, betaAlbumId, "Beta One", 120, trackNumber: 1); + Guid playlistId = await SeedPlaylistAsync(userId, "Whole library", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(playlistId, addedEntries!.PlaylistId); + Assert.Equal(3, addedEntries.AddedCount); + Assert.NotEqual(default, addedEntries.UpdatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId); + Assert.Equal([alphaFirstTrackId, alphaSecondTrackId, betaTrackId], storedTrackIds); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(3, playlist.EntryCount); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenAnArtistIsScoped_ShouldAppendOnlyThatArtistsTracks() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid alphaArtistId = await SeedArtistAsync(libraryId, "Alpha Artist"); + Guid alphaAlbumId = await SeedAlbumAsync(libraryId, alphaArtistId, "Alpha Album"); + Guid alphaFirstTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha One", 100, trackNumber: 1); + Guid alphaSecondTrackId = await SeedTrackAsync(libraryId, alphaAlbumId, "Alpha Two", 110, trackNumber: 2); + Guid betaArtistId = await SeedArtistAsync(libraryId, "Beta Artist"); + Guid betaAlbumId = await SeedAlbumAsync(libraryId, betaArtistId, "Beta Album"); + await SeedTrackAsync(libraryId, betaAlbumId, "Beta One", 120, trackNumber: 1); + Guid playlistId = await SeedPlaylistAsync(userId, "One artist", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, artistId: alphaArtistId, includeArtistId: true); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(2, addedEntries!.AddedCount); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId); + Assert.Equal([alphaFirstTrackId, alphaSecondTrackId], storedTrackIds); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenAnAlbumIsScoped_ShouldAppendOnlyThatAlbumsTracks() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Alpha Artist"); + Guid firstAlbumId = await SeedAlbumAsync(libraryId, artistId, "First Album"); + await SeedTrackAsync(libraryId, firstAlbumId, "First One", 100, trackNumber: 1); + await SeedTrackAsync(libraryId, firstAlbumId, "First Two", 110, trackNumber: 2); + Guid secondAlbumId = await SeedAlbumAsync(libraryId, artistId, "Second Album"); + Guid scopedTrackId = await SeedTrackAsync(libraryId, secondAlbumId, "Second One", 120, trackNumber: 1); + Guid playlistId = await SeedPlaylistAsync(userId, "One album", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, albumId: secondAlbumId, includeAlbumId: true); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(1, addedEntries!.AddedCount); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List storedTrackIds = await GetOrderedTrackIdsAsync(dbContext, playlistId); + Assert.Equal([scopedTrackId], storedTrackIds); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheScopeIsEmpty_ShouldAppendNothingAndReportAZeroCount() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid artistId = await SeedArtistAsync(libraryId, "Alpha Artist"); + Guid albumId = await SeedAlbumAsync(libraryId, artistId, "Empty Album"); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty scope", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, albumId: albumId, includeAlbumId: true); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntriesAddedResponse? addedEntries = await DeserializeAsync(response); + Assert.NotNull(addedEntries); + Assert.Equal(0, addedEntries!.AddedCount); + // An empty scope is a successful no-op, so the playlist activity time is not touched. + Assert.Null(addedEntries.UpdatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(0, playlist.EntryCount); + Assert.Equal(0, playlist.Version); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid libraryId = await SeedLibraryAsync(userId); + Guid playlistId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundWithoutAddingEntries() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Someone Else"); + Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Private Album"); + await SeedTrackAsync(otherLibraryId, otherAlbumId, "Private Track", 200, trackNumber: 1); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: otherLibraryId); + string url = $"{PATH}/{otherPlaylistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == otherPlaylistId)); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutAddingEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Only my library", entryCount: 0); + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherLibraryId = await SeedLibraryAsync(otherUserId); + Guid otherArtistId = await SeedArtistAsync(otherLibraryId, "Not Mine"); + Guid otherAlbumId = await SeedAlbumAsync(otherLibraryId, otherArtistId, "Not Mine Either"); + await SeedTrackAsync(otherLibraryId, otherAlbumId, "Unreachable Track", 210, trackNumber: 1); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: otherLibraryId); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheLibraryDoesNotExist_ShouldReturnForbiddenWithoutAddingEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Unknown library", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: Guid.NewGuid()); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.Forbidden, "General.Unauthorized", "NotAuthorized", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(candidate => candidate.PlaylistId == playlistId)); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheLibraryIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty library", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: Guid.Empty); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "LibraryIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheArtistIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty artist", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: Guid.NewGuid(), artistId: Guid.Empty, includeArtistId: true); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "ArtistIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheAlbumIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Empty album", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: Guid.NewGuid(), albumId: Guid.Empty, includeAlbumId: true); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "AlbumIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + string url = $"{PATH}/not-a-guid/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + /// + /// Reads the media item Ids of the entries of , in stored order. + /// + /// The database context to read from. + /// The Id of the playlist whose entries are read. + /// The media item Ids in stored order. + private static async Task> GetOrderedTrackIdsAsync(LuminaDbContext dbContext, Guid playlistId) + { + return await dbContext.PlaylistEntries + .AsNoTracking() + .Where(candidate => candidate.PlaylistId == playlistId) + .OrderBy(candidate => candidate.Position) + .Select(candidate => candidate.MediaItemId) + .ToListAsync(); + } + + /// + /// Seeds a music library owned by and tracks it for cleanup. + /// + /// The Id of the user that owns the media library. + /// The Id of the seeded media library. + private async Task SeedLibraryAsync(Guid userId) + { + 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: $"Library-{Guid.NewGuid():N}", 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(); + dbContext.Albums.Add(_albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: title, + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + 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 number of the track on its album. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds, int trackNumber) + { + 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, + title: title, + trackNumber: trackNumber, + // Catalogue order is resolved by disc and then track number, so the disc is pinned to keep the appended order deterministic. + discNumber: 1, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false); + track.DurationInSeconds = durationInSeconds; + dbContext.Tracks.Add(track); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist already holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List libraryIds = [.. _seededLibraryIds]; + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId))); + dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId))); + dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId))); + dbContext.Libraries.RemoveRange(dbContext.Libraries.Where(library => libraryIds.Contains(library.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs new file mode 100644 index 00000000..611a4f36 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs @@ -0,0 +1,355 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Playlists.CreatePlaylist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CreatePlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task CreatePlaylist_WhenTheRequestIsValid_ShouldCreateThePlaylistForTheCallerAndReturnIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create( + name: "Evening listening", description: "Quiet tracks for the end of the day", type: PlaylistType.Music); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + Assert.NotEqual(Guid.Empty, playlist!.Id); + Assert.Equal("Evening listening", playlist.Name); + Assert.Equal("Quiet tracks for the end of the day", playlist.Description); + Assert.Equal(PlaylistType.Music, playlist.Type); + Assert.Empty(playlist.Entries.Data); + Assert.Equal(0, playlist.Entries.Count); + Assert.NotEqual(default, playlist.CreatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Equal(userId, storedPlaylist.UserId); + Assert.Equal(userId, storedPlaylist.CreatedBy); + Assert.Equal("Evening listening", storedPlaylist.Name); + Assert.Equal("Quiet tracks for the end of the day", storedPlaylist.Description); + Assert.Equal(PlaylistType.Music, storedPlaylist.Type); + Assert.Equal(0, storedPlaylist.EntryCount); + Assert.Equal(0, storedPlaylist.Version); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlist.Id)); + } + + [Fact] + public async Task CreatePlaylist_WhenTheDescriptionIsOmitted_ShouldCreateThePlaylistWithoutADescription() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "No description", includeDescription: false); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + Assert.Null(playlist!.Description); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Null(storedPlaylist.Description); + } + + [Fact] + public async Task CreatePlaylist_WhenTheNameHasTheMaximumLength_ShouldCreateThePlaylist() + { + // Arrange + string maximumLengthName = new('a', 255); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: maximumLengthName); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + Assert.Equal(maximumLengthName, playlist!.Name); + } + + [Fact] + public async Task CreatePlaylist_WhenTheNameIsMissing_ShouldReturnValidationProblem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeName: false); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertValidationProblemAsync(response, PATH, "PlaylistNameCannotBeEmpty"); + } + + [Fact] + public async Task CreatePlaylist_WhenTheNameIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: string.Empty); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertValidationProblemAsync(response, PATH, "PlaylistNameCannotBeEmpty"); + } + + [Fact] + public async Task CreatePlaylist_WhenTheNameIsTooLong_ShouldReturnValidationProblem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: new string('a', 256)); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertValidationProblemAsync(response, PATH, "PlaylistNameMustBeMaximum255CharactersLong"); + } + + [Fact] + public async Task CreatePlaylist_WhenTheDescriptionIsTooLong_ShouldReturnValidationProblem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(description: new string('a', 2001)); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertValidationProblemAsync(response, PATH, "PlaylistDescriptionMustBeMaximum2000CharactersLong"); + } + + [Fact] + public async Task CreatePlaylist_WhenTheTypeIsMissing_ShouldReturnValidationProblem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeType: false); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertValidationProblemAsync(response, PATH, "PlaylistTypeIsInvalid"); + } + + [Fact] + public async Task CreatePlaylist_WhenTheTypeIsNotADefinedMember_ShouldReturnValidationProblem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(type: (PlaylistType)99); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertValidationProblemAsync(response, PATH, "PlaylistTypeIsInvalid"); + } + + [Fact] + public async Task CreatePlaylist_WhenAnotherUserHasPlaylists_ShouldCreateThePlaylistOnlyForTheCaller() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist"); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "Mine"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist!.Id); + Assert.Equal(GetCurrentUserId(), storedPlaylist.UserId); + PlaylistEntity otherPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == otherPlaylistId); + Assert.Equal(otherUserId, otherPlaylist.UserId); + Assert.Equal("Someone else's playlist", otherPlaylist.Name); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: 0, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs new file mode 100644 index 00000000..4994eb1a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs @@ -0,0 +1,312 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeletePlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task DeletePlaylist_WhenThePlaylistExists_ShouldDeleteItTogetherWithItsEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "To delete", entryCount: 2); + await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0); + await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 1_000_000_000L); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/{playlistId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + string content = await response.Content.ReadAsStringAsync(); + using JsonDocument document = JsonDocument.Parse(content); + Assert.Equal(JsonValueKind.Object, document.RootElement.ValueKind); + Assert.Empty(document.RootElement.EnumerateObject()); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId)); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId)); + } + + [Fact] + public async Task DeletePlaylist_WhenCalledTwice_ShouldDeleteOnlyOnceAndReportTheSecondCallAsNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Deleted once", entryCount: 1); + Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Untouched", entryCount: 1); + await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0); + await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0); + + // Act + HttpResponseMessage firstResponse = await _client.DeleteAsync($"{PATH}/{playlistId}"); + HttpResponseMessage secondResponse = await _client.DeleteAsync($"{PATH}/{playlistId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode); + await AssertProblemAsync(secondResponse, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", $"{PATH}/{playlistId}"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId)); + Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId)); + Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == otherPlaylistId)); + } + + [Fact] + public async Task DeletePlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheData() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", entryCount: 1); + await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0); + string url = $"{PATH}/{otherPlaylistId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId)); + Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == otherPlaylistId)); + } + + [Fact] + public async Task DeletePlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task DeletePlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + string url = $"{PATH}/not-a-guid"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + [Fact] + public async Task DeletePlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + string url = $"{PATH}/{Guid.Empty}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The Id of the referenced track. + /// The sparse order key of the entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + playlistId: playlistId, + mediaItemId: mediaItemId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs new file mode 100644 index 00000000..2776a7fd --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs @@ -0,0 +1,259 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPlaylistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetPlaylists_WhenTheCallerHasNoPlaylists_ShouldReturnAnEmptyList() + { + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertCacheHeaders(response); + PlaylistSummaryResponse[]? playlists = await DeserializeAsync(response); + Assert.NotNull(playlists); + Assert.Empty(playlists!); + } + + [Fact] + public async Task GetPlaylists_WhenTheCallerHasPlaylists_ShouldReturnThemWithTheirEntryCountsOrderedByActivity() + { + // Arrange + Guid userId = GetCurrentUserId(); + DateTime now = DateTime.UtcNow; + Guid oldestId = await SeedPlaylistAsync(userId, "Beta Morning", description: "Oldest", entryCount: 0, createdOnUtc: now.AddHours(-3)); + Guid middleId = await SeedPlaylistAsync(userId, "Alpha Evening", description: "Middle", entryCount: 2, createdOnUtc: now.AddHours(-2)); + Guid mostRecentId = await SeedPlaylistAsync(userId, "Gamma Afternoon", description: "Most recent", entryCount: 1, createdOnUtc: now.AddHours(-4), updatedOnUtc: now); + + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertCacheHeaders(response); + PlaylistSummaryResponse[]? playlists = await DeserializeAsync(response); + Assert.NotNull(playlists); + Assert.Equal(3, playlists!.Length); + // The order is the most recent activity first: the updated playlist, then the two that were never updated, by creation time. + Assert.Equal([mostRecentId, middleId, oldestId], playlists.Select(playlist => playlist.Id)); + + PlaylistSummaryResponse mostRecent = playlists[0]; + Assert.Equal("Gamma Afternoon", mostRecent.Name); + Assert.Equal("Most recent", mostRecent.Description); + Assert.Equal(PlaylistType.Music, mostRecent.Type); + Assert.Equal(1, mostRecent.EntryCount); + Assert.NotEqual(default, mostRecent.CreatedOnUtc); + Assert.NotNull(mostRecent.UpdatedOnUtc); + + PlaylistSummaryResponse middle = playlists[1]; + Assert.Equal("Alpha Evening", middle.Name); + Assert.Equal(2, middle.EntryCount); + Assert.Null(middle.UpdatedOnUtc); + } + + [Fact] + public async Task GetPlaylists_WhenTwoPlaylistsShareTheSameActivityTime_ShouldOrderThemByName() + { + // Arrange + Guid userId = GetCurrentUserId(); + DateTime sharedCreationTime = DateTime.UtcNow.AddHours(-1); + Guid zebraId = await SeedPlaylistAsync(userId, "Zebra", description: null, entryCount: 0, createdOnUtc: sharedCreationTime); + Guid alphaId = await SeedPlaylistAsync(userId, "Alpha", description: null, entryCount: 0, createdOnUtc: sharedCreationTime); + + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistSummaryResponse[]? playlists = await DeserializeAsync(response); + Assert.NotNull(playlists); + Assert.Equal([alphaId, zebraId], playlists!.Select(playlist => playlist.Id)); + } + + [Fact] + public async Task GetPlaylists_WhenAnotherUserHasPlaylists_ShouldReturnOnlyTheCallersPlaylists() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid ownPlaylistId = await SeedPlaylistAsync(userId, "Mine", description: null, entryCount: 0, createdOnUtc: DateTime.UtcNow); + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", description: "Private", entryCount: 3, createdOnUtc: DateTime.UtcNow); + + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Someone else's playlist", content, StringComparison.Ordinal); + Assert.DoesNotContain(otherPlaylistId.ToString(), content, StringComparison.Ordinal); + PlaylistSummaryResponse[]? playlists = await DeserializeAsync(response); + Assert.NotNull(playlists); + PlaylistSummaryResponse playlist = Assert.Single(playlists!); + Assert.Equal(ownPlaylistId, playlist.Id); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The description of the playlist, or . + /// The number of entries the playlist holds. + /// The creation time of the playlist. + /// The activity time of the playlist, or when it was never updated. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, string? description, int entryCount, DateTime createdOnUtc, DateTime? updatedOnUtc = null) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + description: description ?? string.Empty, + includeDescription: description is not null, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + // The auditing interceptor overwrites both timestamps when a row is inserted, so the activity times that the ordering depends on + // are written afterwards, in the same form a real details update or entry operation would leave them. + await dbContext.Playlists + .Where(playlist => playlist.Id == playlistId) + .ExecuteUpdateAsync(setters => setters + .SetProperty(playlist => playlist.CreatedOnUtc, createdOnUtc) + .SetProperty(playlist => playlist.UpdatedOnUtc, updatedOnUtc) + .SetProperty(playlist => playlist.UpdatedBy, updatedOnUtc is null ? (Guid?)null : userId)); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response carries the cache headers of a private, authorization varying resource. + /// + /// The HTTP response to assert on. + private static void AssertCacheHeaders(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// 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(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..e5b6abf5 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs @@ -0,0 +1,508 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Playlists.MovePlaylistEntry; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public MovePlaylistEntryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task MovePlaylistEntry_WhenMovedToTheFront_ShouldReturnTheNewPositionAndReorderTheEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistEntryMovedResponse? movedEntry = await DeserializeAsync(response); + Assert.NotNull(movedEntry); + Assert.Equal(playlistId, movedEntry!.PlaylistId); + Assert.Equal(secondEntryId, movedEntry.EntryId); + Assert.Equal(0, movedEntry.Position); + Assert.NotEqual(default, movedEntry.UpdatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal(secondEntryId, orderedEntryIds[0]); + Assert.Equal(firstEntryId, orderedEntryIds[1]); + } + + [Fact] + public async Task MovePlaylistEntry_WhenMovedToTheEnd_ShouldReturnTheLastPositionAndReorderTheEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 2); + string url = $"{PATH}/{playlistId}/entries/{firstEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntryMovedResponse? movedEntry = await DeserializeAsync(response); + Assert.NotNull(movedEntry); + Assert.Equal(2, movedEntry!.Position); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal(secondEntryId, orderedEntryIds[0]); + Assert.Equal(thirdEntryId, orderedEntryIds[1]); + Assert.Equal(firstEntryId, orderedEntryIds[2]); + } + + [Fact] + public async Task MovePlaylistEntry_WhenMovedToAMiddlePosition_ShouldReorderOnlyTheAffectedEntries() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 1); + string url = $"{PATH}/{playlistId}/entries/{thirdEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistEntryMovedResponse? movedEntry = await DeserializeAsync(response); + Assert.NotNull(movedEntry); + Assert.Equal(1, movedEntry!.Position); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal(firstEntryId, orderedEntryIds[0]); + Assert.Equal(thirdEntryId, orderedEntryIds[1]); + Assert.Equal(secondEntryId, orderedEntryIds[2]); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheTargetPositionIsBeyondTheEntryCount_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 3); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistMoveTargetPositionIsInvalid"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntryEntity storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == secondEntryId); + Assert.Equal(1_000_000_000L, storedEntry.Position); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheTargetPositionIsNegative_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: -1); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistMoveTargetPositionIsInvalid"); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheTargetPositionIsMissing_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(includeTargetPosition: false); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistMoveTargetPositionIsInvalid"); + } + + [Fact] + public async Task MovePlaylistEntry_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/{Guid.NewGuid()}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task MovePlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheOrder() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{otherPlaylistId}/entries/{otherEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntryEntity storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == otherEntryId); + Assert.Equal(1_000_000_000L, storedEntry.Position); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheEntryBelongsToAnotherPlaylist_ShouldReturnNotFoundAndKeepTheOrder() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Another playlist", entryCount: 1); + Guid otherPlaylistEntryId = await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/{otherPlaylistEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], orderedEntryIds); + PlaylistEntryEntity storedEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == otherPlaylistEntryId); + Assert.Equal(0, storedEntry.Position); + Assert.Equal(otherPlaylistId, storedEntry.PlaylistId); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheEntryBelongsToAnotherUsersPlaylist_ShouldReturnNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, _, _) = await SeedOrderedPlaylistAsync(userId); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/{otherEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntryEntity callerEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == firstEntryId); + Assert.Equal(0, callerEntry.Position); + PlaylistEntryEntity otherEntry = await dbContext.PlaylistEntries.AsNoTracking().FirstAsync(entry => entry.Id == otherEntryId); + Assert.Equal(1_000_000_000L, otherEntry.Position); + Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId)); + } + + [Fact] + public async Task MovePlaylistEntry_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/not-a-guid/entries/{Guid.NewGuid()}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheEntryIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Invalid entry id", entryCount: 0); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/not-a-guid/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistEntryIdCannotBeEmpty"); + } + + /// + /// Seeds a playlist of with three ordered entries and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The Id of the playlist and the Ids of its first, second and third entries. + private async Task<(Guid PlaylistId, Guid FirstEntryId, Guid SecondEntryId, Guid ThirdEntryId)> SeedOrderedPlaylistAsync(Guid userId) + { + Guid playlistId = await SeedPlaylistAsync(userId, "Ordered playlist", entryCount: 3); + Guid firstEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0); + Guid secondEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 1_000_000_000L); + Guid thirdEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 2_000_000_000L); + return (playlistId, firstEntryId, secondEntryId, thirdEntryId); + } + + /// + /// Reads the entry Ids of the playlist identified by , in stored order. + /// + /// The database context to read from. + /// The Id of the playlist whose entries are read. + /// The entry Ids in stored order. + private static async Task> GetOrderedEntryIdsAsync(LuminaDbContext dbContext, Guid playlistId) + { + return await dbContext.PlaylistEntries + .AsNoTracking() + .Where(candidate => candidate.PlaylistId == playlistId) + .OrderBy(candidate => candidate.Position) + .Select(candidate => candidate.Id) + .ToListAsync(); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The Id of the referenced track. + /// The sparse order key of the entry. + /// The Id of the seeded entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid entryId = Guid.NewGuid(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + id: entryId, + playlistId: playlistId, + mediaItemId: mediaItemId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + return entryId; + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..4e08de6b --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs @@ -0,0 +1,438 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RemovePlaylistEntryEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryExists_ShouldRemoveOnlyThatEntryAndReturnTheResult() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistEntryRemovedResponse? removedEntry = await DeserializeAsync(response); + Assert.NotNull(removedEntry); + Assert.Equal(playlistId, removedEntry!.PlaylistId); + Assert.Equal(secondEntryId, removedEntry.RemovedEntryId); + Assert.Equal(0, removedEntry.RepositionedCount); + Assert.NotEqual(default, removedEntry.UpdatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == secondEntryId)); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal([firstEntryId, thirdEntryId], orderedEntryIds); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(2, playlist.EntryCount); + Assert.Equal(1, playlist.Version); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryIsTheLastOne_ShouldLeaveThePlaylistEmpty() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "One entry", entryCount: 1); + Guid entryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0); + string url = $"{PATH}/{playlistId}/entries/{entryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId)); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(0, playlist.EntryCount); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenCalledTwice_ShouldRemoveOnceAndReportTheSecondCallAsNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}"; + + // Act + HttpResponseMessage firstResponse = await _client.DeleteAsync(url); + HttpResponseMessage secondResponse = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode); + await AssertProblemAsync(secondResponse, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity playlist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(2, playlist.EntryCount); + Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == firstEntryId)); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheEntry() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId); + string url = $"{PATH}/{otherPlaylistId}/entries/{otherEntryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherEntryId)); + PlaylistEntity otherPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == otherPlaylistId); + Assert.Equal(3, otherPlaylist.EntryCount); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryBelongsToAnotherPlaylist_ShouldReturnNotFoundAndKeepIt() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Another playlist", entryCount: 1); + Guid otherPlaylistEntryId = await SeedPlaylistEntryAsync(otherPlaylistId, Guid.NewGuid(), 0); + string url = $"{PATH}/{playlistId}/entries/{otherPlaylistEntryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherPlaylistEntryId)); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], orderedEntryIds); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryBelongsToAnotherUsersPlaylist_ShouldReturnNotFound() + { + // Arrange + Guid userId = GetCurrentUserId(); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + Guid otherUserId = await SeedOtherUserAsync(); + (Guid otherPlaylistId, _, Guid otherEntryId, _) = await SeedOrderedPlaylistAsync(otherUserId); + string url = $"{PATH}/{playlistId}/entries/{otherEntryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistEntryNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherEntryId)); + List orderedEntryIds = await GetOrderedEntryIdsAsync(dbContext, playlistId); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], orderedEntryIds); + Assert.True(await dbContext.Playlists.AnyAsync(playlist => playlist.Id == otherPlaylistId)); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + string url = $"{PATH}/{playlistId}/entries/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + string url = $"{PATH}/not-a-guid/entries/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Invalid entry id", entryCount: 0); + string url = $"{PATH}/{playlistId}/entries/not-a-guid"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistEntryIdCannotBeEmpty"); + } + + /// + /// Seeds a playlist of with three ordered entries and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The Id of the playlist and the Ids of its first, second and third entries. + private async Task<(Guid PlaylistId, Guid FirstEntryId, Guid SecondEntryId, Guid ThirdEntryId)> SeedOrderedPlaylistAsync(Guid userId) + { + Guid playlistId = await SeedPlaylistAsync(userId, "Ordered playlist", entryCount: 3); + Guid firstEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 0); + Guid secondEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 1_000_000_000L); + Guid thirdEntryId = await SeedPlaylistEntryAsync(playlistId, Guid.NewGuid(), 2_000_000_000L); + return (playlistId, firstEntryId, secondEntryId, thirdEntryId); + } + + /// + /// Reads the entry Ids of the playlist identified by , in stored order. + /// + /// The database context to read from. + /// The Id of the playlist whose entries are read. + /// The entry Ids in stored order. + private static async Task> GetOrderedEntryIdsAsync(LuminaDbContext dbContext, Guid playlistId) + { + return await dbContext.PlaylistEntries + .AsNoTracking() + .Where(candidate => candidate.PlaylistId == playlistId) + .OrderBy(candidate => candidate.Position) + .Select(candidate => candidate.Id) + .ToListAsync(); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The Id of the referenced track. + /// The sparse order key of the entry. + /// The Id of the seeded entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid entryId = Guid.NewGuid(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + id: entryId, + playlistId: playlistId, + mediaItemId: mediaItemId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + return entryId; + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs new file mode 100644 index 00000000..16948cf6 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs @@ -0,0 +1,420 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +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.Playlists.UpdatePlaylist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointTests : IClassFixture, IAsyncLifetime +{ + private const string PATH = "/api/v1/users/me/playlists"; + + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + private readonly List _seededUserIds = []; + private readonly List _seededPlaylistIds = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdatePlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheRequestIsValid_ShouldUpdateTheDetailsAndReturnThem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Old name", "Old description"); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "New name", description: "New description"); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("no-store", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + PlaylistDetailsResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + Assert.Equal(playlistId, playlist!.Id); + Assert.Equal("New name", playlist.Name); + Assert.Equal("New description", playlist.Description); + Assert.Equal(PlaylistType.Music, playlist.Type); + Assert.NotNull(playlist.UpdatedOnUtc); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal("New name", storedPlaylist.Name); + Assert.Equal("New description", storedPlaylist.Description); + Assert.Equal(userId, storedPlaylist.UpdatedBy); + Assert.NotNull(storedPlaylist.UpdatedOnUtc); + Assert.Equal(1, storedPlaylist.Version); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheDescriptionIsOmitted_ShouldClearTheStoredDescription() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Named playlist", "Description to clear"); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Named playlist", includeDescription: false); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistDetailsResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + Assert.Null(playlist!.Description); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Null(storedPlaylist.Description); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheNameHasTheMaximumLength_ShouldUpdateTheDetails() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Short name", null); + string maximumLengthName = new('a', 255); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: maximumLengthName); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + PlaylistDetailsResponse? playlist = await DeserializeAsync(response); + Assert.NotNull(playlist); + Assert.Equal(maximumLengthName, playlist!.Name); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheNameIsMissing_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(includeName: false); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistNameCannotBeEmpty"); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal("Old name", storedPlaylist.Name); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheNameIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: string.Empty); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistNameCannotBeEmpty"); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheNameIsTooLong_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: new string('a', 256)); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistNameMustBeMaximum255CharactersLong"); + } + + [Fact] + public async Task UpdatePlaylist_WhenTheDescriptionIsTooLong_ShouldReturnValidationProblem() + { + // Arrange + Guid userId = GetCurrentUserId(); + Guid playlistId = await SeedPlaylistAsync(userId, "Old name", null); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(description: new string('a', 2001)); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistDescriptionMustBeMaximum2000CharactersLong"); + } + + [Fact] + public async Task UpdatePlaylist_WhenThePlaylistDoesNotExist_ShouldReturnNotFound() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + } + + [Fact] + public async Task UpdatePlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnNotFoundAndKeepTheData() + { + // Arrange + Guid otherUserId = await SeedOtherUserAsync(); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Someone else's playlist", "Private"); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Hijacked", description: "Hijacked"); + string url = $"{PATH}/{otherPlaylistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertProblemAsync(response, HttpStatusCode.NotFound, "General.NotFound", "PlaylistNotFound", url); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == otherPlaylistId); + Assert.Equal("Someone else's playlist", storedPlaylist.Name); + Assert.Equal("Private", storedPlaylist.Description); + Assert.Equal(otherUserId, storedPlaylist.UserId); + } + + [Fact] + public async Task UpdatePlaylist_WhenThePlaylistIdIsNotAGuid_ShouldReturnValidationProblem() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + string url = $"{PATH}/not-a-guid"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + [Fact] + public async Task UpdatePlaylist_WhenThePlaylistIdIsEmpty_ShouldReturnValidationProblem() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + string url = $"{PATH}/{Guid.Empty}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "PlaylistIdCannotBeEmpty"); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The description of the playlist, or . + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, string? description) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + description: description ?? string.Empty, + includeDescription: description is not null, + type: PlaylistType.Music, + entryCount: 0, + version: 0, + createdBy: userId, + includeUpdatedOnUtc: true, + updatedOnUtc: DateTime.UtcNow.AddHours(-1), + updatedBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds a user distinct from the authenticated test user and tracks it for cleanup. + /// + /// The Id of the seeded user. + private async Task SeedOtherUserAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid userId = Guid.NewGuid(); + dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!")); + await dbContext.SaveChangesAsync(); + _seededUserIds.Add(userId); + return userId; + } + + /// + /// 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(candidate => candidate.Username == _apiFactory.TestUsername); + return user.Id; + } + + /// + /// Deserializes the body of to . + /// + /// The type to deserialize the body to. + /// The HTTP response to read. + /// The deserialized body. + private async Task DeserializeAsync(HttpResponseMessage response) + { + string content = await response.Content.ReadAsStringAsync(); + return JsonSerializer.Deserialize(content, _jsonOptions); + } + + /// + /// Asserts that the response is a problem details document with the expected status, title and detail. + /// + /// The HTTP response to assert on. + /// The expected HTTP status. + /// The expected problem title. + /// The expected problem detail. + /// The expected request instance path. + private static async Task AssertProblemAsync(HttpResponseMessage response, HttpStatusCode expectedStatus, string expectedTitle, string expectedDetail, string expectedInstance) + { + Assert.Equal(expectedStatus, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal((int)expectedStatus, problemDetails!["status"].GetInt32()); + Assert.Equal(expectedTitle, problemDetails["title"].GetString()); + Assert.Equal(expectedDetail, problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// Asserts that the response is a validation problem details document carrying the expected error code. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + /// The expected validation error code. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(422, problemDetails!["status"].GetInt32()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + } + + /// + /// 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(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Users.RemoveRange(dbContext.Users.Where(user => _seededUserIds.Contains(user.Id))); + await dbContext.SaveChangesAsync(); + } + await _apiFactory.RemoveTestUserAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs new file mode 100644 index 00000000..4ed2e1ec --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs @@ -0,0 +1,176 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; +using Lumina.Presentation.Api.IntegrationTests.Common.Setup; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPlaybackStateEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task GetPlaybackState_WhenNoSettingsAreStored_ShouldReturnTheDefaultPlaybackState() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + Assert.NotNull(result); + Assert.Equal(1.0, result!.Volume); + Assert.False(result.IsMuted); + } + + [Fact] + public async Task GetPlaybackState_WhenSettingsAreStored_ShouldReturnTheStoredPlaybackState() + { + // Arrange + await CreateTestUserSettings(volume: 0.42, isMuted: true); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + string content = await response.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + Assert.NotNull(result); + Assert.Equal(0.42, result!.Volume); + Assert.True(result.IsMuted); + } + + [Fact] + public async Task GetPlaybackState_WhenSettingsBelongToAnotherUser_ShouldReturnTheDefaultPlaybackState() + { + // Arrange + await CreateSettingsForAnotherUserAsync(volume: 0.1, isMuted: true); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + + Assert.NotNull(result); + Assert.Equal(1.0, result!.Volume); + Assert.False(result.IsMuted); + } + + [Fact] + public async Task GetPlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + + // Act + HttpResponseMessage response = await unauthenticatedClient.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Stores the playback state of the currently authenticated test user. + /// + /// The volume to store. + /// The mute state to store. + /// The stored settings. + private async Task CreateTestUserSettings(double volume, bool isMuted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; + UserSettingsEntity settings = _userSettingsEntityFixture.Create(userId: userId, volume: volume, isMuted: isMuted); + + dbContext.UserSettings.Add(settings); + await dbContext.SaveChangesAsync(); + return settings; + } + + /// + /// Seeds another user and stores that user's playback state, keeping it out of the current user's scope. + /// + /// The volume to store. + /// The mute state to store. + /// A task representing the asynchronous operation. + private async Task CreateSettingsForAnotherUserAsync(double volume, bool isMuted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + UserEntity otherUser = _userEntityFixture.Create(username: $"otheruser_{Guid.NewGuid()}", password: "TestPass123!"); + otherUser.TotpSecret = null; + dbContext.Users.Add(otherUser); + dbContext.UserSettings.Add(_userSettingsEntityFixture.Create(userId: otherUser.Id, volume: volume, isMuted: isMuted)); + await dbContext.SaveChangesAsync(); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs new file mode 100644 index 00000000..35fd307a --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -0,0 +1,294 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; +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; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.IntegrationTests.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointTests : IClassFixture, IAsyncLifetime +{ + private HttpClient _client; + private readonly AuthenticatedLuminaApiFactory _apiFactory; + private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdatePlaybackStateEndpointTests(AuthenticatedLuminaApiFactory apiFactory) + { + _client = apiFactory.CreateClient(); + _apiFactory = apiFactory; + } + + /// + /// Initializes the authenticated API client. + /// + public async Task InitializeAsync() + { + _client = await _apiFactory.CreateAuthenticatedClientAsync(); + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledWithValidRequest_ShouldStoreTheReportedStateWithTheDefaultHandEditedSettings() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + + UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync(); + Assert.NotNull(storedSettings); + Assert.Equal(0.35, storedSettings!.Volume); + Assert.True(storedSettings.IsMuted); + Assert.True(storedSettings.IsPaginationEnabled); + Assert.Equal(48, storedSettings.ItemsPerPage); + } + + [Fact] + public async Task UpdatePlaybackState_WhenSettingsAlreadyExist_ShouldPreserveTheHandEditedSettings() + { + // Arrange + await CreateTestUserSettingsAsync(volume: 1.0, isMuted: false, itemsPerPage: 24, isPaginationEnabled: false); + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + response.EnsureSuccessStatusCode(); + + UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync(); + Assert.NotNull(storedSettings); + Assert.Equal(0.25, storedSettings!.Volume); + Assert.True(storedSettings.IsMuted); + Assert.False(storedSettings.IsPaginationEnabled); + Assert.Equal(24, storedSettings.ItemsPerPage); + } + + [Fact] + public async Task UpdatePlaybackState_WhenUpdatedThenRead_ShouldReturnTheReportedState() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.6, isMuted: true); + + // Act + HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + HttpResponseMessage getResponse = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + updateResponse.EnsureSuccessStatusCode(); + getResponse.EnsureSuccessStatusCode(); + string content = await getResponse.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(result); + Assert.Equal(0.6, result!.Volume); + Assert.True(result.IsMuted); + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledByOneUser_ShouldNotChangeThePlaybackStateOfAnotherUser() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true); + HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + HttpClient otherClient = await _apiFactory.CreateAuthenticatedClientAsync(); + + // Act + HttpResponseMessage getResponse = await otherClient.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + updateResponse.EnsureSuccessStatusCode(); + getResponse.EnsureSuccessStatusCode(); + string content = await getResponse.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(result); + Assert.Equal(1.0, result!.Volume); + Assert.False(result.IsMuted); + } + + [Fact] + public async Task UpdatePlaybackState_WhenVolumeIsNull_ShouldReturnValidationError() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeVolume: false); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + await AssertValidationErrorAsync(response, "VolumeCannotBeNull"); + } + + [Theory] + [InlineData(-0.01)] // just below the minimum + [InlineData(1.01)] // just above the maximum + public async Task UpdatePlaybackState_WhenVolumeIsOutOfRange_ShouldReturnValidationError(double volume) + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: volume); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + await AssertValidationErrorAsync(response, "VolumeMustBeBetweenZeroAndOne"); + } + + [Fact] + public async Task UpdatePlaybackState_WhenIsMutedIsNull_ShouldReturnValidationError() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeIsMuted: false); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + await AssertValidationErrorAsync(response, "IsMutedCannotBeNull"); + } + + [Fact] + public async Task UpdatePlaybackState_WhenPayloadHasUnknownFields_ShouldIgnoreThemAndStoreTheReportedState() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.15, isMuted: false); + JsonObject payload = JsonSerializer.SerializeToNode(request, new JsonSerializerOptions(JsonSerializerDefaults.Web))!.AsObject(); + payload["unknownField"] = "ignored"; + StringContent requestContent = new(payload.ToJsonString(), Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await _client.PutAsync("/api/v1/users/me/settings/playback-state", requestContent); + + // Assert + response.EnsureSuccessStatusCode(); + UserSettingsEntity? storedSettings = await GetCurrentUserSettingsAsync(); + Assert.NotNull(storedSettings); + Assert.Equal(0.15, storedSettings!.Volume); + Assert.False(storedSettings.IsMuted); + } + + [Fact] + public async Task UpdatePlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + HttpClient unauthenticatedClient = _apiFactory.CreateClient(); + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true); + + // Act + HttpResponseMessage response = await unauthenticatedClient.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + } + + /// + /// Asserts that is a validation problem response carrying the specified error. + /// + /// The response to assert. + /// The exact error description expected in the validation errors. + /// A task representing the asynchronous operation. + private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("/api/v1/users/me/settings/playback-state", problemDetails["instance"].GetString()); + + Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions); + Assert.NotNull(errors); + Assert.Contains("General.Validation", errors.Keys); + Assert.Contains(expectedError, errors["General.Validation"]); + } + + /// + /// Stores a playback state for the currently authenticated test user. + /// + /// The volume to store. + /// The mute state to store. + /// The number of items displayed per page to store. + /// Whether pagination is enabled. + /// The stored settings. + private async Task CreateTestUserSettingsAsync(double volume, bool isMuted, int itemsPerPage, bool isPaginationEnabled) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; + UserSettingsEntity settings = _userSettingsEntityFixture.Create( + userId: userId, + volume: volume, + isMuted: isMuted, + itemsPerPage: itemsPerPage, + isPaginationEnabled: isPaginationEnabled); + + dbContext.UserSettings.Add(settings); + await dbContext.SaveChangesAsync(); + return settings; + } + + /// + /// Reads the stored playback state of the currently authenticated test user. + /// + /// The stored settings, or when the user has none. + private async Task GetCurrentUserSettingsAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id; + return await dbContext.UserSettings.FirstOrDefaultAsync(settings => settings.UserId == userId); + } + + /// + /// Disposes API factory resources. + /// + public async Task DisposeAsync() + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.Set().ExecuteDeleteAsync(); + await dbContext.SaveChangesAsync(); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs new file mode 100644 index 00000000..c4f6c1b7 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; +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.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StreamMusicTrackEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StreamMusicTrack_WhenRequestIsValid_ShouldProxyTheApiStream() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId); + byte[] contentBytes = CreateBytes(2048); + _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(HttpStatusCode.OK, contentBytes, "audio/mpeg")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId)); + byte[] responseBytes = await response.Content.ReadAsByteArrayAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType); + Assert.Equal(contentBytes.Length, response.Content.Headers.ContentLength); + Assert.Equal(contentBytes, responseBytes); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString()); + Assert.Contains("Cookie", response.Headers.Vary); + Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled); + Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]); + } + + [Fact] + public async Task StreamMusicTrack_WhenConditionalHeadersArePresent_ShouldForwardThemToTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId); + _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(HttpStatusCode.PartialContent, CreateBytes(100), "audio/mpeg")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId)); + request.Headers.Range = new RangeHeaderValue(100, 199); + request.Headers.IfRange = new RangeConditionHeaderValue(new EntityTagHeaderValue("\"etag-value\"")); + request.Headers.IfNoneMatch.Add(new EntityTagHeaderValue("\"etag-value\"")); + request.Headers.IfModifiedSince = new DateTimeOffset(2015, 10, 21, 7, 28, 0, TimeSpan.Zero); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.PartialContent, response.StatusCode); + Assert.Single(_apiFactory.StreamingApiClientStub.StreamRequests); + IReadOnlyDictionary forwardedHeaders = _apiFactory.StreamingApiClientStub.StreamRequests[0].Headers; + Assert.Equal("bytes=100-199", forwardedHeaders["Range"]); + Assert.Equal("\"etag-value\"", forwardedHeaders["If-Range"]); + Assert.Equal("\"etag-value\"", forwardedHeaders["If-None-Match"]); + Assert.Equal("Wed, 21 Oct 2015 07:28:00 GMT", forwardedHeaders["If-Modified-Since"]); + } + + [Theory] + [InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition + [InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached + public async Task StreamMusicTrack_WhenApiReportsATransientCondition_ShouldReturnABareStatus(HttpStatusCode statusCode) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId); + _apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException( + new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode }, + statusCode, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId)); + // A media caller asks for audio, which is what makes the failure a bare status rather than a JSON or page response. + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("audio/mpeg")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(statusCode, response.StatusCode); + Assert.Equal(string.Empty, content); + } + + [Theory] + [InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition + [InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached + public async Task StreamMusicTrack_WhenApiReportsATransientConditionForANonMediaCaller_ShouldStillReturnABareStatus(HttpStatusCode statusCode) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + string expectedEndpoint = BuildExpectedEndpoint(libraryId, artistId, albumId, trackId); + _apiFactory.StreamingApiClientStub.RegisterStreamException(expectedEndpoint, new ApiException( + new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode }, + statusCode, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + // No Accept and no Range header: a caller that is not asking for media must still receive the bare transient status, not a + // JSON body with status 200 that the navigation error middleware would otherwise produce. + using HttpRequestMessage request = new(HttpMethod.Get, BuildBrowserPath(libraryId, artistId, albumId, trackId)); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(statusCode, response.StatusCode); + Assert.Equal(string.Empty, content); + } + + [Fact] + public async Task StreamMusicTrack_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid())); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled); + } + + /// + /// Builds the browser facing route of the direct stream of a track. + /// + /// The Id of the media library the track belongs to. + /// The Id of the artist the album belongs to. + /// The Id of the album the track belongs to. + /// The Id of the track. + /// The browser facing route of the requested stream. + private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}"; + } + + /// + /// Builds the upstream endpoint the stream request is expected to be sent to. + /// + /// The Id of the media library the track belongs to. + /// The Id of the artist the album belongs to. + /// The Id of the album the track belongs to. + /// The Id of the track. + /// The expected upstream endpoint. + private static string BuildExpectedEndpoint(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + return ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", artistId.ToString()) + .Replace("{albumId}", albumId.ToString()) + .Replace("{trackId}", trackId.ToString()); + } + + /// + /// Creates a streamed API response with a status code, a body and a media type. + /// + /// The status code of the response. + /// The bytes of the content of the response. + /// The media type of the content. + /// The created streamed response. + private static async Task CreateStreamResultAsync(HttpStatusCode statusCode, byte[] contentBytes, string contentType) + { + HttpResponseMessage response = new(statusCode) + { + Content = new ByteArrayContent(contentBytes) + }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); + response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(60) }; + return await ApiStreamResult.CreateAsync(response, CancellationToken.None); + } + + /// + /// Creates a deterministic byte array that stands in for the content of a stream. + /// + /// The number of bytes to create. + /// The created bytes. + private static byte[] CreateBytes(int length) + { + return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))]; + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs new file mode 100644 index 00000000..f9a295fa --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs @@ -0,0 +1,211 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +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.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddPlaylistEntriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddPlaylistEntries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheEntriesAndReturnTheAddedCount() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + List trackIds = [Guid.NewGuid(), Guid.NewGuid()]; + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: trackIds); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch"; + PlaylistEntriesAddedDto expectedResult = _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId, addedCount: 2); + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, expectedResult); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid()); + Assert.Equal(expectedResult.AddedCount, data.GetProperty("addedCount").GetInt32()); + Assert.Equal(expectedResult.UpdatedOnUtc, data.GetProperty("updatedOnUtc").GetDateTime()); + List<(string Endpoint, object? Data)> addRequests = GetAddRequests(); + (string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests); + Assert.Equal(expectedEndpoint, addRequestCall.Endpoint); + AddPlaylistEntriesRequest forwardedPayload = Assert.IsType(addRequestCall.Data); + Assert.Equal(trackIds, forwardedPayload.TrackIds); + } + + [Fact] + public async Task AddPlaylistEntries_WhenApiRejectsTheEntries_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch"; + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "PlaylistEntryCannotBeNull"), + HttpStatusCode.UnprocessableEntity, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistEntries_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch"; + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public async Task AddPlaylistEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistEntries_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-batch"; + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest("not-a-guid", request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)); + Assert.DoesNotContain("not-a-guid", string.Join(",", GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)), StringComparison.Ordinal); + } + + /// + /// Gets the add entries requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream add entries requests that were sent. + private List<(string Endpoint, object? Data)> GetAddRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && postRequest.Endpoint.EndsWith("/entries-batch", StringComparison.Ordinal))]; + } + + /// + /// Builds the add entries request for the specified playlist route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured add entries request. + private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntriesRequest request, string? antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-add-entries") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..68587414 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs @@ -0,0 +1,221 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +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.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private readonly LuminaWebFactory _apiFactory; + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new(); + private readonly PlaylistEntryAddedDtoFixture _playlistEntryAddedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddPlaylistEntryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddPlaylistEntry_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheTrackAndReturnTheAddedEntry() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + PlaylistEntryDto expectedEntry = _playlistEntryDtoFixture.Create( + mediaItemId: trackId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: 3, + mediaItemTitle: "Added track"); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries"; + PlaylistEntryAddedDto expectedResult = _playlistEntryAddedDtoFixture.Create(playlistId: playlistId, entry: expectedEntry); + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, expectedResult); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid()); + JsonElement entry = data.GetProperty("entry"); + Assert.Equal(expectedEntry.Id, entry.GetProperty("id").GetGuid()); + Assert.Equal(expectedEntry.MediaItemId, entry.GetProperty("mediaItemId").GetGuid()); + Assert.Equal(nameof(PlaylistMediaItemType.MusicTrack), entry.GetProperty("mediaItemType").GetString()); + Assert.Equal(expectedEntry.Position, entry.GetProperty("position").GetInt32()); + Assert.Equal(expectedEntry.MediaItemTitle, entry.GetProperty("mediaItemTitle").GetString()); + List<(string Endpoint, object? Data)> addRequests = GetAddRequests(); + (string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests); + Assert.Equal(expectedEndpoint, addRequestCall.Endpoint); + AddPlaylistEntryRequest forwardedPayload = Assert.IsType(addRequestCall.Data); + Assert.Equal(trackId, forwardedPayload.TrackId); + } + + [Fact] + public async Task AddPlaylistEntry_WhenApiRejectsTheTrack_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries"; + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "MusicTrackNotFound"), + HttpStatusCode.UnprocessableEntity, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistEntry_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries"; + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public async Task AddPlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistEntry_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries"; + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntryAddedDtoFixture.Create(playlistId: playlistId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString().ToUpperInvariant(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)); + Assert.DoesNotContain(playlistId.ToString().ToUpperInvariant(), string.Join(",", GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)), StringComparison.Ordinal); + } + + /// + /// Gets the add entry requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream add entry requests that were sent. + private List<(string Endpoint, object? Data)> GetAddRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && postRequest.Endpoint.EndsWith("/entries", StringComparison.Ordinal))]; + } + + /// + /// Builds the add entry request for the specified playlist route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured add entry request. + private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntryRequest request, string? antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/entries/api-add-entry") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs new file mode 100644 index 00000000..e16a693c --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs @@ -0,0 +1,245 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +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.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddPlaylistScopeEntriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheScopeAndReturnTheAddedCount() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + artistId: artistId, + albumId: albumId); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope"; + PlaylistEntriesAddedDto expectedResult = _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId, addedCount: 12); + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, expectedResult); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid()); + Assert.Equal(expectedResult.AddedCount, data.GetProperty("addedCount").GetInt32()); + List<(string Endpoint, object? Data)> addRequests = GetAddRequests(); + (string Endpoint, object? Data) addRequestCall = Assert.Single(addRequests); + Assert.Equal(expectedEndpoint, addRequestCall.Endpoint); + AddPlaylistScopeEntriesRequest forwardedPayload = Assert.IsType(addRequestCall.Data); + Assert.Equal(libraryId, forwardedPayload.LibraryId); + Assert.Equal(artistId, forwardedPayload.ArtistId); + Assert.Equal(albumId, forwardedPayload.AlbumId); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenScopeIsLimitedToTheLibrary_ShouldForwardTheOptionalIdsAsNull() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + includeArtistId: false, + includeAlbumId: false); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope"; + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + (string Endpoint, object? Data) addRequestCall = Assert.Single(GetAddRequests()); + AddPlaylistScopeEntriesRequest forwardedPayload = Assert.IsType(addRequestCall.Data); + Assert.Equal(libraryId, forwardedPayload.LibraryId); + Assert.Null(forwardedPayload.ArtistId); + Assert.Null(forwardedPayload.AlbumId); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenApiRejectsTheScope_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope"; + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "MusicLibraryNotFound"), + HttpStatusCode.UnprocessableEntity, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope"; + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-scope"; + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage addRequest = CreateAddRequest("not-a-guid", request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)); + Assert.DoesNotContain("not-a-guid", string.Join(",", GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint)), StringComparison.Ordinal); + } + + /// + /// Gets the add scope entries requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream add scope entries requests that were sent. + private List<(string Endpoint, object? Data)> GetAddRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && postRequest.Endpoint.EndsWith("/entries-scope", StringComparison.Ordinal))]; + } + + /// + /// Builds the add scope entries request for the specified playlist route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured add scope entries request. + private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistScopeEntriesRequest request, string? antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-add-scope-entries") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs new file mode 100644 index 00000000..a3ae9df4 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs @@ -0,0 +1,193 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +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.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string UPSTREAM_ENDPOINT = "users/me/playlists"; + + private readonly LuminaWebFactory _apiFactory; + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + private readonly PlaylistDtoFixture _playlistDtoFixture = new(); + private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new(); + private readonly PaginatedDtoFixture _paginatedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CreatePlaylistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task CreatePlaylist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDetailsAndReturnThePlaylist() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create( + name: "Road trip", + description: "Songs for the highway.", + type: PlaylistType.Music); + PlaylistDto expectedPlaylist = _playlistDtoFixture.Create( + name: request.Name!, + description: request.Description, + type: PlaylistType.Music, + entries: _paginatedDtoFixture.Create(data: _playlistEntryDtoFixture.CreateMany(1))); + _apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, expectedPlaylist); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = CreateCreateRequest(request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(expectedPlaylist.Id, data.GetProperty("id").GetGuid()); + Assert.Equal(expectedPlaylist.Name, data.GetProperty("name").GetString()); + Assert.Equal(expectedPlaylist.Description, data.GetProperty("description").GetString()); + Assert.Equal(nameof(PlaylistType.Music), data.GetProperty("type").GetString()); + List<(string Endpoint, object? Data)> createRequests = GetCreateRequests(); + (string Endpoint, object? Data) createRequestCall = Assert.Single(createRequests); + Assert.Equal(UPSTREAM_ENDPOINT, createRequestCall.Endpoint); + CreatePlaylistRequest forwardedPayload = Assert.IsType(createRequestCall.Data); + Assert.Equal(request.Name, forwardedPayload.Name); + Assert.Equal(request.Description, forwardedPayload.Description); + Assert.Equal(PlaylistType.Music, forwardedPayload.Type); + } + + [Fact] + public async Task CreatePlaylist_WhenNoDescriptionIsProvided_ShouldForwardTheNullDescription() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "No description", includeDescription: false); + _apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, _playlistDtoFixture.Create(includeDescription: false)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = CreateCreateRequest(request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + response.EnsureSuccessStatusCode(); + (string Endpoint, object? Data) createRequestCall = Assert.Single(GetCreateRequests()); + CreatePlaylistRequest forwardedPayload = Assert.IsType(createRequestCall.Data); + Assert.Null(forwardedPayload.Description); + } + + [Fact] + public async Task CreatePlaylist_WhenApiRejectsTheDetails_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeName: false); + _apiFactory.ApiClientStub.RegisterPostException(UPSTREAM_ENDPOINT, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "PlaylistNameCannotBeEmpty"), + HttpStatusCode.UnprocessableEntity, + UPSTREAM_ENDPOINT)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = CreateCreateRequest(request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task CreatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage createRequest = CreateCreateRequest(request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetCreateRequests()); + } + + /// + /// Gets the create playlist requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream create playlist requests that were sent. + private List<(string Endpoint, object? Data)> GetCreateRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)]; + } + + /// + /// Builds the create playlist request that sends the given . + /// + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured create playlist request. + private static HttpRequestMessage CreateCreateRequest(CreatePlaylistRequest request, string? antiforgeryToken) + { + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/playlists/api-create-playlist") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return createRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs new file mode 100644 index 00000000..316f8295 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs @@ -0,0 +1,182 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; +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.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeletePlaylistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task DeletePlaylist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDeleteAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.Equal([expectedEndpoint], GetDeleteEndpointCalls()); + } + + [Fact] + public async Task DeletePlaylist_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public async Task DeletePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetDeleteEndpointCalls()); + } + + [Fact] + public async Task DeletePlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest("not-a-guid", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetDeleteEndpointCalls()); + Assert.DoesNotContain("not-a-guid", string.Join(",", GetDeleteEndpointCalls()), StringComparison.Ordinal); + } + + [Fact] + public async Task DeletePlaylist_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage deleteRequest = CreateDeleteRequest(playlistId.ToString().ToUpperInvariant(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List deleteEndpoints = GetDeleteEndpointCalls(); + Assert.Equal([expectedEndpoint], deleteEndpoints); + Assert.DoesNotContain(playlistId.ToString().ToUpperInvariant(), string.Join(",", deleteEndpoints), StringComparison.Ordinal); + } + + /// + /// Gets the delete playlist endpoints that were called upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream delete playlist endpoints that were called. + private List GetDeleteEndpointCalls() + { + return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled + .Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))]; + } + + /// + /// Builds the delete playlist request for the specified route value. + /// + /// The value of the playlist identifier route segment. + /// The antiforgery token to include in the request, or to omit it. + /// The configured delete playlist request. + private static HttpRequestMessage CreateDeleteRequest(string playlistId, string? antiforgeryToken) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-delete-playlist") + { + // The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return deleteRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs new file mode 100644 index 00000000..5146bba8 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs @@ -0,0 +1,169 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +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.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointTests : IClassFixture, IDisposable +{ + private const string UPSTREAM_ENDPOINT = "users/me/playlists"; + + private readonly LuminaWebFactory _apiFactory; + private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPlaylistsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPlaylists_WhenCalledByAuthenticatedUser_ShouldReturnThePlaylistsWithNonStorableCacheHeaders() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + PlaylistSummaryDto firstPlaylist = _playlistSummaryDtoFixture.Create( + name: "Evening listening", + description: "Quiet tracks.", + type: PlaylistType.Music, + entryCount: 7); + PlaylistSummaryDto secondPlaylist = _playlistSummaryDtoFixture.Create( + name: "Morning run", + type: PlaylistType.Music, + entryCount: 0); + _apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, new[] { firstPlaylist, secondPlaylist }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/api-get-playlists"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + List data = [.. json.RootElement.GetProperty("data").EnumerateArray()]; + Assert.Equal(2, data.Count); + Assert.Equal(firstPlaylist.Id, data[0].GetProperty("id").GetGuid()); + Assert.Equal(firstPlaylist.Name, data[0].GetProperty("name").GetString()); + Assert.Equal(firstPlaylist.Description, data[0].GetProperty("description").GetString()); + Assert.Equal(nameof(PlaylistType.Music), data[0].GetProperty("type").GetString()); + Assert.Equal(firstPlaylist.EntryCount, data[0].GetProperty("entryCount").GetInt32()); + Assert.Equal(firstPlaylist.CreatedOnUtc, data[0].GetProperty("createdOnUtc").GetDateTime()); + Assert.Equal(secondPlaylist.Id, data[1].GetProperty("id").GetGuid()); + Assert.Equal([UPSTREAM_ENDPOINT], GetPlaylistEndpointCalls()); + Assert.True(response.Headers.CacheControl?.Private); + Assert.True(response.Headers.CacheControl?.NoStore); + Assert.Contains("Cookie", response.Headers.Vary); + } + + [Fact] + public async Task GetPlaylists_WhenUserHasNoPlaylists_ShouldReturnAnEmptyArray() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, Array.Empty()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/api-get-playlists"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Empty(json.RootElement.GetProperty("data").EnumerateArray()); + } + + [Fact] + public async Task GetPlaylists_WhenApiReportsAnError_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetException(UPSTREAM_ENDPOINT, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Failure", detail: "UnexpectedError"), + HttpStatusCode.InternalServerError, + UPSTREAM_ENDPOINT)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/playlists/api-get-playlists"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task GetPlaylists_WhenApiReportsNotFound_ShouldReturnTheNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetException(UPSTREAM_ENDPOINT, new ApiException(null, HttpStatusCode.NotFound, UPSTREAM_ENDPOINT)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/playlists/api-get-playlists"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + } + + /// + /// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers. + /// + /// The list of upstream playlist endpoints that were called. + private List GetPlaylistEndpointCalls() + { + return [.. _apiFactory.ApiClientStub.GetEndpointsCalled + .Where(endpoint => endpoint == UPSTREAM_ENDPOINT)]; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs new file mode 100644 index 00000000..b4847665 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs @@ -0,0 +1,101 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.Index; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistsIndexViewEndpointTests : IClassFixture, IDisposable +{ + private const string WEB_ROUTE = "/en-us/playlists"; + + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public PlaylistsIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldRenderThePlaylistsPage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType!.MediaType); + Assert.Contains("playlists-container", content, StringComparison.Ordinal); + Assert.Contains("no-playlists", content, StringComparison.Ordinal); + Assert.Contains("create-playlist-button", content, StringComparison.Ordinal); + Assert.Contains("playlist-count", content, StringComparison.Ordinal); + Assert.Contains("__RequestVerificationToken", content, StringComparison.Ordinal); + Assert.Contains("Playlists", content, StringComparison.Ordinal); + Assert.Contains("You have no playlists yet.", content, StringComparison.Ordinal); + } + + [Fact] + public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldRenderThePageDataUrls() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Contains("/playlists/api-get-playlists", content, StringComparison.Ordinal); + Assert.Contains("/playlists/item/00000000-0000-0000-0000-000000000000", content, StringComparison.Ordinal); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/me/playlists", StringComparison.Ordinal)); + } + + [Fact] + public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldReturnANonStorablePage() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.True(response.Headers.CacheControl?.Private); + Assert.True(response.Headers.CacheControl?.NoStore); + Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase); + Assert.Contains("Cookie", response.Headers.Vary); + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..f9bf5816 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs @@ -0,0 +1,215 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +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.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryMovedDtoFixture _playlistEntryMovedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public MovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task MovePlaylistEntry_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardThePositionAndReturnTheMovedEntry() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 2); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + PlaylistEntryMovedDto expectedResult = _playlistEntryMovedDtoFixture.Create( + playlistId: playlistId, + entryId: playlistEntryId, + position: 2); + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResult); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage moveRequest = CreateMoveRequest(playlistId.ToString(), playlistEntryId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(expectedResult.PlaylistId, data.GetProperty("playlistId").GetGuid()); + Assert.Equal(expectedResult.EntryId, data.GetProperty("entryId").GetGuid()); + Assert.Equal(expectedResult.Position, data.GetProperty("position").GetInt32()); + List<(string Endpoint, object? Data)> moveRequests = GetMoveRequests(); + (string Endpoint, object? Data) moveRequestCall = Assert.Single(moveRequests); + Assert.Equal(expectedEndpoint, moveRequestCall.Endpoint); + MovePlaylistEntryRequest forwardedPayload = Assert.IsType(moveRequestCall.Data); + Assert.Equal(2, forwardedPayload.TargetPosition); + } + + [Fact] + public async Task MovePlaylistEntry_WhenApiRejectsThePosition_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + _apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "TargetPositionOutOfRange"), + HttpStatusCode.UnprocessableEntity, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage moveRequest = CreateMoveRequest(playlistId.ToString(), playlistEntryId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheEntryDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + _apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage moveRequest = CreateMoveRequest(playlistId.ToString(), playlistEntryId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + } + + [Fact] + public async Task MovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetMoveRequests()); + } + + [Fact] + public async Task MovePlaylistEntry_WhenRouteIdsAreNotGuids_ShouldForwardTheEmptyGuids() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move"; + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistEntryMovedDtoFixture.Create(playlistId: Guid.Empty, entryId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage moveRequest = CreateMoveRequest("not-a-guid", "also-not-a-guid", request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint)); + Assert.DoesNotContain("not-a-guid", string.Join(",", GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint)), StringComparison.Ordinal); + } + + /// + /// Gets the move entry requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream move entry requests that were sent. + private List<(string Endpoint, object? Data)> GetMoveRequests() + { + return [.. _apiFactory.ApiClientStub.PutRequests + .Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && putRequest.Endpoint.EndsWith("/move", StringComparison.Ordinal))]; + } + + /// + /// Builds the move entry request for the specified route values. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured move entry request. + private static HttpRequestMessage CreateMoveRequest(string playlistId, string playlistEntryId, MovePlaylistEntryRequest request, string? antiforgeryToken) + { + HttpRequestMessage moveRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/entries/{Uri.EscapeDataString(playlistEntryId)}/api-move-entry") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + moveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + moveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + moveRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return moveRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..546b01ad --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs @@ -0,0 +1,188 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; +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.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RemovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task RemovePlaylistEntry_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDeleteAndReturnSuccess() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage removeRequest = CreateRemoveRequest(playlistId.ToString(), playlistEntryId.ToString(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.Equal([expectedEndpoint], GetRemoveEndpointCalls()); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + _apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage removeRequest = CreateRemoveRequest(playlistId.ToString(), playlistEntryId.ToString(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetRemoveEndpointCalls()); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenRouteIdsAreNotGuids_ShouldForwardTheEmptyGuids() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage removeRequest = CreateRemoveRequest("not-a-guid", "also-not-a-guid", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetRemoveEndpointCalls()); + Assert.DoesNotContain("not-a-guid", string.Join(",", GetRemoveEndpointCalls()), StringComparison.Ordinal); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenRouteIdsAreUppercaseGuids_ShouldForwardThemInLowercase() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + Guid playlistEntryId = Guid.Parse("FEDCBAFE-DCBA-FEDC-BAFE-DCBAFEDCBAFE"); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage removeRequest = CreateRemoveRequest( + playlistId.ToString().ToUpperInvariant(), + playlistEntryId.ToString().ToUpperInvariant(), + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List removeEndpoints = GetRemoveEndpointCalls(); + Assert.Equal([expectedEndpoint], removeEndpoints); + Assert.DoesNotContain(playlistEntryId.ToString().ToUpperInvariant(), string.Join(",", removeEndpoints), StringComparison.Ordinal); + } + + /// + /// Gets the remove entry endpoints that were called upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream remove entry endpoints that were called. + private List GetRemoveEndpointCalls() + { + return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled + .Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && endpoint.Contains("/entries/", StringComparison.Ordinal))]; + } + + /// + /// Builds the remove entry request for the specified route values. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + /// The antiforgery token to include in the request, or to omit it. + /// The configured remove entry request. + private static HttpRequestMessage CreateRemoveRequest(string playlistId, string playlistEntryId, string? antiforgeryToken) + { + HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/entries/{Uri.EscapeDataString(playlistEntryId)}/api-remove-entry") + { + // The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return removeRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs new file mode 100644 index 00000000..9cab06f1 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs @@ -0,0 +1,240 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +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.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + private readonly PlaylistDetailsDtoFixture _playlistDetailsDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdatePlaylistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdatePlaylist_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheDetailsAndReturnThePlaylist() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create( + name: "Renamed playlist", + description: "Updated description."); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + PlaylistDetailsDto expectedResult = _playlistDetailsDtoFixture.Create( + id: playlistId, + name: request.Name!, + description: request.Description!, + type: PlaylistType.Music); + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, expectedResult); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(expectedResult.Id, data.GetProperty("id").GetGuid()); + Assert.Equal(expectedResult.Name, data.GetProperty("name").GetString()); + Assert.Equal(expectedResult.Description, data.GetProperty("description").GetString()); + Assert.Equal(nameof(PlaylistType.Music), data.GetProperty("type").GetString()); + Assert.Equal(expectedResult.UpdatedOnUtc, data.GetProperty("updatedOnUtc").GetDateTime()); + List<(string Endpoint, object? Data)> updateRequests = GetUpdateRequests(); + (string Endpoint, object? Data) updateRequestCall = Assert.Single(updateRequests); + Assert.Equal(expectedEndpoint, updateRequestCall.Endpoint); + UpdatePlaylistRequest forwardedPayload = Assert.IsType(updateRequestCall.Data); + Assert.Equal(request.Name, forwardedPayload.Name); + Assert.Equal(request.Description, forwardedPayload.Description); + } + + [Fact] + public async Task UpdatePlaylist_WhenNoDescriptionIsProvided_ShouldForwardTheNullDescription() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Cleared description", includeDescription: false); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: playlistId, includeDescription: false)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + response.EnsureSuccessStatusCode(); + (string Endpoint, object? Data) updateRequestCall = Assert.Single(GetUpdateRequests()); + UpdatePlaylistRequest forwardedPayload = Assert.IsType(updateRequestCall.Data); + Assert.Null(forwardedPayload.Description); + } + + [Fact] + public async Task UpdatePlaylist_WhenApiRejectsTheDetails_ShouldReturnAFailureEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(includeName: false); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Validation", detail: "PlaylistNameCannotBeEmpty"), + HttpStatusCode.UnprocessableEntity, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Contains("", json.RootElement.GetProperty("errorMessage").GetString(), StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task UpdatePlaylist_WhenPlaylistDoesNotExist_ShouldReturnNotFoundEnvelope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException(null, HttpStatusCode.NotFound, expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal("NotFound", json.RootElement.GetProperty("errorMessage").GetString()); + } + + [Fact] + public async Task UpdatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetUpdateRequests()); + } + + [Fact] + public async Task UpdatePlaylist_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + string expectedEndpoint = $"users/me/playlists/{ZERO_GUID}"; + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = CreateUpdateRequest("not-a-guid", request, webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal([expectedEndpoint], GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint)); + Assert.DoesNotContain("not-a-guid", string.Join(",", GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint)), StringComparison.Ordinal); + } + + /// + /// Gets the update playlist requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream update playlist requests that were sent. + private List<(string Endpoint, object? Data)> GetUpdateRequests() + { + return [.. _apiFactory.ApiClientStub.PutRequests + .Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))]; + } + + /// + /// Builds the update playlist request for the specified route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured update playlist request. + private static HttpRequestMessage CreateUpdateRequest(string playlistId, UpdatePlaylistRequest request, string? antiforgeryToken) + { + HttpRequestMessage updateRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{Uri.EscapeDataString(playlistId)}/api-update-playlist") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return updateRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs new file mode 100644 index 00000000..5842127f --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs @@ -0,0 +1,83 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPlaybackStateEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPlaybackState_WhenCalledByAuthenticatedUser_ShouldReturnPlaybackStateFromApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + PlaybackStateDto expectedState = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); + _apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings/playback-state", expectedState); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + 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(0.35, data.GetProperty("volume").GetDouble()); + Assert.True(data.GetProperty("isMuted").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings/playback-state"); + } + + [Fact] + public async Task GetPlaybackState_WhenApiReturnsTheDefaultState_ShouldReturnIt() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + PlaybackStateDto expectedState = _playbackStateDtoFixture.Create(volume: 1.0, isMuted: false); + _apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings/playback-state", expectedState); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + using JsonDocument json = JsonDocument.Parse(content); + JsonElement data = json.RootElement.GetProperty("data"); + Assert.Equal(1.0, data.GetProperty("volume").GetDouble()); + Assert.False(data.GetProperty("isMuted").GetBoolean()); + } +} diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs new file mode 100644 index 00000000..d3338969 --- /dev/null +++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Requests.Common; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.IntegrationTests.Common.Setup; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// Contains integration tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdatePlaybackStateEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledByAuthenticatedUser_ShouldUpdatePlaybackState() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdatePlaybackStateRequest(state, webClient.AntiforgeryToken)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.True(json.RootElement.GetProperty("success").GetBoolean()); + Assert.True(json.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); + Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings/playback-state"); + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledByAuthenticatedUser_ShouldForwardTheStateToApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(CreateUpdatePlaybackStateRequest(state, webClient.AntiforgeryToken)); + + // Assert + response.EnsureSuccessStatusCode(); + (string Endpoint, object? Data) putRequest = Assert.Single( + _apiFactory.ApiClientStub.PutRequests, + request => request.Endpoint == "users/me/settings/playback-state"); + PlaybackStateDto forwardedState = Assert.IsType(putRequest.Data); + Assert.Equal(0.0, forwardedState.Volume); + Assert.False(forwardedState.IsMuted); + } + + /// + /// Builds the update request that sends the given to the update playback state endpoint. + /// + /// The playback state to send. + /// The antiforgery token to include in the request. + /// The configured update request. + private static HttpRequestMessage CreateUpdatePlaybackStateRequest(PlaybackStateDto state, string antiforgeryToken) + { + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state") + { + Content = JsonContent.Create(state) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return updateRequest; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointTests.cs index 168d4030..4e7fe498 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Favorites/RemoveFavorite/RemoveFavoriteEndpointTests.cs @@ -220,7 +220,7 @@ public class RemoveFavoriteEndpointTests : IClassFixture, IDis /// /// The HTTP response to assert on. /// The expected request instance path. - private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs new file mode 100644 index 00000000..d30b9c5e --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs @@ -0,0 +1,380 @@ +#region ========================================================================= USING ===================================================================================== +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.GetTrackStream; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// Contains security tests for the class. +/// +/// +/// The concurrency rate limiter of the stream route is not exercised, because it requires four concurrent long lived streams, which needs a real +/// normalization pipeline and ffmpeg, neither of which is available in the test environment. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointTests : IClassFixture, IDisposable +{ + private const string ACTIVE_CONTENT_BODY = ""; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly string _contentRootPath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-security-tests-{Guid.NewGuid():N}"); + 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 _temporaryFiles = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetTrackStreamEndpointTests(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()); + Directory.CreateDirectory(_contentRootPath); + } + + [Fact] + public async Task GetTrackStream_WhenCalledWithoutCredentials_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid())); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("Unauthorized", problemDetails!["title"].GetString()); + } + + [Theory] + [InlineData("libraryId", "'; DROP TABLE Tracks; --")] // destructive injection in the library Id + [InlineData("libraryId", "' OR '1'='1")] // boolean based injection in the library Id + [InlineData("artistId", "'; DROP TABLE Tracks; --")] // destructive injection in the artist Id + [InlineData("artistId", "'; EXEC xp_cmdshell('dir'); --")] // command execution attempt in the artist Id + [InlineData("albumId", "' OR '1'='1")] // boolean based injection in the album Id + [InlineData("albumId", "'; DROP TABLE Tracks; --")] // destructive injection in the album Id + [InlineData("trackId", "' OR '1'='1")] // boolean based injection in the track Id + [InlineData("trackId", "'; EXEC xp_cmdshell('dir'); --")] // command execution attempt in the track Id + [InlineData("libraryId", "../../etc/passwd")] // path traversal in the library Id + [InlineData("artistId", "../../etc/passwd")] // path traversal in the artist Id + [InlineData("albumId", "../../etc/passwd")] // path traversal in the album Id + [InlineData("trackId", "../../etc/passwd")] // path traversal in the track Id + public async Task GetTrackStream_WithAnInjectionPayloadInARouteValue_ShouldRejectItWithoutLeakingData(string routeValue, string payload) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string path = BuildStreamPathWithPayload(routeValue, payload); + + // Act + HttpResponseMessage response = await _client.GetAsync(path); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("C:\\", content, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task GetTrackStream_WhenLibraryBelongsToAnotherUser_ShouldReturnForbiddenWithoutLeakingTheTrackPath() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + Guid otherUserId = await SeedOtherUserAsync(); + string secretTrackPath = WriteContentFile($"secret-{Guid.NewGuid():N}.flac", [1, 2, 3, 4]); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(otherUserId, secretTrackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode); + Assert.DoesNotContain("secret-", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(secretTrackPath, content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.Unauthorized", problemDetails!["title"].GetString()); + Assert.Equal("NotAuthorized", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetTrackStream_WhenTrackIsRequestedThroughAnotherAlbum_ShouldReturnTrackNotFound() + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string trackPath = WriteContentFile($"track-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4]); + (Guid libraryId, Guid artistId, _, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + Guid otherAlbumId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, otherAlbumId, trackId)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain(trackPath, content, StringComparison.OrdinalIgnoreCase); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenTrackIsRequestedThroughAnotherArtist_ShouldReturnTrackNotFound() + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string trackPath = WriteContentFile($"track-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4]); + (Guid libraryId, _, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + Guid otherArtistId = Guid.NewGuid(); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, otherArtistId, albumId, trackId)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenTrackIsRequestedThroughAnotherLibraryOwnedByTheSameUser_ShouldReturnTrackNotFound() + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string trackPath = WriteContentFile($"track-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4]); + (_, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + Guid otherLibraryId = await SeedEmptyLibraryAsync(userId); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(otherLibraryId, artistId, albumId, trackId)); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("TrackNotFound", problemDetails!.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenAudioFileIsOutsideTheLibraryContentLocations_ShouldReturnTrackFileNotFoundWithoutLeakingThePath() + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string outsideFilePath = Path.Combine(Path.GetTempPath(), $"lumina-track-stream-outside-{Guid.NewGuid():N}.mp3"); + await File.WriteAllBytesAsync(outsideFilePath, [1, 2, 3, 4]); + _temporaryFiles.Add(outsideFilePath); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, outsideFilePath); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId)); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); + Assert.DoesNotContain(outsideFilePath, content, StringComparison.OrdinalIgnoreCase); + Microsoft.AspNetCore.Mvc.ProblemDetails? problemDetails = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(problemDetails); + Assert.Equal("General.NotFound", problemDetails!.Title); + Assert.Equal("TrackFileNotFound", problemDetails.Detail); + } + + [Fact] + public async Task GetTrackStream_WhenTheAudioFileHasAnActiveContentExtension_ShouldServeItAsOpaqueContentWithSniffingDisabled() + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string activeContentPath = WriteContentFile($"active-{Guid.NewGuid():N}.html", System.Text.Encoding.UTF8.GetBytes(ACTIVE_CONTENT_BODY)); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, activeContentPath); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId)); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("application/octet-stream", response.Content.Headers.ContentType?.MediaType); + Assert.NotEqual("text/html", response.Content.Headers.ContentType?.MediaType); + Assert.Contains("nosniff", response.Headers.GetValues("X-Content-Type-Options")); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + Assert.Null(response.Content.Headers.ContentDisposition); + } + + [Fact] + public async Task GetTrackStream_WhenTheTrackBelongsToAnOwnedLibrary_ShouldServeItPrivatelyWithoutADownloadName() + { + // Arrange + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string trackPath = WriteContentFile($"owned-{Guid.NewGuid():N}.mp3", [1, 2, 3, 4, 5, 6, 7, 8]); + (Guid libraryId, Guid artistId, Guid albumId, Guid trackId) = await SeedLibraryArtistAlbumAndTrackAsync(userId, trackPath); + + // Act + HttpResponseMessage response = await _client.GetAsync(BuildStreamPath(libraryId, artistId, albumId, trackId)); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("audio/mpeg", response.Content.Headers.ContentType?.MediaType); + Assert.NotNull(response.Headers.ETag); + Assert.NotNull(response.Content.Headers.LastModified); + Assert.Contains("private", response.Headers.CacheControl?.ToString()); + Assert.DoesNotContain("public", response.Headers.CacheControl?.ToString()); + Assert.Contains("Authorization", response.Headers.Vary); + Assert.Null(response.Content.Headers.ContentDisposition); + Assert.DoesNotContain(trackPath, response.Headers.ETag!.Tag.ToString(), StringComparison.OrdinalIgnoreCase); + } + + /// + /// 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 an empty music library owned by . + /// + /// The Id of the user that owns the library. + /// The Id of the seeded library. + private async Task SeedEmptyLibraryAsync(Guid userId) + { + 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: "Other Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath])); + await dbContext.SaveChangesAsync(); + return libraryId; + } + + /// + /// Seeds a library owned by , an artist of that library, an album of that artist and a track of that album. + /// + /// The Id of the user that owns the library. + /// The file system path of the audio file of the track. + /// The Ids of the seeded library, artist, album and track. + private async Task<(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)> SeedLibraryArtistAlbumAndTrackAsync(Guid userId, string trackPath) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Queen Library", libraryType: LibraryType.Music, contentLocations: [_contentRootPath])); + dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: "Queen")); + dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: "A Night at the Opera")); + dbContext.Tracks.Add(_trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: trackPath, title: "A Track", includeMetadata: false)); + await dbContext.SaveChangesAsync(); + return (libraryId, artistId, albumId, trackId); + } + + /// + /// Writes a file with the provided inside the content root of the test, and returns its full path. + /// + /// The name of the file to write. + /// The bytes of the file to write. + /// The full path of the written file. + private string WriteContentFile(string fileName, byte[] contentBytes) + { + string filePath = Path.Combine(_contentRootPath, fileName); + File.WriteAllBytes(filePath, contentBytes); + return filePath; + } + + /// + /// Builds the route of the direct stream of a track. + /// + /// The Id of the media library the track belongs to. + /// The Id of the artist the album belongs to. + /// The Id of the album the track belongs to. + /// The Id of the track. + /// The route of the requested stream. + private static string BuildStreamPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + } + + /// + /// Builds the route of the direct stream of a track, with a malicious payload in one of its route values. + /// + /// The name of the route value that carries the payload. + /// The malicious payload. + /// The route of the requested stream, with the payload URL-escaped. + private static string BuildStreamPathWithPayload(string routeValue, string payload) + { + string libraryId = routeValue == "libraryId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString(); + string artistId = routeValue == "artistId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString(); + string albumId = routeValue == "albumId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString(); + string trackId = routeValue == "trackId" ? Uri.EscapeDataString(payload) : Guid.NewGuid().ToString(); + return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream"; + } + + /// + /// Disposes the API factory resources, the seeded users and the temporary files of the test. + /// + public void Dispose() + { + _client.Dispose(); + if (Directory.Exists(_contentRootPath)) + Directory.Delete(_contentRootPath, recursive: true); + foreach (string temporaryFile in _temporaryFiles) + if (File.Exists(temporaryFile)) + File.Delete(temporaryFile); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs new file mode 100644 index 00000000..6d956aa8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs @@ -0,0 +1,435 @@ +#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.Playlists; +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.Playlists; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries; +using Lumina.Presentation.Api.SecurityTests.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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddPlaylistEntriesEndpointTests(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 AddPlaylistEntries_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task AddPlaylistEntries_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingData(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [Guid.NewGuid()]); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.True(await PlaylistExistsAsync(playlistId)); + Assert.False(await PlaylistHasEntriesAsync(playlistId)); + } + + [Fact] + public async Task AddPlaylistEntries_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerPlaylistId = await SeedPlaylistAsync(ownerId, "Owner playlist", entryCount: 0); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + Guid callerLibraryId = await SeedLibraryAsync(callerId); + Guid callerTrackId = await SeedTrackAsync(callerLibraryId, "Caller track"); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [callerTrackId]); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.PostAsJsonAsync($"{PATH}/{ownerPlaylistId}/entries-batch", request); + HttpResponseMessage missingResponse = await _client.PostAsJsonAsync($"{PATH}/{missingPlaylistId}/entries-batch", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.False(await PlaylistHasEntriesAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task AddPlaylistEntries_WhenATrackBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingTrack() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerLibraryId = await SeedLibraryAsync(ownerId); + Guid ownerTrackId = await SeedTrackAsync(ownerLibraryId, "Unreachable track"); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + Guid callerPlaylistId = await SeedPlaylistAsync(callerId, "Caller playlist", entryCount: 0); + AddPlaylistEntriesRequest foreignTrackRequest = _addPlaylistEntriesRequestFixture.Create(trackIds: [ownerTrackId]); + AddPlaylistEntriesRequest missingTrackRequest = _addPlaylistEntriesRequestFixture.Create(trackIds: [Guid.NewGuid()]); + + // Act + HttpResponseMessage foreignTrackResponse = await _client.PostAsJsonAsync($"{PATH}/{callerPlaylistId}/entries-batch", foreignTrackRequest); + HttpResponseMessage missingTrackResponse = await _client.PostAsJsonAsync($"{PATH}/{callerPlaylistId}/entries-batch", missingTrackRequest); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignTrackResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingTrackResponse.StatusCode); + string foreignTrackContent = await foreignTrackResponse.Content.ReadAsStringAsync(); + string missingTrackContent = await missingTrackResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignTrackContent), GetProblemDetail(missingTrackContent)); + Assert.Equal("TrackNotFound", GetProblemDetail(foreignTrackContent)); + AssertNoSensitiveData(foreignTrackContent); + Assert.False(await PlaylistHasEntriesAsync(callerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task AddPlaylistEntries_WhenTheTrackListIsEmpty_ShouldReturnValidationProblemWithoutLeaking() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: []); + string url = $"{PATH}/{playlistId}/entries-batch"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "TrackIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistEntries_WhenSuccessful_ShouldReturnOnlyTheCallersDataWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid libraryId = await SeedLibraryAsync(userId); + Guid firstTrackId = await SeedTrackAsync(libraryId, "First caller track"); + Guid secondTrackId = await SeedTrackAsync(libraryId, "Second caller track"); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: [firstTrackId, secondTrackId]); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-batch", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + Assert.DoesNotContain("Library-", content, StringComparison.Ordinal); + Assert.True(await PlaylistHasEntriesAsync(playlistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and tracks it for cleanup. + /// + /// The Id of the user that owns the media library. + /// The Id of the seeded media library. + private async Task SeedLibraryAsync(Guid userId) + { + 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: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + _seededLibraryIds.Add(libraryId); + return libraryId; + } + + /// + /// Seeds an artist, an album and a track of the library identified by . + /// + /// The Id of the library the track belongs to. + /// The title of the track. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string title) + { + 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: $"Artist-{Guid.NewGuid():N}", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + Guid albumId = Guid.NewGuid(); + dbContext.Albums.Add(_albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: $"Album-{Guid.NewGuid():N}", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + await dbContext.SaveChangesAsync(); + Guid trackId = Guid.NewGuid(); + dbContext.Tracks.Add(_trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + title: title, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist already holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Determines whether the playlist identified by holds any entry. + /// + /// The Id of the playlist to look up. + /// when the playlist holds at least one entry. + private async Task PlaylistHasEntriesAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the catalogue rows and playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List libraryIds = [.. _seededLibraryIds]; + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId))); + dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId))); + dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..f189069d --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs @@ -0,0 +1,419 @@ +#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.Playlists; +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.Playlists; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry; +using Lumina.Presentation.Api.SecurityTests.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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddPlaylistEntryEndpointTests(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 AddPlaylistEntry_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + string url = $"{PATH}/{playlistId}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task AddPlaylistEntry_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingData(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: Guid.NewGuid()); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}/entries"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.True(await PlaylistExistsAsync(playlistId)); + } + + [Fact] + public async Task AddPlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerPlaylistId = await SeedPlaylistAsync(ownerId, "Owner playlist", entryCount: 0); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + Guid callerLibraryId = await SeedLibraryAsync(callerId); + Guid callerTrackId = await SeedTrackAsync(callerLibraryId, "Caller track"); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: callerTrackId); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.PostAsJsonAsync($"{PATH}/{ownerPlaylistId}/entries", request); + HttpResponseMessage missingResponse = await _client.PostAsJsonAsync($"{PATH}/{missingPlaylistId}/entries", request); + + // Assert + // Both answers are indistinguishable, so the route cannot be used as an existence oracle for another user's playlist. + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.False(await PlaylistHasEntriesAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task AddPlaylistEntry_WhenTheTrackBelongsToAnotherUsersLibrary_ShouldReturnTheSameNotFoundAsAMissingTrack() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerLibraryId = await SeedLibraryAsync(ownerId); + Guid ownerTrackId = await SeedTrackAsync(ownerLibraryId, "Unreachable track"); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + Guid callerPlaylistId = await SeedPlaylistAsync(callerId, "Caller playlist", entryCount: 0); + AddPlaylistEntryRequest foreignTrackRequest = _addPlaylistEntryRequestFixture.Create(trackId: ownerTrackId); + AddPlaylistEntryRequest missingTrackRequest = _addPlaylistEntryRequestFixture.Create(trackId: Guid.NewGuid()); + + // Act + HttpResponseMessage foreignTrackResponse = await _client.PostAsJsonAsync($"{PATH}/{callerPlaylistId}/entries", foreignTrackRequest); + HttpResponseMessage missingTrackResponse = await _client.PostAsJsonAsync($"{PATH}/{callerPlaylistId}/entries", missingTrackRequest); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignTrackResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingTrackResponse.StatusCode); + string foreignTrackContent = await foreignTrackResponse.Content.ReadAsStringAsync(); + string missingTrackContent = await missingTrackResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignTrackContent), GetProblemDetail(missingTrackContent)); + Assert.Equal("TrackNotFound", GetProblemDetail(foreignTrackContent)); + AssertNoSensitiveData(foreignTrackContent); + Assert.False(await PlaylistHasEntriesAsync(callerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task AddPlaylistEntry_WhenSuccessful_ShouldReturnOnlyTheCallersDataWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid libraryId = await SeedLibraryAsync(userId); + Guid trackId = await SeedTrackAsync(libraryId, "Caller track"); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + Assert.DoesNotContain("Library-", content, StringComparison.Ordinal); + Assert.True(await PlaylistHasEntriesAsync(playlistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and tracks it for cleanup. + /// + /// The Id of the user that owns the media library. + /// The Id of the seeded media library. + private async Task SeedLibraryAsync(Guid userId) + { + 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: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + _seededLibraryIds.Add(libraryId); + return libraryId; + } + + /// + /// Seeds an artist, an album and a track of the library identified by . + /// + /// The Id of the library the track belongs to. + /// The title of the track. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string title) + { + 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: $"Artist-{Guid.NewGuid():N}", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + Guid albumId = Guid.NewGuid(); + dbContext.Albums.Add(_albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: $"Album-{Guid.NewGuid():N}", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + await dbContext.SaveChangesAsync(); + Guid trackId = Guid.NewGuid(); + dbContext.Tracks.Add(_trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + title: title, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist already holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Determines whether the playlist identified by holds any entry. + /// + /// The Id of the playlist to look up. + /// when the playlist holds at least one entry. + private async Task PlaylistHasEntriesAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist entry contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the catalogue rows and playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List libraryIds = [.. _seededLibraryIds]; + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId))); + dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId))); + dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs new file mode 100644 index 00000000..b956a09a --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs @@ -0,0 +1,439 @@ +#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.Playlists; +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.Playlists; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries; +using Lumina.Presentation.Api.SecurityTests.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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + private readonly ArtistEntityFixture _artistEntityFixture = new(); + private readonly AlbumEntityFixture _albumEntityFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + private readonly List _seededLibraryIds = []; + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public AddPlaylistScopeEntriesEndpointTests(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 AddPlaylistScopeEntries_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task AddPlaylistScopeEntries_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingData(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedTrackAsync(libraryId, "Caller track"); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.True(await PlaylistExistsAsync(playlistId)); + Assert.False(await PlaylistHasEntriesAsync(playlistId)); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerPlaylistId = await SeedPlaylistAsync(ownerId, "Owner playlist", entryCount: 0); + Guid ownerLibraryId = await SeedLibraryAsync(ownerId); + await SeedTrackAsync(ownerLibraryId, "Owner track"); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + Guid callerLibraryId = await SeedLibraryAsync(callerId); + await SeedTrackAsync(callerLibraryId, "Caller track"); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: callerLibraryId); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.PostAsJsonAsync($"{PATH}/{ownerPlaylistId}/entries-scope", request); + HttpResponseMessage missingResponse = await _client.PostAsJsonAsync($"{PATH}/{missingPlaylistId}/entries-scope", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.False(await PlaylistHasEntriesAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheLibraryBelongsToAnotherUser_ShouldReturnTheSameForbiddenAsAMissingLibrary() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerLibraryId = await SeedLibraryAsync(ownerId); + await SeedTrackAsync(ownerLibraryId, "Owner track"); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + Guid callerPlaylistId = await SeedPlaylistAsync(callerId, "Caller playlist", entryCount: 0); + AddPlaylistScopeEntriesRequest foreignLibraryRequest = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: ownerLibraryId); + AddPlaylistScopeEntriesRequest missingLibraryRequest = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: Guid.NewGuid()); + + // Act + HttpResponseMessage foreignLibraryResponse = await _client.PostAsJsonAsync($"{PATH}/{callerPlaylistId}/entries-scope", foreignLibraryRequest); + HttpResponseMessage missingLibraryResponse = await _client.PostAsJsonAsync($"{PATH}/{callerPlaylistId}/entries-scope", missingLibraryRequest); + + // Assert + // Both answers are indistinguishable, so the route cannot be used to probe whether a library exists for another user. + Assert.Equal(HttpStatusCode.Forbidden, foreignLibraryResponse.StatusCode); + Assert.Equal(HttpStatusCode.Forbidden, missingLibraryResponse.StatusCode); + string foreignLibraryContent = await foreignLibraryResponse.Content.ReadAsStringAsync(); + string missingLibraryContent = await missingLibraryResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignLibraryContent), GetProblemDetail(missingLibraryContent)); + Assert.Equal("NotAuthorized", GetProblemDetail(foreignLibraryContent)); + AssertNoSensitiveData(foreignLibraryContent); + Assert.False(await PlaylistHasEntriesAsync(callerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenTheLibraryIdIsEmpty_ShouldReturnValidationProblemWithoutLeaking() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: Guid.Empty); + string url = $"{PATH}/{playlistId}/entries-scope"; + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(url, request); + + // Assert + await AssertValidationProblemAsync(response, url, "LibraryIdCannotBeEmpty"); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenSuccessful_ShouldReturnOnlyTheCallersDataWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid libraryId = await SeedLibraryAsync(userId); + await SeedTrackAsync(libraryId, "Caller track"); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync($"{PATH}/{playlistId}/entries-scope", request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + Assert.DoesNotContain("Library-", content, StringComparison.Ordinal); + Assert.True(await PlaylistHasEntriesAsync(playlistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a music library owned by and tracks it for cleanup. + /// + /// The Id of the user that owns the media library. + /// The Id of the seeded media library. + private async Task SeedLibraryAsync(Guid userId) + { + 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: $"Library-{Guid.NewGuid():N}", libraryType: LibraryType.Music, contentLocations: [])); + await dbContext.SaveChangesAsync(); + _seededLibraryIds.Add(libraryId); + return libraryId; + } + + /// + /// Seeds an artist, an album and a track of the library identified by . + /// + /// The Id of the library the track belongs to. + /// The title of the track. + /// The Id of the seeded track. + private async Task SeedTrackAsync(Guid libraryId, string title) + { + 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: $"Artist-{Guid.NewGuid():N}", includeAlbums: false, includeContributors: false)); + await dbContext.SaveChangesAsync(); + Guid albumId = Guid.NewGuid(); + dbContext.Albums.Add(_albumEntityFixture.Create( + id: albumId, + artistId: artistId, + libraryId: libraryId, + title: $"Album-{Guid.NewGuid():N}", + includeTracks: false, + includeMetadata: false, + includeBarcode: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + await dbContext.SaveChangesAsync(); + Guid trackId = Guid.NewGuid(); + dbContext.Tracks.Add(_trackEntityFixture.Create( + id: trackId, + albumId: albumId, + libraryId: libraryId, + title: title, + includeMetadata: false, + includeOriginalReleaseDate: false, + includeOriginalReleaseYear: false, + includeReReleaseDate: false, + includeReReleaseYear: false)); + await dbContext.SaveChangesAsync(); + return trackId; + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist already holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Determines whether the playlist identified by holds any entry. + /// + /// The Id of the playlist to look up. + /// when the playlist holds at least one entry. + private async Task PlaylistHasEntriesAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private static async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist response contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the catalogue rows and playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List libraryIds = [.. _seededLibraryIds]; + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.Tracks.RemoveRange(dbContext.Tracks.Where(track => libraryIds.Contains(track.LibraryId))); + dbContext.Albums.RemoveRange(dbContext.Albums.Where(album => libraryIds.Contains(album.LibraryId))); + dbContext.Artists.RemoveRange(dbContext.Artists.Where(artist => libraryIds.Contains(artist.LibraryId))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs new file mode 100644 index 00000000..93a64d84 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs @@ -0,0 +1,244 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist; +using Lumina.Presentation.Api.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public CreatePlaylistEndpointTests(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 CreatePlaylist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + await AssertUnauthorizedAsync(response, PATH); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task CreatePlaylist_WithInjectionInTheName_ShouldStoreItVerbatimWithoutExecutingOrLeaking(string maliciousName) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: maliciousName, description: maliciousName); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + PlaylistResponse? playlist = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(playlist); + _seededPlaylistIds.Add(playlist!.Id); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlist.Id); + Assert.Equal(maliciousName, storedPlaylist.Name); + Assert.Equal(maliciousName, storedPlaylist.Description); + Assert.Equal(userId, storedPlaylist.UserId); + } + + [Fact] + public async Task CreatePlaylist_WhenSuccessful_ShouldReturnOnlyTheCallersDataWithoutSensitiveInformation() + { + // Arrange + await CreateAuthenticatedUserAsync(_client); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "Caller playlist"); + + // Act + HttpResponseMessage response = await _client.PostAsJsonAsync(PATH, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + PlaylistResponse? playlist = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(playlist); + _seededPlaylistIds.Add(playlist!.Id); + Assert.Equal("Caller playlist", playlist.Name); + } + + [Fact] + public async Task CreatePlaylist_WhenAnotherUserIsAuthenticated_ShouldNotExposeTheNewPlaylistToThem() + { + // Arrange + await CreateAuthenticatedUserAsync(_client); + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(name: "Only mine"); + HttpClient otherClient = _apiFactory.CreateClient(); + (_, string otherUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(otherClient); + _seededUsernames.Add(otherUsername); + + // Act + HttpResponseMessage createResponse = await _client.PostAsJsonAsync(PATH, request); + string createContent = await createResponse.Content.ReadAsStringAsync(); + PlaylistResponse? playlist = JsonSerializer.Deserialize(createContent, _jsonOptions); + Assert.NotNull(playlist); + _seededPlaylistIds.Add(playlist!.Id); + HttpResponseMessage ownerResponse = await _client.GetAsync($"{PATH}/{playlist.Id}"); + HttpResponseMessage otherResponse = await otherClient.GetAsync($"{PATH}/{playlist.Id}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, ownerResponse.StatusCode); + // The other user receives the same not-found answer as for a playlist that never existed, so no data leaks. + Assert.Equal(HttpStatusCode.NotFound, otherResponse.StatusCode); + string otherContent = await otherResponse.Content.ReadAsStringAsync(); + Assert.Equal("PlaylistNotFound", GetProblemDetail(otherContent)); + Assert.DoesNotContain("Only mine", otherContent, StringComparison.Ordinal); + AssertNoSensitiveData(otherContent); + otherClient.Dispose(); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs new file mode 100644 index 00000000..5998e2e8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs @@ -0,0 +1,288 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist; +using Lumina.Presentation.Api.SecurityTests.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.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public DeletePlaylistEndpointTests(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 DeletePlaylist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"{PATH}/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task DeletePlaylist_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrDeletingData(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.True(await PlaylistExistsAsync(playlistId)); + } + + [Fact] + public async Task DeletePlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerPlaylistId = await SeedPlaylistAsync(ownerId, "Owner playlist", entryCount: 0); + await CreateAuthenticatedUserAsync(_client); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.DeleteAsync($"{PATH}/{ownerPlaylistId}"); + HttpResponseMessage missingResponse = await _client.DeleteAsync($"{PATH}/{missingPlaylistId}"); + + // Assert + // Both answers are indistinguishable, so the route cannot be used as an existence oracle for another user's playlist. + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.True(await PlaylistExistsAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task DeletePlaylist_WhenSuccessful_ShouldDeleteOnlyTheCallersPlaylistWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 1); + Guid otherPlaylistId = await SeedPlaylistAsync(userId, "Caller other playlist", entryCount: 0); + + // Act + HttpResponseMessage response = await _client.DeleteAsync($"{PATH}/{playlistId}"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + Assert.False(await PlaylistExistsAsync(playlistId)); + Assert.True(await PlaylistExistsAsync(otherPlaylistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + if (entryCount > 0) + { + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + playlistId: playlistId, + mediaItemId: Guid.NewGuid(), + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: 0)); + await dbContext.SaveChangesAsync(); + } + return playlistId; + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointTests.cs index c3e65a53..bbd01df8 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylist/GetPlaylistEndpointTests.cs @@ -287,7 +287,7 @@ public class GetPlaylistEndpointTests : IClassFixture, IDispos /// /// The HTTP response to assert on. /// The expected request instance path. - private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs new file mode 100644 index 00000000..e73b5460 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs @@ -0,0 +1,259 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists; +using Lumina.Presentation.Api.SecurityTests.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.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true, + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) } + }; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPlaylistsEndpointTests(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 GetPlaylists_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + await AssertUnauthorizedAsync(response, PATH); + } + + [Fact] + public async Task GetPlaylists_WhenSuccessful_ShouldReturnNonCacheableResponseWithoutSensitiveData() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 1); + + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + AssertNonCacheable(response); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + } + + [Fact] + public async Task GetPlaylists_WhenAnotherUserHasPlaylists_ShouldReturnOnlyTheCallersPlaylists() + { + // Arrange + HttpClient otherClient = _apiFactory.CreateClient(); + (Guid otherUserId, string otherUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(otherClient); + _seededUsernames.Add(otherUsername); + Guid otherPlaylistId = await SeedPlaylistAsync(otherUserId, "Other user's private playlist", entryCount: 2); + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid ownPlaylistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + + // Act + HttpResponseMessage response = await _client.GetAsync(PATH); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("Other user's private playlist", content, StringComparison.Ordinal); + Assert.DoesNotContain(otherPlaylistId.ToString(), content, StringComparison.Ordinal); + AssertNoSensitiveData(content); + PlaylistSummaryResponse[]? playlists = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(playlists); + PlaylistSummaryResponse playlist = Assert.Single(playlists!); + Assert.Equal(ownPlaylistId, playlist.Id); + otherClient.Dispose(); + } + + [Fact] + public async Task GetPlaylists_WithInjectionInTheQueryString_ShouldIgnoreItAndReturnOnlyTheCallersPlaylists() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid ownPlaylistId = await SeedPlaylistAsync(userId, "Caller playlist", entryCount: 0); + string url = $"{PATH}?name={Uri.EscapeDataString("' OR '1'='1")}&playlistId=1;%20DELETE%20FROM%20Playlists"; + + // Act + HttpResponseMessage response = await _client.GetAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + PlaylistSummaryResponse[]? playlists = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(playlists); + PlaylistSummaryResponse playlist = Assert.Single(playlists!); + Assert.Equal(ownPlaylistId, playlist.Id); + Assert.True(await PlaylistExistsAsync(ownPlaylistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts that the response is not storable by any intermediary and varies by the authorization header. + /// + /// The HTTP response to assert on. + private static void AssertNonCacheable(HttpResponseMessage response) + { + Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString()); + Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString()); + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist summary contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..bebaec38 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs @@ -0,0 +1,404 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry; +using Lumina.Presentation.Api.SecurityTests.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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public MovePlaylistEntryEndpointTests(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 MovePlaylistEntry_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{Guid.NewGuid()}/entries/{Guid.NewGuid()}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task MovePlaylistEntry_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingTheOrder(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}/entries/{secondEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], await GetOrderedEntryIdsAsync(playlistId)); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task MovePlaylistEntry_WithInjectionInPlaylistEntryId_ShouldRejectWithoutLeakingOrChangingTheOrder(string maliciousEntryId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/{Uri.EscapeDataString(maliciousEntryId)}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistEntryIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousEntryId, content, StringComparison.Ordinal); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], await GetOrderedEntryIdsAsync(playlistId)); + } + + [Fact] + public async Task MovePlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid ownerPlaylistId, Guid ownerFirstEntryId, Guid ownerSecondEntryId, Guid ownerThirdEntryId) = await SeedOrderedPlaylistAsync(ownerId); + await CreateAuthenticatedUserAsync(_client); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.PutAsJsonAsync($"{PATH}/{ownerPlaylistId}/entries/{ownerSecondEntryId}/move", request); + HttpResponseMessage missingResponse = await _client.PutAsJsonAsync($"{PATH}/{missingPlaylistId}/entries/{ownerSecondEntryId}/move", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.Equal([ownerFirstEntryId, ownerSecondEntryId, ownerThirdEntryId], await GetOrderedEntryIdsAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task MovePlaylistEntry_WhenTheEntryBelongsToAnotherUsersPlaylist_ShouldReturnTheSameNotFoundAsAMissingEntry() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid ownerPlaylistId, _, Guid ownerEntryId, _) = await SeedOrderedPlaylistAsync(ownerId); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid callerPlaylistId, Guid callerFirstEntryId, Guid callerSecondEntryId, Guid callerThirdEntryId) = await SeedOrderedPlaylistAsync(callerId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + Guid missingEntryId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignEntryResponse = await _client.PutAsJsonAsync($"{PATH}/{callerPlaylistId}/entries/{ownerEntryId}/move", request); + HttpResponseMessage missingEntryResponse = await _client.PutAsJsonAsync($"{PATH}/{callerPlaylistId}/entries/{missingEntryId}/move", request); + + // Assert + // Both answers are indistinguishable, so the route cannot be used to probe whether an entry exists in another user's playlist. + Assert.Equal(HttpStatusCode.NotFound, foreignEntryResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingEntryResponse.StatusCode); + string foreignEntryContent = await foreignEntryResponse.Content.ReadAsStringAsync(); + string missingEntryContent = await missingEntryResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignEntryContent), GetProblemDetail(missingEntryContent)); + Assert.Equal("PlaylistEntryNotFound", GetProblemDetail(foreignEntryContent)); + AssertNoSensitiveData(foreignEntryContent); + Assert.Equal([callerFirstEntryId, callerSecondEntryId, callerThirdEntryId], await GetOrderedEntryIdsAsync(callerPlaylistId)); + Assert.True(await PlaylistExistsAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task MovePlaylistEntry_WhenSuccessful_ShouldReturnOnlyTheCallersDataWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid playlistId, _, Guid secondEntryId, _) = await SeedOrderedPlaylistAsync(userId); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 0); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}/move"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + Assert.DoesNotContain("Artist-", content, StringComparison.Ordinal); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a playlist of with three ordered entries and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The Id of the playlist and the Ids of its first, second and third entries. + private async Task<(Guid PlaylistId, Guid FirstEntryId, Guid SecondEntryId, Guid ThirdEntryId)> SeedOrderedPlaylistAsync(Guid userId) + { + Guid playlistId = await SeedPlaylistAsync(userId, "Ordered playlist", entryCount: 3); + Guid firstEntryId = await SeedPlaylistEntryAsync(playlistId, 0); + Guid secondEntryId = await SeedPlaylistEntryAsync(playlistId, 1_000_000_000L); + Guid thirdEntryId = await SeedPlaylistEntryAsync(playlistId, 2_000_000_000L); + return (playlistId, firstEntryId, secondEntryId, thirdEntryId); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The sparse order key of the entry. + /// The Id of the seeded entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid entryId = Guid.NewGuid(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + id: entryId, + playlistId: playlistId, + mediaItemId: Guid.NewGuid(), + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + return entryId; + } + + /// + /// Reads the entry Ids of the playlist identified by , in stored order. + /// + /// The Id of the playlist whose entries are read. + /// The entry Ids in stored order. + private async Task> GetOrderedEntryIdsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId) + .OrderBy(entry => entry.Position) + .Select(entry => entry.Id) + .ToListAsync(); + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist entry contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..8b2c4e47 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs @@ -0,0 +1,393 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry; +using Lumina.Presentation.Api.SecurityTests.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.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public RemovePlaylistEntryEndpointTests(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 RemovePlaylistEntry_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + string url = $"{PATH}/{Guid.NewGuid()}/entries/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task RemovePlaylistEntry_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrDeletingData(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}/entries/{secondEntryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], await GetOrderedEntryIdsAsync(playlistId)); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE PlaylistEntries--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task RemovePlaylistEntry_WithInjectionInPlaylistEntryId_ShouldRejectWithoutLeakingOrDeletingData(string maliciousEntryId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + string url = $"{PATH}/{playlistId}/entries/{Uri.EscapeDataString(maliciousEntryId)}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistEntryIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousEntryId, content, StringComparison.Ordinal); + Assert.Equal([firstEntryId, secondEntryId, thirdEntryId], await GetOrderedEntryIdsAsync(playlistId)); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid ownerPlaylistId, Guid ownerFirstEntryId, Guid ownerSecondEntryId, Guid ownerThirdEntryId) = await SeedOrderedPlaylistAsync(ownerId); + await CreateAuthenticatedUserAsync(_client); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.DeleteAsync($"{PATH}/{ownerPlaylistId}/entries/{ownerSecondEntryId}"); + HttpResponseMessage missingResponse = await _client.DeleteAsync($"{PATH}/{missingPlaylistId}/entries/{ownerSecondEntryId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.Equal([ownerFirstEntryId, ownerSecondEntryId, ownerThirdEntryId], await GetOrderedEntryIdsAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenTheEntryBelongsToAnotherUsersPlaylist_ShouldReturnTheSameNotFoundAsAMissingEntry() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + (Guid ownerPlaylistId, Guid ownerFirstEntryId, _, _) = await SeedOrderedPlaylistAsync(ownerId); + (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid callerPlaylistId, Guid callerFirstEntryId, Guid callerSecondEntryId, Guid callerThirdEntryId) = await SeedOrderedPlaylistAsync(callerId); + Guid missingEntryId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignEntryResponse = await _client.DeleteAsync($"{PATH}/{callerPlaylistId}/entries/{ownerFirstEntryId}"); + HttpResponseMessage missingEntryResponse = await _client.DeleteAsync($"{PATH}/{callerPlaylistId}/entries/{missingEntryId}"); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignEntryResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingEntryResponse.StatusCode); + string foreignEntryContent = await foreignEntryResponse.Content.ReadAsStringAsync(); + string missingEntryContent = await missingEntryResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignEntryContent), GetProblemDetail(missingEntryContent)); + Assert.Equal("PlaylistEntryNotFound", GetProblemDetail(foreignEntryContent)); + AssertNoSensitiveData(foreignEntryContent); + Assert.Equal([callerFirstEntryId, callerSecondEntryId, callerThirdEntryId], await GetOrderedEntryIdsAsync(callerPlaylistId)); + Assert.True(await PlaylistExistsAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenSuccessful_ShouldRemoveOnlyTheCallersEntryWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + (Guid playlistId, Guid firstEntryId, Guid secondEntryId, Guid thirdEntryId) = await SeedOrderedPlaylistAsync(userId); + string url = $"{PATH}/{playlistId}/entries/{secondEntryId}"; + + // Act + HttpResponseMessage response = await _client.DeleteAsync(url); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + Assert.Equal([firstEntryId, thirdEntryId], await GetOrderedEntryIdsAsync(playlistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a playlist of with three ordered entries and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The Id of the playlist and the Ids of its first, second and third entries. + private async Task<(Guid PlaylistId, Guid FirstEntryId, Guid SecondEntryId, Guid ThirdEntryId)> SeedOrderedPlaylistAsync(Guid userId) + { + Guid playlistId = await SeedPlaylistAsync(userId, "Ordered playlist", entryCount: 3); + Guid firstEntryId = await SeedPlaylistEntryAsync(playlistId, 0); + Guid secondEntryId = await SeedPlaylistEntryAsync(playlistId, 1_000_000_000L); + Guid thirdEntryId = await SeedPlaylistEntryAsync(playlistId, 2_000_000_000L); + return (playlistId, firstEntryId, secondEntryId, thirdEntryId); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The number of entries the playlist holds. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, int entryCount) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + type: PlaylistType.Music, + entryCount: entryCount, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Seeds an entry of the playlist identified by . + /// + /// The Id of the playlist the entry belongs to. + /// The sparse order key of the entry. + /// The Id of the seeded entry. + private async Task SeedPlaylistEntryAsync(Guid playlistId, long position) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid entryId = Guid.NewGuid(); + dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create( + id: entryId, + playlistId: playlistId, + mediaItemId: Guid.NewGuid(), + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: position)); + await dbContext.SaveChangesAsync(); + return entryId; + } + + /// + /// Reads the entry Ids of the playlist identified by , in stored order. + /// + /// The Id of the playlist whose entries are read. + /// The entry Ids in stored order. + private async Task> GetOrderedEntryIdsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.PlaylistEntries + .AsNoTracking() + .Where(entry => entry.PlaylistId == playlistId) + .OrderBy(entry => entry.Position) + .Select(entry => entry.Id) + .ToListAsync(); + } + + /// + /// Asserts that the playlist identified by still exists. + /// + /// The Id of the playlist to look up. + /// when the playlist still exists. + private async Task PlaylistExistsAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist entry contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs new file mode 100644 index 00000000..535911f8 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs @@ -0,0 +1,327 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist; +using Lumina.Presentation.Api.SecurityTests.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.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Contains security tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt"; + private const string PATH = "/api/v1/users/me/playlists"; + + private readonly LuminaApiFactory _apiFactory; + private readonly HttpClient _client; + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + private readonly List _seededPlaylistIds = []; + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdatePlaylistEndpointTests(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 UpdatePlaylist_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + string url = $"{PATH}/{Guid.NewGuid()}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + await AssertUnauthorizedAsync(response, url); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task UpdatePlaylist_WithInjectionInTheName_ShouldStoreItVerbatimWithoutExecutingOrLeaking(string maliciousName) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Original name", "Original description"); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: maliciousName, description: maliciousName); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + PlaylistEntity storedPlaylist = await dbContext.Playlists.AsNoTracking().FirstAsync(candidate => candidate.Id == playlistId); + Assert.Equal(maliciousName, storedPlaylist.Name); + Assert.Equal(maliciousName, storedPlaylist.Description); + Assert.Equal(userId, storedPlaylist.UserId); + } + + [Theory] + [InlineData("' OR '1'='1")] // boolean-based injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("1; DELETE FROM Playlists")] // stacked statement injection + [InlineData("../../../etc/passwd")] // path traversal + [InlineData("")] // markup injection + [InlineData("Ünïcödé-💥")] // non ascii input + public async Task UpdatePlaylist_WithInjectionInPlaylistId_ShouldRejectWithoutLeakingOrChangingData(string maliciousPlaylistId) + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Original name", "Original description"); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Changed name"); + string url = $"{PATH}/{Uri.EscapeDataString(maliciousPlaylistId)}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + string content = await AssertValidationProblemAsync(response, $"{PATH}/", "PlaylistIdCannotBeEmpty"); + Assert.DoesNotContain(maliciousPlaylistId, content, StringComparison.Ordinal); + Assert.Equal("Original name", await GetPlaylistNameAsync(playlistId)); + } + + [Fact] + public async Task UpdatePlaylist_WhenThePlaylistBelongsToAnotherUser_ShouldReturnTheSameNotFoundAsAMissingPlaylist() + { + // Arrange + HttpClient ownerClient = _apiFactory.CreateClient(); + (Guid ownerId, string ownerUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(ownerClient); + _seededUsernames.Add(ownerUsername); + Guid ownerPlaylistId = await SeedPlaylistAsync(ownerId, "Owner playlist", "Owner description"); + await CreateAuthenticatedUserAsync(_client); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Hijacked", description: "Hijacked"); + Guid missingPlaylistId = Guid.NewGuid(); + + // Act + HttpResponseMessage foreignResponse = await _client.PutAsJsonAsync($"{PATH}/{ownerPlaylistId}", request); + HttpResponseMessage missingResponse = await _client.PutAsJsonAsync($"{PATH}/{missingPlaylistId}", request); + + // Assert + Assert.Equal(HttpStatusCode.NotFound, foreignResponse.StatusCode); + Assert.Equal(HttpStatusCode.NotFound, missingResponse.StatusCode); + string foreignContent = await foreignResponse.Content.ReadAsStringAsync(); + string missingContent = await missingResponse.Content.ReadAsStringAsync(); + Assert.Equal(GetProblemDetail(foreignContent), GetProblemDetail(missingContent)); + Assert.Equal("PlaylistNotFound", GetProblemDetail(foreignContent)); + AssertNoSensitiveData(foreignContent); + Assert.Equal("Owner playlist", await GetPlaylistNameAsync(ownerPlaylistId)); + ownerClient.Dispose(); + } + + [Fact] + public async Task UpdatePlaylist_WhenSuccessful_ShouldReturnOnlyTheCallersDataWithoutSensitiveInformation() + { + // Arrange + (Guid userId, _) = await CreateAuthenticatedUserAsync(_client); + Guid playlistId = await SeedPlaylistAsync(userId, "Original name", "Original description"); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(name: "Updated name", description: "Updated description"); + string url = $"{PATH}/{playlistId}"; + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync(url, request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string content = await response.Content.ReadAsStringAsync(); + AssertNoSensitiveData(content); + AssertNoDatabaseOnlyFields(content); + Assert.Equal("Updated name", await GetPlaylistNameAsync(playlistId)); + } + + /// + /// Creates a test user and authenticates it on . + /// + /// The HTTP client to authenticate. + /// The Id and username of the created user. + private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client) + { + (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client); + _seededUsernames.Add(username); + return (userId, username); + } + + /// + /// Seeds a playlist of and tracks it for cleanup. + /// + /// The Id of the user that owns the playlist. + /// The name of the playlist. + /// The description of the playlist. + /// The Id of the seeded playlist. + private async Task SeedPlaylistAsync(Guid userId, string name, string description) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + Guid playlistId = Guid.NewGuid(); + dbContext.Playlists.Add(_playlistEntityFixture.Create( + id: playlistId, + userId: userId, + name: name, + description: description, + type: PlaylistType.Music, + entryCount: 0, + version: 0, + createdBy: userId)); + await dbContext.SaveChangesAsync(); + _seededPlaylistIds.Add(playlistId); + return playlistId; + } + + /// + /// Reads the stored name of the playlist identified by . + /// + /// The Id of the playlist to read. + /// The stored name of the playlist. + private async Task GetPlaylistNameAsync(Guid playlistId) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + return await dbContext.Playlists.AsNoTracking().Where(playlist => playlist.Id == playlistId).Select(playlist => playlist.Name).FirstAsync(); + } + + /// + /// Reads the detail of a problem details body. + /// + /// The problem details body to read. + /// The problem detail. + private static string? GetProblemDetail(string content) + { + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + return problemDetails!["detail"].GetString(); + } + + /// + /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware. + /// + /// The HTTP response to assert on. + /// The expected request instance path. + private static async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance) + { + Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); + Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + 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("Authentication failed", problemDetails["detail"].GetString()); + Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString()); + AssertNoSensitiveData(content); + } + + /// + /// Asserts the shape of a validation problem details response and returns its raw body. + /// + /// The HTTP response to assert on. + /// The expected prefix of the request instance path. + /// The expected validation error code. + /// The raw response body, so that leak assertions can be applied to it. + private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstancePrefix, string expectedErrorCode) + { + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType); + + string content = await response.Content.ReadAsStringAsync(); + Dictionary? problemDetails = JsonSerializer.Deserialize>(content); + Assert.NotNull(problemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32()); + Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString()); + Assert.Equal("General.Validation", problemDetails["title"].GetString()); + Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString()); + Assert.StartsWith(expectedInstancePrefix, problemDetails["instance"].GetString()); + Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString())); + + Dictionary? errors = problemDetails["errors"].Deserialize>(); + Assert.NotNull(errors); + Assert.Contains(expectedErrorCode, errors!["General.Validation"]); + AssertNoSensitiveData(content); + return content; + } + + /// + /// Asserts that the response body carries no credentials, secrets or stack traces. + /// + /// The response body to assert on. + private static void AssertNoSensitiveData(string content) + { + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal); + Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal); + Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body exposes only the fields of the documented playlist details contract. + /// + /// The response body to assert on. + private static void AssertNoDatabaseOnlyFields(string content) + { + Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Removes the playlists seeded by the test and the test users. + /// + public void Dispose() + { + _client.Dispose(); + using (IServiceScope scope = _apiFactory.Services.CreateScope()) + { + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + List playlistIds = [.. _seededPlaylistIds]; + dbContext.PlaylistEntries.RemoveRange(dbContext.PlaylistEntries.Where(entry => playlistIds.Contains(entry.PlaylistId))); + dbContext.Playlists.RemoveRange(dbContext.Playlists.Where(playlist => playlistIds.Contains(playlist.Id))); + dbContext.SaveChanges(); + } + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs new file mode 100644 index 00000000..211afd46 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs @@ -0,0 +1,141 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.DataAccess.Core.UoW; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; +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.Linq; +using System.Net; +using System.Text.Json; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; + +/// +/// Contains security tests for the class. +/// +/// +/// The route has no user controlled string input and no configured rate limiting policy, so injection resistance and rate limiting are not +/// applicable to it. It also never issues a token, so token and claim correctness is not applicable either. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointTests : IClassFixture, IDisposable +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly UserEntityFixture _userEntityFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public GetPlaybackStateEndpointTests(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 GetPlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // 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("/api/v1/users/me/settings/playback-state", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Fact] + public async Task GetPlaybackState_WhenAnotherUserHasStoredState_ShouldReturnOnlyTheAuthenticatedUsersState() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + await SeedOtherUserWithPlaybackStateAsync(volume: 0.1, isMuted: true); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(result); + Assert.Equal(1.0, result!.Volume); + Assert.False(result.IsMuted); + } + + [Fact] + public async Task GetPlaybackState_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + + // Act + HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Seeds a user distinct from the authenticated one, with a stored playback state. + /// + /// The volume to store. + /// The mute state to store. + /// A task representing the asynchronous operation. + private async Task SeedOtherUserWithPlaybackStateAsync(double volume, bool isMuted) + { + using IServiceScope scope = _apiFactory.Services.CreateScope(); + LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService(); + + string username = $"otheruser_{Guid.NewGuid()}"; + UserEntity otherUser = _userEntityFixture.Create(username: username, password: "TestPass123!"); + otherUser.TotpSecret = null; + dbContext.Users.Add(otherUser); + dbContext.UserSettings.Add(_userSettingsEntityFixture.Create(userId: otherUser.Id, volume: volume, isMuted: isMuted)); + await dbContext.SaveChangesAsync(); + _seededUsernames.Add(username); + } + + /// + /// Disposes the API factory resources and the seeded users. + /// + public void Dispose() + { + _client.Dispose(); + foreach (string username in _seededUsernames) + _apiFactory.RemoveTestUser(username); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs new file mode 100644 index 00000000..1cc1f883 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -0,0 +1,187 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; +using Lumina.Presentation.Api.SecurityTests.Common.Setup; +using Microsoft.AspNetCore.Http; +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; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; + +/// +/// Contains security tests for the class. +/// +/// +/// The route accepts only numeric and boolean JSON fields and has no configured rate limiting policy, so rate limiting and timing attack +/// resistance are not applicable to it. It never issues a token, so token and claim correctness is not applicable either. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointTests : IClassFixture, IDisposable +{ + private readonly HttpClient _client; + private readonly LuminaApiFactory _apiFactory; + private readonly JsonSerializerOptions _jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new(); + private readonly List _seededUsernames = []; + + /// + /// Initializes a new instance of the class. + /// + /// Injected in-memory API factory. + public UpdatePlaybackStateEndpointTests(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 UpdatePlaybackState_WhenUnauthorized_ShouldReturnUnauthorizedResult() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // 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("/api/v1/users/me/settings/playback-state", problemDetails["instance"].GetProperty("value").GetString()); + Assert.Equal("Authentication failed", problemDetails["detail"].GetString()); + } + + [Theory] + [InlineData(double.MaxValue)] // far above the maximum + [InlineData(double.MinValue)] // far below the minimum + public async Task UpdatePlaybackState_WhenVolumeIsAtADoubleExtreme_ShouldReturnValidationErrorWithoutLeakingInternals(double volume) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: volume); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); + AssertResponseDoesNotLeakInternalDetails(content); + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledByOneUser_ShouldNotChangeTheStateOfAnotherUser() + { + // Arrange + (_, string firstUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(firstUsername); + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: true); + HttpResponseMessage updateResponse = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + HttpClient otherClient = _apiFactory.CreateClient(); + (_, string secondUsername) = await _apiFactory.CreateAndAuthenticateUserAsync(otherClient); + _seededUsernames.Add(secondUsername); + + // Act + HttpResponseMessage getResponse = await otherClient.GetAsync("/api/v1/users/me/settings/playback-state"); + + // Assert + updateResponse.EnsureSuccessStatusCode(); + getResponse.EnsureSuccessStatusCode(); + string content = await getResponse.Content.ReadAsStringAsync(); + PlaybackStateResponse? result = JsonSerializer.Deserialize(content, _jsonOptions); + Assert.NotNull(result); + Assert.Equal(1.0, result!.Volume); + Assert.False(result.IsMuted); + otherClient.Dispose(); + } + + [Fact] + public async Task UpdatePlaybackState_WhenAuthenticated_ShouldNotLeakSensitiveData() + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true); + + // Act + HttpResponseMessage response = await _client.PutAsJsonAsync("/api/v1/users/me/settings/playback-state", request); + + // Assert + response.EnsureSuccessStatusCode(); + string content = await response.Content.ReadAsStringAsync(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase); + } + + [Theory(Skip = "Production bug: a JSON payload whose volume is a string makes the FastEndpoints binder throw a System.Text.Json.JsonException, which escapes because UpdatePlaybackStateEndpoint calls DontCatchExceptions(), so the API responds with 500 instead of 400 or 422. The body is the generic ProblemDetails and leaks no internals. The test stays skipped until the endpoint maps binding failures to a client error.")] + [InlineData("'; DROP TABLE UserSettings; --")] // SQL injection + [InlineData("$(rm -rf /)")] // command injection + [InlineData("../../etc/passwd")] // path traversal + public async Task UpdatePlaybackState_WhenAStringIsSentInTheVolumeField_ShouldReturnAClientErrorWithoutLeakingInternalDetails(string maliciousValue) + { + // Arrange + (_, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(_client); + _seededUsernames.Add(username); + string payload = $"{{\"volume\":\"{maliciousValue}\",\"isMuted\":true}}"; + StringContent requestContent = new(payload, Encoding.UTF8, "application/json"); + + // Act + HttpResponseMessage response = await _client.PutAsync("/api/v1/users/me/settings/playback-state", requestContent); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.True(response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.UnprocessableEntity, $"Actual status: {(int)response.StatusCode}"); + AssertResponseDoesNotLeakInternalDetails(content); + Assert.DoesNotContain("DROP TABLE", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("rm -rf", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("/etc/passwd", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Asserts that the response body does not expose exception details, stack frames, or database internals. + /// + /// The response body to inspect. + private static void AssertResponseDoesNotLeakInternalDetails(string content) + { + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("stack trace", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina.", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Microsoft.Data.Sqlite", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Microsoft.EntityFrameworkCore", content, StringComparison.OrdinalIgnoreCase); + } + + /// + /// Disposes the API factory resources and the seeded users. + /// + 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/StreamMusicTrack/StreamMusicTrackEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs new file mode 100644 index 00000000..690b81d9 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs @@ -0,0 +1,167 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; +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.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.StreamMusicTrack; + +/// +/// Contains security tests for the class. +/// +/// +/// The concurrency rate limiter of the stream route is not exercised, because it requires four concurrent long lived streams, which needs a real +/// normalization pipeline and ffmpeg, neither of which is available in the test environment. +/// +[ExcludeFromCodeCoverage] +public class StreamMusicTrackEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public StreamMusicTrackEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task StreamMusicTrack_WhenNotAuthenticated_ShouldRedirectToLoginWithoutCallingTheApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + HttpClient anonymousClient = WebTestHelpers.CreateAnonymousClient(_apiFactory); + + // Act + HttpResponseMessage response = await anonymousClient.GetAsync(BuildBrowserPath(Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid())); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Empty(_apiFactory.StreamingApiClientStub.GetEndpointsCalled); + } + + [Theory] + [InlineData("artistId")] // injection in the artist Id + [InlineData("albumId")] // injection in the album Id + [InlineData("trackId")] // injection in the track Id + public async Task StreamMusicTrack_WithAnInjectionPayloadInATrackRouteId_ShouldNormalizeTheIdWithoutLeakingData(string routeValue) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + const string PAYLOAD = "'; DROP TABLE Tracks; --"; + Guid libraryId = Guid.NewGuid(); + string validArtistId = Guid.NewGuid().ToString(); + string validAlbumId = Guid.NewGuid().ToString(); + string validTrackId = Guid.NewGuid().ToString(); + string artistId = routeValue == "artistId" ? Uri.EscapeDataString(PAYLOAD) : validArtistId; + string albumId = routeValue == "albumId" ? Uri.EscapeDataString(PAYLOAD) : validAlbumId; + string trackId = routeValue == "trackId" ? Uri.EscapeDataString(PAYLOAD) : validTrackId; + string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", routeValue == "artistId" ? Guid.Empty.ToString() : validArtistId) + .Replace("{albumId}", routeValue == "albumId" ? Guid.Empty.ToString() : validAlbumId) + .Replace("{trackId}", routeValue == "trackId" ? Guid.Empty.ToString() : validTrackId); + byte[] contentBytes = CreateBytes(128); + _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(contentBytes)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync( + $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}"); + byte[] responseBytes = await response.Content.ReadAsByteArrayAsync(); + string responseText = Encoding.UTF8.GetString(responseBytes); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(contentBytes, responseBytes); + Assert.DoesNotContain("SQL", responseText, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", responseText, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("at Lumina", responseText, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(PAYLOAD, responseText, StringComparison.Ordinal); + Assert.Single(_apiFactory.StreamingApiClientStub.GetEndpointsCalled); + Assert.Equal(expectedEndpoint, _apiFactory.StreamingApiClientStub.GetEndpointsCalled[0]); + } + + [Fact] + public async Task StreamMusicTrack_WhenTheApiDeclaresAPublicCache_ShouldNeverExposeAPublicCacheControl() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.StreamingApiClientStub.Reset(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + string expectedEndpoint = ApiRoutes.Music.STREAM_TRACK + .Replace("{libraryId}", libraryId.ToString()) + .Replace("{artistId}", artistId.ToString()) + .Replace("{albumId}", albumId.ToString()) + .Replace("{trackId}", trackId.ToString()); + _apiFactory.StreamingApiClientStub.RegisterStreamResponse(expectedEndpoint, await CreateStreamResultAsync(CreateBytes(64))); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(BuildBrowserPath(libraryId, artistId, albumId, trackId)); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + string cacheControl = response.Headers.CacheControl?.ToString() ?? string.Empty; + Assert.DoesNotContain("public", cacheControl, StringComparison.OrdinalIgnoreCase); + Assert.Contains("private", cacheControl); + Assert.Contains("Cookie", response.Headers.Vary); + } + + /// + /// Builds the browser facing route of the direct stream of a track. + /// + /// The Id of the media library the track belongs to. + /// The Id of the artist the album belongs to. + /// The Id of the album the track belongs to. + /// The Id of the track. + /// The browser facing route of the requested stream. + private static string BuildBrowserPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId) + { + return $"/en-us/library/audio-library/music-library/artists/{artistId}/albums/{albumId}/tracks/{trackId}/api-stream-track?libraryId={libraryId}"; + } + + /// + /// Creates a streamed API response with an ok status and a body. + /// + /// The bytes of the content of the response. + /// The created streamed response. + private static async Task CreateStreamResultAsync(byte[] contentBytes) + { + HttpResponseMessage response = new(HttpStatusCode.OK) + { + Content = new ByteArrayContent(contentBytes) + }; + response.Content.Headers.ContentType = new MediaTypeHeaderValue("audio/mpeg"); + response.Headers.CacheControl = new CacheControlHeaderValue { Public = true, MaxAge = TimeSpan.FromSeconds(120) }; + return await ApiStreamResult.CreateAsync(response, CancellationToken.None); + } + + /// + /// Creates a deterministic byte array that stands in for the content of a stream. + /// + /// The number of bytes to create. + /// The created bytes. + private static byte[] CreateBytes(int length) + { + return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))]; + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs new file mode 100644 index 00000000..ec298a26 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs @@ -0,0 +1,283 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddPlaylistEntriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task AddPlaylistEntries_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), request, antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), request, antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistEntries_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), request, "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task AddPlaylistEntries_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-batch"; + _apiFactory.ApiClientStub.RegisterPostResponse(sanitizedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Uri.EscapeDataString(payload), _addPlaylistEntriesRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + public async Task AddPlaylistEntries_WithInjectionPayloadInTrackIds_ShouldRejectTheRequestWithoutCallingTheApi(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateRawAddRequest( + Guid.NewGuid().ToString(), + $"{{\"trackIds\": [{JsonSerializer.Serialize(payload)}]}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Empty(GetAddRequests()); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistEntries_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid otherUserId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch"; + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateRawAddRequest( + playlistId.ToString(), + $"{{\"trackIds\": [\"{Guid.NewGuid()}\"], \"userId\": \"{otherUserId}\"}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistEntries_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-batch"; + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), _addPlaylistEntriesRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the add entries requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream add entries requests that were sent. + private List<(string Endpoint, object? Data)> GetAddRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && postRequest.Endpoint.EndsWith("/entries-batch", StringComparison.Ordinal))]; + } + + /// + /// Builds the add entries request for the specified playlist route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured add entries request. + private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntriesRequest request, string? antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-entries") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Builds the add entries request that posts the given raw JSON body. + /// + /// The value of the playlist identifier route segment. + /// The raw JSON body to send. + /// The antiforgery token to include in the request. + /// The configured add entries request. + private static HttpRequestMessage CreateRawAddRequest(string playlistId, string jsonBody, string antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-entries") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + addRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..96a0e975 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs @@ -0,0 +1,280 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryAddedDtoFixture _playlistEntryAddedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddPlaylistEntryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task AddPlaylistEntry_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistEntryRequestFixture.Create(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistEntryRequestFixture.Create(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistEntry_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistEntryRequestFixture.Create(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task AddPlaylistEntry_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries"; + _apiFactory.ApiClientStub.RegisterPostResponse(sanitizedEndpoint, _playlistEntryAddedDtoFixture.Create(playlistId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Uri.EscapeDataString(payload), _addPlaylistEntryRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + public async Task AddPlaylistEntry_WithInjectionPayloadInTrackId_ShouldRejectTheRequestWithoutCallingTheApi(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateRawAddRequest( + Guid.NewGuid().ToString(), + $"{{\"trackId\": {JsonSerializer.Serialize(payload)}}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Empty(GetAddRequests()); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistEntry_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid otherUserId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries"; + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntryAddedDtoFixture.Create(playlistId: playlistId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateRawAddRequest( + playlistId.ToString(), + $"{{\"trackId\": \"{Guid.NewGuid()}\", \"userId\": \"{otherUserId}\"}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistEntry_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries"; + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), _addPlaylistEntryRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the add entry requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream add entry requests that were sent. + private List<(string Endpoint, object? Data)> GetAddRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && postRequest.Endpoint.EndsWith("/entries", StringComparison.Ordinal))]; + } + + /// + /// Builds the add entry request for the specified playlist route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured add entry request. + private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistEntryRequest request, string? antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/entries/api-add-entry") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Builds the add entry request that posts the given raw JSON body. + /// + /// The value of the playlist identifier route segment. + /// The raw JSON body to send. + /// The antiforgery token to include in the request. + /// The configured add entry request. + private static HttpRequestMessage CreateRawAddRequest(string playlistId, string jsonBody, string antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/entries/api-add-entry") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + addRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs new file mode 100644 index 00000000..28d8705b --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs @@ -0,0 +1,281 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public AddPlaylistScopeEntriesEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Guid.NewGuid().ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetAddRequests()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task AddPlaylistScopeEntries_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries-scope"; + _apiFactory.ApiClientStub.RegisterPostResponse(sanitizedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(Uri.EscapeDataString(payload), _addPlaylistScopeEntriesRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("libraryId")] // required scope identifier + [InlineData("artistId")] // optional scope identifier + [InlineData("albumId")] // optional scope identifier + public async Task AddPlaylistScopeEntries_WithInjectionPayloadInScopeIds_ShouldRejectTheRequestWithoutCallingTheApi(string propertyName) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + const string payload = "'; DROP TABLE Playlists--"; + HttpRequestMessage addRequest = CreateRawAddRequest( + Guid.NewGuid().ToString(), + $"{{\"libraryId\": \"{Guid.NewGuid()}\", \"{propertyName}\": {JsonSerializer.Serialize(payload)}}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Empty(GetAddRequests()); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid otherUserId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope"; + _apiFactory.ApiClientStub.RegisterPostResponse(expectedEndpoint, _playlistEntriesAddedDtoFixture.Create(playlistId: playlistId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateRawAddRequest( + playlistId.ToString(), + $"{{\"libraryId\": \"{Guid.NewGuid()}\", \"userId\": \"{otherUserId}\"}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetAddRequests().Select(addRequestCall => addRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal); + } + + [Fact] + public async Task AddPlaylistScopeEntries_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries-scope"; + _apiFactory.ApiClientStub.RegisterPostException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage addRequest = CreateAddRequest(playlistId.ToString(), _addPlaylistScopeEntriesRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(addRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the add scope entries requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream add scope entries requests that were sent. + private List<(string Endpoint, object? Data)> GetAddRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && postRequest.Endpoint.EndsWith("/entries-scope", StringComparison.Ordinal))]; + } + + /// + /// Builds the add scope entries request for the specified playlist route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured add scope entries request. + private static HttpRequestMessage CreateAddRequest(string playlistId, AddPlaylistScopeEntriesRequest request, string? antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-scope-entries") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + addRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Builds the add scope entries request that posts the given raw JSON body. + /// + /// The value of the playlist identifier route segment. + /// The raw JSON body to send. + /// The antiforgery token to include in the request. + /// The configured add scope entries request. + private static HttpRequestMessage CreateRawAddRequest(string playlistId, string jsonBody, string antiforgeryToken) + { + HttpRequestMessage addRequest = new(HttpMethod.Post, $"/en-us/playlists/item/{playlistId}/api-add-scope-entries") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + addRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + addRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + addRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return addRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs new file mode 100644 index 00000000..8fb696af --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Enums.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string UPSTREAM_ENDPOINT = "users/me/playlists"; + + private readonly LuminaWebFactory _apiFactory; + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + private readonly PlaylistDtoFixture _playlistDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public CreatePlaylistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task CreatePlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetCreateRequests()); + } + + [Fact] + public async Task CreatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetCreateRequests()); + } + + [Fact] + public async Task CreatePlaylist_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetCreateRequests()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task CreatePlaylist_WithInjectionPayloadInName_ShouldNotFailOrLeakThePayload(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, _playlistDtoFixture.Create(name: "Injected playlist")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(name: payload), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // A playlist name is a free-form string, so the Web layer forwards it and the API is responsible for storing it safely; the Web layer must never echo it back. + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + 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(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + public async Task CreatePlaylist_WithInjectionPayloadInType_ShouldRejectTheRequestWithoutCallingTheApi(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage createRequest = CreateRawCreateRequest( + $"{{\"name\": \"Test playlist\", \"type\": {JsonSerializer.Serialize(payload)}}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // The media type is bound to an enum, so the crafted value is rejected before the endpoint executes and can never reach the API. + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Empty(GetCreateRequests()); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task CreatePlaylist_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid otherUserId = Guid.NewGuid(); + _apiFactory.ApiClientStub.RegisterPostResponse(UPSTREAM_ENDPOINT, _playlistDtoFixture.Create()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage createRequest = CreateRawCreateRequest( + $"{{\"name\": \"Test playlist\", \"type\": \"{PlaylistType.Music}\", \"userId\": \"{otherUserId}\"}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetCreateRequests().Select(createRequestCall => createRequestCall.Endpoint).ToList(); + Assert.Equal([UPSTREAM_ENDPOINT], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal); + } + + [Fact] + public async Task CreatePlaylist_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPostException(UPSTREAM_ENDPOINT, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistCreationForbidden"), + HttpStatusCode.Forbidden, + UPSTREAM_ENDPOINT)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage createRequest = CreateCreateRequest(_createPlaylistRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(createRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the create playlist requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream create playlist requests that were sent. + private List<(string Endpoint, object? Data)> GetCreateRequests() + { + return [.. _apiFactory.ApiClientStub.PostRequests + .Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)]; + } + + /// + /// Builds the create playlist request that sends the given . + /// + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured create playlist request. + private static HttpRequestMessage CreateCreateRequest(CreatePlaylistRequest request, string? antiforgeryToken) + { + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/playlists/api-create-playlist") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + createRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return createRequest; + } + + /// + /// Builds the create playlist request that posts the given raw JSON body. + /// + /// The raw JSON body to send. + /// The antiforgery token to include in the request. + /// The configured create playlist request. + private static HttpRequestMessage CreateRawCreateRequest(string jsonBody, string antiforgeryToken) + { + HttpRequestMessage createRequest = new(HttpMethod.Post, "/en-us/playlists/api-create-playlist") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + createRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + createRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + createRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return createRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs new file mode 100644 index 00000000..f7d11935 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs @@ -0,0 +1,199 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public DeletePlaylistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task DeletePlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetDeleteEndpointCalls()); + } + + [Fact] + public async Task DeletePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetDeleteEndpointCalls()); + } + + [Fact] + public async Task DeletePlaylist_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Guid.NewGuid().ToString(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetDeleteEndpointCalls()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task DeletePlaylist_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage deleteRequest = CreateDeleteRequest(Uri.EscapeDataString(payload), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetDeleteEndpointCalls(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task DeletePlaylist_WhenPlaylistBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid otherUsersPlaylistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}"; + _apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage deleteRequest = CreateDeleteRequest(otherUsersPlaylistId.ToString(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + List endpointCalls = GetDeleteEndpointCalls(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the delete playlist endpoints that were called upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream delete playlist endpoints that were called. + private List GetDeleteEndpointCalls() + { + return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled + .Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))]; + } + + /// + /// Builds the delete playlist request for the specified route value. + /// + /// The value of the playlist identifier route segment. + /// The antiforgery token to include in the request, or to omit it. + /// The configured delete playlist request. + private static HttpRequestMessage CreateDeleteRequest(string playlistId, string? antiforgeryToken) + { + HttpRequestMessage deleteRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{playlistId}/api-delete-playlist") + { + // The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + deleteRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + deleteRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return deleteRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs new file mode 100644 index 00000000..58c3d3fd --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs @@ -0,0 +1,160 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointTests : IClassFixture, IDisposable +{ + private const string UPSTREAM_ENDPOINT = "users/me/playlists"; + + private readonly LuminaWebFactory _apiFactory; + private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPlaylistsEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task GetPlaylists_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + + // Act + HttpResponseMessage response = await client.GetAsync("/en-us/playlists/api-get-playlists"); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task GetPlaylists_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, new[] { _playlistSummaryDtoFixture.Create() }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync("/en-us/playlists/api-get-playlists"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.True(response.Headers.CacheControl?.Private); + Assert.True(response.Headers.CacheControl?.NoStore); + Assert.Contains("Cookie", response.Headers.Vary); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("other-user-id")] // a plain identifier of another user + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + public async Task GetPlaylists_WithAnotherUserIdInTheQueryString_ShouldKeepTheUsersMeScope(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse(UPSTREAM_ENDPOINT, new[] { _playlistSummaryDtoFixture.Create() }); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync($"/en-us/playlists/api-get-playlists?userId={Uri.EscapeDataString(payload)}"); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetPlaylistEndpointCalls(); + Assert.Equal([UPSTREAM_ENDPOINT], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + } + + [Fact] + public async Task GetPlaylists_WhenApiReportsForbidden_ShouldReturnASanitizedErrorWithoutLeakingAnotherUsersPlaylists() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetException(UPSTREAM_ENDPOINT, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistsAccessDenied"), + HttpStatusCode.Forbidden, + UPSTREAM_ENDPOINT)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/playlists/api-get-playlists"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers. + /// + /// The list of upstream playlist endpoints that were called. + private List GetPlaylistEndpointCalls() + { + return [.. _apiFactory.ApiClientStub.GetEndpointsCalled + .Where(endpoint => endpoint == UPSTREAM_ENDPOINT)]; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs new file mode 100644 index 00000000..3cffe998 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.Index; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, token or claim correctness does not apply because the Web layer issues no token for this route, and +/// cross-user isolation does not apply because the page accepts no user or resource identifier and shows only the signed-in user's own data. +/// +[ExcludeFromCodeCoverage] +public class PlaylistsIndexViewEndpointTests : IClassFixture, IDisposable +{ + private const string WEB_ROUTE = "/en-us/playlists"; + + private readonly LuminaWebFactory _apiFactory; + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public PlaylistsIndexViewEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task PlaylistsIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + + // Act + HttpResponseMessage response = await client.GetAsync(WEB_ROUTE); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled); + } + + [Fact] + public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldBePrivateAndNotLeakSensitiveData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.True(response.Headers.CacheControl?.Private); + Assert.True(response.Headers.CacheControl?.NoStore); + Assert.Contains("no-store", string.Join(", ", response.Headers.GetValues("Cache-Control")), StringComparison.OrdinalIgnoreCase); + Assert.Contains("Cookie", response.Headers.Vary); + Assert.Contains("__RequestVerificationToken", content, StringComparison.Ordinal); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("TestPass123!", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task PlaylistsIndexView_WhenCalledByAuthenticatedUser_ShouldNotProxyAnyPlaylistCall() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + + // Act + HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/me/playlists", StringComparison.Ordinal)); + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..b9d6ec3f --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs @@ -0,0 +1,297 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryMovedDtoFixture _playlistEntryMovedDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public MovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task MovePlaylistEntry_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _movePlaylistEntryRequestFixture.Create(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(moveRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetMoveRequests()); + } + + [Fact] + public async Task MovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _movePlaylistEntryRequestFixture.Create(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetMoveRequests()); + } + + [Fact] + public async Task MovePlaylistEntry_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage moveRequest = CreateMoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), _movePlaylistEntryRequestFixture.Create(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetMoveRequests()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task MovePlaylistEntry_WithInjectionPayloadInRouteIds_ShouldNormalizeThemAndNotForwardTheRawValues(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move"; + _apiFactory.ApiClientStub.RegisterPutResponse(sanitizedEndpoint, _playlistEntryMovedDtoFixture.Create(playlistId: Guid.Empty, entryId: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage moveRequest = CreateMoveRequest( + Uri.EscapeDataString(payload), + Uri.EscapeDataString(payload), + _movePlaylistEntryRequestFixture.Create(), + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint).ToList(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + public async Task MovePlaylistEntry_WithInjectionPayloadInTargetPosition_ShouldRejectTheRequestWithoutCallingTheApi(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage moveRequest = CreateRawMoveRequest( + Guid.NewGuid().ToString(), + Guid.NewGuid().ToString(), + $"{{\"targetPosition\": {JsonSerializer.Serialize(payload)}}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.Empty(GetMoveRequests()); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task MovePlaylistEntry_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + Guid otherUserId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"; + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistEntryMovedDtoFixture.Create(playlistId: playlistId, entryId: playlistEntryId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage moveRequest = CreateRawMoveRequest( + playlistId.ToString(), + playlistEntryId.ToString(), + $"{{\"targetPosition\": 1, \"userId\": \"{otherUserId}\"}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal); + } + + [Fact] + public async Task MovePlaylistEntry_WhenPlaylistBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid otherUsersPlaylistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}/entries/{playlistEntryId}/move"; + _apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage moveRequest = CreateMoveRequest( + otherUsersPlaylistId.ToString(), + playlistEntryId.ToString(), + _movePlaylistEntryRequestFixture.Create(), + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(moveRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + List endpointCalls = GetMoveRequests().Select(moveRequestCall => moveRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the move entry requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream move entry requests that were sent. + private List<(string Endpoint, object? Data)> GetMoveRequests() + { + return [.. _apiFactory.ApiClientStub.PutRequests + .Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && putRequest.Endpoint.EndsWith("/move", StringComparison.Ordinal))]; + } + + /// + /// Builds the move entry request for the specified route values. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured move entry request. + private static HttpRequestMessage CreateMoveRequest(string playlistId, string playlistEntryId, MovePlaylistEntryRequest request, string? antiforgeryToken) + { + HttpRequestMessage moveRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + moveRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + moveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + moveRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return moveRequest; + } + + /// + /// Builds the move entry request that posts the given raw JSON body. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + /// The raw JSON body to send. + /// The antiforgery token to include in the request. + /// The configured move entry request. + private static HttpRequestMessage CreateRawMoveRequest(string playlistId, string playlistEntryId, string jsonBody, string antiforgeryToken) + { + HttpRequestMessage moveRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/entries/{playlistEntryId}/api-move-entry") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + moveRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + moveRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + moveRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return moveRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..fef630f2 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs @@ -0,0 +1,209 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.Text; +using System.Text.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public RemovePlaylistEntryEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task RemovePlaylistEntry_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(removeRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetRemoveEndpointCalls()); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetRemoveEndpointCalls()); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage removeRequest = CreateRemoveRequest(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetRemoveEndpointCalls()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task RemovePlaylistEntry_WithInjectionPayloadInRouteIds_ShouldNormalizeThemAndNotForwardTheRawValues(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}"; + _apiFactory.ApiClientStub.RegisterDeleteSuccess(sanitizedEndpoint); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage removeRequest = CreateRemoveRequest( + Uri.EscapeDataString(payload), + Uri.EscapeDataString(payload), + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetRemoveEndpointCalls(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task RemovePlaylistEntry_WhenEntryBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid otherUsersPlaylistId = Guid.NewGuid(); + Guid otherUsersPlaylistEntryId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}/entries/{otherUsersPlaylistEntryId}"; + _apiFactory.ApiClientStub.RegisterDeleteException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistEntryAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage removeRequest = CreateRemoveRequest( + otherUsersPlaylistId.ToString(), + otherUsersPlaylistEntryId.ToString(), + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(removeRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + List endpointCalls = GetRemoveEndpointCalls(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the remove entry endpoints that were called upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream remove entry endpoints that were called. + private List GetRemoveEndpointCalls() + { + return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled + .Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal) + && endpoint.Contains("/entries/", StringComparison.Ordinal))]; + } + + /// + /// Builds the remove entry request for the specified route values. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + /// The antiforgery token to include in the request, or to omit it. + /// The configured remove entry request. + private static HttpRequestMessage CreateRemoveRequest(string playlistId, string playlistEntryId, string? antiforgeryToken) + { + HttpRequestMessage removeRequest = new(HttpMethod.Delete, $"/en-us/playlists/item/{playlistId}/entries/{playlistEntryId}/api-remove-entry") + { + // The front-end sends the JSON content type even for DELETE requests, which triggers the antiforgery validation. + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + removeRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + removeRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + removeRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return removeRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs new file mode 100644 index 00000000..effaf129 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs @@ -0,0 +1,283 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Common; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.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.SecurityTests.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Contains security tests for the class. +/// +/// +/// The route declares no rate limiter policy, so rate limiting is not exercised here. Timing attack resistance does not apply because the route +/// performs no credential comparison, and token or claim correctness does not apply because the Web layer issues no token for this route. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointTests : IClassFixture, IDisposable +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly LuminaWebFactory _apiFactory; + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + private readonly PlaylistDetailsDtoFixture _playlistDetailsDtoFixture = new(); + private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new(); + private readonly string _clientIp; + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdatePlaylistEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + _clientIp = $"10.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(0, 256)}.{Random.Shared.Next(1, 254)}"; + } + + [Fact] + public async Task UpdatePlaylist_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = CreateUpdateRequest(Guid.NewGuid().ToString(), _updatePlaylistRequestFixture.Create(), antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.Empty(GetUpdateRequests()); + } + + [Fact] + public async Task UpdatePlaylist_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage updateRequest = CreateUpdateRequest(Guid.NewGuid().ToString(), _updatePlaylistRequestFixture.Create(), antiforgeryToken: null); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetUpdateRequests()); + } + + [Fact] + public async Task UpdatePlaylist_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage updateRequest = CreateUpdateRequest(Guid.NewGuid().ToString(), _updatePlaylistRequestFixture.Create(), "invalid-token"); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.Empty(GetUpdateRequests()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task UpdatePlaylist_WithInjectionPayloadInPlaylistId_ShouldNormalizeItAndNotForwardTheRawValue(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + string sanitizedEndpoint = $"users/me/playlists/{ZERO_GUID}"; + _apiFactory.ApiClientStub.RegisterPutResponse(sanitizedEndpoint, _playlistDetailsDtoFixture.Create(id: Guid.Empty)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage updateRequest = CreateUpdateRequest(Uri.EscapeDataString(payload), _updatePlaylistRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + List endpointCalls = GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint).ToList(); + Assert.All(endpointCalls, endpoint => Assert.Equal(sanitizedEndpoint, endpoint)); + Assert.DoesNotContain(payload, string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(Uri.EscapeDataString(payload), string.Join(",", endpointCalls), StringComparison.Ordinal); + Assert.DoesNotContain(payload, content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("'; DROP TABLE Playlists--")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + public async Task UpdatePlaylist_WithInjectionPayloadInName_ShouldNotFailOrLeakThePayload(string payload) + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: playlistId, name: "Updated playlist")); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage updateRequest = CreateUpdateRequest(playlistId.ToString(), _updatePlaylistRequestFixture.Create(name: payload), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + // A playlist name is a free-form string, so the Web layer forwards it and the API is responsible for storing it safely; the Web layer must never echo it back. + Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode); + 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(" at Lumina", content, StringComparison.Ordinal); + } + + [Fact] + public async Task UpdatePlaylist_WhenBodyTriesToTargetAnotherUser_ShouldKeepTheUsersMeScope() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid playlistId = Guid.NewGuid(); + Guid otherUserId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{playlistId}"; + _apiFactory.ApiClientStub.RegisterPutResponse(expectedEndpoint, _playlistDetailsDtoFixture.Create(id: playlistId)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage updateRequest = CreateRawUpdateRequest( + playlistId.ToString(), + $"{{\"name\": \"Updated playlist\", \"userId\": \"{otherUserId}\"}}", + webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + response.EnsureSuccessStatusCode(); + List endpointCalls = GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain(otherUserId.ToString(), string.Join(",", endpointCalls), StringComparison.Ordinal); + } + + [Fact] + public async Task UpdatePlaylist_WhenPlaylistBelongsToAnotherUser_ShouldKeepTheUsersMeScopeAndNotLeakData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + Guid otherUsersPlaylistId = Guid.NewGuid(); + string expectedEndpoint = $"users/me/playlists/{otherUsersPlaylistId}"; + _apiFactory.ApiClientStub.RegisterPutException(expectedEndpoint, new ApiException( + _problemDetailsDtoFixture.Create(title: "General.Forbidden", detail: "PlaylistAccessDenied"), + HttpStatusCode.Forbidden, + expectedEndpoint)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + webClient.Client.DefaultRequestHeaders.Add("X-Forwarded-For", _clientIp); + HttpRequestMessage updateRequest = CreateUpdateRequest(otherUsersPlaylistId.ToString(), _updatePlaylistRequestFixture.Create(), webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + using JsonDocument json = JsonDocument.Parse(content); + Assert.False(json.RootElement.GetProperty("success").GetBoolean()); + Assert.False(json.RootElement.TryGetProperty("data", out _)); + List endpointCalls = GetUpdateRequests().Select(updateRequestCall => updateRequestCall.Endpoint).ToList(); + Assert.Equal([expectedEndpoint], endpointCalls); + Assert.All(endpointCalls, endpoint => Assert.StartsWith("users/me/", endpoint, StringComparison.Ordinal)); + Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal); + } + + /// + /// Gets the update playlist requests that were sent upstream, excluding the requests made to authenticate the test client. + /// + /// The list of upstream update playlist requests that were sent. + private List<(string Endpoint, object? Data)> GetUpdateRequests() + { + return [.. _apiFactory.ApiClientStub.PutRequests + .Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))]; + } + + /// + /// Builds the update playlist request for the specified route value. + /// + /// The value of the playlist identifier route segment. + /// The request payload to send. + /// The antiforgery token to include in the request, or to omit it. + /// The configured update playlist request. + private static HttpRequestMessage CreateUpdateRequest(string playlistId, UpdatePlaylistRequest request, string? antiforgeryToken) + { + HttpRequestMessage updateRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/api-update-playlist") + { + Content = JsonContent.Create(request) + }; + // The antiforgery middleware matches the content type exactly, so the charset suffix must be omitted. + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + if (antiforgeryToken is not null) + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return updateRequest; + } + + /// + /// Builds the update playlist request that posts the given raw JSON body. + /// + /// The value of the playlist identifier route segment. + /// The raw JSON body to send. + /// The antiforgery token to include in the request. + /// The configured update playlist request. + private static HttpRequestMessage CreateRawUpdateRequest(string playlistId, string jsonBody, string antiforgeryToken) + { + HttpRequestMessage updateRequest = new(HttpMethod.Put, $"/en-us/playlists/item/{playlistId}/api-update-playlist") + { + Content = new StringContent(jsonBody, Encoding.UTF8, "application/json") + }; + updateRequest.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + return updateRequest; + } + + /// + /// Releases the resources used by the test class and resets the remote API stub. + /// + public void Dispose() + { + _apiFactory.ApiClientStub.Reset(); + GC.SuppressFinalize(this); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs new file mode 100644 index 00000000..4c228628 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// Contains security tests for the class. +/// +/// +/// The route takes no user controlled input, has no configured rate limiting policy and never issues a token, so injection resistance, rate +/// limiting, timing attack resistance and token claim correctness are not applicable to it. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public GetPlaybackStateEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task GetPlaybackState_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await client.SendAsync(getRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings/playback-state"); + } + + [Fact] + public async Task GetPlaybackState_WhenCalledByAuthenticatedUser_ShouldNotLeakSensitiveData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterGetResponse("users/me/settings/playback-state", _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true)); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage getRequest = new(HttpMethod.Get, "/en-us/tools/settings/api-get-playback-state"); + getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(getRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + Assert.Contains(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint == "users/me/settings/playback-state"); + } +} diff --git a/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs new file mode 100644 index 00000000..372ed035 --- /dev/null +++ b/tests/SecurityTests/Lumina.Presentation.Web.SecurityTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -0,0 +1,113 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Requests.Common; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Lumina.Presentation.Web.SecurityTests.Common.Setup; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// Contains security tests for the class. +/// +/// +/// The route accepts only numeric and boolean fields, has no configured rate limiting policy and never issues a token, so injection resistance, +/// rate limiting, timing attack resistance and token claim correctness are not applicable to it. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointTests : IClassFixture +{ + private readonly LuminaWebFactory _apiFactory; + private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + /// Injected Web application factory. + public UpdatePlaybackStateEndpointTests(LuminaWebFactory apiFactory) + { + _apiFactory = apiFactory; + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledWithoutAuthentication_ShouldRedirectToLogin() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory); + string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state") + { + Content = JsonContent.Create(_playbackStateDtoFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", antiforgeryToken); + + // Act + HttpResponseMessage response = await client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString()); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings/playback-state"); + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state") + { + Content = JsonContent.Create(_playbackStateDtoFixture.Create()) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + + // Assert + Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); + Assert.DoesNotContain(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == "users/me/settings/playback-state"); + } + + [Fact] + public async Task UpdatePlaybackState_WhenCalledByAuthenticatedUser_ShouldNotLeakSensitiveData() + { + // Arrange + _apiFactory.ApiClientStub.Reset(); + _apiFactory.ApiClientStub.RegisterPutResponseFactory("users/me/settings/playback-state", _ => new EmptyRequest()); + AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory); + PlaybackStateDto state = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); + HttpRequestMessage updateRequest = new(HttpMethod.Post, "/en-us/tools/settings/api-update-playback-state") + { + Content = JsonContent.Create(state) + }; + updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json"); + updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken); + + // Act + HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest); + string content = await response.Content.ReadAsStringAsync(); + + // Assert + response.EnsureSuccessStatusCode(); + Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistEntriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistEntriesRequestMappingTests.cs new file mode 100644 index 00000000..7e923bb2 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistEntriesRequestMappingTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesRequestMappingTests +{ + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + + [Fact] + public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveTheTrackOrderAndThePlaylistId() + { + // Arrange + List trackIds = [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]; + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: trackIds); + + // Act + AddPlaylistEntriesCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Equal("playlist-id", command.PlaylistId); + Assert.NotNull(command.TrackIds); + Assert.Equal(trackIds, command.TrackIds); + } + + [Fact] + public void ToCommand_WhenTrackIdsAreNull_ShouldPreserveNull() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(includeTrackIds: false); + + // Act + AddPlaylistEntriesCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Null(command.TrackIds); + Assert.Equal("playlist-id", command.PlaylistId); + } + + [Fact] + public void ToCommand_WhenPlaylistIdIsNull_ShouldPreserveNull() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + + // Act + AddPlaylistEntriesCommand command = request.ToCommand(null); + + // Assert + Assert.Null(command.PlaylistId); + Assert.NotNull(command.TrackIds); + } + + [Fact] + public void ToCommand_WhenPlaylistIdIsEmpty_ShouldPreserveEmpty() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + + // Act + AddPlaylistEntriesCommand command = request.ToCommand(string.Empty); + + // Assert + Assert.Equal(string.Empty, command.PlaylistId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistEntryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistEntryRequestMappingTests.cs new file mode 100644 index 00000000..e0b77507 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistEntryRequestMappingTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryRequestMappingTests +{ + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + + [Fact] + public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveThem() + { + // Arrange + Guid trackId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + + // Act + AddPlaylistEntryCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Equal("playlist-id", command.PlaylistId); + Assert.Equal(trackId, command.TrackId); + } + + [Fact] + public void ToCommand_WhenTrackIdIsNull_ShouldPreserveNull() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(includeTrackId: false); + + // Act + AddPlaylistEntryCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Null(command.TrackId); + Assert.Equal("playlist-id", command.PlaylistId); + } + + [Fact] + public void ToCommand_WhenPlaylistIdIsNull_ShouldPreserveNull() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + + // Act + AddPlaylistEntryCommand command = request.ToCommand(null); + + // Assert + Assert.Null(command.PlaylistId); + Assert.NotNull(command.TrackId); + } + + [Fact] + public void ToCommand_WhenPlaylistIdIsEmpty_ShouldPreserveEmpty() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + + // Act + AddPlaylistEntryCommand command = request.ToCommand(string.Empty); + + // Assert + Assert.Equal(string.Empty, command.PlaylistId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMappingTests.cs new file mode 100644 index 00000000..484121a8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/AddPlaylistScopeEntriesRequestMappingTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesRequestMappingTests +{ + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + + [Fact] + public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveThem() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + artistId: artistId, + albumId: albumId, + includeArtistId: true, + includeAlbumId: true); + + // Act + AddPlaylistScopeEntriesCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Equal("playlist-id", command.PlaylistId); + Assert.Equal(libraryId, command.LibraryId); + Assert.Equal(artistId, command.ArtistId); + Assert.Equal(albumId, command.AlbumId); + } + + [Fact] + public void ToCommand_WhenArtistAndAlbumAreOmitted_ShouldPreserveThemAsNull() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(libraryId: libraryId); + + // Act + AddPlaylistScopeEntriesCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Equal(libraryId, command.LibraryId); + Assert.Null(command.ArtistId); + Assert.Null(command.AlbumId); + } + + [Fact] + public void ToCommand_WhenPlaylistIdIsNull_ShouldPreserveNull() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + + // Act + AddPlaylistScopeEntriesCommand command = request.ToCommand(null); + + // Assert + Assert.Null(command.PlaylistId); + Assert.NotNull(command.LibraryId); + } + + [Fact] + public void ToCommand_WhenPlaylistIdIsEmpty_ShouldPreserveEmpty() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + + // Act + AddPlaylistScopeEntriesCommand command = request.ToCommand(string.Empty); + + // Assert + Assert.Equal(string.Empty, command.PlaylistId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/CreatePlaylistRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/CreatePlaylistRequestMappingTests.cs new file mode 100644 index 00000000..35745d11 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/CreatePlaylistRequestMappingTests.cs @@ -0,0 +1,68 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistRequestMappingTests +{ + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + + [Fact] + public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveThem() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create( + name: "Focus", + description: "Deep work", + type: PlaylistType.Music); + + // Act + CreatePlaylistCommand command = request.ToCommand(); + + // Assert + Assert.Equal("Focus", command.Name); + Assert.Equal("Deep work", command.Description); + Assert.Equal(PlaylistType.Music, command.Type); + } + + [Fact] + public void ToCommand_WhenTheOptionalMembersAreOmitted_ShouldPreserveThemAsNull() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create( + name: "Focus", + includeDescription: false, + includeType: false); + + // Act + CreatePlaylistCommand command = request.ToCommand(); + + // Assert + Assert.Equal("Focus", command.Name); + Assert.Null(command.Description); + Assert.Null(command.Type); + } + + [Fact] + public void ToCommand_WhenTheNameIsNull_ShouldPreserveNull() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeName: false); + + // Act + CreatePlaylistCommand command = request.ToCommand(); + + // Assert + Assert.Null(command.Name); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/MovePlaylistEntryRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/MovePlaylistEntryRequestMappingTests.cs new file mode 100644 index 00000000..bd2d06d6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/MovePlaylistEntryRequestMappingTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryRequestMappingTests +{ + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + + [Fact] + public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveThem() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 7); + + // Act + MovePlaylistEntryCommand command = request.ToCommand("playlist-id", "entry-id"); + + // Assert + Assert.Equal("playlist-id", command.PlaylistId); + Assert.Equal("entry-id", command.PlaylistEntryId); + Assert.Equal(7, command.TargetPosition); + } + + [Fact] + public void ToCommand_WhenTargetPositionIsNull_ShouldPreserveNull() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(includeTargetPosition: false); + + // Act + MovePlaylistEntryCommand command = request.ToCommand("playlist-id", "entry-id"); + + // Assert + Assert.Null(command.TargetPosition); + Assert.Equal("playlist-id", command.PlaylistId); + Assert.Equal("entry-id", command.PlaylistEntryId); + } + + [Fact] + public void ToCommand_WhenTheRouteIdentifiersAreNull_ShouldPreserveNull() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + + // Act + MovePlaylistEntryCommand command = request.ToCommand(null, null); + + // Assert + Assert.Null(command.PlaylistId); + Assert.Null(command.PlaylistEntryId); + Assert.NotNull(command.TargetPosition); + } + + [Fact] + public void ToCommand_WhenTheRouteIdentifiersAreEmpty_ShouldPreserveEmpty() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + + // Act + MovePlaylistEntryCommand command = request.ToCommand(string.Empty, string.Empty); + + // Assert + Assert.Equal(string.Empty, command.PlaylistId); + Assert.Equal(string.Empty, command.PlaylistEntryId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntityMappingTests.cs new file mode 100644 index 00000000..49ef25ea --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntityMappingTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntityMappingTests +{ + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + + [Fact] + public void ToDomainEntity_WhenUpdatedOnUtcIsPresent_ShouldMapEveryField() + { + // Arrange + Guid id = Guid.NewGuid(); + Guid userId = Guid.NewGuid(); + DateTime createdOnUtc = new(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc); + DateTime updatedOnUtc = new(2024, 2, 3, 4, 5, 6, DateTimeKind.Utc); + PlaylistEntity entity = _playlistEntityFixture.Create( + id: id, + userId: userId, + name: "Focus", + description: "Deep work", + type: PlaylistType.Music, + createdOnUtc: createdOnUtc, + includeUpdatedOnUtc: true, + updatedOnUtc: updatedOnUtc); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Playlist playlist = result.Value; + Assert.Equal(id, playlist.Id.Value); + Assert.Equal(userId, playlist.UserId.Value); + Assert.Equal("Focus", playlist.Name); + Assert.True(playlist.Description.HasValue); + Assert.Equal("Deep work", playlist.Description.Value); + Assert.Equal(PlaylistType.Music, playlist.Type); + Assert.Equal(createdOnUtc, playlist.CreatedOnUtc); + Assert.True(playlist.UpdatedOnUtc.HasValue); + Assert.Equal(updatedOnUtc, playlist.UpdatedOnUtc.Value); + Assert.False(playlist.IsDeleted); + Assert.Empty(playlist.Entries); + } + + [Fact] + public void ToDomainEntity_WhenTheDescriptionAndUpdatedOnUtcAreMissing_ShouldMapNoValuesForThem() + { + // Arrange + PlaylistEntity entity = _playlistEntityFixture.Create( + includeDescription: false, + includeUpdatedOnUtc: false); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Description.HasValue); + Assert.False(result.Value.UpdatedOnUtc.HasValue); + } + + [Fact] + public void ToDomainEntity_WhenTheStoredEntriesAreOutOfOrder_ShouldOrderThemByTheirPosition() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + PlaylistEntryEntity lastEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 900, mediaItemType: PlaylistMediaItemType.MusicTrack); + PlaylistEntryEntity firstEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 100, mediaItemType: PlaylistMediaItemType.MusicTrack); + PlaylistEntryEntity middleEntry = _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 500, mediaItemType: PlaylistMediaItemType.MusicTrack); + PlaylistEntity entity = _playlistEntityFixture.Create( + id: playlistId, + entries: [lastEntry, firstEntry, middleEntry]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([100L, 500L, 900L], result.Value.Entries.Select(entry => entry.Position)); + Assert.Equal([firstEntry.Id, middleEntry.Id, lastEntry.Id], result.Value.Entries.Select(entry => entry.Id.Value)); + } + + [Fact] + public void ToDomainEntity_WhenTwoStoredEntriesShareAPosition_ShouldReturnThePositionsError() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + PlaylistEntity entity = _playlistEntityFixture.Create( + id: playlistId, + entries: + [ + _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 256, mediaItemType: PlaylistMediaItemType.MusicTrack), + _playlistEntryEntityFixture.Create(playlistId: playlistId, position: 256, mediaItemType: PlaylistMediaItemType.MusicTrack), + ]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playlists.PlaylistEntryPositionsAreInvalid, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenAStoredEntryReferencesAMediaItemThePlaylistCannotContain_ShouldReturnTheMediaItemsError() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + PlaylistEntity entity = _playlistEntityFixture.Create( + id: playlistId, + type: PlaylistType.Music, + entries: [_playlistEntryEntityFixture.Create(playlistId: playlistId, mediaItemType: PlaylistMediaItemType.VideoFile)]); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playlists.PlaylistDoesNotAcceptMediaItems, result.FirstError); + } + + [Fact] + public void ToDomainEntity_WhenRehydrating_ShouldRaiseNoDomainEvents() + { + // Arrange + PlaylistEntity entity = _playlistEntityFixture.Create(); + entity.Entries = [_playlistEntryEntityFixture.Create(playlistId: entity.Id, mediaItemType: PlaylistMediaItemType.MusicTrack)]; + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value.GetDomainEvents()); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryDtoMappingTests.cs index c51372bb..000e48d0 100644 --- a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryDtoMappingTests.cs +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryDtoMappingTests.cs @@ -112,10 +112,10 @@ public class PlaylistEntryDtoMappingTests // Assert Assert.Equal(3, response.Data.Count); - Assert.Equal( + Assert.Equal( entries.Select(entry => entry.Entry.Id), response.Data.Select(entry => entry.Id)); - Assert.Equal([0, 1, 2], response.Data.Select(entry => entry.Position)); + Assert.Equal([0, 1, 2], response.Data.Select(entry => entry.Position)); Assert.Equal(2, response.CurrentPage); Assert.Equal(3, response.PerPage); Assert.Equal(7, response.Count); diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryEntityMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryEntityMappingTests.cs new file mode 100644 index 00000000..2ac616bf --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryEntityMappingTests.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryEntityMappingTests +{ + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + + [Fact] + public void ToDomainEntity_WhenMappingTheEntity_ShouldMapEveryField() + { + // Arrange + Guid id = Guid.NewGuid(); + Guid mediaItemId = Guid.NewGuid(); + PlaylistEntryEntity entity = _playlistEntryEntityFixture.Create( + id: id, + mediaItemId: mediaItemId, + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: 4_096); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + PlaylistEntry entry = result.Value; + Assert.Equal(id, entry.Id.Value); + Assert.Equal(mediaItemId, entry.MediaItemId.Value); + Assert.Equal(PlaylistMediaItemType.MusicTrack, entry.MediaItemType); + Assert.Equal(4_096, entry.Position); + } + + [Fact] + public void ToDomainEntity_WhenTheStoredMediaItemTypeIsNotAcceptedByAnyPlaylistToday_ShouldStillRehydrateIt() + { + // Arrange + PlaylistEntryEntity entity = _playlistEntryEntityFixture.Create(mediaItemType: PlaylistMediaItemType.VideoFile); + + // Act + Result result = entity.ToDomainEntity(); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(PlaylistMediaItemType.VideoFile, result.Value.MediaItemType); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryMappingTests.cs new file mode 100644 index 00000000..042ba832 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistEntryMappingTests.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryMappingTests +{ + private readonly PlaylistEntryFixture _playlistEntryFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingTheDomainEntry_ShouldMapEveryFieldIncludingTheOwnerPlaylist() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + PlaylistEntry entry = _playlistEntryFixture.Create( + mediaItemType: PlaylistMediaItemType.MusicTrack, + position: 1_024); + + // Act + PlaylistEntryEntity result = entry.ToRepositoryEntity(playlistId); + + // Assert + Assert.Equal(entry.Id.Value, result.Id); + Assert.Equal(playlistId, result.PlaylistId); + Assert.Equal(entry.MediaItemId.Value, result.MediaItemId); + Assert.Equal(PlaylistMediaItemType.MusicTrack, result.MediaItemType); + Assert.Equal(1_024, result.Position); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistMappingTests.cs new file mode 100644 index 00000000..c81632fb --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistMappingTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistMappingTests +{ + private readonly PlaylistFixture _playlistFixture = new(); + private readonly PlaylistEntryFixture _playlistEntryFixture = new(); + + [Fact] + public void ToRepositoryEntity_WhenMappingTheAggregate_ShouldMapEveryScalar() + { + // Arrange + DateTime createdOnUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc); + DateTime updatedOnUtc = new(2024, 4, 5, 6, 7, 8, DateTimeKind.Utc); + Playlist playlist = _playlistFixture.Create( + name: "Focus", + description: "Deep work", + type: PlaylistType.Music, + createdOnUtc: createdOnUtc, + updatedOnUtc: updatedOnUtc, + includeUpdatedOnUtc: true); + + // Act + PlaylistEntity result = playlist.ToRepositoryEntity(); + + // Assert + Assert.Equal(playlist.Id.Value, result.Id); + Assert.Equal(playlist.UserId.Value, result.UserId); + Assert.Equal("Focus", result.Name); + Assert.Equal("Deep work", result.Description); + Assert.Equal(PlaylistType.Music, result.Type); + Assert.Equal(createdOnUtc, result.CreatedOnUtc); + Assert.Equal(updatedOnUtc, result.UpdatedOnUtc); + Assert.Equal(Guid.Empty, result.CreatedBy); + Assert.Null(result.UpdatedBy); + } + + [Fact] + public void ToRepositoryEntity_WhenTheDescriptionAndUpdatedOnUtcAreMissing_ShouldMapNulls() + { + // Arrange + Playlist playlist = _playlistFixture.Create( + includeDescription: false, + includeUpdatedOnUtc: false); + + // Act + PlaylistEntity result = playlist.ToRepositoryEntity(); + + // Assert + Assert.Null(result.Description); + Assert.Null(result.UpdatedOnUtc); + } + + [Fact] + public void ToRepositoryEntity_WhenTheAggregateHasEntries_ShouldMapThemOrderedByPositionAndCountThem() + { + // Arrange + PlaylistEntry lastEntry = _playlistEntryFixture.Create(position: 900); + PlaylistEntry firstEntry = _playlistEntryFixture.Create(position: 100); + List entries = [lastEntry, firstEntry]; + Playlist playlist = _playlistFixture.Create(entries: entries); + + // Act + PlaylistEntity result = playlist.ToRepositoryEntity(); + + // Assert + Assert.Equal(2, result.EntryCount); + Assert.Equal([100L, 900L], result.Entries.Select(entry => entry.Position)); + Assert.Equal([firstEntry.Id.Value, lastEntry.Id.Value], result.Entries.Select(entry => entry.Id)); + Assert.All(result.Entries, entry => Assert.Equal(playlist.Id.Value, entry.PlaylistId)); + } + + [Fact] + public void ToRepositoryEntity_WhenTheAggregateHasNoEntries_ShouldMapAnEmptyCollectionAndAZeroCount() + { + // Arrange + Playlist playlist = _playlistFixture.Create(); + + // Act + PlaylistEntity result = playlist.ToRepositoryEntity(); + + // Assert + Assert.Empty(result.Entries); + Assert.Equal(0, result.EntryCount); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistSummaryDtoMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistSummaryDtoMappingTests.cs new file mode 100644 index 00000000..81cd602a --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/PlaylistSummaryDtoMappingTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Fixtures.Common.DTO.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistSummaryDtoMappingTests +{ + private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new(); + + [Fact] + public void ToResponse_WhenMappingTheSummary_ShouldMapEveryField() + { + // Arrange + Guid id = Guid.NewGuid(); + DateTime createdOnUtc = new(2024, 5, 6, 7, 8, 9, DateTimeKind.Utc); + DateTime updatedOnUtc = new(2024, 6, 7, 8, 9, 10, DateTimeKind.Utc); + PlaylistSummaryDto dto = _playlistSummaryDtoFixture.Create( + id: id, + name: "Commute", + description: "Train rides", + type: PlaylistType.Music, + entryCount: 37, + createdOnUtc: createdOnUtc, + updatedOnUtc: updatedOnUtc, + includeUpdatedOnUtc: true); + + // Act + PlaylistSummaryResponse response = dto.ToResponse(); + + // Assert + Assert.Equal(id, response.Id); + Assert.Equal("Commute", response.Name); + Assert.Equal("Train rides", response.Description); + Assert.Equal(PlaylistType.Music, response.Type); + Assert.Equal(37, response.EntryCount); + Assert.Equal(createdOnUtc, response.CreatedOnUtc); + Assert.True(response.UpdatedOnUtc.HasValue); + Assert.Equal(updatedOnUtc, response.UpdatedOnUtc.Value); + } + + [Fact] + public void ToResponse_WhenTheOptionalMembersAreMissing_ShouldMapNulls() + { + // Arrange + PlaylistSummaryDto dto = _playlistSummaryDtoFixture.Create( + includeDescription: false, + includeUpdatedOnUtc: false); + + // Act + PlaylistSummaryResponse response = dto.ToResponse(); + + // Assert + Assert.Null(response.Description); + Assert.Null(response.UpdatedOnUtc); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/UpdatePlaylistRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/UpdatePlaylistRequestMappingTests.cs new file mode 100644 index 00000000..5bf1e866 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/Playlists/UpdatePlaylistRequestMappingTests.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.Playlists; +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Requests.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.Playlists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistRequestMappingTests +{ + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + + [Fact] + public void ToCommand_WhenEveryMemberIsSupplied_ShouldPreserveThem() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create( + name: "Deep Focus", + description: "Long sessions"); + + // Act + UpdatePlaylistCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Equal("playlist-id", command.PlaylistId); + Assert.Equal("Deep Focus", command.Name); + Assert.Equal("Long sessions", command.Description); + } + + [Fact] + public void ToCommand_WhenTheOptionalMembersAreOmitted_ShouldPreserveThemAsNull() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create( + name: "Deep Focus", + includeDescription: false); + + // Act + UpdatePlaylistCommand command = request.ToCommand("playlist-id"); + + // Assert + Assert.Equal("Deep Focus", command.Name); + Assert.Null(command.Description); + } + + [Fact] + public void ToCommand_WhenThePlaylistIdIsNull_ShouldPreserveNull() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + + // Act + UpdatePlaylistCommand command = request.ToCommand(null); + + // Assert + Assert.Null(command.PlaylistId); + Assert.NotNull(command.Name); + } + + [Fact] + public void ToCommand_WhenThePlaylistIdIsEmpty_ShouldPreserveEmpty() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + + // Act + UpdatePlaylistCommand command = request.ToCommand(string.Empty); + + // Assert + Assert.Equal(string.Empty, command.PlaylistId); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMappingTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMappingTests.cs new file mode 100644 index 00000000..29a90003 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Common/Mapping/UsersManagement/Users/UpdatePlaybackStateRequestMappingTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.Mapping.UsersManagement.Users; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Common.Mapping.UsersManagement.Users; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateRequestMappingTests +{ + private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new(); + + [Fact] + public void ToCommand_WhenMappingValidRequest_ShouldMapCorrectly() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true); + + // Act + UpdatePlaybackStateCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Equal(0.35, result.Volume); + Assert.True(result.IsMuted); + } + + [Fact] + public void ToCommand_WhenRequestHasNullValues_ShouldPreserveTheNulls() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeVolume: false, includeIsMuted: false); + + // Act + UpdatePlaybackStateCommand result = request.ToCommand(); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Volume); + Assert.Null(result.IsMuted); + } + + [Theory] + [InlineData(0.0, false)] // the minimum volume, not muted + [InlineData(1.0, true)] // the maximum volume, muted + public void ToCommand_WhenMappingBoundaryValues_ShouldMapThemExactly(double volume, bool isMuted) + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: volume, isMuted: isMuted); + + // Act + UpdatePlaybackStateCommand result = request.ToCommand(); + + // Assert + Assert.Equal(volume, result.Volume); + Assert.Equal(isMuted, result.IsMuted); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidatorTests.cs new file mode 100644 index 00000000..7b11fd93 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetPlaybackManifest/GetPlaybackManifestQueryValidatorTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetPlaybackManifest; +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.GetPlaybackManifest; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackManifestQueryValidatorTests +{ + private readonly GetPlaybackManifestQueryFixture _getPlaybackManifestQueryFixture = new(); + private readonly GetPlaybackManifestQueryValidator _validator = new(); + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveLibraryIdError(string? libraryId) + { + // Arrange + GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveArtistIdError(string? artistId) + { + // Arrange + GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveAlbumIdError(string? albumId) + { + // Arrange + GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-a-track-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveTrackIdError(string? trackId) + { + // Arrange + GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create(trackId: trackId, includeTrackId: trackId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenSeveralFieldsAreInvalid_ShouldReportEachSpecificError() + { + // Arrange + GetPlaybackManifestQuery query = _getPlaybackManifestQueryFixture.Create( + libraryId: "not-a-library-guid", + artistId: null, + includeArtistId: false, + albumId: Guid.Empty.ToString(), + trackId: "not-a-track-guid"); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + Assert.Equal(4, result.Count); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandlerTests.cs new file mode 100644 index 00000000..4b2558cd --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryHandlerTests.cs @@ -0,0 +1,399 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary; +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.GetTrackStream; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.FileSystemManagementBoundedContext.FileSystemManagementAggregate.Services; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +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.GetTrackStream; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamQueryHandlerTests : IDisposable +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ITrackRepository _mockTrackRepository; + private readonly ILibraryRepository _mockLibraryRepository; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IPathService _mockPathService; + private readonly IValidator _mockValidator; + private readonly GetTrackStreamQueryHandler _sut; + private readonly Guid _userId; + private readonly string _contentRoot; + private readonly GetTrackStreamQueryFixture _getTrackStreamQueryFixture = new(); + private readonly TrackStreamDtoFixture _trackStreamDtoFixture = new(); + private readonly LibraryEntityFixture _libraryEntityFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetTrackStreamQueryHandlerTests() + { + _mockTrackRepository = Substitute.For(); + _mockLibraryRepository = Substitute.For(); + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockUnitOfWork.LibraryRepository.Returns(_mockLibraryRepository); + _mockAuthorizationService = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockPathService = Substitute.For(); + _mockValidator = Substitute.For>(); + _userId = Guid.NewGuid(); + _contentRoot = Path.Combine(Path.GetTempPath(), "lumina-track-stream-handler-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_contentRoot); + + // Default stubs: the user is authenticated, the library ownership policy allows access, the query validates and every path is inside its content location. + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Any()) + .Returns(true); + _mockValidator.Validate(Arg.Any()).Returns([]); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(true); + + _sut = new GetTrackStreamQueryHandler( + _mockUnitOfWork, + _mockAuthorizationService, + _mockCurrentUserService, + _mockPathService, + _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsWithoutReadingAnything() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + _mockValidator.Validate(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); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetTrackStreamInfoAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUserIsNotAuthenticated_ShouldReturnNotAuthorizedWithoutEvaluatingPolicies() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.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()); + } + + [Fact] + public async Task HandleAsync_WhenLibraryOwnershipIsDenied_ShouldReturnNotAuthorizedWithoutLookingUpTheTrack() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + _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 _mockTrackRepository.DidNotReceive().GetTrackStreamInfoAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheTrackLookupFails_ShouldReturnItsError() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + _mockTrackRepository.GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + Arg.Any()) + .Returns(Errors.Music.TrackFileNotFound); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheTrackIsNotFound_ShouldReturnTrackNotFoundError() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + _mockTrackRepository.GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + await _mockLibraryRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheRouteIdentifiersDoNotAddressTheTrack_ShouldLookThemUpExactlyAndReturnTrackNotFound() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + _mockTrackRepository.GetTrackStreamInfoAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackNotFound, result.FirstError); + await _mockTrackRepository.Received(1).GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheLibraryLookupFails_ShouldReturnItsError() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + TrackStreamDto track = _trackStreamDtoFixture.Create(path: Path.Combine(_contentRoot, "track.flac"), libraryId: Guid.Parse(query.LibraryId!)); + StubTrackLookup(query, track); + _mockLibraryRepository.GetByIdAsync(track.LibraryId, shouldTrackEntities: false, cancellationToken: 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_WhenTheLibraryIsNotFound_ShouldReturnLibraryNotFoundError() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + TrackStreamDto track = _trackStreamDtoFixture.Create(path: Path.Combine(_contentRoot, "track.flac"), libraryId: Guid.Parse(query.LibraryId!)); + StubTrackLookup(query, track); + _mockLibraryRepository.GetByIdAsync(track.LibraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Library.LibraryNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenTheFileIsOutsideEveryContentLocation_ShouldReturnTrackFileNotFoundWithoutLeakingThePath() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + string trackPath = Path.Combine(_contentRoot, "track.flac"); + await File.WriteAllBytesAsync(trackPath, new byte[64]); + TrackStreamDto track = _trackStreamDtoFixture.Create(path: trackPath, libraryId: Guid.Parse(query.LibraryId!)); + StubTrackLookup(query, track); + StubLibrary(track.LibraryId, Path.Combine(_contentRoot, "elsewhere")); + _mockPathService.IsPathWithin(Arg.Any(), Arg.Any()).Returns(false); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError); + Assert.DoesNotContain(trackPath, result.FirstError.Description, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task HandleAsync_WhenTheFileDoesNotExist_ShouldReturnTrackFileNotFound() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + string trackPath = Path.Combine(_contentRoot, "missing-track.flac"); + TrackStreamDto track = _trackStreamDtoFixture.Create(path: trackPath, libraryId: Guid.Parse(query.LibraryId!)); + StubTrackLookup(query, track); + StubLibrary(track.LibraryId, _contentRoot); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Music.TrackFileNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenTheFileExists_ShouldReturnItsStreamData() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + string trackPath = Path.Combine(_contentRoot, "track.flac"); + byte[] audioBytes = [1, 2, 3, 4, 5, 6, 7, 8]; + await File.WriteAllBytesAsync(trackPath, audioBytes); + DateTime expectedLastModifiedUtc = new(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc); + File.SetLastWriteTimeUtc(trackPath, expectedLastModifiedUtc); + DateTime resolvedLastModifiedUtc = File.GetLastWriteTimeUtc(trackPath); + TrackStreamDto track = _trackStreamDtoFixture.Create(path: trackPath, libraryId: Guid.Parse(query.LibraryId!)); + StubTrackLookup(query, track); + StubLibrary(track.LibraryId, _contentRoot); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(trackPath, result.Value.Path); + Assert.Equal(AudioFileFormat.FLAC, result.Value.Format); + Assert.Equal(audioBytes.Length, result.Value.Length); + Assert.Equal(resolvedLastModifiedUtc, result.Value.LastModified.UtcDateTime); + _mockPathService.Received(1).IsPathWithin(trackPath, _contentRoot); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldForwardTheRouteIdentifiersAndCancellationToken() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + TrackStreamDto track = _trackStreamDtoFixture.Create(path: Path.Combine(_contentRoot, "track.flac"), libraryId: Guid.Parse(query.LibraryId!)); + _mockTrackRepository.GetTrackStreamInfoAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(track)); + StubLibrary(track.LibraryId, _contentRoot); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockTrackRepository.Received(1).GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + Arg.Is(cancellationToken)); + await _mockLibraryRepository.Received(1).GetByIdAsync(track.LibraryId, shouldTrackEntities: false, cancellationToken: cancellationToken); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, + Arg.Is(context => context.LibraryId == Guid.Parse(query.LibraryId!)), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenCancellationIsRequested_ShouldCancelTheOperation() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockTrackRepository.GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + cancellationTokenSource.Token) + .Returns(Task.FromCanceled>(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.HandleAsync(query, cancellationTokenSource.Token)); + await _mockTrackRepository.Received(1).GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + cancellationTokenSource.Token); + } + + /// + /// Stubs the track projection lookup of the query's route with the provided track. + /// + /// The query whose route identifiers are looked up. + /// The track projection the lookup returns. + private void StubTrackLookup(GetTrackStreamQuery query, TrackStreamDto track) + { + _mockTrackRepository.GetTrackStreamInfoAsync( + Guid.Parse(query.LibraryId!), + Guid.Parse(query.AlbumId!), + Guid.Parse(query.ArtistId!), + Guid.Parse(query.TrackId!), + Arg.Any()) + .Returns(Result.From(track)); + } + + /// + /// Stubs the library lookup with a library whose single content location is the provided path. + /// + /// The Id of the library the lookup returns. + /// The content location of the returned library. + private void StubLibrary(Guid libraryId, string contentLocation) + { + LibraryEntity library = _libraryEntityFixture.Create(id: libraryId, contentLocations: [contentLocation]); + _mockLibraryRepository.GetByIdAsync(libraryId, shouldTrackEntities: false, cancellationToken: Arg.Any()) + .Returns(Result.From(library)); + } + + /// + /// Releases the temporary directory the file tests use. + /// + public void Dispose() + { + try + { + if (Directory.Exists(_contentRoot)) + Directory.Delete(_contentRoot, recursive: true); + } + catch (IOException) + { + // A temporary directory that cannot be removed does not fail the test. + } + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidatorTests.cs new file mode 100644 index 00000000..6337b12c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/MediaLibrary/AudioLibrary/MusicLibrary/Tracks/Queries/GetTrackStream/GetTrackStreamQueryValidatorTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +using Lumina.Application.Fixtures.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +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.GetTrackStream; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamQueryValidatorTests +{ + private readonly GetTrackStreamQueryFixture _getTrackStreamQueryFixture = new(); + private readonly GetTrackStreamQueryValidator _validator = new(); + + [Fact] + public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-a-library-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveLibraryIdError(string? libraryId) + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(libraryId: libraryId, includeLibraryId: libraryId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-an-artist-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenArtistIdIsEmptyOrInvalid_ShouldHaveArtistIdError(string? artistId) + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(artistId: artistId, includeArtistId: artistId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-an-album-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenAlbumIdIsEmptyOrInvalid_ShouldHaveAlbumIdError(string? albumId) + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(albumId: albumId, includeAlbumId: albumId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Theory] + [InlineData(null)] // missing route value + [InlineData("")] // empty route value + [InlineData(" ")] // whitespace route value + [InlineData("not-a-track-guid")] // non-Guid route value + [InlineData("00000000-0000-0000-0000-000000000000")] // empty Guid route value + public void Validate_WhenTrackIdIsEmptyOrInvalid_ShouldHaveTrackIdError(string? trackId) + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create(trackId: trackId, includeTrackId: trackId is not null); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenSeveralFieldsAreInvalid_ShouldReportEachSpecificError() + { + // Arrange + GetTrackStreamQuery query = _getTrackStreamQueryFixture.Create( + libraryId: "not-a-library-guid", + artistId: null, + includeArtistId: false, + albumId: Guid.Empty.ToString(), + trackId: "not-a-track-guid"); + + // Act + List result = _validator.TestValidate(query); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + Assert.Equal(4, result.Count); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandlerTests.cs new file mode 100644 index 00000000..332100b0 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandHandlerTests.cs @@ -0,0 +1,330 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Application.Fixtures.Common.DTO.Playlists; +using Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.AddPlaylistEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IValidator _mockValidator; + private readonly AddPlaylistEntriesCommandHandler _sut; + private readonly AddPlaylistEntriesCommandFixture _addPlaylistEntriesCommandFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistBulkAddResultDtoFixture _playlistBulkAddResultDtoFixture = new(); + private readonly TrackAccessSummaryDtoFixture _trackAccessSummaryDtoFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + private readonly Guid _libraryId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(true); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: PlaylistType.Music))); + _mockTrackRepository.GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(callInfo => Result.From(_trackAccessSummaryDtoFixture.Create( + trackCount: callInfo.ArgAt>(0).Count, + libraryIds: [_libraryId]))); + _mockPlaylistRepository.AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 3))); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new AddPlaylistEntriesCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + Error error = DomainErrors.Music.TrackIdCannotBeEmpty; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadThePlaylist() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistReadFails_ShouldReturnThatErrorAndNotResolveTheTracks() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be read."); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistDoesNotExistForTheUser_ShouldReturnPlaylistNotFoundAndNotResolveTheTracks() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheTrackAccessLookupFails_ShouldReturnThatErrorAndNotAuthorize() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The tracks could not be read."); + _mockTrackRepository.GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAtLeastOneOfTheTracksDoesNotExist_ShouldReturnTrackNotFoundAndNotAuthorize() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(trackCount: 3); + _mockTrackRepository.GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(_trackAccessSummaryDtoFixture.Create(trackCount: 2, libraryIds: [_libraryId]))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenOneOfTheLibrariesIsNotAccessible_ShouldReturnTrackNotFoundAndNotAppendTheEntries() + { + // Arrange + Guid deniedLibraryId = Guid.NewGuid(); + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + _mockTrackRepository.GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(_trackAccessSummaryDtoFixture.Create(libraryIds: [_libraryId, deniedLibraryId]))); + _mockAuthorizationService.EvaluatePolicyAsync( + _userId, + Arg.Is(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == deniedLibraryId), + Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistCannotContainTracks_ShouldReturnPlaylistDoesNotAcceptMediaItemsAndNotAppendTheEntries() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: (PlaylistType)999))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAppendingTheEntriesFails_ShouldReturnThatError() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The entries could not be appended."); + _mockPlaylistRepository.AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldLookUpDistinctTracksAndAppendEveryRequestedTrackInOrder() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid repeatedTrackId = Guid.NewGuid(); + Guid otherTrackId = Guid.NewGuid(); + List trackIds = [repeatedTrackId, otherTrackId, repeatedTrackId]; + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create( + playlistId: playlistId.ToString(), + trackIds: trackIds); + _mockPlaylistRepository.AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 3))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(playlistId, result.Value.PlaylistId); + Assert.Equal(3, result.Value.AddedCount); + Assert.NotNull(result.Value.UpdatedOnUtc); + Assert.InRange(result.Value.UpdatedOnUtc!.Value, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow); + await _mockTrackRepository.Received(1).GetAccessInfoByIdsAsync( + Arg.Is>(distinctTrackIds => distinctTrackIds.Count == 2 && distinctTrackIds.Contains(repeatedTrackId) && distinctTrackIds.Contains(otherTrackId)), + Arg.Any()); + await _mockPlaylistRepository.Received(1).AddEntriesAsync( + playlistId, + _userId, + Arg.Is>(mediaItemIds => mediaItemIds.SequenceEqual(trackIds)), + PlaylistMediaItemType.MusicTrack, + Arg.Is?>(entryIds => entryIds == null), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSeveralTracksShareOneLibrary_ShouldEvaluateTheLibraryPolicyOnce() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(trackCount: 4); + _mockTrackRepository.GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Any()) + .Returns(Result.From(_trackAccessSummaryDtoFixture.Create(trackCount: 4, libraryIds: [_libraryId]))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, + Arg.Is(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == _libraryId), + Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldScopeEveryRepositoryAndPolicyCallToTheCurrentUserAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(playlistId: playlistId.ToString()); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).GetByIdForUserAsync(playlistId, _userId, false, false, Arg.Is(cancellationToken)); + await _mockTrackRepository.Received(1).GetAccessInfoByIdsAsync(Arg.Any>(), Arg.Is(cancellationToken)); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync(_userId, Arg.Any(), Arg.Is(cancellationToken)); + await _mockPlaylistRepository.Received(1).AddEntriesAsync( + playlistId, _userId, Arg.Any>(), PlaylistMediaItemType.MusicTrack, Arg.Any?>(), Arg.Any(), Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidatorTests.cs new file mode 100644 index 00000000..7dbbad45 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntries/AddPlaylistEntriesCommandValidatorTests.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistEntries; +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.Playlists.Commands.AddPlaylistEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesCommandValidatorTests +{ + private readonly AddPlaylistEntriesCommandValidator _validator = new(); + private readonly AddPlaylistEntriesCommandFixture _addPlaylistEntriesCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdsAreNotSupplied_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(includeTrackIds: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdsAreEmpty_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(trackIds: []); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenOneTrackIdIsTheEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create( + trackIds: [Guid.NewGuid(), Guid.Empty]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenARepeatedTrackIsRequested_ShouldNotHaveAnyValidationError() + { + // Arrange + Guid repeatedTrackId = Guid.NewGuid(); + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create( + trackIds: [repeatedTrackId, repeatedTrackId]); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + AddPlaylistEntriesCommand command = _addPlaylistEntriesCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandlerTests.cs new file mode 100644 index 00000000..3b42cdc8 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandHandlerTests.cs @@ -0,0 +1,351 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DTO.Playlists; +using Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.AddPlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly ITrackRepository _mockTrackRepository; + private readonly IValidator _mockValidator; + private readonly AddPlaylistEntryCommandHandler _sut; + private readonly AddPlaylistEntryCommandFixture _addPlaylistEntryCommandFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new(); + private readonly PlaylistBulkAddResultDtoFixture _playlistBulkAddResultDtoFixture = new(); + private readonly TrackEntityFixture _trackEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + private readonly Guid _libraryId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + _mockTrackRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(true); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: PlaylistType.Music))); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackEntityFixture.Create(libraryId: _libraryId))); + _mockPlaylistRepository.AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 1))); + _mockPlaylistRepository.GetAppendedEntryDetailsForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryDtoFixture.Create(displayPosition: 0))); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new AddPlaylistEntryCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + Error error = DomainErrors.Playlists.PlaylistIdCannotBeEmpty; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadThePlaylist() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistReadFails_ShouldReturnThatErrorAndNotReadTheTrack() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be read."); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistDoesNotExistForTheUser_ShouldReturnPlaylistNotFoundAndNotReadTheTrack() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError); + await _mockTrackRepository.DidNotReceive().GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheTrackReadFails_ShouldReturnThatErrorAndNotAuthorize() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The track could not be read."); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheTrackDoesNotExist_ShouldReturnTrackNotFoundAndNotAuthorize() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + _mockTrackRepository.GetByIdAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheTrackLibraryIsNotAccessible_ShouldReturnTrackNotFoundAndNotAppendTheEntry() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + _mockAuthorizationService.EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Music.TrackNotFound, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().GetAppendedEntryDetailsForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistCannotContainTracks_ShouldReturnPlaylistDoesNotAcceptMediaItemsAndNotAppendTheEntry() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: (PlaylistType)999))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAppendingTheEntryFails_ShouldReturnThatErrorAndNotReadTheAppendedEntry() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The entry could not be appended."); + _mockPlaylistRepository.AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any?>(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().GetAppendedEntryDetailsForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheAppendedEntryReadFails_ShouldReturnThatError() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The appended entry could not be read."); + _mockPlaylistRepository.GetAppendedEntryDetailsForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenTheAppendedEntryIsMissing_ShouldReturnPlaylistEntryNotFound() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + _mockPlaylistRepository.GetAppendedEntryDetailsForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistEntryNotFound, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldAppendOneTrackEntryAndReturnTheReadBackEntryAndActivityTime() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create( + playlistId: playlistId.ToString(), + trackId: trackId); + PlaylistEntryDto appendedEntry = _playlistEntryDtoFixture.Create(displayPosition: 4); + _mockPlaylistRepository.GetAppendedEntryDetailsForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(appendedEntry)); + Guid generatedEntryId = Guid.Empty; + _mockPlaylistRepository.AddEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Do?>(entryIds => generatedEntryId = entryIds![0]), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 1))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(playlistId, result.Value.PlaylistId); + Assert.NotEqual(Guid.Empty, generatedEntryId); + Assert.Equal(appendedEntry.Entry.Id, result.Value.Entry.Id); + Assert.Equal(appendedEntry.DisplayPosition, result.Value.Entry.Position); + Assert.NotNull(result.Value.UpdatedOnUtc); + Assert.InRange(result.Value.UpdatedOnUtc!.Value, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow); + await _mockPlaylistRepository.Received(1).AddEntriesAsync( + playlistId, + _userId, + Arg.Is>(mediaItemIds => mediaItemIds.Count == 1 && mediaItemIds[0] == trackId), + PlaylistMediaItemType.MusicTrack, + Arg.Is?>(entryIds => entryIds != null && entryIds.Count == 1 && entryIds[0] == generatedEntryId), + Arg.Any(), + Arg.Any()); + await _mockPlaylistRepository.Received(1).GetAppendedEntryDetailsForUserAsync(playlistId, _userId, generatedEntryId, Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldScopeEveryRepositoryAndPolicyCallToTheCurrentUserAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create( + playlistId: playlistId.ToString(), + trackId: trackId); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).GetByIdForUserAsync(playlistId, _userId, false, false, Arg.Is(cancellationToken)); + await _mockTrackRepository.Received(1).GetByIdAsync(trackId, false, false, Arg.Is(cancellationToken)); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, + Arg.Is(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == _libraryId), + Arg.Is(cancellationToken)); + await _mockPlaylistRepository.Received(1).AddEntriesAsync( + playlistId, _userId, Arg.Any>(), PlaylistMediaItemType.MusicTrack, Arg.Any?>(), Arg.Any(), Arg.Is(cancellationToken)); + await _mockPlaylistRepository.Received(1).GetAppendedEntryDetailsForUserAsync(playlistId, _userId, Arg.Any(), Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidatorTests.cs new file mode 100644 index 00000000..5b57c57d --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistEntry/AddPlaylistEntryCommandValidatorTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistEntry; +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.Playlists.Commands.AddPlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryCommandValidatorTests +{ + private readonly AddPlaylistEntryCommandValidator _validator = new(); + private readonly AddPlaylistEntryCommandFixture _addPlaylistEntryCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(includeTrackId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTrackIdIsTheEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(trackId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.TrackIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + AddPlaylistEntryCommand command = _addPlaylistEntryCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandlerTests.cs new file mode 100644 index 00000000..3b878d60 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandHandlerTests.cs @@ -0,0 +1,276 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Authorization; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.Common.Base; +using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Common.DTO.Playlists; +using Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IAuthorizationService _mockAuthorizationService; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly IValidator _mockValidator; + private readonly AddPlaylistScopeEntriesCommandHandler _sut; + private readonly AddPlaylistScopeEntriesCommandFixture _addPlaylistScopeEntriesCommandFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistBulkAddResultDtoFixture _playlistBulkAddResultDtoFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + private readonly Guid _libraryId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockAuthorizationService = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockAuthorizationService.EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(true); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: PlaylistType.Music))); + _mockPlaylistRepository.AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 5))); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new AddPlaylistScopeEntriesCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + Error error = DomainErrors.Library.LibraryIdCannotBeEmpty; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadThePlaylist() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistReadFails_ShouldReturnThatErrorAndNotAuthorize() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be read."); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistDoesNotExistForTheUser_ShouldReturnPlaylistNotFoundAndNotAuthorize() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError); + await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheLibraryIsNotAccessible_ShouldReturnNotAuthorizedAndNotAppendTheScope() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + _mockAuthorizationService.EvaluatePolicyAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(false); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistCannotContainTracks_ShouldReturnPlaylistDoesNotAcceptMediaItemsAndNotAppendTheScope() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: (PlaylistType)999))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistDoesNotAcceptMediaItems, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenAppendingTheScopeFails_ShouldReturnThatError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The scope could not be appended."); + _mockPlaylistRepository.AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenTheScopeAddedEntries_ShouldReturnTheAddedCountAndTheActivityTime() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create( + playlistId: playlistId.ToString(), + libraryId: _libraryId); + _mockPlaylistRepository.AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 7))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(playlistId, result.Value.PlaylistId); + Assert.Equal(7, result.Value.AddedCount); + Assert.NotNull(result.Value.UpdatedOnUtc); + Assert.InRange(result.Value.UpdatedOnUtc!.Value, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow); + } + + [Fact] + public async Task HandleAsync_WhenTheScopeIsEmptyForTheUser_ShouldReturnZeroAddedEntriesWithoutAnActivityTime() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(libraryId: _libraryId); + _mockPlaylistRepository.AddScopeEntriesAsync( + Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistBulkAddResultDtoFixture.Create(addedCount: 0))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0, result.Value.AddedCount); + Assert.Null(result.Value.UpdatedOnUtc); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldPassTheResolvedScopeToTheRepositoryAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create( + playlistId: playlistId.ToString(), + libraryId: _libraryId, + artistId: artistId, + albumId: albumId, + includeArtistId: true, + includeAlbumId: true); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).GetByIdForUserAsync(playlistId, _userId, false, false, Arg.Is(cancellationToken)); + await _mockAuthorizationService.Received(1).EvaluatePolicyAsync( + _userId, + Arg.Is(context => context is LibraryOwnershipPolicyContext && ((LibraryOwnershipPolicyContext)context).LibraryId == _libraryId), + Arg.Is(cancellationToken)); + await _mockPlaylistRepository.Received(1).AddScopeEntriesAsync( + playlistId, + _userId, + _libraryId, + artistId, + albumId, + PlaylistMediaItemType.MusicTrack, + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidatorTests.cs new file mode 100644 index 00000000..71970305 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/AddPlaylistScopeEntries/AddPlaylistScopeEntriesCommandValidatorTests.cs @@ -0,0 +1,136 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Application.Fixtures.Core.Playlists.Commands.AddPlaylistScopeEntries; +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.Playlists.Commands.AddPlaylistScopeEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesCommandValidatorTests +{ + private readonly AddPlaylistScopeEntriesCommandValidator _validator = new(); + private readonly AddPlaylistScopeEntriesCommandFixture _addPlaylistScopeEntriesCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(includeLibraryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenLibraryIdIsTheEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(libraryId: Guid.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistIdIsTheEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create( + artistId: Guid.Empty, + includeArtistId: true); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.ArtistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenAlbumIdIsTheEmptyGuid_ShouldHaveValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create( + albumId: Guid.Empty, + includeAlbumId: true); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Music.AlbumIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenArtistAndAlbumAreOmitted_ShouldNotHaveAnyValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + AddPlaylistScopeEntriesCommand command = _addPlaylistScopeEntriesCommandFixture.Create( + includeArtistId: true, + includeAlbumId: true); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidatorTests.cs new file mode 100644 index 00000000..5462ed71 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/CreatePlaylist/CreatePlaylistCommandValidatorTests.cs @@ -0,0 +1,156 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Application.Fixtures.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.CreatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistCommandValidatorTests +{ + private const int MAXIMUM_PLAYLIST_NAME_LENGTH = 255; + + private readonly CreatePlaylistCommandValidator _validator = new(); + private readonly CreatePlaylistCommandFixture _createPlaylistCommandFixture = new(); + + [Fact] + public void Validate_WhenNameIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(includeName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(name: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsWhiteSpaceOnly_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(name: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsLongerThanTheMaximumLength_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create( + name: new string('a', MAXIMUM_PLAYLIST_NAME_LENGTH + 1)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenNameHasTheMaximumLength_ShouldNotHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create( + name: new string('a', MAXIMUM_PLAYLIST_NAME_LENGTH)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsLongerThanTheMaximumLength_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(description: new string('a', 2001)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsOmitted_ShouldNotHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(includeDescription: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenTypeIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(includeType: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistTypeIsInvalid); + } + + [Fact] + public void Validate_WhenTypeIsNotADefinedMember_ShouldHaveValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(type: (PlaylistType)999); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistTypeIsInvalid); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + CreatePlaylistCommand command = _createPlaylistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandlerTests.cs new file mode 100644 index 00000000..1a83799c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandHandlerTests.cs @@ -0,0 +1,242 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly IValidator _mockValidator; + private readonly DeletePlaylistCommandHandler _sut; + private readonly DeletePlaylistCommandFixture _deletePlaylistCommandFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockCurrentUserService.UserId.Returns(_userId); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId))); + _mockPlaylistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new DeletePlaylistCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockDomainEventsQueue, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + Error error = DomainErrors.Playlists.PlaylistIdCannotBeEmpty; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadThePlaylist() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistReadFails_ShouldReturnThatErrorAndNotDelete() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be read."); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistDoesNotExistForTheUser_ShouldReturnPlaylistNotFoundAndNotDelete() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheStoredPlaylistCannotBeRebuiltAsADomainAggregate_ShouldReturnThatErrorAndNotDelete() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + List entries = + [ + _playlistEntryEntityFixture.Create(position: 512, mediaItemType: PlaylistMediaItemType.MusicTrack), + _playlistEntryEntityFixture.Create(position: 512, mediaItemType: PlaylistMediaItemType.MusicTrack), + ]; + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, entries: entries))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistEntryPositionsAreInvalid, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().DeleteByIdAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheDeletionFails_ShouldReturnThatErrorAndNotSaveChanges() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be removed."); + _mockPlaylistRepository.DeleteByIdAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveFails_ShouldReturnThatErrorAndNotRaiseTheDeletedEvent() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The changes could not be saved."); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldDeleteSaveAndEnqueueOneDeletedEvent() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(playlistId: playlistId.ToString()); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(id: playlistId, userId: _userId))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); + await _mockPlaylistRepository.Received(1).DeleteByIdAsync(playlistId, Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is PlaylistDeletedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldLoadThePlaylistTrackedAndScopedToTheCurrentUserAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(playlistId: playlistId.ToString()); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(id: playlistId, userId: _userId))); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).GetByIdForUserAsync(playlistId, _userId, false, true, Arg.Is(cancellationToken)); + await _mockPlaylistRepository.Received(1).DeleteByIdAsync(playlistId, Arg.Is(cancellationToken)); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidatorTests.cs new file mode 100644 index 00000000..ab612daa --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/DeletePlaylist/DeletePlaylistCommandValidatorTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Application.Fixtures.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.DeletePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistCommandValidatorTests +{ + private readonly DeletePlaylistCommandValidator _validator = new(); + private readonly DeletePlaylistCommandFixture _deletePlaylistCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + DeletePlaylistCommand command = _deletePlaylistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandlerTests.cs new file mode 100644 index 00000000..db9717d4 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandHandlerTests.cs @@ -0,0 +1,154 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Application.Fixtures.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly IValidator _mockValidator; + private readonly MovePlaylistEntryCommandHandler _sut; + private readonly MovePlaylistEntryCommandFixture _movePlaylistEntryCommandFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockPlaylistRepository.MoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new MovePlaylistEntryCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepository() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(); + Error error = DomainErrors.Playlists.PlaylistMoveTargetPositionIsInvalid; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().MoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotMoveTheEntry() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().MoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenMovingTheEntryFails_ShouldReturnThatError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The entry could not be moved."); + _mockPlaylistRepository.MoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldReturnTheMovedEntryAndItsTargetPosition() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create( + playlistId: playlistId.ToString(), + playlistEntryId: playlistEntryId.ToString(), + targetPosition: 3); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(playlistId, result.Value.PlaylistId); + Assert.Equal(playlistEntryId, result.Value.EntryId); + Assert.Equal(3, result.Value.Position); + Assert.NotNull(result.Value.UpdatedOnUtc); + Assert.InRange(result.Value.UpdatedOnUtc!.Value, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldPassTheRouteIdentifiersAndTheTargetPositionToTheRepositoryAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create( + playlistId: playlistId.ToString(), + playlistEntryId: playlistEntryId.ToString(), + targetPosition: 12); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).MoveEntryAsync( + playlistId, + _userId, + playlistEntryId, + 12, + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidatorTests.cs new file mode 100644 index 00000000..c40228ce --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/MovePlaylistEntry/MovePlaylistEntryCommandValidatorTests.cs @@ -0,0 +1,133 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Application.Fixtures.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.MovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryCommandValidatorTests +{ + private readonly MovePlaylistEntryCommandValidator _validator = new(); + private readonly MovePlaylistEntryCommandFixture _movePlaylistEntryCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPlaylistEntryIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(includePlaylistEntryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid entry + public void Validate_WhenPlaylistEntryIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistEntryId) + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(playlistEntryId: playlistEntryId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenTargetPositionIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(includeTargetPosition: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + } + + [Fact] + public void Validate_WhenTargetPositionIsNegative_ShouldHaveValidationError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(targetPosition: -1); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + } + + [Fact] + public void Validate_WhenTargetPositionIsZero_ShouldNotHaveValidationError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(targetPosition: 0); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Playlists.PlaylistMoveTargetPositionIsInvalid); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + MovePlaylistEntryCommand command = _movePlaylistEntryCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandlerTests.cs new file mode 100644 index 00000000..7274a24c --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandHandlerTests.cs @@ -0,0 +1,167 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Application.Fixtures.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly IValidator _mockValidator; + private readonly RemovePlaylistEntryCommandHandler _sut; + private readonly RemovePlaylistEntryCommandFixture _removePlaylistEntryCommandFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockPlaylistRepository.RemoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(0)); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new RemovePlaylistEntryCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepository() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(); + Error error = DomainErrors.Playlists.PlaylistEntryIdCannotBeEmpty; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().RemoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotRemoveTheEntry() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().RemoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenRemovingTheEntryFails_ShouldReturnThatError() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The entry could not be removed."); + _mockPlaylistRepository.RemoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldReturnTheRemovedEntryWithNoRepositionedEntries() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create( + playlistId: playlistId.ToString(), + playlistEntryId: playlistEntryId.ToString()); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(playlistId, result.Value.PlaylistId); + Assert.Equal(playlistEntryId, result.Value.RemovedEntryId); + Assert.Equal(0, result.Value.RepositionedCount); + Assert.NotNull(result.Value.UpdatedOnUtc); + Assert.InRange(result.Value.UpdatedOnUtc!.Value, DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow); + } + + [Fact] + public async Task HandleAsync_WhenTheRepositoryReportsARepositionedCount_ShouldPreserveIt() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(); + _mockPlaylistRepository.RemoveEntryAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(4)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(4, result.Value.RepositionedCount); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldPassTheRouteIdentifiersToTheRepositoryAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create( + playlistId: playlistId.ToString(), + playlistEntryId: playlistEntryId.ToString()); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).RemoveEntryAsync( + playlistId, + _userId, + playlistEntryId, + Arg.Any(), + Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidatorTests.cs new file mode 100644 index 00000000..2a25a58f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/RemovePlaylistEntry/RemovePlaylistEntryCommandValidatorTests.cs @@ -0,0 +1,94 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Application.Fixtures.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.RemovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryCommandValidatorTests +{ + private readonly RemovePlaylistEntryCommandValidator _validator = new(); + private readonly RemovePlaylistEntryCommandFixture _removePlaylistEntryCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenPlaylistEntryIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(includePlaylistEntryId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid entry + public void Validate_WhenPlaylistEntryIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistEntryId) + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(playlistEntryId: playlistEntryId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistEntryIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + RemovePlaylistEntryCommand command = _removePlaylistEntryCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandlerTests.cs new file mode 100644 index 00000000..b9c900e7 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandHandlerTests.cs @@ -0,0 +1,312 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DomainEvents; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Fixtures.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Events; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IDomainEventsQueue _mockDomainEventsQueue; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly IValidator _mockValidator; + private readonly UpdatePlaylistCommandHandler _sut; + private readonly UpdatePlaylistCommandFixture _updatePlaylistCommandFixture = new(); + private readonly PlaylistEntityFixture _playlistEntityFixture = new(); + private readonly PlaylistEntryEntityFixture _playlistEntryEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockDomainEventsQueue = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockCurrentUserService.UserId.Returns(_userId); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, type: PlaylistType.Music))); + _mockPlaylistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()).Returns([]); + + _sut = new UpdatePlaylistCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockDomainEventsQueue, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotTouchTheRepositories() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + Error error = DomainErrors.Playlists.PlaylistNameCannotBeEmpty; + _mockValidator.Validate(Arg.Any()).Returns([error]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _ = _mockCurrentUserService.DidNotReceive().UserId; + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + await _mockPlaylistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadThePlaylist() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistReadFails_ShouldReturnThatErrorAndNotUpdate() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be read."); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenThePlaylistDoesNotExistForTheUser_ShouldReturnPlaylistNotFoundAndNotUpdate() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistNotFound, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheStoredPlaylistCannotBeRebuiltAsADomainAggregate_ShouldReturnThatErrorAndNotUpdate() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + List entries = + [ + _playlistEntryEntityFixture.Create(position: 64, mediaItemType: PlaylistMediaItemType.MusicTrack), + _playlistEntryEntityFixture.Create(position: 64, mediaItemType: PlaylistMediaItemType.MusicTrack), + ]; + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create(userId: _userId, entries: entries))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.Playlists.PlaylistEntryPositionsAreInvalid, result.FirstError); + await _mockPlaylistRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheUpdateFails_ShouldReturnThatErrorAndNotSaveChanges() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlist could not be updated."); + _mockPlaylistRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveFails_ShouldReturnThatErrorAndNotRaiseTheDetailsUpdatedEvent() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The changes could not be saved."); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldPersistTheNewDetailsRaiseOneEventAndReturnTheStoredActivityTime() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + DateTime storedUpdatedOnUtc = new(2024, 8, 9, 10, 11, 12, DateTimeKind.Utc); + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create( + playlistId: playlistId.ToString(), + name: "Deep Focus", + description: "Long sessions"); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create( + id: playlistId, + userId: _userId, + name: "Focus", + description: "Deep work", + type: PlaylistType.Music, + includeUpdatedOnUtc: true, + updatedOnUtc: storedUpdatedOnUtc))); + PlaylistEntity? updatedEntity = null; + _mockPlaylistRepository.UpdateAsync(Arg.Do(playlist => updatedEntity = playlist), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(playlistId, result.Value.Id); + Assert.Equal("Deep Focus", result.Value.Name); + Assert.Equal("Long sessions", result.Value.Description); + Assert.Equal(PlaylistType.Music, result.Value.Type); + Assert.True(result.Value.UpdatedOnUtc.HasValue); + Assert.Equal(storedUpdatedOnUtc, result.Value.UpdatedOnUtc!.Value); + Assert.NotNull(updatedEntity); + Assert.Equal(playlistId, updatedEntity!.Id); + Assert.Equal(_userId, updatedEntity.UserId); + Assert.Equal("Deep Focus", updatedEntity.Name); + Assert.Equal("Long sessions", updatedEntity.Description); + await _mockPlaylistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is PlaylistDetailsUpdatedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenTheDescriptionIsCleared_ShouldPersistWithoutADescriptionAndRaiseOneEvent() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create( + name: "Focus", + includeDescription: false); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create( + userId: _userId, + name: "Focus", + description: "Deep work"))); + PlaylistEntity? updatedEntity = null; + _mockPlaylistRepository.UpdateAsync(Arg.Do(playlist => updatedEntity = playlist), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Null(result.Value.Description); + Assert.NotNull(updatedEntity); + Assert.Null(updatedEntity!.Description); + _mockDomainEventsQueue.Received(1).Enqueue(Arg.Is(domainEvent => domainEvent is PlaylistDetailsUpdatedDomainEvent)); + } + + [Fact] + public async Task HandleAsync_WhenNothingChanges_ShouldStillPersistAndRaiseNoEvent() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create( + name: "Focus", + description: "Deep work"); + _mockPlaylistRepository.GetByIdForUserAsync(Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntityFixture.Create( + userId: _userId, + name: "Focus", + description: "Deep work"))); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Focus", result.Value.Name); + _mockDomainEventsQueue.DidNotReceive().Enqueue(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldLoadThePlaylistTrackedAndScopedToTheCurrentUserAndForwardTheCancellationToken() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(playlistId: playlistId.ToString()); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).GetByIdForUserAsync(playlistId, _userId, false, true, Arg.Is(cancellationToken)); + await _mockPlaylistRepository.Received(1).UpdateAsync(Arg.Any(), Arg.Is(cancellationToken)); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidatorTests.cs new file mode 100644 index 00000000..0def9d6b --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Commands/UpdatePlaylist/UpdatePlaylistCommandValidatorTests.cs @@ -0,0 +1,159 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Application.Fixtures.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.Playlists.Commands.UpdatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistCommandValidatorTests +{ + private const int MAXIMUM_PLAYLIST_NAME_LENGTH = 255; + + private readonly UpdatePlaylistCommandValidator _validator = new(); + private readonly UpdatePlaylistCommandFixture _updatePlaylistCommandFixture = new(); + + [Fact] + public void Validate_WhenPlaylistIdIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(includePlaylistId: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Theory] + [InlineData("")] // an empty identifier + [InlineData(" ")] // a white-space only identifier + [InlineData("not-a-guid")] // an identifier that cannot be parsed + [InlineData("00000000-0000-0000-0000-000000000000")] // the empty Guid, which is never a valid playlist + public void Validate_WhenPlaylistIdIsNotAValidIdentifier_ShouldHaveValidationError(string playlistId) + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(playlistId: playlistId); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistIdCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsNotSupplied_ShouldHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(includeName: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsEmpty_ShouldHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(name: string.Empty); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsWhiteSpaceOnly_ShouldHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(name: " "); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameCannotBeEmpty); + } + + [Fact] + public void Validate_WhenNameIsLongerThanTheMaximumLength_ShouldHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create( + name: new string('a', MAXIMUM_PLAYLIST_NAME_LENGTH + 1)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenNameHasTheMaximumLength_ShouldNotHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create( + name: new string('a', MAXIMUM_PLAYLIST_NAME_LENGTH)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Playlists.PlaylistNameMustBeMaximum255CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsLongerThanTheMaximumLength_ShouldHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(description: new string('a', 2001)); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenDescriptionIsOmitted_ShouldNotHaveValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(includeDescription: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + UpdatePlaylistCommand command = _updatePlaylistCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandlerTests.cs new file mode 100644 index 00000000..988a7e76 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/Playlists/Queries/GetPlaylists/GetPlaylistsQueryHandlerTests.cs @@ -0,0 +1,166 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Repositories.Playlists; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.DTO.Playlists; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Core.Playlists.Queries.GetPlaylists; +using Lumina.Application.Fixtures.Common.DTO.Playlists; +using Lumina.Application.Fixtures.Core.Playlists.Queries.GetPlaylists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +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.Playlists.Queries.GetPlaylists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IPlaylistRepository _mockPlaylistRepository; + private readonly GetPlaylistsQueryHandler _sut; + private readonly GetPlaylistsQueryFixture _getPlaylistsQueryFixture = new(); + private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockPlaylistRepository = Substitute.For(); + + _mockUnitOfWork.PlaylistRepository.Returns(_mockPlaylistRepository); + _mockCurrentUserService.UserId.Returns(_userId); + _mockPlaylistRepository.GetAllForUserAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([_playlistSummaryDtoFixture.Create()])); + + _sut = new GetPlaylistsQueryHandler(_mockUnitOfWork, _mockCurrentUserService); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadTheRepository() + { + // Arrange + GetPlaylistsQuery query = _getPlaylistsQueryFixture.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 _mockPlaylistRepository.DidNotReceive().GetAllForUserAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenTheRepositoryFails_ShouldReturnThatError() + { + // Arrange + GetPlaylistsQuery query = _getPlaylistsQueryFixture.Create(); + Error error = Error.Failure("Persistence.Failure", "The playlists could not be read."); + _mockPlaylistRepository.GetAllForUserAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenTheUserHasNoPlaylists_ShouldReturnAnEmptyArray() + { + // Arrange + GetPlaylistsQuery query = _getPlaylistsQueryFixture.Create(); + _mockPlaylistRepository.GetAllForUserAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([])); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Empty(result.Value); + } + + [Fact] + public async Task HandleAsync_WhenSuccessful_ShouldMapEveryPlaylistSummaryInOrder() + { + // Arrange + DateTime firstCreatedOnUtc = new(2024, 1, 2, 3, 4, 5, DateTimeKind.Utc); + DateTime secondCreatedOnUtc = new(2024, 6, 7, 8, 9, 10, DateTimeKind.Utc); + DateTime secondUpdatedOnUtc = new(2024, 7, 8, 9, 10, 11, DateTimeKind.Utc); + PlaylistSummaryDto firstPlaylist = _playlistSummaryDtoFixture.Create( + name: "Focus", + description: "Deep work", + type: PlaylistType.Music, + entryCount: 12, + createdOnUtc: firstCreatedOnUtc, + includeUpdatedOnUtc: false); + PlaylistSummaryDto secondPlaylist = _playlistSummaryDtoFixture.Create( + name: "Commute", + includeDescription: false, + type: PlaylistType.Music, + entryCount: 3, + createdOnUtc: secondCreatedOnUtc, + includeUpdatedOnUtc: true, + updatedOnUtc: secondUpdatedOnUtc); + _mockPlaylistRepository.GetAllForUserAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From>([firstPlaylist, secondPlaylist])); + GetPlaylistsQuery query = _getPlaylistsQueryFixture.Create(); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(2, result.Value.Length); + Assert.Equal(firstPlaylist.Id, result.Value[0].Id); + Assert.Equal("Focus", result.Value[0].Name); + Assert.Equal("Deep work", result.Value[0].Description); + Assert.Equal(PlaylistType.Music, result.Value[0].Type); + Assert.Equal(12, result.Value[0].EntryCount); + Assert.Equal(firstCreatedOnUtc, result.Value[0].CreatedOnUtc); + Assert.Null(result.Value[0].UpdatedOnUtc); + Assert.Equal(secondPlaylist.Id, result.Value[1].Id); + Assert.Equal("Commute", result.Value[1].Name); + Assert.Null(result.Value[1].Description); + Assert.Equal(3, result.Value[1].EntryCount); + Assert.Equal(secondCreatedOnUtc, result.Value[1].CreatedOnUtc); + Assert.True(result.Value[1].UpdatedOnUtc.HasValue); + Assert.Equal(secondUpdatedOnUtc, result.Value[1].UpdatedOnUtc!.Value); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldReadThePlaylistsOfTheCurrentUserAndForwardTheCancellationToken() + { + // Arrange + GetPlaylistsQuery query = _getPlaylistsQueryFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockPlaylistRepository.Received(1).GetAllForUserAsync(_userId, Arg.Is(cancellationToken)); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandlerTests.cs new file mode 100644 index 00000000..4bfffd87 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandHandlerTests.cs @@ -0,0 +1,302 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Common.Infrastructure.Validation; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateCommandHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly IValidator _mockValidator; + private readonly UpdatePlaybackStateCommandHandler _sut; + private readonly UpdatePlaybackStateCommandFixture _updatePlaybackStateCommandFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateCommandHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()).Returns(Result.Success); + _mockCurrentUserService = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockCurrentUserService.UserId.Returns(_userId); + + _mockValidator = Substitute.For>(); + _mockValidator.Validate(Arg.Any()) + .Returns([]); + + _sut = new UpdatePlaybackStateCommandHandler(_mockCurrentUserService, _mockUnitOfWork, _mockValidator); + } + + [Fact] + public async Task HandleAsync_WhenValidationFails_ShouldReturnValidationErrorsAndNotPersist() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + _mockValidator.Validate(Arg.Any()) + .Returns([DomainErrors.UserSettings.VolumeMustBeBetweenZeroAndOne]); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(DomainErrors.UserSettings.VolumeMustBeBetweenZeroAndOne, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotPersist() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + _mockCurrentUserService.UserId.Returns((Guid?)null); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnErrorAndNotPersist() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to retrieve user settings"); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSettingsDoNotExist_ShouldInsertTheReportedStateKeepingTheHandEditedSettingsAtTheirDefaults() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: 0.35, isMuted: true); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + _mockUserSettingsRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockUserSettingsRepository.Received(1).InsertAsync( + Arg.Is(settings => + settings.UserId == _userId && + settings.Volume == 0.35 && + settings.IsMuted && + settings.IsPaginationEnabled && + settings.ItemsPerPage == 48 && + settings.ShouldAutoplay && + settings.IsGaplessPlaybackEnabled && + settings.VuMeterSegmentCount == 12), + Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().UpdateAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenInsertFails_ShouldReturnErrorAndNotSaveChanges() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + Error error = Error.Failure("Database.Error", "Failed to insert user settings"); + _mockUserSettingsRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSettingsExist_ShouldUpdateTheReportedStateAndPreserveTheHandEditedSettings() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: 0.25, isMuted: true); + UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create( + userId: _userId, + volume: 1.0, + isMuted: false, + itemsPerPage: 24, + isPaginationEnabled: false); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(existingSettings)); + _mockUserSettingsRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + await _mockUserSettingsRepository.Received(1).UpdateAsync( + Arg.Is(settings => + settings.UserId == _userId && + settings.Volume == 0.25 && + settings.IsMuted && + !settings.IsPaginationEnabled && + settings.ItemsPerPage == 24), + Arg.Any()); + await _mockUserSettingsRepository.DidNotReceive().InsertAsync(Arg.Any(), Arg.Any()); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenUpdateFails_ShouldReturnErrorAndNotSaveChanges() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(existingSettings)); + Error error = Error.Failure("Database.Error", "Failed to update user settings"); + _mockUserSettingsRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFailsAfterInsert_ShouldReturnError() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + _mockUserSettingsRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + Error error = Error.Failure("Database.Error", "Failed to save changes"); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenSaveChangesFailsAfterUpdate_ShouldReturnError() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + UserSettingsEntity existingSettings = _userSettingsEntityFixture.Create(userId: _userId); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(existingSettings)); + _mockUserSettingsRepository.UpdateAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + Error error = Error.Failure("Database.Error", "Failed to save changes"); + _mockUnitOfWork.SaveChangesAsync(Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(command, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldForwardTheCurrentUserIdAndCancellationToken() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + _mockUserSettingsRepository.InsertAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Created); + + // Act + await _sut.HandleAsync(command, cancellationToken); + + // Assert + await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, Arg.Is(cancellationToken)); + await _mockUserSettingsRepository.Received(1).InsertAsync(Arg.Any(), Arg.Is(cancellationToken)); + await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenCancellationIsRequested_ShouldCancelTheOperation() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationTokenSource.Token) + .Returns(Task.FromCanceled>(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.HandleAsync(command, cancellationTokenSource.Token)); + await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, cancellationTokenSource.Token); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidatorTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidatorTests.cs new file mode 100644 index 00000000..a3fe4cf6 --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Commands/UpdatePlaybackState/UpdatePlaybackStateCommandValidatorTests.cs @@ -0,0 +1,125 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Application.UnitTests.Common.Setup; +using Lumina.Domain.Common.Errors; +using Lumina.Domain.Common.Primitives; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateCommandValidatorTests +{ + private readonly UpdatePlaybackStateCommandValidator _validator = new(); + private readonly UpdatePlaybackStateCommandFixture _updatePlaybackStateCommandFixture = new(); + + [Fact] + public void Validate_WhenVolumeIsNull_ShouldHaveVolumeCannotBeNullErrorAndNoRangeError() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(includeVolume: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VolumeCannotBeNull); + result.ShouldNotHaveValidationError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne); + } + + [Theory] + [InlineData(-0.01)] // just below the minimum + [InlineData(-1.0)] // well below the minimum + [InlineData(double.MinValue)] // far below the minimum + public void Validate_WhenVolumeIsBelowZero_ShouldHaveRangeError(double volume) + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: volume); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne); + } + + [Theory] + [InlineData(1.01)] // just above the maximum + [InlineData(2.0)] // well above the maximum + [InlineData(double.MaxValue)] // far above the maximum + public void Validate_WhenVolumeIsAboveOne_ShouldHaveRangeError(double volume) + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: volume); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne); + } + + [Theory] + [InlineData(0.0)] // the minimum + [InlineData(0.5)] // a middle value + [InlineData(1.0)] // the maximum + public void Validate_WhenVolumeIsInRange_ShouldNotHaveRangeError(double volume) + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(volume: volume); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.VolumeMustBeBetweenZeroAndOne); + result.ShouldNotHaveValidationError(Errors.UserSettings.VolumeCannotBeNull); + } + + [Fact] + public void Validate_WhenIsMutedIsNull_ShouldHaveIsMutedCannotBeNullError() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(includeIsMuted: false); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldHaveValidationError(Errors.UserSettings.IsMutedCannotBeNull); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Validate_WhenIsMutedIsSpecified_ShouldNotHaveIsMutedCannotBeNullError(bool isMuted) + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(isMuted: isMuted); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveValidationError(Errors.UserSettings.IsMutedCannotBeNull); + } + + [Fact] + public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError() + { + // Arrange + UpdatePlaybackStateCommand command = _updatePlaybackStateCommandFixture.Create(); + + // Act + List result = _validator.TestValidate(command); + + // Assert + result.ShouldNotHaveAnyValidationErrors(); + } +} diff --git a/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandlerTests.cs b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandlerTests.cs new file mode 100644 index 00000000..622d0f4f --- /dev/null +++ b/tests/UnitTests/Lumina.Application.UnitTests/Core/UsersManagement/Settings/Queries/GetPlaybackState/GetPlaybackStateQueryHandlerTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Common.DataAccess.Repositories.Users; +using Lumina.Application.Common.DataAccess.UoW; +using Lumina.Application.Common.Infrastructure.Authentication; +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; +using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement; +using Lumina.Application.Fixtures.Core.UsersManagement.Settings.Queries.GetPlaybackState; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +#endregion + +namespace Lumina.Application.UnitTests.Core.UsersManagement.Settings.Queries.GetPlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateQueryHandlerTests +{ + private readonly IUnitOfWork _mockUnitOfWork; + private readonly ICurrentUserService _mockCurrentUserService; + private readonly IUserSettingsRepository _mockUserSettingsRepository; + private readonly GetPlaybackStateQueryHandler _sut; + private readonly GetPlaybackStateQueryFixture _getPlaybackStateQueryFixture = new(); + private readonly UserSettingsEntityFixture _userSettingsEntityFixture = new(); + private readonly Guid _userId = Guid.NewGuid(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateQueryHandlerTests() + { + _mockUnitOfWork = Substitute.For(); + _mockCurrentUserService = Substitute.For(); + _mockUserSettingsRepository = Substitute.For(); + + _mockUnitOfWork.UserSettingsRepository.Returns(_mockUserSettingsRepository); + _mockCurrentUserService.UserId.Returns(_userId); + + _sut = new GetPlaybackStateQueryHandler(_mockCurrentUserService, _mockUnitOfWork); + } + + [Fact] + public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedWithoutReadingSettings() + { + // Arrange + GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.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 _mockUserSettingsRepository.DidNotReceive().GetByUserIdAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task HandleAsync_WhenGetByUserIdReturnsError_ShouldReturnError() + { + // Arrange + GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create(); + Error error = Error.Failure("Database.Error", "Failed to retrieve user settings"); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(error); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(error, result.FirstError); + } + + [Fact] + public async Task HandleAsync_WhenSettingsDoNotExist_ShouldReturnTheDefaultPlaybackState() + { + // Arrange + GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(1.0, result.Value.Volume); + Assert.False(result.Value.IsMuted); + } + + [Fact] + public async Task HandleAsync_WhenSettingsExist_ShouldReturnTheStoredPlaybackState() + { + // Arrange + GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create(); + UserSettingsEntity storedSettings = _userSettingsEntityFixture.Create(userId: _userId, volume: 0.42, isMuted: true); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(storedSettings)); + + // Act + Result result = await _sut.HandleAsync(query, CancellationToken.None); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(0.42, result.Value.Volume); + Assert.True(result.Value.IsMuted); + } + + [Fact] + public async Task HandleAsync_WhenCalled_ShouldForwardTheCurrentUserIdAndCancellationToken() + { + // Arrange + GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + CancellationToken cancellationToken = cancellationTokenSource.Token; + _mockUserSettingsRepository.GetByUserIdAsync(_userId, Arg.Any()) + .Returns(Result.From(null)); + + // Act + await _sut.HandleAsync(query, cancellationToken); + + // Assert + await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, Arg.Is(cancellationToken)); + } + + [Fact] + public async Task HandleAsync_WhenCancellationIsRequested_ShouldCancelTheOperation() + { + // Arrange + GetPlaybackStateQuery query = _getPlaybackStateQueryFixture.Create(); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + _mockUserSettingsRepository.GetByUserIdAsync(_userId, cancellationTokenSource.Token) + .Returns(Task.FromCanceled>(cancellationTokenSource.Token)); + + // Act & Assert + await Assert.ThrowsAsync(() => _sut.HandleAsync(query, cancellationTokenSource.Token)); + await _mockUserSettingsRepository.Received(1).GetByUserIdAsync(_userId, cancellationTokenSource.Token); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PlaylistConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PlaylistConfigurationTests.cs new file mode 100644 index 00000000..d1ab334b --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PlaylistConfigurationTests.cs @@ -0,0 +1,239 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.Application.Common.DataAccess.Entities.UsersManagement; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public PlaylistConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + /// + /// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits. + /// + private IModel DesignTimeModel => _context.GetService().Model; + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("Playlists", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + Assert.Equal(0, idProperty.GetColumnOrder()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureCascadingRelationshipWithUser() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IForeignKey userForeignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(typeof(UserEntity), userForeignKey.PrincipalEntityType.ClrType); + Assert.Equal(nameof(PlaylistEntity.UserId), userForeignKey.Properties[0].Name); + Assert.Equal(DeleteBehavior.Cascade, userForeignKey.DeleteBehavior); + Assert.True(userForeignKey.IsRequired); + } + + [Fact] + public void Configure_WhenApplied_ShouldStoreThePlaylistTypeAsABoundedRequiredString() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty typeProperty = entityType.GetProperty(nameof(PlaylistEntity.Type)); + + // Assert + Assert.Equal(typeof(PlaylistType), typeProperty.ClrType); + Assert.Equal(typeof(string), typeProperty.GetTypeMapping().Converter!.ProviderClrType); + Assert.Equal("TEXT", typeProperty.GetColumnType()); + Assert.Equal(20, typeProperty.GetMaxLength()); + Assert.False(typeProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheNameAndDescriptionLengths() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty nameProperty = entityType.GetProperty(nameof(PlaylistEntity.Name)); + IProperty descriptionProperty = entityType.GetProperty(nameof(PlaylistEntity.Description)); + + // Assert + Assert.False(nameProperty.IsNullable); + Assert.Equal(255, nameProperty.GetMaxLength()); + Assert.True(descriptionProperty.IsNullable); + Assert.Equal(2000, descriptionProperty.GetMaxLength()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty userIdProperty = entityType.GetProperty(nameof(PlaylistEntity.UserId)); + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedBy)); + IProperty entryCountProperty = entityType.GetProperty(nameof(PlaylistEntity.EntryCount)); + + // Assert + Assert.False(userIdProperty.IsNullable); + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + Assert.False(entryCountProperty.IsNullable); + Assert.Equal(0, entryCountProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedBy)); + + // Assert + Assert.True(updatedOnUtcProperty.IsNullable); + Assert.True(updatedByProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + Assert.Null(updatedByProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheVersionAsAConcurrencyTokenStartingAtZero() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty versionProperty = entityType.GetProperty(nameof(PlaylistEntity.Version)); + + // Assert + Assert.True(versionProperty.IsConcurrencyToken); + Assert.Equal(0L, versionProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheEntriesRelationshipWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + IEntityType entryEntityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + INavigation entriesNavigation = Assert.Single(entityType.GetNavigations()); + IForeignKey entriesForeignKey = Assert.Single(entryEntityType.GetForeignKeys()); + + // Assert + Assert.Equal(nameof(PlaylistEntity.Entries), entriesNavigation.Name); + Assert.Equal(typeof(PlaylistEntryEntity), entriesNavigation.TargetEntityType.ClrType); + Assert.True(entriesNavigation.IsCollection); + Assert.Equal(typeof(PlaylistEntity), entriesForeignKey.PrincipalEntityType.ClrType); + Assert.Equal(nameof(PlaylistEntryEntity.PlaylistId), entriesForeignKey.Properties[0].Name); + Assert.Equal(DeleteBehavior.Cascade, entriesForeignKey.DeleteBehavior); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheMostRecentActivityIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IIndex activityIndex = Assert.Single( + entityType.GetIndexes(), + index => index.Properties.Select(property => property.Name).SequenceEqual( + [ + nameof(PlaylistEntity.UserId), + nameof(PlaylistEntity.UpdatedOnUtc) + ])); + + // Assert + Assert.False(activityIndex.IsUnique); + Assert.Equal(2, activityIndex.Properties.Count); + } + + [Fact] + public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntity.Id)); + IProperty userIdProperty = entityType.GetProperty(nameof(PlaylistEntity.UserId)); + IProperty nameProperty = entityType.GetProperty(nameof(PlaylistEntity.Name)); + IProperty descriptionProperty = entityType.GetProperty(nameof(PlaylistEntity.Description)); + IProperty typeProperty = entityType.GetProperty(nameof(PlaylistEntity.Type)); + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntity.UpdatedBy)); + IProperty versionProperty = entityType.GetProperty(nameof(PlaylistEntity.Version)); + IProperty entryCountProperty = entityType.GetProperty(nameof(PlaylistEntity.EntryCount)); + + // Assert + Assert.Equal(0, idProperty.GetColumnOrder()); + Assert.Equal(1, userIdProperty.GetColumnOrder()); + Assert.Equal(2, nameProperty.GetColumnOrder()); + Assert.Equal(3, descriptionProperty.GetColumnOrder()); + Assert.Equal(4, typeProperty.GetColumnOrder()); + Assert.Equal(5, createdOnUtcProperty.GetColumnOrder()); + Assert.Equal(6, createdByProperty.GetColumnOrder()); + Assert.Equal(7, updatedOnUtcProperty.GetColumnOrder()); + Assert.Equal(8, updatedByProperty.GetColumnOrder()); + Assert.Equal(9, versionProperty.GetColumnOrder()); + Assert.Equal(10, entryCountProperty.GetColumnOrder()); + } +} diff --git a/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PlaylistEntryConfigurationTests.cs b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PlaylistEntryConfigurationTests.cs new file mode 100644 index 00000000..f85c4439 --- /dev/null +++ b/tests/UnitTests/Lumina.DataAccess.UnitTests/Common/Configuration/PlaylistEntryConfigurationTests.cs @@ -0,0 +1,212 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.DataAccess.Entities.Playlists; +using Lumina.DataAccess.Core.UoW; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.DataAccess.UnitTests.Common.Configuration; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryConfigurationTests +{ + private readonly LuminaDbContext _context; + + /// + /// Initializes a new instance of the class. + /// + public PlaylistEntryConfigurationTests() + { + _context = new LuminaDbContext(new DbContextOptionsBuilder().UseSqlite("Data Source=:memory:").Options); + } + + /// + /// Gets the design-time model, which retains configuration such as column order that the read-optimized runtime model omits. + /// + private IModel DesignTimeModel => _context.GetService().Model; + + [Fact] + public void Configure_WhenApplied_ShouldSetTableNameAndKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + string? tableName = entityType.GetTableName(); + IReadOnlyList keyProperties = entityType.FindPrimaryKey()!.Properties; + + // Assert + Assert.Equal("PlaylistEntries", tableName); + Assert.Equal(["Id"], keyProperties.Select(property => property.Name)); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotGenerateTheIdValueAndOrderItFirst() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Id)); + + // Assert + Assert.Equal(ValueGenerated.Never, idProperty.ValueGenerated); + Assert.Equal(0, idProperty.GetColumnOrder()); + } + + [Fact] + public void Configure_WhenApplied_ShouldStoreTheMediaItemTypeAsABoundedRequiredString() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IProperty mediaItemTypeProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemType)); + + // Assert + Assert.Equal(typeof(PlaylistMediaItemType), mediaItemTypeProperty.ClrType); + Assert.Equal(typeof(string), mediaItemTypeProperty.GetTypeMapping().Converter!.ProviderClrType); + Assert.Equal("TEXT", mediaItemTypeProperty.GetColumnType()); + Assert.Equal(20, mediaItemTypeProperty.GetMaxLength()); + Assert.False(mediaItemTypeProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheRequiredColumns() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IProperty playlistIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.PlaylistId)); + IProperty mediaItemIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemId)); + IProperty positionProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Position)); + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedBy)); + + // Assert + Assert.False(playlistIdProperty.IsNullable); + Assert.False(mediaItemIdProperty.IsNullable); + Assert.False(positionProperty.IsNullable); + Assert.False(createdOnUtcProperty.IsNullable); + Assert.False(createdByProperty.IsNullable); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheNullableAuditColumns() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedBy)); + + // Assert + Assert.True(updatedOnUtcProperty.IsNullable); + Assert.True(updatedByProperty.IsNullable); + Assert.Null(updatedOnUtcProperty.GetDefaultValue()); + Assert.Null(updatedByProperty.GetDefaultValue()); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheUniquePositionIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IIndex positionIndex = Assert.Single( + entityType.GetIndexes(), + index => index.Properties.Select(property => property.Name).SequenceEqual( + [ + nameof(PlaylistEntryEntity.PlaylistId), + nameof(PlaylistEntryEntity.Position) + ])); + + // Assert + Assert.True(positionIndex.IsUnique); + Assert.Equal(2, positionIndex.Properties.Count); + } + + [Fact] + public void Configure_WhenApplied_ShouldConfigureTheMediaItemLookupIndex() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IIndex mediaItemIndex = Assert.Single( + entityType.GetIndexes(), + index => index.Properties.Select(property => property.Name).SequenceEqual([nameof(PlaylistEntryEntity.MediaItemId)])); + + // Assert + Assert.False(mediaItemIndex.IsUnique); + } + + [Fact] + public void Configure_WhenApplied_ShouldOwnTheEntryThroughThePlaylistWithCascadeDelete() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IForeignKey playlistForeignKey = Assert.Single(entityType.GetForeignKeys()); + + // Assert + Assert.Equal(typeof(PlaylistEntity), playlistForeignKey.PrincipalEntityType.ClrType); + Assert.Equal(nameof(PlaylistEntryEntity.PlaylistId), playlistForeignKey.Properties[0].Name); + Assert.Equal(DeleteBehavior.Cascade, playlistForeignKey.DeleteBehavior); + } + + [Fact] + public void Configure_WhenApplied_ShouldNotReferenceTheMediaItemByAForeignKey() + { + // Arrange + IEntityType entityType = _context.Model.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + List foreignKeys = [.. entityType.GetForeignKeys()]; + + // Assert + // The media item is referenced by Id only, so an entry survives the deletion of the item it references. + Assert.DoesNotContain(foreignKeys, foreignKey => foreignKey.Properties.Any(property => property.Name == nameof(PlaylistEntryEntity.MediaItemId))); + } + + [Fact] + public void Configure_WhenApplied_ShouldOrderEveryColumnAsConfigured() + { + // Arrange + IEntityType entityType = DesignTimeModel.FindEntityType(typeof(PlaylistEntryEntity))!; + + // Act + IProperty idProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Id)); + IProperty playlistIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.PlaylistId)); + IProperty mediaItemIdProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemId)); + IProperty mediaItemTypeProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.MediaItemType)); + IProperty positionProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.Position)); + IProperty createdOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedOnUtc)); + IProperty createdByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.CreatedBy)); + IProperty updatedOnUtcProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedOnUtc)); + IProperty updatedByProperty = entityType.GetProperty(nameof(PlaylistEntryEntity.UpdatedBy)); + + // Assert + Assert.Equal(0, idProperty.GetColumnOrder()); + Assert.Equal(1, playlistIdProperty.GetColumnOrder()); + Assert.Equal(2, mediaItemIdProperty.GetColumnOrder()); + Assert.Equal(3, mediaItemTypeProperty.GetColumnOrder()); + Assert.Equal(4, positionProperty.GetColumnOrder()); + Assert.Equal(5, createdOnUtcProperty.GetColumnOrder()); + Assert.Equal(6, createdByProperty.GetColumnOrder()); + Assert.Equal(7, updatedOnUtcProperty.GetColumnOrder()); + Assert.Equal(8, updatedByProperty.GetColumnOrder()); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryModeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryModeTests.cs new file mode 100644 index 00000000..77634ee1 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryModeTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playback; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PlaybackDeliveryModeTests +{ + [Fact] + public void PlaybackDeliveryMode_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PlaybackDeliveryMode[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void PlaybackDeliveryMode_WhenEnumeratingNames_ShouldHaveTheThreeDocumentedMembersInOrder() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(PlaybackDeliveryMode.DirectPlay), + nameof(PlaybackDeliveryMode.Remux), + nameof(PlaybackDeliveryMode.Transcode) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void PlaybackDeliveryMode_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + PlaybackDeliveryMode[] values = Enum.GetValues(); + + // Assert + PlaybackDeliveryMode[] expectedValues = + [ + PlaybackDeliveryMode.DirectPlay, + PlaybackDeliveryMode.Remux, + PlaybackDeliveryMode.Transcode + ]; + int[] expectedUnderlyingValues = [0, 1, 2]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void PlaybackDeliveryMode_WhenDefaulted_ShouldBeDirectPlay() + { + // Act + PlaybackDeliveryMode deliveryMode = default; + + // Assert + Assert.Equal(PlaybackDeliveryMode.DirectPlay, deliveryMode); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryShapeExtensionsTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryShapeExtensionsTests.cs new file mode 100644 index 00000000..0dc78c1f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryShapeExtensionsTests.cs @@ -0,0 +1,46 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playback; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaybackDeliveryShapeExtensionsTests +{ + [Fact] + public void IsSeekable_WhenShapeIsByteRangeSeekable_ShouldReturnTrue() + { + // Act + bool isSeekable = PlaybackDeliveryShape.ByteRangeSeekable.IsSeekable(); + + // Assert + Assert.True(isSeekable); + } + + [Fact] + public void IsSeekable_WhenShapeIsTimeAddressedSegments_ShouldReturnTrue() + { + // Act + bool isSeekable = PlaybackDeliveryShape.TimeAddressedSegments.IsSeekable(); + + // Assert + Assert.True(isSeekable); + } + + [Fact] + public void IsSeekable_WhenShapeIsUndefined_ShouldReturnFalse() + { + // Arrange + PlaybackDeliveryShape undefinedShape = (PlaybackDeliveryShape)99; + + // Act + bool isSeekable = undefinedShape.IsSeekable(); + + // Assert + Assert.False(isSeekable); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryShapeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryShapeTests.cs new file mode 100644 index 00000000..19fab6c9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackDeliveryShapeTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playback; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PlaybackDeliveryShapeTests +{ + [Fact] + public void PlaybackDeliveryShape_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PlaybackDeliveryShape[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void PlaybackDeliveryShape_WhenEnumeratingNames_ShouldHaveTheTwoDocumentedMembersInOrder() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(PlaybackDeliveryShape.ByteRangeSeekable), + nameof(PlaybackDeliveryShape.TimeAddressedSegments) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void PlaybackDeliveryShape_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + PlaybackDeliveryShape[] values = Enum.GetValues(); + + // Assert + PlaybackDeliveryShape[] expectedValues = + [ + PlaybackDeliveryShape.ByteRangeSeekable, + PlaybackDeliveryShape.TimeAddressedSegments + ]; + int[] expectedUnderlyingValues = [0, 1]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void PlaybackDeliveryShape_WhenDefaulted_ShouldBeByteRangeSeekable() + { + // Act + PlaybackDeliveryShape deliveryShape = default; + + // Assert + Assert.Equal(PlaybackDeliveryShape.ByteRangeSeekable, deliveryShape); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackStreamingQualityTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackStreamingQualityTests.cs new file mode 100644 index 00000000..a7f14fee --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/PlaybackStreamingQualityTests.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playback; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PlaybackStreamingQualityTests +{ + [Fact] + public void PlaybackStreamingQuality_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PlaybackStreamingQuality[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void PlaybackStreamingQuality_WhenEnumeratingNames_ShouldHaveTheFourDocumentedMembersInOrder() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(PlaybackStreamingQuality.Auto), + nameof(PlaybackStreamingQuality.Low), + nameof(PlaybackStreamingQuality.Medium), + nameof(PlaybackStreamingQuality.High) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void PlaybackStreamingQuality_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + PlaybackStreamingQuality[] values = Enum.GetValues(); + + // Assert + PlaybackStreamingQuality[] expectedValues = + [ + PlaybackStreamingQuality.Auto, + PlaybackStreamingQuality.Low, + PlaybackStreamingQuality.Medium, + PlaybackStreamingQuality.High + ]; + int[] expectedUnderlyingValues = [0, 1, 2, 3]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void PlaybackStreamingQuality_WhenDefaulted_ShouldBeAuto() + { + // Act + PlaybackStreamingQuality streamingQuality = default; + + // Assert + Assert.Equal(PlaybackStreamingQuality.Auto, streamingQuality); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/ReplayGainModeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/ReplayGainModeTests.cs new file mode 100644 index 00000000..b41fa2f3 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/ReplayGainModeTests.cs @@ -0,0 +1,69 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playback; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class ReplayGainModeTests +{ + [Fact] + public void ReplayGainMode_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + ReplayGainMode[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void ReplayGainMode_WhenEnumeratingNames_ShouldHaveTheThreeDocumentedMembersInOrder() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(ReplayGainMode.Off), + nameof(ReplayGainMode.Track), + nameof(ReplayGainMode.Album) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void ReplayGainMode_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + ReplayGainMode[] values = Enum.GetValues(); + + // Assert + ReplayGainMode[] expectedValues = + [ + ReplayGainMode.Off, + ReplayGainMode.Track, + ReplayGainMode.Album + ]; + int[] expectedUnderlyingValues = [0, 1, 2]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void ReplayGainMode_WhenDefaulted_ShouldBeOff() + { + // Act + ReplayGainMode replayGainMode = default; + + // Assert + Assert.Equal(ReplayGainMode.Off, replayGainMode); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/VuMeterOrientationTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/VuMeterOrientationTests.cs new file mode 100644 index 00000000..25fc3038 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playback/VuMeterOrientationTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playback; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playback; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class VuMeterOrientationTests +{ + [Fact] + public void VuMeterOrientation_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + VuMeterOrientation[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void VuMeterOrientation_WhenEnumeratingNames_ShouldHaveTheTwoDocumentedMembersInOrder() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(VuMeterOrientation.Vertical), + nameof(VuMeterOrientation.Horizontal) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void VuMeterOrientation_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + VuMeterOrientation[] values = Enum.GetValues(); + + // Assert + VuMeterOrientation[] expectedValues = + [ + VuMeterOrientation.Vertical, + VuMeterOrientation.Horizontal + ]; + int[] expectedUnderlyingValues = [0, 1]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void VuMeterOrientation_WhenDefaulted_ShouldBeVertical() + { + // Act + VuMeterOrientation orientation = default; + + // Assert + Assert.Equal(VuMeterOrientation.Vertical, orientation); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playlists/PlaylistMediaItemTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playlists/PlaylistMediaItemTypeTests.cs new file mode 100644 index 00000000..7c58613c --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playlists/PlaylistMediaItemTypeTests.cs @@ -0,0 +1,67 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playlists; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PlaylistMediaItemTypeTests +{ + [Fact] + public void PlaylistMediaItemType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PlaylistMediaItemType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void PlaylistMediaItemType_WhenEnumeratingNames_ShouldHaveTheTwoDocumentedMembersInOrder() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(PlaylistMediaItemType.MusicTrack), + nameof(PlaylistMediaItemType.VideoFile) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void PlaylistMediaItemType_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + PlaylistMediaItemType[] values = Enum.GetValues(); + + // Assert + PlaylistMediaItemType[] expectedValues = + [ + PlaylistMediaItemType.MusicTrack, + PlaylistMediaItemType.VideoFile + ]; + int[] expectedUnderlyingValues = [0, 1]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void PlaylistMediaItemType_WhenDefaulted_ShouldBeMusicTrack() + { + // Act + PlaylistMediaItemType mediaItemType = default; + + // Assert + Assert.Equal(PlaylistMediaItemType.MusicTrack, mediaItemType); + } +} diff --git a/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playlists/PlaylistTypeTests.cs b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playlists/PlaylistTypeTests.cs new file mode 100644 index 00000000..d052f5b9 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.SharedKernel.UnitTests/Common/Enums/Playlists/PlaylistTypeTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Domain.SharedKernel.UnitTests.Common.Enums.Playlists; + +/// +/// Contains unit tests for the enumeration. +/// +[ExcludeFromCodeCoverage] +public class PlaylistTypeTests +{ + [Fact] + public void PlaylistType_WhenEnumeratingValues_ShouldHaveNoDuplicateValues() + { + // Act + PlaylistType[] values = Enum.GetValues(); + + // Assert + Assert.Equal(values.Length, values.Distinct().Count()); + } + + [Fact] + public void PlaylistType_WhenEnumeratingNames_ShouldHaveTheSingleDocumentedMember() + { + // Act + string[] names = Enum.GetNames(); + + // Assert + string[] expectedNames = + [ + nameof(PlaylistType.Music) + ]; + Assert.Equal(expectedNames, names); + } + + [Fact] + public void PlaylistType_WhenEnumeratingValues_ShouldHaveTheDocumentedUnderlyingValues() + { + // Act + PlaylistType[] values = Enum.GetValues(); + + // Assert + PlaylistType[] expectedValues = + [ + PlaylistType.Music + ]; + int[] expectedUnderlyingValues = [0]; + Assert.Equal(expectedValues, values); + Assert.Equal(expectedUnderlyingValues, values.Select(value => (int)value)); + } + + [Fact] + public void PlaylistType_WhenDefaulted_ShouldBeMusic() + { + // Act + PlaylistType playlistType = default; + + // Assert + Assert.Equal(PlaylistType.Music, playlistType); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntryTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntryTests.cs new file mode 100644 index 00000000..ca5c959c --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Entities/PlaylistEntryTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryTests +{ + private readonly PlaylistEntryFixture _playlistEntryFixture = new(); + private readonly PlaylistEntryIdFixture _playlistEntryIdFixture = new(); + private readonly MediaItemIdFixture _mediaItemIdFixture = new(); + + [Fact] + public void Create_WhenCalled_ShouldSetEveryProperty() + { + // Arrange + PlaylistEntryId id = _playlistEntryIdFixture.Create(); + MediaItemId mediaItemId = _mediaItemIdFixture.Create(); + + // Act + Result result = PlaylistEntry.Create(id, mediaItemId, PlaylistMediaItemType.MusicTrack, 2_048); + + // Assert + Assert.False(result.IsFailure); + PlaylistEntry entry = result.Value; + Assert.Equal(id, entry.Id); + Assert.Equal(mediaItemId, entry.MediaItemId); + Assert.Equal(PlaylistMediaItemType.MusicTrack, entry.MediaItemType); + Assert.Equal(2_048, entry.Position); + } + + [Theory] + [InlineData(PlaylistMediaItemType.MusicTrack)] // a track of a music library + [InlineData(PlaylistMediaItemType.VideoFile)] // a video file, kept whatever the playlist that references it accepts today + public void Create_WhenCalled_ShouldPreserveTheMediaItemType(PlaylistMediaItemType mediaItemType) + { + // Act + Result result = PlaylistEntry.Create( + _playlistEntryIdFixture.Create(), + _mediaItemIdFixture.Create(), + mediaItemType, + 0); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(mediaItemType, result.Value.MediaItemType); + } + + [Fact] + public void Create_WhenTwoEntriesShareTheSameId_ShouldBeEqual() + { + // Arrange + PlaylistEntryId id = _playlistEntryIdFixture.Create(); + PlaylistEntry firstEntry = _playlistEntryFixture.Create(id: id); + PlaylistEntry secondEntry = _playlistEntryFixture.Create(id: id); + + // Act + bool areEqual = firstEntry.Equals(secondEntry); + + // Assert + Assert.True(areEqual); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEventTests.cs new file mode 100644 index 00000000..f418014a --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistCreatedDomainEventTests.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistCreatedDomainEventTests +{ + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly PlaylistCreatedDomainEventFixture _playlistCreatedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + PlaylistId playlistId = _playlistIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + PlaylistCreatedDomainEvent domainEvent = _playlistCreatedDomainEventFixture.Create( + id, + playlistId, + userId, + "Morning", + PlaylistType.Music, + occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(playlistId, domainEvent.PlaylistId); + Assert.Equal(userId, domainEvent.UserId); + Assert.Equal("Morning", domainEvent.Name); + Assert.Equal(PlaylistType.Music, domainEvent.Type); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEventTests.cs new file mode 100644 index 00000000..d48c5303 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDeletedDomainEventTests.cs @@ -0,0 +1,48 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistDeletedDomainEventTests +{ + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly PlaylistDeletedDomainEventFixture _playlistDeletedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + PlaylistId playlistId = _playlistIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + PlaylistDeletedDomainEvent domainEvent = _playlistDeletedDomainEventFixture.Create( + id, + playlistId, + userId, + occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(playlistId, domainEvent.PlaylistId); + Assert.Equal(userId, domainEvent.UserId); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEventTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEventTests.cs new file mode 100644 index 00000000..a0fd31db --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/Events/PlaylistDetailsUpdatedDomainEventTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistDetailsUpdatedDomainEventTests +{ + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + private readonly PlaylistDetailsUpdatedDomainEventFixture _playlistDetailsUpdatedDomainEventFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldSetAllProperties() + { + // Arrange + Guid id = Guid.NewGuid(); + PlaylistId playlistId = _playlistIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + DateTime occurredOnUtc = DateTime.UtcNow; + + // Act + PlaylistDetailsUpdatedDomainEvent domainEvent = _playlistDetailsUpdatedDomainEventFixture.Create( + id, + playlistId, + userId, + "Deep Focus", + occurredOnUtc); + + // Assert + Assert.Equal(id, domainEvent.Id); + Assert.Equal(playlistId, domainEvent.PlaylistId); + Assert.Equal(userId, domainEvent.UserId); + Assert.Equal("Deep Focus", domainEvent.Name); + Assert.Equal(occurredOnUtc, domainEvent.OccurredOnUtc); + Assert.IsType(domainEvent, exactMatch: false); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs index 446f3f93..8cd08d6c 100644 --- a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/PlaylistTests.cs @@ -1,13 +1,21 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Common.Errors; using Lumina.Domain.Common.Events; using Lumina.Domain.Common.Primitives; using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Events; +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.Entities; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; using Lumina.Domain.SharedKernel.Common.Enums.Playlists; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Linq; #endregion namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate; @@ -18,18 +26,356 @@ namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.Pl [ExcludeFromCodeCoverage] public class PlaylistTests { + private readonly PlaylistFixture _playlistFixture = new(); + private readonly PlaylistIdFixture _playlistIdFixture = new(); + private readonly PlaylistEntryFixture _playlistEntryFixture = new(); + private readonly UserIdFixture _userIdFixture = new(); + + [Fact] + public void Create_WhenCalled_ShouldCreateAPlaylistWithoutEntriesAndRaiseTheCreatedEvent() + { + // Arrange + UserId userId = _userIdFixture.Create(); + DateTime beforeUtc = DateTime.UtcNow; + + // Act + Result result = Playlist.Create(userId, "Morning", Optional.Some("Wake up slowly"), PlaylistType.Music); + + // Assert + Assert.False(result.IsFailure); + Playlist playlist = result.Value; + Assert.NotEqual(Guid.Empty, playlist.Id.Value); + Assert.Equal(userId, playlist.UserId); + Assert.Equal("Morning", playlist.Name); + Assert.True(playlist.Description.HasValue); + Assert.Equal("Wake up slowly", playlist.Description.Value); + Assert.Equal(PlaylistType.Music, playlist.Type); + Assert.False(playlist.IsDeleted); + Assert.Empty(playlist.Entries); + Assert.InRange(playlist.CreatedOnUtc, beforeUtc, DateTime.UtcNow); + Assert.False(playlist.UpdatedOnUtc.HasValue); + PlaylistCreatedDomainEvent createdEvent = Assert.IsType(Assert.Single(playlist.GetDomainEvents())); + Assert.NotEqual(Guid.Empty, createdEvent.Id); + Assert.Equal(playlist.Id, createdEvent.PlaylistId); + Assert.Equal(userId, createdEvent.UserId); + Assert.Equal("Morning", createdEvent.Name); + Assert.Equal(PlaylistType.Music, createdEvent.Type); + Assert.Equal(playlist.CreatedOnUtc, createdEvent.OccurredOnUtc); + } + + [Fact] + public void Create_WhenDescriptionIsNotSupplied_ShouldCreateThePlaylistWithoutADescription() + { + // Act + Result result = Playlist.Create(_userIdFixture.Create(), "Morning", Optional.None(), PlaylistType.Music); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Description.HasValue); + Assert.Single(result.Value.GetDomainEvents()); + } + + [Fact] + public void Create_WhenCalledTwice_ShouldGenerateDistinctIds() + { + // Arrange + UserId userId = _userIdFixture.Create(); + + // Act + Result firstResult = Playlist.Create(userId, "Morning", Optional.None(), PlaylistType.Music); + Result secondResult = Playlist.Create(userId, "Morning", Optional.None(), PlaylistType.Music); + + // Assert + Assert.False(firstResult.IsFailure); + Assert.False(secondResult.IsFailure); + Assert.NotEqual(firstResult.Value.Id, secondResult.Value.Id); + } + + [Fact] + public void Create_WhenRehydratingWithEntries_ShouldPreserveEveryMemberAndRaiseNoEvents() + { + // Arrange + PlaylistId id = _playlistIdFixture.Create(); + UserId userId = _userIdFixture.Create(); + List entries = _playlistEntryFixture.CreateMany(3); + DateTime createdOnUtc = new(2024, 2, 3, 4, 5, 6, DateTimeKind.Utc); + DateTime updatedOnUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc); + + // Act + Result result = Playlist.Create( + id, + userId, + "Commute", + Optional.Some("Train rides"), + PlaylistType.Music, + entries, + createdOnUtc, + Optional.Some(updatedOnUtc)); + + // Assert + Assert.False(result.IsFailure); + Playlist playlist = result.Value; + Assert.Equal(id, playlist.Id); + Assert.Equal(userId, playlist.UserId); + Assert.Equal("Commute", playlist.Name); + Assert.True(playlist.Description.HasValue); + Assert.Equal("Train rides", playlist.Description.Value); + Assert.Equal(PlaylistType.Music, playlist.Type); + Assert.Equal(createdOnUtc, playlist.CreatedOnUtc); + Assert.True(playlist.UpdatedOnUtc.HasValue); + Assert.Equal(updatedOnUtc, playlist.UpdatedOnUtc.Value); + Assert.False(playlist.IsDeleted); + Assert.Equal(entries.Select(entry => entry.Id), playlist.Entries.Select(entry => entry.Id)); + Assert.Empty(playlist.GetDomainEvents()); + } + + [Fact] + public void Create_WhenRehydratingWithoutUpdatedOnUtcOrDescription_ShouldLeaveBothWithoutAValue() + { + // Arrange + DateTime createdOnUtc = new(2024, 2, 3, 4, 5, 6, DateTimeKind.Utc); + + // Act + Result result = Playlist.Create( + _playlistIdFixture.Create(), + _userIdFixture.Create(), + "Commute", + Optional.None(), + PlaylistType.Music, + [], + createdOnUtc, + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(result.Value.Description.HasValue); + Assert.False(result.Value.UpdatedOnUtc.HasValue); + Assert.Empty(result.Value.Entries); + Assert.Empty(result.Value.GetDomainEvents()); + } + + [Theory] + [InlineData(PlaylistMediaItemType.VideoFile)] // a video file cannot belong to a music playlist + [InlineData((PlaylistMediaItemType)999)] // a value outside the declared enumeration members + public void Create_WhenAnEntryReferencesAMediaItemTypeThePlaylistCannotContain_ShouldReturnPlaylistDoesNotAcceptMediaItems(PlaylistMediaItemType mediaItemType) + { + // Arrange + List entries = [_playlistEntryFixture.Create(mediaItemType: mediaItemType)]; + + // Act + Result result = Playlist.Create( + _playlistIdFixture.Create(), + _userIdFixture.Create(), + "Commute", + Optional.None(), + PlaylistType.Music, + entries, + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playlists.PlaylistDoesNotAcceptMediaItems, result.FirstError); + } + + [Fact] + public void Create_WhenThePlaylistTypeIsNotDefined_ShouldReturnPlaylistDoesNotAcceptMediaItems() + { + // Arrange + List entries = [_playlistEntryFixture.Create(mediaItemType: PlaylistMediaItemType.MusicTrack)]; + + // Act + Result result = Playlist.Create( + _playlistIdFixture.Create(), + _userIdFixture.Create(), + "Commute", + Optional.None(), + (PlaylistType)999, + entries, + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playlists.PlaylistDoesNotAcceptMediaItems, result.FirstError); + } + + [Fact] + public void Create_WhenTwoEntriesShareAPosition_ShouldReturnPlaylistEntryPositionsAreInvalid() + { + // Arrange + List entries = + [ + _playlistEntryFixture.Create(position: 1024), + _playlistEntryFixture.Create(position: 1024), + ]; + + // Act + Result result = Playlist.Create( + _playlistIdFixture.Create(), + _userIdFixture.Create(), + "Commute", + Optional.None(), + PlaylistType.Music, + entries, + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.Playlists.PlaylistEntryPositionsAreInvalid, result.FirstError); + } + + [Fact] + public void Create_WhenThePositionsAreSparseAndUnique_ShouldAcceptTheEntries() + { + // Arrange + List entries = + [ + _playlistEntryFixture.Create(position: 0), + _playlistEntryFixture.Create(position: 1_048_576), + _playlistEntryFixture.Create(position: long.MaxValue), + ]; + + // Act + Result result = Playlist.Create( + _playlistIdFixture.Create(), + _userIdFixture.Create(), + "Commute", + Optional.None(), + PlaylistType.Music, + entries, + DateTime.UtcNow, + Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal([0L, 1_048_576L, long.MaxValue], result.Value.Entries.Select(entry => entry.Position)); + } + + [Fact] + public void UpdateDetails_WhenTheNameChanges_ShouldApplyTheNewDetailsAndRaiseTheDetailsUpdatedEvent() + { + // Arrange + UserId userId = _userIdFixture.Create(); + Playlist playlist = _playlistFixture.Create( + userId: userId, + name: "Focus", + description: "Deep work"); + DateTime beforeUtc = DateTime.UtcNow; + + // Act + Result result = playlist.UpdateDetails("Deep Focus", Optional.Some("Long sessions")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.Equal("Deep Focus", playlist.Name); + Assert.True(playlist.Description.HasValue); + Assert.Equal("Long sessions", playlist.Description.Value); + PlaylistDetailsUpdatedDomainEvent updatedEvent = Assert.IsType(Assert.Single(playlist.GetDomainEvents())); + Assert.NotEqual(Guid.Empty, updatedEvent.Id); + Assert.Equal(playlist.Id, updatedEvent.PlaylistId); + Assert.Equal(userId, updatedEvent.UserId); + Assert.Equal("Deep Focus", updatedEvent.Name); + Assert.InRange(updatedEvent.OccurredOnUtc, beforeUtc, DateTime.UtcNow); + } + + [Fact] + public void UpdateDetails_WhenOnlyTheDescriptionChanges_ShouldApplyItAndRaiseTheDetailsUpdatedEvent() + { + // Arrange + Playlist playlist = _playlistFixture.Create( + name: "Focus", + description: "Deep work"); + + // Act + Result result = playlist.UpdateDetails("Focus", Optional.Some("Deeper work")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal("Focus", playlist.Name); + Assert.Equal("Deeper work", playlist.Description.Value); + Assert.Single(playlist.GetDomainEvents()); + } + + [Fact] + public void UpdateDetails_WhenNothingChanges_ShouldReturnUpdatedWithoutRaisingAnEvent() + { + // Arrange + Playlist playlist = _playlistFixture.Create( + name: "Focus", + description: "Deep work"); + + // Act + Result result = playlist.UpdateDetails("Focus", Optional.Some("Deep work")); + + // Assert + Assert.False(result.IsFailure); + Assert.Equal(Result.Updated, result.Value); + Assert.Equal("Focus", playlist.Name); + Assert.Equal("Deep work", playlist.Description.Value); + Assert.Empty(playlist.GetDomainEvents()); + } + + [Fact] + public void UpdateDetails_WhenTheDescriptionAppears_ShouldTreatItAsAChangeAndRaiseTheDetailsUpdatedEvent() + { + // Arrange + Playlist playlist = _playlistFixture.Create( + name: "Focus", + includeDescription: false); + + // Act + Result result = playlist.UpdateDetails("Focus", Optional.Some("Deep work")); + + // Assert + Assert.False(result.IsFailure); + Assert.True(playlist.Description.HasValue); + Assert.Equal("Deep work", playlist.Description.Value); + Assert.Single(playlist.GetDomainEvents()); + } + + [Fact] + public void UpdateDetails_WhenTheDescriptionDisappears_ShouldTreatItAsAChangeAndRaiseTheDetailsUpdatedEvent() + { + // Arrange + Playlist playlist = _playlistFixture.Create( + name: "Focus", + description: "Deep work"); + + // Act + Result result = playlist.UpdateDetails("Focus", Optional.None()); + + // Assert + Assert.False(result.IsFailure); + Assert.False(playlist.Description.HasValue); + Assert.Single(playlist.GetDomainEvents()); + } + + [Theory] + [InlineData(PlaylistType.Music, PlaylistMediaItemType.MusicTrack, true)] // a music playlist accepts music tracks + [InlineData(PlaylistType.Music, PlaylistMediaItemType.VideoFile, false)] // a music playlist does not accept video files + [InlineData(PlaylistType.Music, (PlaylistMediaItemType)999, false)] // a value outside the declared enumeration members + [InlineData((PlaylistType)999, PlaylistMediaItemType.MusicTrack, false)] // a playlist type outside the declared enumeration members + [InlineData((PlaylistType)999, PlaylistMediaItemType.VideoFile, false)] // both sides outside the declared enumeration members + [InlineData((PlaylistType)(-1), PlaylistMediaItemType.MusicTrack, false)] // a playlist type below the declared enumeration members + [InlineData((PlaylistType)(-1), PlaylistMediaItemType.VideoFile, false)] // both sides below the declared enumeration members + public void CanContain_WhenCalled_ShouldOnlyAcceptMusicTracksForMusicPlaylists(PlaylistType playlistType, PlaylistMediaItemType mediaItemType, bool expectedCanContain) + { + // Act + bool canContain = Playlist.CanContain(playlistType, mediaItemType); + + // Assert + Assert.Equal(expectedCanContain, canContain); + } + [Fact] public void Delete_WhenCalled_ShouldMarkThePlaylistAsDeletedAndRaiseOneEvent() { // Arrange - Result createResult = Playlist.Create( - UserId.Create(Guid.NewGuid()), - "Playlist", - Optional.None(), - PlaylistType.Music); - Assert.False(createResult.IsFailure); - Playlist playlist = createResult.Value; - Assert.False(playlist.IsDeleted); + Playlist playlist = _playlistFixture.Create(name: "Playlist"); + DateTime beforeUtc = DateTime.UtcNow; // Act Result result = playlist.Delete(); @@ -37,23 +383,22 @@ public class PlaylistTests // Assert Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); Assert.True(playlist.IsDeleted); - Assert.Single(domainEvents); - Assert.IsType(domainEvents[0]); + PlaylistDeletedDomainEvent deletedEvent = Assert.IsType(Assert.Single(domainEvents)); + Assert.Equal(playlist.Id, deletedEvent.PlaylistId); + Assert.Equal(playlist.UserId, deletedEvent.UserId); + Assert.InRange(deletedEvent.OccurredOnUtc, beforeUtc, DateTime.UtcNow); } [Fact] - public void Delete_WhenCalledAgain_ShouldNotRaiseAnotherEvent() + public void Delete_WhenCalledAgain_ShouldReturnDeletedWithoutMarkingAnythingOrRaisingAnotherEvent() { // Arrange - Result createResult = Playlist.Create( - UserId.Create(Guid.NewGuid()), - "Playlist", - Optional.None(), - PlaylistType.Music); - Assert.False(createResult.IsFailure); - Playlist playlist = createResult.Value; - playlist.Delete(); + Playlist playlist = _playlistFixture.Create(name: "Playlist"); + Result firstResult = playlist.Delete(); + Assert.False(firstResult.IsFailure); + Assert.Single(playlist.GetDomainEvents()); // Act Result result = playlist.Delete(); @@ -61,7 +406,8 @@ public class PlaylistTests // Assert Assert.False(result.IsFailure); + Assert.Equal(Result.Deleted, result.Value); Assert.True(playlist.IsDeleted); - Assert.Single(domainEvents); + Assert.Empty(domainEvents); } } diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryIdTests.cs new file mode 100644 index 00000000..77e29300 --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistEntryIdTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistEntryIdTests +{ + private readonly PlaylistEntryIdFixture _playlistEntryIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + PlaylistEntryId playlistEntryId = PlaylistEntryId.CreateUnique(); + + // Assert + Assert.NotNull(playlistEntryId); + Assert.NotEqual(Guid.Empty, playlistEntryId.Value); + } + + [Fact] + public void CreateUnique_WhenCalledTwice_ShouldGenerateDistinctValues() + { + // Act + PlaylistEntryId firstId = PlaylistEntryId.CreateUnique(); + PlaylistEntryId secondId = PlaylistEntryId.CreateUnique(); + + // Assert + Assert.NotEqual(firstId, secondId); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + PlaylistEntryId playlistEntryId = PlaylistEntryId.Create(value); + + // Assert + Assert.Equal(value, playlistEntryId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + PlaylistEntryId firstId = _playlistEntryIdFixture.Create(value); + PlaylistEntryId secondId = _playlistEntryIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + PlaylistEntryId firstId = _playlistEntryIdFixture.Create(); + PlaylistEntryId secondId = _playlistEntryIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } + + [Fact] + public void GetEqualityComponents_WhenCalled_ShouldReturnOnlyTheValue() + { + // Arrange + PlaylistEntryId playlistEntryId = _playlistEntryIdFixture.Create(); + + // Act + List components = [.. playlistEntryId.GetEqualityComponents()]; + + // Assert + object? component = Assert.Single(components); + Assert.Equal(playlistEntryId.Value, component); + } +} diff --git a/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistIdTests.cs b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistIdTests.cs new file mode 100644 index 00000000..d64fca2f --- /dev/null +++ b/tests/UnitTests/Lumina.Domain.UnitTests/Core/BoundedContexts/PlaylistBoundedContext/PlaylistAggregate/ValueObjects/PlaylistIdTests.cs @@ -0,0 +1,96 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using Lumina.Domain.Fixtures.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Domain.UnitTests.Core.BoundedContexts.PlaylistBoundedContext.PlaylistAggregate.ValueObjects; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistIdTests +{ + private readonly PlaylistIdFixture _playlistIdFixture = new(); + + [Fact] + public void CreateUnique_WhenCalled_ShouldReturnIdWithNonEmptyValue() + { + // Act + PlaylistId playlistId = PlaylistId.CreateUnique(); + + // Assert + Assert.NotNull(playlistId); + Assert.NotEqual(Guid.Empty, playlistId.Value); + } + + [Fact] + public void CreateUnique_WhenCalledTwice_ShouldGenerateDistinctValues() + { + // Act + PlaylistId firstId = PlaylistId.CreateUnique(); + PlaylistId secondId = PlaylistId.CreateUnique(); + + // Assert + Assert.NotEqual(firstId, secondId); + } + + [Fact] + public void Create_WhenCalledWithValue_ShouldReturnIdWithThatValue() + { + // Arrange + Guid value = Guid.NewGuid(); + + // Act + PlaylistId playlistId = PlaylistId.Create(value); + + // Assert + Assert.Equal(value, playlistId.Value); + } + + [Fact] + public void Equals_WithSameValue_ShouldReturnTrue() + { + // Arrange + Guid value = Guid.NewGuid(); + PlaylistId firstId = _playlistIdFixture.Create(value); + PlaylistId secondId = _playlistIdFixture.Create(value); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.True(result); + } + + [Fact] + public void Equals_WithDifferentValue_ShouldReturnFalse() + { + // Arrange + PlaylistId firstId = _playlistIdFixture.Create(); + PlaylistId secondId = _playlistIdFixture.Create(); + + // Act + bool result = firstId.Equals(secondId); + + // Assert + Assert.False(result); + } + + [Fact] + public void GetEqualityComponents_WhenCalled_ShouldReturnOnlyTheValue() + { + // Arrange + PlaylistId playlistId = _playlistIdFixture.Create(); + + // Act + List components = [.. playlistId.GetEqualityComponents()]; + + // Assert + object? component = Assert.Single(components); + Assert.Equal(playlistId.Value, component); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs new file mode 100644 index 00000000..723bdad1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/GetTrackStream/GetTrackStreamEndpointTests.cs @@ -0,0 +1,278 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.Tracks.Queries.GetTrackStream; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.AudioLibrary.MusicLibrary.Tracks.GetTrackStream; + +/// +/// Contains unit tests for the class. +/// +/// +/// The endpoint returns a , so these tests verify everything the endpoint resolves itself: the status, the +/// media type, the entity tag, the last modification time, the range processing flag and the response headers. The actual bytes of the file and +/// the range and conditional request handling are performed by the framework when the result is executed, and are covered by the API +/// integration tests. +/// +[ExcludeFromCodeCoverage] +public class GetTrackStreamEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetTrackStreamEndpoint _sut; + private readonly TrackStreamDataDtoFixture _trackStreamDataDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetTrackStreamEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnPhysicalFileResultWithTheStreamData() + { + // Arrange + DateTimeOffset lastModified = new(2026, 1, 2, 3, 4, 5, TimeSpan.Zero); + TrackStreamDataDto streamData = _trackStreamDataDtoFixture.Create( + path: @"C:\music\track.flac", + format: AudioFileFormat.FLAC, + length: 1234, + lastModified: lastModified); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(streamData)); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + PhysicalFileHttpResult fileResult = Assert.IsType(result); + Assert.Equal(streamData.Path, fileResult.FileName); + Assert.Equal("audio/flac", fileResult.ContentType); + Assert.Null(fileResult.FileDownloadName); + Assert.True(fileResult.EnableRangeProcessing); + Assert.Equal(lastModified, fileResult.LastModified); + Assert.NotNull(fileResult.EntityTag); + Assert.Equal($"\"{lastModified.ToUnixTimeSeconds()}-{streamData.Length}\"", fileResult.EntityTag.Tag.ToString()); + } + + [Theory] + [InlineData(AudioFileFormat.MP3, "audio/mpeg")] // mp3 audio + [InlineData(AudioFileFormat.FLAC, "audio/flac")] // flac audio + [InlineData(AudioFileFormat.OGG, "audio/ogg")] // ogg audio + [InlineData(AudioFileFormat.None, "application/octet-stream")] // an unrecognized format stays opaque binary + public async Task ExecuteAsync_WhenSuccessful_ShouldServeTheMediaTypeOfTheFormat(AudioFileFormat format, string expectedContentType) + { + // Arrange + TrackStreamDataDto streamData = _trackStreamDataDtoFixture.Create(format: format); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(streamData)); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + PhysicalFileHttpResult fileResult = Assert.IsType(result); + Assert.Equal(expectedContentType, fileResult.ContentType); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldDisableContentSniffingAndKeepTheStreamPrivate() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackStreamDataDtoFixture.Create())); + SetRouteValues(); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("nosniff", _sut.HttpContext.Response.Headers["X-Content-Type-Options"].ToString()); + Assert.Equal("private", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenTrackIsNotFound_ShouldReturnNotFoundProblemResult() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Music.TrackNotFound); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal(DomainErrors.Music.TrackNotFound.Code, problemResult.ProblemDetails.Title); + Assert.Equal(DomainErrors.Music.TrackNotFound.Description, problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenTheFileIsOutsideEveryContentLocation_ShouldReturnNotFoundProblemResultWithoutLeakingThePath() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Music.TrackFileNotFound); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("TrackFileNotFound", problemResult.ProblemDetails.Detail); + Assert.DoesNotContain(@"C:\", problemResult.ProblemDetails.Detail, StringComparison.OrdinalIgnoreCase); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserIsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("General.Unauthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + List errors = [DomainErrors.Library.LibraryIdCannotBeEmpty, DomainErrors.Music.TrackIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(errors); + SetRouteValues(); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Contains("LibraryIdCannotBeEmpty", validationProblemDetails.Errors["General.Validation"]); + Assert.Contains("TrackIdCannotBeEmpty", validationProblemDetails.Errors["General.Validation"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendTheExactRouteValuesToTheHandler() + { + // Arrange + string libraryId = "11111111-1111-1111-1111-111111111111"; + string artistId = "22222222-2222-2222-2222-222222222222"; + string albumId = "33333333-3333-3333-3333-333333333333"; + string trackId = "44444444-4444-4444-4444-444444444444"; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackStreamDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues["libraryId"] = libraryId; + _sut.HttpContext.Request.RouteValues["artistId"] = artistId; + _sut.HttpContext.Request.RouteValues["albumId"] = albumId; + _sut.HttpContext.Request.RouteValues["trackId"] = trackId; + CancellationToken cancellationToken = CancellationToken.None; + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == libraryId && + query.ArtistId == artistId && + query.AlbumId == albumId && + query.TrackId == trackId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendNullRouteValuesToTheHandler() + { + // Arrange + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_trackStreamDataDtoFixture.Create())); + _sut.HttpContext.Request.RouteValues.Clear(); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(query => + query.LibraryId == null && + query.ArtistId == null && + query.AlbumId == null && + query.TrackId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_trackStreamDataDtoFixture.Create()); + }, callInfo.Arg())); + SetRouteValues(); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the four route values the endpoint reads from the route. + /// + private void SetRouteValues() + { + _sut.HttpContext.Request.RouteValues["libraryId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["artistId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["albumId"] = Guid.NewGuid().ToString(); + _sut.HttpContext.Request.RouteValues["trackId"] = Guid.NewGuid().ToString(); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs new file mode 100644 index 00000000..bddc533c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs @@ -0,0 +1,264 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntries; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntries; +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.Linq; +using System.Threading; +using System.Threading.Tasks; +using ApplicationErrors = Lumina.Application.Common.Errors.Errors; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddPlaylistEntriesEndpoint _sut; + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedResponseFixture _playlistEntriesAddedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistEntriesAddedResponse() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PlaylistEntriesAddedResponse expectedResponse = _playlistEntriesAddedResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistIdCannotBeEmpty, DomainErrors.Playlists.PlaylistEntryPositionsAreInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRoutePlaylistId("not-a-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistIdCannotBeEmpty", "PlaylistEntryPositionsAreInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistNotFound); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddPlaylistEntriesCommandWithTheRouteIdAndTrackIds() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + List trackIds = [Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()]; + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(trackIds: trackIds); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + SetRoutePlaylistId(playlistId); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == playlistId.ToString() && + command.TrackIds != null && + command.TrackIds.SequenceEqual(trackIds)), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenTrackIdsAreNull_ShouldSendCommandWithNullTrackIds() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(includeTrackIds: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.TrackIds == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithTheRawRouteValue() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + SetRoutePlaylistId("not-a-playlist-guid"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == "not-a-playlist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullPlaylistId() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + PlaylistEntriesAddedResponse expectedResponse = _playlistEntriesAddedResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..aeb4915b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs @@ -0,0 +1,262 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistEntry; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistEntry; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddPlaylistEntryEndpoint _sut; + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryAddedResponseFixture _playlistEntryAddedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistEntryAddedResponse() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PlaylistEntryAddedResponse expectedResponse = _playlistEntryAddedResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistIdCannotBeEmpty, DomainErrors.Playlists.PlaylistEntryPositionsAreInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRoutePlaylistId("not-a-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistIdCannotBeEmpty", "PlaylistEntryPositionsAreInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistNotFound); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddPlaylistEntryCommandWithTheRouteIdAndTrackId() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid trackId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(trackId: trackId); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryAddedResponseFixture.Create())); + SetRoutePlaylistId(playlistId); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == playlistId.ToString() && + command.TrackId == trackId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenTrackIdIsNull_ShouldSendCommandWithNullTrackId() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(includeTrackId: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryAddedResponseFixture.Create())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.TrackId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithTheRawRouteValue() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryAddedResponseFixture.Create())); + SetRoutePlaylistId("not-a-playlist-guid"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == "not-a-playlist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullPlaylistId() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryAddedResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + PlaylistEntryAddedResponse expectedResponse = _playlistEntryAddedResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs new file mode 100644 index 00000000..fd99cfaf --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs @@ -0,0 +1,278 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.AddPlaylistScopeEntries; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.AddPlaylistScopeEntries; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly AddPlaylistScopeEntriesEndpoint _sut; + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedResponseFixture _playlistEntriesAddedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistEntriesAddedResponse() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PlaylistEntriesAddedResponse expectedResponse = _playlistEntriesAddedResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistIdCannotBeEmpty, DomainErrors.Playlists.PlaylistEntryPositionsAreInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRoutePlaylistId("not-a-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistIdCannotBeEmpty", "PlaylistEntryPositionsAreInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistNotFound); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendAddPlaylistScopeEntriesCommandWithTheRouteIdAndTheScope() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + artistId: artistId, + albumId: albumId, + includeArtistId: true, + includeAlbumId: true); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + SetRoutePlaylistId(playlistId); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == playlistId.ToString() && + command.LibraryId == libraryId && + command.ArtistId == artistId && + command.AlbumId == albumId), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenOnlyTheLibraryIsScoped_ShouldSendCommandWithNullArtistAndAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + includeArtistId: false, + includeAlbumId: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.LibraryId == libraryId && + command.ArtistId == null && + command.AlbumId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithTheRawRouteValue() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + SetRoutePlaylistId("not-a-playlist-guid"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == "not-a-playlist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullPlaylistId() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntriesAddedResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + PlaylistEntriesAddedResponse expectedResponse = _playlistEntriesAddedResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs new file mode 100644 index 00000000..8fdb93c8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs @@ -0,0 +1,214 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.CreatePlaylist; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Domain.SharedKernel.Common.Enums.Playlists; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.CreatePlaylist; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly CreatePlaylistEndpoint _sut; + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + private readonly PlaylistResponseFixture _playlistResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistResponse() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PlaylistResponse expectedResponse = _playlistResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistNameCannotBeEmpty, DomainErrors.Playlists.PlaylistNameMustBeMaximum255CharactersLong]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistNameCannotBeEmpty", "PlaylistNameMustBeMaximum255CharactersLong" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistAlreadyExistsError_ShouldReturnConflictProblemResult() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistAlreadyExists); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status409Conflict, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status409Conflict, problemDetails.Status); + Assert.Equal("General.Conflict", problemDetails.Title); + Assert.Equal("PlaylistAlreadyExists", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.10", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendCreatePlaylistCommandWithTheMappedFields() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create( + name: "Road trip", + description: "Songs for the highway.", + type: PlaylistType.Music); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Name == "Road trip" && + command.Description == "Songs for the highway." && + command.Type == PlaylistType.Music), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenOptionalFieldsAreMissing_ShouldSendCommandWithNullDescriptionAndType() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeDescription: false, includeType: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Name == request.Name && + command.Description == null && + command.Type == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + PlaylistResponse expectedResponse = _playlistResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs new file mode 100644 index 00000000..04aa0072 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs @@ -0,0 +1,224 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.DeletePlaylist; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.DeletePlaylist; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly DeletePlaylistEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Deleted, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistNotFound); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationError_ShouldReturnValidationProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRoutePlaylistId("not-a-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistIdCannotBeEmpty" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendDeletePlaylistCommandWithTheRouteId() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + SetRoutePlaylistId(playlistId); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == playlistId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithTheRawRouteValue() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + SetRoutePlaylistId("not-a-playlist-guid"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == "not-a-playlist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullPlaylistId() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Deleted); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Deleted); + }, callInfo.Arg())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs new file mode 100644 index 00000000..d7958ee8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs @@ -0,0 +1,183 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Queries.GetPlaylists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.GetPlaylists; +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.Playlists.GetPlaylists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetPlaylistsEndpoint _sut; + private readonly PlaylistSummaryResponseFixture _playlistSummaryResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistSummaries() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + PlaylistSummaryResponse[] expectedResponse = [.. _playlistSummaryResponseFixture.CreateMany(3)]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserHasNoPlaylists_ShouldReturnOkResultWithAnEmptyArray() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + PlaylistSummaryResponse[] expectedResponse = []; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Empty(okResult.Value!); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders() + { + // Arrange + PlaylistSummaryResponse[] expectedResponse = [.. _playlistSummaryResponseFixture.CreateMany(2)]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResultAndStillSetCacheHeaders() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsInternalError_ShouldReturnInternalServerErrorProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Error.Internal("Playlists.Failed", "An internal error has occurred.")); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status500InternalServerError, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status); + Assert.Equal("Playlists.Failed", problemDetails.Title); + Assert.Equal("An internal error has occurred.", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendOneGetPlaylistsQueryWithTheCallerToken() + { + // Arrange + PlaylistSummaryResponse[] expectedResponse = [.. _playlistSummaryResponseFixture.CreateMany(1)]; + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + PlaylistSummaryResponse[] expectedResponse = [.. _playlistSummaryResponseFixture.CreateMany(1)]; + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..8dccf1de --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs @@ -0,0 +1,268 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.MovePlaylistEntry; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.MovePlaylistEntry; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly MovePlaylistEntryEndpoint _sut; + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryMovedResponseFixture _playlistEntryMovedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistEntryMovedResponse() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PlaylistEntryMovedResponse expectedResponse = _playlistEntryMovedResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistEntryIdCannotBeEmpty, DomainErrors.Playlists.PlaylistMoveTargetPositionIsInvalid]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRouteValues("not-a-guid", "not-an-entry-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistEntryIdCannotBeEmpty", "PlaylistMoveTargetPositionIsInvalid" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistEntryNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistEntryNotFound); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistEntryNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendMovePlaylistEntryCommandWithTheRouteIdsAndTargetPosition() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 7); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryMovedResponseFixture.Create())); + SetRouteValues(playlistId, playlistEntryId); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == playlistId.ToString() && + command.PlaylistEntryId == playlistEntryId.ToString() && + command.TargetPosition == 7), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenTargetPositionIsMissing_ShouldSendCommandWithNullTargetPosition() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(includeTargetPosition: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryMovedResponseFixture.Create())); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.TargetPosition == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithTheRawRouteValues() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryMovedResponseFixture.Create())); + SetRouteValues("not-a-playlist-guid", "not-an-entry-guid"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == "not-a-playlist-guid" && + command.PlaylistEntryId == "not-an-entry-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullRouteValues() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryMovedResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + _sut.HttpContext.Request.RouteValues.Remove("playlistEntryId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null && command.PlaylistEntryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + PlaylistEntryMovedResponse expectedResponse = _playlistEntryMovedResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route values of the playlist and playlist entry identifier route segments. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + private void SetRouteValues(object playlistId, object playlistEntryId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + _sut.HttpContext.Request.RouteValues["playlistEntryId"] = playlistEntryId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..1ee203ed --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs @@ -0,0 +1,237 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.RemovePlaylistEntry; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.RemovePlaylistEntry; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly RemovePlaylistEntryEndpoint _sut; + private readonly PlaylistEntryRemovedResponseFixture _playlistEntryRemovedResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistEntryRemovedResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + PlaylistEntryRemovedResponse expectedResponse = _playlistEntryRemovedResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistIdCannotBeEmpty, DomainErrors.Playlists.PlaylistEntryIdCannotBeEmpty]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRouteValues("not-a-guid", "not-an-entry-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistIdCannotBeEmpty", "PlaylistEntryIdCannotBeEmpty" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistEntryNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistEntryNotFound); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistEntryNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendRemovePlaylistEntryCommandWithTheRouteIds() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryRemovedResponseFixture.Create())); + SetRouteValues(playlistId, playlistEntryId); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == playlistId.ToString() && + command.PlaylistEntryId == playlistEntryId.ToString()), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotParseable_ShouldSendCommandWithTheRawRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryRemovedResponseFixture.Create())); + SetRouteValues("not-a-playlist-guid", "not-an-entry-guid"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == "not-a-playlist-guid" && + command.PlaylistEntryId == "not-an-entry-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldSendCommandWithNullRouteValues() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistEntryRemovedResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + _sut.HttpContext.Request.RouteValues.Remove("playlistEntryId"); + + // Act + await _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null && command.PlaylistEntryId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + PlaylistEntryRemovedResponse expectedResponse = _playlistEntryRemovedResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + SetRouteValues(Guid.NewGuid(), Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(FastEndpoints.EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route values of the playlist and playlist entry identifier route segments. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + private void SetRouteValues(object playlistId, object playlistEntryId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + _sut.HttpContext.Request.RouteValues["playlistEntryId"] = playlistEntryId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs new file mode 100644 index 00000000..eb7f8eab --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs @@ -0,0 +1,266 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.Playlists.Commands.UpdatePlaylist; +using Lumina.Contracts.Fixtures.Core.Requests.Playlists; +using Lumina.Contracts.Fixtures.Core.Responses.Playlists; +using Lumina.Contracts.Requests.Playlists; +using Lumina.Contracts.Responses.Playlists; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.Playlists.UpdatePlaylist; +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; +using DomainErrors = Lumina.Domain.Common.Errors.Errors; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdatePlaylistEndpoint _sut; + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + private readonly PlaylistDetailsResponseFixture _playlistDetailsResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaylistDetailsResponse() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + PlaylistDetailsResponse expectedResponse = _playlistDetailsResponseFixture.Create(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + List expectedErrors = [DomainErrors.Playlists.PlaylistNameCannotBeEmpty, DomainErrors.Playlists.PlaylistDescriptionMustBeMaximum2000CharactersLong]; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedErrors); + SetRoutePlaylistId("not-a-guid"); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.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.NotNull(validationProblemDetails.Extensions["traceId"]); + KeyValuePair singleErrorGroup = Assert.Single(validationProblemDetails.Errors); + Assert.Equal("General.Validation", singleErrorGroup.Key); + Assert.Equal(new[] { "PlaylistNameCannotBeEmpty", "PlaylistDescriptionMustBeMaximum2000CharactersLong" }, singleErrorGroup.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsPlaylistNotFoundError_ShouldReturnNotFoundProblemResult() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(DomainErrors.Playlists.PlaylistNotFound); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status); + Assert.Equal("General.NotFound", problemDetails.Title); + Assert.Equal("PlaylistNotFound", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + ProblemDetails problemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status); + Assert.Equal("General.Unauthorized", problemDetails.Title); + Assert.Equal("NotAuthorized", problemDetails.Detail); + Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type); + Assert.NotNull(problemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdatePlaylistCommandWithTheRouteIdAndTheMappedFields() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create( + name: "Late night", + description: "Quiet tracks."); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistDetailsResponseFixture.Create())); + SetRoutePlaylistId(playlistId); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.PlaylistId == playlistId.ToString() && + command.Name == "Late night" && + command.Description == "Quiet tracks."), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenDescriptionIsMissing_ShouldSendCommandWithNullDescription() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(includeDescription: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistDetailsResponseFixture.Create())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Name == request.Name && + command.Description == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsNotParseable_ShouldSendCommandWithTheRawRouteValue() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistDetailsResponseFixture.Create())); + SetRoutePlaylistId("not-a-playlist-guid"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == "not-a-playlist-guid"), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullPlaylistId() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playlistDetailsResponseFixture.Create())); + _sut.HttpContext.Request.RouteValues.Remove("playlistId"); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => command.PlaylistId == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + PlaylistDetailsResponse expectedResponse = _playlistDetailsResponseFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(expectedResponse); + }, callInfo.Arg())); + SetRoutePlaylistId(Guid.NewGuid()); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs new file mode 100644 index 00000000..44c4e308 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs @@ -0,0 +1,139 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.UsersManagement.Settings.Queries.GetPlaybackState; +using Lumina.Contracts.Fixtures.Core.Responses.UsersManagement.Settings; +using Lumina.Contracts.Responses.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.GetPlaybackState; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +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.UsersManagement.Settings.GetPlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointTests +{ + private readonly IQueryHandler> _mockHandler; + private readonly GetPlaybackStateEndpoint _sut; + private readonly PlaybackStateResponseFixture _playbackStateResponseFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithPlaybackStateResponse() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + PlaybackStateResponse expectedResponse = _playbackStateResponseFixture.Create(volume: 0.35, isMuted: true); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(expectedResponse)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(expectedResponse, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsFailureError_ShouldReturnProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Failure("General.Failure", "An error has occurred."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + Assert.Equal("General.Failure", problemResult.ProblemDetails.Title); + Assert.Equal("An error has occurred.", problemResult.ProblemDetails.Detail); + Assert.NotNull(problemResult.ProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorized_ShouldReturnForbiddenProblemResult() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(ApplicationErrors.Authorization.NotAuthorized); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode); + Assert.Equal("General.Unauthorized", problemResult.ProblemDetails.Title); + Assert.Equal("NotAuthorized", problemResult.ProblemDetails.Detail); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendGetPlaybackStateQueryToHandler() + { + // Arrange + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.From(_playbackStateResponseFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Any(), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(_playbackStateResponseFixture.Create()); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs new file mode 100644 index 00000000..4812fbca --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Api.UnitTests/Core/Endpoints/UsersManagement/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -0,0 +1,145 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Application.Common.CQRS; +using Lumina.Application.Core.UsersManagement.Settings.Commands.UpdatePlaybackState; +using Lumina.Contracts.Fixtures.Core.Requests.UsersManagement.Settings; +using Lumina.Contracts.Requests.UsersManagement.Settings; +using Lumina.Domain.Common.Primitives; +using Lumina.Presentation.Api.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.UsersManagement.Settings.UpdatePlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointTests +{ + private readonly ICommandHandler> _mockHandler; + private readonly UpdatePlaybackStateEndpoint _sut; + private readonly UpdatePlaybackStateRequestFixture _updatePlaybackStateRequestFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateEndpointTests() + { + _mockHandler = Substitute.For>>(); + _sut = FastEndpoints.Factory.Create(_mockHandler); + } + + [Fact] + public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithUpdatedMarker() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.35, isMuted: true); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + Ok okResult = Assert.IsType>(result); + Assert.Equal(Result.Updated, okResult.Value); + } + + [Fact] + public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResult() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 1.5); + CancellationToken cancellationToken = CancellationToken.None; + Error expectedError = Error.Validation("UserSettings.VolumeMustBeBetweenZeroAndOne", "Volume must be between zero and one."); + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(expectedError); + + // Act + IResult result = await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + ProblemHttpResult problemResult = Assert.IsType(result); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode); + Assert.Equal("application/problem+json", problemResult.ContentType); + HttpValidationProblemDetails validationProblemDetails = Assert.IsType(problemResult.ProblemDetails); + Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status); + Assert.Equal("General.Validation", validationProblemDetails.Title); + Assert.Equal(new[] { "Volume must be between zero and one." }, validationProblemDetails.Errors["UserSettings.VolumeMustBeBetweenZeroAndOne"]); + Assert.NotNull(validationProblemDetails.Extensions["traceId"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSendUpdatePlaybackStateCommandToHandler() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(volume: 0.25, isMuted: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Volume == 0.25 && + command.IsMuted == false), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestHasNullValues_ShouldForwardTheNullsToTheHandler() + { + // Arrange + UpdatePlaybackStateRequest request = _updatePlaybackStateRequestFixture.Create(includeVolume: false, includeIsMuted: false); + CancellationToken cancellationToken = CancellationToken.None; + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(Result.Updated); + + // Act + await _sut.ExecuteAsync(request, cancellationToken); + + // Assert + await _mockHandler.Received(1).HandleAsync( + Arg.Is(command => + command.Volume == null && + command.IsMuted == null), + Arg.Is(cancellationToken)); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + + _mockHandler.HandleAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.Arg().ThrowIfCancellationRequested(); + return Result.From(Result.Updated); + }, callInfo.Arg())); + + // Act + Task operationTask = _sut.ExecuteAsync(_updatePlaybackStateRequestFixture.Create(), cancellationTokenSource.Token); + await operationStarted.Task; + cancellationTokenSource.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/StreamingApiHttpClientTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/StreamingApiHttpClientTests.cs new file mode 100644 index 00000000..a80c0ff7 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Common/Api/StreamingApiHttpClientTests.cs @@ -0,0 +1,374 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Configuration; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Fixtures.Common.Api; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Configuration; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Options; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Common.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class StreamingApiHttpClientTests +{ + private const string ENDPOINT = "libraries/tracks/1/stream"; + + private readonly ServerConfigurationDtoFixture _serverConfigurationDtoFixture = new(); + + [Fact] + public void Constructor_WhenCalled_ShouldConfigureTheBaseAddressFromTheServerConfiguration() + { + // Arrange + HttpClient httpClient = new(new TestApiHttpMessageHandler(_ => new HttpResponseMessage(HttpStatusCode.OK))); + + // Act + _ = CreateSut(httpClient); + + // Assert + Assert.Equal(new Uri("http://localhost:5214/api/v1/"), httpClient.BaseAddress); + } + + [Fact] + public void Constructor_WhenCalled_ShouldConfigureATwelveHourTimeout() + { + // Arrange + HttpClient httpClient = new(new TestApiHttpMessageHandler(_ => new HttpResponseMessage(HttpStatusCode.OK))); + + // Act + _ = CreateSut(httpClient); + + // Assert + Assert.Equal(TimeSpan.FromHours(12), httpClient.Timeout); + } + + [Fact] + public async Task GetStreamAsync_WhenCalled_ShouldSendAGetRequestToTheEndpoint() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK)); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.Equal(HttpMethod.Get, messageHandler.Requests[0].Method); + Assert.Equal(new Uri("http://localhost:5214/api/v1/libraries/tracks/1/stream"), messageHandler.Requests[0].RequestUri); + } + + [Fact] + public async Task GetStreamAsync_WhenRequestHeadersProvided_ShouldForwardThemVerbatim() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK)); + StreamingApiHttpClient sut = CreateSut(messageHandler); + Dictionary requestHeaders = new() + { + ["Range"] = "bytes=1024-2047", + ["If-None-Match"] = "\"etag-value\"", + ["If-Modified-Since"] = "Wed, 21 Oct 2026 07:28:00 GMT" + }; + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, requestHeaders, CancellationToken.None); + + // Assert + HttpRequestMessage request = messageHandler.Requests[0]; + Assert.Equal("bytes=1024-2047", request.Headers.Range!.ToString()); + Assert.Equal("\"etag-value\"", Assert.Single(request.Headers.IfNoneMatch).Tag); + Assert.Equal(new DateTimeOffset(2026, 10, 21, 7, 28, 0, TimeSpan.Zero), request.Headers.IfModifiedSince); + } + + [Fact] + public async Task GetStreamAsync_WhenUserHasToken_ShouldSendTheBearerToken() + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK)); + StreamingApiHttpClient sut = CreateSut(messageHandler, token: "test-jwt-token"); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.Equal("Bearer", messageHandler.Requests[0].Headers.Authorization!.Scheme); + Assert.Equal("test-jwt-token", messageHandler.Requests[0].Headers.Authorization!.Parameter); + } + + [Theory] + [InlineData(false, null)] // there is no HTTP context at all + [InlineData(true, null)] // the HTTP context has no token claim + [InlineData(true, "")] // the token claim is empty + public async Task GetStreamAsync_WhenTokenIsUnavailable_ShouldNotSendAnAuthorizationHeader(bool hasHttpContext, string? token) + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => CreateStreamResponse(HttpStatusCode.OK)); + StreamingApiHttpClient sut = CreateSut(messageHandler, token: token, hasHttpContext: hasHttpContext); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.Null(messageHandler.Requests[0].Headers.Authorization); + } + + [Fact] + public async Task GetStreamAsync_WhenCalled_ShouldHandOverTheContentStreamWithoutBufferingIt() + { + // Arrange + TrackingStreamContent content = new(Encoding.UTF8.GetBytes("streamed-audio"), "audio/mp4"); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.False(content.WasBufferedByClient); + Assert.Same(content.ContentStream, result.Content); + } + + [Fact] + public async Task GetStreamAsync_WhenApiReturnsOk_ShouldReturnAStreamResultWithTheContent() + { + // Arrange + byte[] contentBytes = Encoding.UTF8.GetBytes("streamed-audio"); + TrackingStreamContent content = new(contentBytes, "audio/mp4"); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.Equal(HttpStatusCode.OK, result.StatusCode); + Assert.Equal("audio/mp4", result.ContentType); + Assert.Equal(contentBytes.Length, result.ContentLength); + } + + [Fact] + public async Task GetStreamAsync_WhenApiReturnsPartialContent_ShouldReturnAStreamResultWithTheRangeHeaders() + { + // Arrange + byte[] contentBytes = Encoding.UTF8.GetBytes("streamed-audio-segment"); + TrackingStreamContent content = new(contentBytes, "audio/mp4"); + content.Headers.ContentRange = new ContentRangeHeaderValue(0, contentBytes.Length - 1, 4096); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.PartialContent) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.Equal(HttpStatusCode.PartialContent, result.StatusCode); + Assert.Equal($"bytes 0-{contentBytes.Length - 1}/4096", result.ContentRange); + Assert.Equal(contentBytes.Length, result.ContentLength); + } + + [Theory] + [InlineData(HttpStatusCode.NotModified)] // a conditional request that the entity tag did not invalidate + [InlineData(HttpStatusCode.RequestedRangeNotSatisfiable)] // a ranged request that cannot be satisfied + public async Task GetStreamAsync_WhenApiReturnsANonSuccessThatIsAValidOutcome_ShouldPassTheResponseThrough(HttpStatusCode statusCode) + { + // Arrange + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(statusCode)); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await using ApiStreamResult result = await sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None); + + // Assert + Assert.Equal(statusCode, result.StatusCode); + } + + [Theory] + [InlineData(HttpStatusCode.BadRequest)] // a malformed request + [InlineData(HttpStatusCode.NotFound)] // the track does not exist + [InlineData(HttpStatusCode.InternalServerError)] // the API failed + public async Task GetStreamAsync_WhenApiReturnsAnotherNonSuccess_ShouldThrowApiExceptionWithTheProblemDetails(HttpStatusCode statusCode) + { + // Arrange + string problemDetailsJson = $$""" + { + "type": "https://tools.ietf.org/html/rfc9110#section-15.5.5", + "title": "General.NotFound", + "status": {{(int)statusCode}}, + "detail": "The requested track was not found." + } + """; + TrackingStreamContent content = new(Encoding.UTF8.GetBytes(problemDetailsJson), "application/problem+json"); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(statusCode) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None)); + + // Assert + Assert.Equal(statusCode, exception.HttpStatusCode); + Assert.NotNull(exception.ProblemDetails); + Assert.Equal("General.NotFound", exception.ProblemDetails!.Title); + Assert.Equal((int)statusCode, exception.ProblemDetails!.Status); + Assert.Equal("The requested track was not found.", exception.ProblemDetails!.Detail); + Assert.Equal("/api/v1/libraries/tracks/1/stream", exception.RequestPath); + } + + [Fact] + public async Task GetStreamAsync_WhenErrorBodyIsNotProblemDetails_ShouldThrowApiExceptionWithoutProblemDetails() + { + // Arrange + TrackingStreamContent content = new(Encoding.UTF8.GetBytes("upstream failure"), "text/html"); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.BadGateway) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + ApiException exception = await Assert.ThrowsAsync(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None)); + + // Assert + Assert.Equal(HttpStatusCode.BadGateway, exception.HttpStatusCode); + Assert.Null(exception.ProblemDetails); + Assert.Equal("An error occurred.", exception.Message); + } + + [Fact] + public async Task GetStreamAsync_WhenApiReturnsANonSuccess_ShouldDisposeTheResponse() + { + // Arrange + TrackingStreamContent content = new(Encoding.UTF8.GetBytes("""{"title":"General.Failure","status":500}"""), "application/json"); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await Assert.ThrowsAsync(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None)); + + // Assert + Assert.True(content.IsDisposed); + } + + [Fact] + public async Task GetStreamAsync_WhenContentStreamCannotBeObtained_ShouldDisposeTheResponse() + { + // Arrange + TrackingStreamContent content = new(Encoding.UTF8.GetBytes("streamed-audio"), "audio/mp4", shouldFailStreamCreation: true); + TestApiHttpMessageHandler messageHandler = new(_ => new HttpResponseMessage(HttpStatusCode.OK) { Content = content }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + await Assert.ThrowsAsync(() => sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), CancellationToken.None)); + + // Assert + Assert.True(content.IsDisposed); + } + + [Fact] + public async Task GetStreamAsync_WhenCancellationIsRequested_ShouldCancelTheOperation() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + TaskCompletionSource requestStarted = new(); + TestApiHttpMessageHandler messageHandler = new(async (request, cancellationToken) => + { + requestStarted.SetResult(true); + await Task.Delay(Timeout.Infinite, cancellationToken); + return new HttpResponseMessage(HttpStatusCode.OK); + }); + StreamingApiHttpClient sut = CreateSut(messageHandler); + + // Act + Task operationTask = sut.GetStreamAsync(ENDPOINT, CreateForwardedHeaders(), cancellationTokenSource.Token); + await requestStarted.Task; + cancellationTokenSource.Cancel(); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + Assert.True(messageHandler.CancellationTokens[0].IsCancellationRequested); + } + + /// + /// Creates the system under test around the provided HTTP client. + /// + /// The HTTP client the system under test sends its requests through. + /// The created . + private StreamingApiHttpClient CreateSut(HttpClient httpClient) + { + IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); + serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214)); + return new StreamingApiHttpClient(httpClient, Substitute.For(), serverConfigurationOptions); + } + + /// + /// Creates the system under test configured with the provided message handler. + /// + /// The message handler backing the inner . + /// Optional token claim to place on the current HTTP context user. + /// Whether an HTTP context is available to the system under test. + /// The created . + private StreamingApiHttpClient CreateSut(TestApiHttpMessageHandler messageHandler, string? token = null, bool hasHttpContext = true) + { + HttpClient httpClient = new(messageHandler); + IHttpContextAccessor httpContextAccessor = Substitute.For(); + if (hasHttpContext) + { + Claim[] claims = token is null ? [] : [new Claim("Token", token)]; + DefaultHttpContext httpContext = new() + { + User = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuthentication")) + }; + httpContextAccessor.HttpContext.Returns(httpContext); + } + return CreateSut(httpClient, httpContextAccessor); + } + + /// + /// Creates the system under test around the provided HTTP client and HTTP context accessor. + /// + /// The HTTP client the system under test sends its requests through. + /// The accessor that provides the current HTTP context. + /// The created . + private StreamingApiHttpClient CreateSut(HttpClient httpClient, IHttpContextAccessor httpContextAccessor) + { + IOptionsSnapshot serverConfigurationOptions = Substitute.For>(); + serverConfigurationOptions.Value.Returns(_serverConfigurationDtoFixture.Create(apiVersion: '1', baseAddress: "http://localhost", port: 5214)); + return new StreamingApiHttpClient(httpClient, httpContextAccessor, serverConfigurationOptions); + } + + /// + /// Creates the range and conditional headers an incoming streaming request forwards to the API. + /// + /// The forwarded headers. + private static Dictionary CreateForwardedHeaders() + { + return new Dictionary + { + ["Range"] = "bytes=0-1023", + ["If-None-Match"] = "\"etag-value\"" + }; + } + + /// + /// Creates a streamed API response with the given status code and a known content stream. + /// + /// The HTTP status code of the response. + /// The created HTTP response. + private static HttpResponseMessage CreateStreamResponse(HttpStatusCode statusCode) + { + return new HttpResponseMessage(statusCode) + { + Content = new TrackingStreamContent(Encoding.UTF8.GetBytes("streamed-audio"), "audio/mp4") + }; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs index c3036b52..708984c9 100644 --- a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Library/AudioLibrary/MusicLibrary/Tracks/StreamMusicTrack/StreamMusicTrackEndpointTests.cs @@ -1,6 +1,8 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Common; +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.StreamMusicTrack; @@ -139,6 +141,49 @@ public class StreamMusicTrackEndpointTests Arg.Any()); } + [Theory] + [InlineData(HttpStatusCode.ServiceUnavailable)] // a busy normalization pipeline is a transient condition + [InlineData(HttpStatusCode.TooManyRequests)] // the stream concurrency limit was reached + public async Task ExecuteAsync_WhenApiReportsATransientCondition_ShouldReturnABareStatusWithoutThrowing(HttpStatusCode statusCode) + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(); + ApiException apiException = new( + new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = (int)statusCode }, + statusCode, + BuildExpectedEndpoint(request)); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Task.FromException(apiException)); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + Assert.IsType(result); + Assert.Equal((int)statusCode, _sut.HttpContext.Response.StatusCode); + Assert.Equal(0, _sut.HttpContext.Response.ContentLength); + Assert.Equal(0, _sut.HttpContext.Response.Body.Length); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReportsAnUnexpectedFailure_ShouldPropagateTheApiException() + { + // Arrange + StreamMusicTrackRequest request = _streamMusicTrackRequestFixture.Create(); + ApiException apiException = new( + new ProblemDetailsDto { Title = "General.Failure", Detail = "InternalServerError", Status = StatusCodes.Status500InternalServerError }, + HttpStatusCode.InternalServerError, + BuildExpectedEndpoint(request)); + _mockStreamingApiHttpClient.GetStreamAsync(Arg.Any(), Arg.Any>(), Arg.Any()) + .Returns(Task.FromException(apiException)); + + // Act + Task operationTask = _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await Assert.ThrowsAsync(() => operationTask); + } + [Fact] public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() { diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs new file mode 100644 index 00000000..12c9df2c --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntries/AddPlaylistEntriesEndpointTests.cs @@ -0,0 +1,214 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.AddPlaylistEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntriesEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddPlaylistEntriesEndpoint _sut; + private readonly AddPlaylistEntriesRequestFixture _addPlaylistEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntriesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheAddedEntriesSummary() + { + // Arrange + PlaylistEntriesAddedDto expectedSummary = _playlistEntriesAddedDtoFixture.Create( + playlistId: Guid.NewGuid(), + addedCount: 4); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedSummary); + + // Act + IResult result = await _sut.ExecuteAsync(_addPlaylistEntriesRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistEntriesAddedDto actualSummary = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedSummary, actualSummary); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldPostTheRequestPayloadOnceToTheDocumentedEndpoint() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + SetRoutePlaylistId(playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}/entries-batch"), + Arg.Is(payload => payload.TrackIds != null && payload.TrackIds.SequenceEqual(request.TrackIds!)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant()); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}/entries-batch"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + SetRoutePlaylistId("not-a-guid"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries-batch"), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid() + { + // Arrange + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries-batch"), + Arg.Any(), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload) + { + // Arrange + SetRoutePlaylistId(payload); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries-batch"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddPlaylistEntriesRequest request = _addPlaylistEntriesRequestFixture.Create(); + PlaylistEntriesAddedDto expectedSummary = _playlistEntriesAddedDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return expectedSummary; + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..f8f3674a --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistEntry/AddPlaylistEntryEndpointTests.cs @@ -0,0 +1,219 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.AddPlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistEntryEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddPlaylistEntryEndpoint _sut; + private readonly AddPlaylistEntryRequestFixture _addPlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryAddedDtoFixture _playlistEntryAddedDtoFixture = new(); + private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistEntryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheAddedEntry() + { + // Arrange + PlaylistEntryDto expectedAddedEntry = _playlistEntryDtoFixture.Create( + position: 2, + mediaItemTitle: "Added track"); + PlaylistEntryAddedDto expectedEntry = _playlistEntryAddedDtoFixture.Create( + playlistId: Guid.NewGuid(), + entry: expectedAddedEntry); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedEntry); + + // Act + IResult result = await _sut.ExecuteAsync(_addPlaylistEntryRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistEntryAddedDto actualEntry = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedEntry.PlaylistId, actualEntry.PlaylistId); + Assert.Equal(expectedEntry.UpdatedOnUtc, actualEntry.UpdatedOnUtc); + Assert.Equal(expectedEntry.Entry, actualEntry.Entry); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldPostTheRequestPayloadOnceToTheDocumentedEndpoint() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + SetRoutePlaylistId(playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}/entries"), + Arg.Is(payload => payload.TrackId == request.TrackId), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant()); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}/entries"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + SetRoutePlaylistId("not-a-guid"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries"), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid() + { + // Arrange + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries"), + Arg.Any(), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload) + { + // Arrange + SetRoutePlaylistId(payload); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddPlaylistEntryRequest request = _addPlaylistEntryRequestFixture.Create(); + PlaylistEntryAddedDto expectedEntry = _playlistEntryAddedDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return expectedEntry; + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs new file mode 100644 index 00000000..da3c2f43 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/AddPlaylistScopeEntries/AddPlaylistScopeEntriesEndpointTests.cs @@ -0,0 +1,248 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.AddPlaylistScopeEntries; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.AddPlaylistScopeEntries; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class AddPlaylistScopeEntriesEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly AddPlaylistScopeEntriesEndpoint _sut; + private readonly AddPlaylistScopeEntriesRequestFixture _addPlaylistScopeEntriesRequestFixture = new(); + private readonly PlaylistEntriesAddedDtoFixture _playlistEntriesAddedDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public AddPlaylistScopeEntriesEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheAddedEntriesSummary() + { + // Arrange + PlaylistEntriesAddedDto expectedSummary = _playlistEntriesAddedDtoFixture.Create( + playlistId: Guid.NewGuid(), + addedCount: 12); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedSummary); + + // Act + IResult result = await _sut.ExecuteAsync(_addPlaylistScopeEntriesRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistEntriesAddedDto actualSummary = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedSummary, actualSummary); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldPostTheScopeOnceToTheDocumentedEndpoint() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid libraryId = Guid.NewGuid(); + Guid artistId = Guid.NewGuid(); + Guid albumId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + artistId: artistId, + albumId: albumId); + SetRoutePlaylistId(playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}/entries-scope"), + Arg.Is(payload => + payload.LibraryId == libraryId && + payload.ArtistId == artistId && + payload.AlbumId == albumId), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenOnlyTheLibraryIsScoped_ShouldPostTheScopeWithNullArtistAndAlbum() + { + // Arrange + Guid libraryId = Guid.NewGuid(); + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create( + libraryId: libraryId, + includeArtistId: false, + includeAlbumId: false); + SetRoutePlaylistId(Guid.NewGuid()); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Any(), + Arg.Is(payload => + payload.LibraryId == libraryId && + payload.ArtistId == null && + payload.AlbumId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant()); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistScopeEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}/entries-scope"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + SetRoutePlaylistId("not-a-guid"); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistScopeEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries-scope"), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid() + { + // Arrange + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistScopeEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries-scope"), + Arg.Any(), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload) + { + // Arrange + SetRoutePlaylistId(payload); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntriesAddedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_addPlaylistScopeEntriesRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries-scope"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PostAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + AddPlaylistScopeEntriesRequest request = _addPlaylistScopeEntriesRequestFixture.Create(); + PlaylistEntriesAddedDto expectedSummary = _playlistEntriesAddedDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return expectedSummary; + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs new file mode 100644 index 00000000..6f6b5e19 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/CreatePlaylist/CreatePlaylistEndpointTests.cs @@ -0,0 +1,148 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.CreatePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.CreatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class CreatePlaylistEndpointTests +{ + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly CreatePlaylistEndpoint _sut; + private readonly CreatePlaylistRequestFixture _createPlaylistRequestFixture = new(); + private readonly PlaylistDtoFixture _playlistDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public CreatePlaylistEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheCreatedPlaylist() + { + // Arrange + PlaylistDto expectedPlaylist = _playlistDtoFixture.Create( + name: "Road trip", + description: "Songs for the highway."); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedPlaylist); + + // Act + IResult result = await _sut.ExecuteAsync(_createPlaylistRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistDto actualPlaylist = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedPlaylist.Id, actualPlaylist.Id); + Assert.Equal(expectedPlaylist.Name, actualPlaylist.Name); + Assert.Equal(expectedPlaylist.Description, actualPlaylist.Description); + Assert.Equal(expectedPlaylist.Type, actualPlaylist.Type); + Assert.Equal(expectedPlaylist.CreatedOnUtc, actualPlaylist.CreatedOnUtc); + Assert.Equal(expectedPlaylist.UpdatedOnUtc, actualPlaylist.UpdatedOnUtc); + Assert.Equal(expectedPlaylist.Entries.CurrentPage, actualPlaylist.Entries.CurrentPage); + Assert.Equal(expectedPlaylist.Entries.PerPage, actualPlaylist.Entries.PerPage); + Assert.Equal(expectedPlaylist.Entries.Count, actualPlaylist.Entries.Count); + Assert.Equal(expectedPlaylist.Entries.NumberOfPages, actualPlaylist.Entries.NumberOfPages); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldPostTheRequestPayloadOnceToTheDocumentedEndpoint() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create( + name: "Road trip", + description: "Songs for the highway."); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Is(endpoint => endpoint == "users/me/playlists"), + Arg.Is(payload => + payload.Name == "Road trip" && + payload.Description == "Songs for the highway." && + payload.Type == request.Type), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenOptionalFieldsAreMissing_ShouldPostTheRequestWithNulls() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(includeDescription: false, includeType: false); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PostAsync( + Arg.Any(), + Arg.Is(payload => + payload.Name == request.Name && + payload.Description == null && + payload.Type == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CreatePlaylistRequest request = _createPlaylistRequestFixture.Create(); + PlaylistDto expectedPlaylist = _playlistDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockApiHttpClient.PostAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return expectedPlaylist; + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs new file mode 100644 index 00000000..12ebd67b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/DeletePlaylist/DeletePlaylistEndpointTests.cs @@ -0,0 +1,173 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.DeletePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.DeletePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class DeletePlaylistEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly DeletePlaylistEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public DeletePlaylistEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutADataPayload() + { + // Arrange + SetRoutePlaylistId(s_playlistId); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteTheDocumentedEndpointOnce() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + SetRoutePlaylistId(playlistId); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}"), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().DeleteAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + SetRoutePlaylistId("not-a-guid"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid() + { + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}"), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload) + { + // Arrange + SetRoutePlaylistId(payload); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}"), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().DeleteAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.DeleteAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(1).ThrowIfCancellationRequested(); + }, callInfo.ArgAt(1))); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs new file mode 100644 index 00000000..bce8d6f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/GetPlaylists/GetPlaylistsEndpointTests.cs @@ -0,0 +1,143 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylists; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.GetPlaylists; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaylistsEndpointTests +{ + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetPlaylistsEndpoint _sut; + private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaylistsEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsPlaylists_ShouldReturnSuccessJsonWithTheSummaries() + { + // Arrange + PlaylistSummaryDto[] expectedSummaries = + [ + _playlistSummaryDtoFixture.Create(name: "Morning", entryCount: 12), + _playlistSummaryDtoFixture.Create(name: "Evening", entryCount: 4) + ]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedSummaries); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistSummaryDto[] actualSummaries = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedSummaries, actualSummaries); + } + + [Fact] + public async Task ExecuteAsync_WhenTheUserHasNoPlaylists_ShouldReturnSuccessJsonWithAnEmptyArray() + { + // Arrange + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns([]); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.Equal(0, jsonDocument.RootElement.GetProperty("data").GetArrayLength()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldGetTheDocumentedEndpointOnce() + { + // Arrange + PlaylistSummaryDto[] expectedSummaries = [.. _playlistSummaryDtoFixture.CreateMany()]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedSummaries); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync( + Arg.Is(endpoint => endpoint == "users/me/playlists"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders() + { + // Arrange + PlaylistSummaryDto[] expectedSummaries = [.. _playlistSummaryDtoFixture.CreateMany()]; + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(expectedSummaries); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + PlaylistSummaryDto[] expectedSummaries = [.. _playlistSummaryDtoFixture.CreateMany(1)]; + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockApiHttpClient.GetAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(1).ThrowIfCancellationRequested(); + return expectedSummaries; + }, callInfo.ArgAt(1))); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs new file mode 100644 index 00000000..d7f621d2 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/Index/PlaylistsIndexViewEndpointTests.cs @@ -0,0 +1,288 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Http; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Common.Services; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.Index; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.Index; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PlaylistsIndexViewEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IUrlService _mockUrlService; + private readonly ThemePageRenderer _mockThemePageRenderer; + private readonly IAntiforgery _mockAntiforgery; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly PlaylistsIndexViewEndpoint _sut; + private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new(); + private readonly List _itemRouteValues = []; + private readonly List _deleteRouteValues = []; + + /// + /// Initializes a new instance of the class. + /// + public PlaylistsIndexViewEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _mockUrlService = Substitute.For(); + _mockThemePageRenderer = Substitute.For(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine()); + _mockAntiforgery = Substitute.For(); + _mockAntiforgery.GetAndStoreTokens(Arg.Any()) + .Returns(new AntiforgeryTokenSet("request-token", "cookie-token", "__RequestVerificationToken", "RequestVerificationToken")); + _mockStringLocalizer = Substitute.For(); + _mockStringLocalizer[Arg.Any()].Returns(callInfo => new LocalizedString( + callInfo.Arg(), + callInfo.Arg() == "Title" ? "Playlists" : $"Localized-{callInfo.Arg()}")); + _mockStringLocalizer.GetAllStrings(Arg.Any()).Returns(new LocalizedString[] + { + new("Title", "Playlists"), + new("NoPlaylists", "You have no playlists yet.") + }); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _sut = Factory.Create(_mockUrlService, _mockThemePageRenderer, _mockAntiforgery, _mockStringLocalizerFactory); + TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession()); + _sut.HttpContext.Request.Path = "/en-us/playlists"; + + StubUrls(); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldRenderThemedViewWithDocumentedPageData() + { + // Arrange + ThemePageRenderResultDto renderedPage = _themePageRenderResultDtoFixture.Create( + content: "
playlists
", + script: ""); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(renderedPage)); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Shared/_ThemedView.cshtml", GetRenderedViewName(result)); + ThemeViewDto themedView = Assert.IsType(GetRenderedModel(result)); + Assert.Equal(renderedPage.Content, themedView.Content); + Assert.Equal(renderedPage.Script, themedView.Script); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => + page.PageKey == "playlists/index" && + page.Title == "Playlists" && + page.Description == string.Empty && + string.Equals(page.PageData["getPlaylistsUrl"] as string, "http://localhost/en-us/playlists/api-get-playlists", StringComparison.Ordinal) && + string.Equals(page.PageData["addUrl"] as string, "http://localhost/en-us/playlists/item", StringComparison.Ordinal) && + string.Equals(page.PageData["itemUrl"] as string, $"http://localhost/en-us/playlists/item/{ZERO_GUID}", StringComparison.Ordinal) && + string.Equals(page.PageData["deleteUrl"] as string, $"http://localhost/en-us/playlists/item/{ZERO_GUID}/api-delete-playlist", StringComparison.Ordinal) && + HasDocumentedLocalizedStrings(page)), + Arg.Is(requestedThemeId => requestedThemeId == null), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldResolveTheAllZeroGuidTemplatesOfThePlaylistRoutes() + { + // Arrange + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + // The playlist links replace the all-zero Guid placeholder, so the route values must carry an empty Guid. + Assert.Single(_itemRouteValues); + AssertRouteValueIsEmptyGuid(_itemRouteValues[0], "playlistId"); + Assert.Single(_deleteRouteValues); + AssertRouteValueIsEmptyGuid(_deleteRouteValues[0], "playlistId"); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders() + { + // Arrange + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString()); + Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestAndExposeAFreshAntiforgeryToken() + { + // Arrange + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.From(_themePageRenderResultDtoFixture.Create())); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + _mockAntiforgery.Received(1).GetAndStoreTokens(_sut.HttpContext); + await _mockThemePageRenderer.Received(1).RenderAsync( + Arg.Is(page => string.Equals(page.PageData["antiforgeryToken"] as string, "request-token", StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldFallBackToTheRazorViewWithTheLocalizedTitle() + { + // Arrange + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(Result.Failure(Error.Failure("Theme.Render", "The page could not be rendered."))); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + Assert.Equal("/Core/Views/Playlists/Index.cshtml", GetRenderedViewName(result)); + IReadOnlyDictionary viewData = GetRenderedViewData(result); + Assert.Equal("Playlists", viewData["Title"]); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + ThemePageRenderResultDto renderedPage = _themePageRenderResultDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + _mockThemePageRenderer.RenderAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return Result.From(renderedPage); + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Stubs the absolute URLs that the endpoint resolves for the playlists page. + /// + private void StubUrls() + { + _mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLISTS) + .Returns("http://localhost/en-us/playlists/api-get-playlists"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.ADD) + .Returns("http://localhost/en-us/playlists/item"); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, Arg.Any()) + .Returns(callInfo => + { + _itemRouteValues.Add(callInfo.ArgAt(1)); + return $"http://localhost/en-us/playlists/item/{ZERO_GUID}"; + }); + _mockUrlService.GetAbsoluteUrl(WebRoutes.Playlists.DELETE_PLAYLIST, Arg.Any()) + .Returns(callInfo => + { + _deleteRouteValues.Add(callInfo.ArgAt(1)); + return $"http://localhost/en-us/playlists/item/{ZERO_GUID}/api-delete-playlist"; + }); + } + + /// + /// Determines whether the page data carries the localized strings of the playlists page. + /// + /// The page model passed to the theme renderer. + /// when the localized strings are exposed under the strings key; otherwise . + private static bool HasDocumentedLocalizedStrings(ThemePageDto page) + { + if (!page.PageData.TryGetValue("strings", out object? value) || value is not Dictionary strings) + return false; + return string.Equals(strings["Title"] as string, "Playlists", StringComparison.Ordinal) + && string.Equals(strings["NoPlaylists"] as string, "You have no playlists yet.", StringComparison.Ordinal); + } + + /// + /// Asserts that the named property of an anonymous route values object is the empty Guid. + /// + /// The anonymous route values object passed to the URL service. + /// The name of the route value property to check. + private static void AssertRouteValueIsEmptyGuid(object? routeValues, string propertyName) + { + Assert.NotNull(routeValues); + PropertyInfo? property = routeValues!.GetType().GetProperty(propertyName); + Assert.NotNull(property); + Assert.Equal(Guid.Empty, (Guid)property!.GetValue(routeValues)!); + } + + /// + /// Reads the private view name of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The name or path of the rendered view. + private static string GetRenderedViewName(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? viewNameField = typeof(RazorViewResult).GetField("_viewName", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(viewNameField); + return (string)viewNameField.GetValue(viewResult)!; + } + + /// + /// Reads the private model of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The model passed to the rendered view. + private static object? GetRenderedModel(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? modelField = typeof(RazorViewResult).GetField("_model", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(modelField); + return modelField.GetValue(viewResult); + } + + /// + /// Reads the private view data of the rendered , which the result does not expose publicly. + /// + /// The result returned by the endpoint under test. + /// The view data entries passed to the rendered view. + private static IReadOnlyDictionary GetRenderedViewData(IResult result) + { + RazorViewResult viewResult = Assert.IsType(result); + FieldInfo? viewDataField = typeof(RazorViewResult).GetField("_viewData", BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(viewDataField); + return (IReadOnlyDictionary)viewDataField.GetValue(viewResult)!; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..dd08f024 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/MovePlaylistEntry/MovePlaylistEntryEndpointTests.cs @@ -0,0 +1,218 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.MovePlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.MovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MovePlaylistEntryEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + private static readonly Guid s_playlistEntryId = Guid.Parse("FEDCBAFE-DCBA-FEDC-BAFE-DCBAFEDCBAFE"); + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly MovePlaylistEntryEndpoint _sut; + private readonly MovePlaylistEntryRequestFixture _movePlaylistEntryRequestFixture = new(); + private readonly PlaylistEntryMovedDtoFixture _playlistEntryMovedDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public MovePlaylistEntryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheMovedEntry() + { + // Arrange + PlaylistEntryMovedDto expectedEntry = _playlistEntryMovedDtoFixture.Create( + playlistId: Guid.NewGuid(), + entryId: Guid.NewGuid(), + position: 3); + SetRouteValues(s_playlistId, s_playlistEntryId); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedEntry); + + // Act + IResult result = await _sut.ExecuteAsync(_movePlaylistEntryRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistEntryMovedDto actualEntry = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedEntry, actualEntry); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldPutTheRequestPayloadOnceToTheDocumentedEndpoint() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(targetPosition: 5); + SetRouteValues(playlistId, playlistEntryId); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryMovedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}/entries/{playlistEntryId}/move"), + Arg.Is(payload => payload.TargetPosition == 5), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreUppercaseGuids_ShouldForwardThemInLowercase() + { + // Arrange + SetRouteValues(s_playlistId.ToString().ToUpperInvariant(), s_playlistEntryId.ToString().ToUpperInvariant()); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryMovedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_movePlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}/entries/{s_playlistEntryId}/move"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotGuids_ShouldForwardTheEmptyGuids() + { + // Arrange + SetRouteValues("not-a-guid", "not-an-entry-guid"); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryMovedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_movePlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move"), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldForwardTheEmptyGuids() + { + // Arrange + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryMovedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_movePlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move"), + Arg.Any(), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenRouteValuesAreCrafted_ShouldNormalizeThemAndNeverForwardTheRawValues(string payload) + { + // Arrange + SetRouteValues(payload, payload); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistEntryMovedDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_movePlaylistEntryRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}/move"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + MovePlaylistEntryRequest request = _movePlaylistEntryRequestFixture.Create(); + PlaylistEntryMovedDto expectedEntry = _playlistEntryMovedDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRouteValues(s_playlistId, s_playlistEntryId); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return expectedEntry; + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route values of the playlist and playlist entry identifier route segments. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + private void SetRouteValues(object playlistId, object playlistEntryId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + _sut.HttpContext.Request.RouteValues["playlistEntryId"] = playlistEntryId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs new file mode 100644 index 00000000..b4522b7b --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/RemovePlaylistEntry/RemovePlaylistEntryEndpointTests.cs @@ -0,0 +1,177 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.RemovePlaylistEntry; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.RemovePlaylistEntry; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class RemovePlaylistEntryEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + private static readonly Guid s_playlistEntryId = Guid.Parse("FEDCBAFE-DCBA-FEDC-BAFE-DCBAFEDCBAFE"); + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly RemovePlaylistEntryEndpoint _sut; + + /// + /// Initializes a new instance of the class. + /// + public RemovePlaylistEntryEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutADataPayload() + { + // Arrange + SetRouteValues(s_playlistId, s_playlistEntryId); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _)); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldDeleteTheDocumentedEndpointOnce() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + Guid playlistEntryId = Guid.NewGuid(); + SetRouteValues(playlistId, playlistEntryId); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}/entries/{playlistEntryId}"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreUppercaseGuids_ShouldForwardThemInLowercase() + { + // Arrange + SetRouteValues(s_playlistId.ToString().ToUpperInvariant(), s_playlistEntryId.ToString().ToUpperInvariant()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}/entries/{s_playlistEntryId}"), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().DeleteAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreNotGuids_ShouldForwardTheEmptyGuids() + { + // Arrange + SetRouteValues("not-a-guid", "not-an-entry-guid"); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}"), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRouteValuesAreMissing_ShouldForwardTheEmptyGuids() + { + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}"), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenRouteValuesAreCrafted_ShouldNormalizeThemAndNeverForwardTheRawValues(string payload) + { + // Arrange + SetRouteValues(payload, payload); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).DeleteAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}/entries/{ZERO_GUID}"), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().DeleteAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRouteValues(s_playlistId, s_playlistEntryId); + _mockApiHttpClient.DeleteAsync(Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(1).ThrowIfCancellationRequested(); + }, callInfo.ArgAt(1))); + + // Act + Task operationTask = _sut.ExecuteAsync(EmptyRequest.Instance, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route values of the playlist and playlist entry identifier route segments. + /// + /// The value of the playlist identifier route segment. + /// The value of the playlist entry identifier route segment. + private void SetRouteValues(object playlistId, object playlistEntryId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + _sut.HttpContext.Request.RouteValues["playlistEntryId"] = playlistEntryId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs new file mode 100644 index 00000000..64ae0cc8 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Playlists/UpdatePlaylist/UpdatePlaylistEndpointTests.cs @@ -0,0 +1,217 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Playlists; +using Lumina.Presentation.Web.Common.Requests.Playlists; +using Lumina.Presentation.Web.Core.Endpoints.Playlists.UpdatePlaylist; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.Requests.Playlists; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Playlists.UpdatePlaylist; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaylistEndpointTests +{ + private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000"; + + private static readonly Guid s_playlistId = Guid.Parse("ABCDEFAB-CDEF-ABCD-EFAB-CDEFABCDEFAB"); + private static readonly JsonSerializerOptions s_jsonOptions = new() + { + PropertyNameCaseInsensitive = true + }; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdatePlaylistEndpoint _sut; + private readonly UpdatePlaylistRequestFixture _updatePlaylistRequestFixture = new(); + private readonly PlaylistDetailsDtoFixture _playlistDetailsDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaylistEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithTheUpdatedDetails() + { + // Arrange + PlaylistDetailsDto expectedDetails = _playlistDetailsDtoFixture.Create( + name: "Late night", + description: "Quiet tracks."); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(expectedDetails); + + // Act + IResult result = await _sut.ExecuteAsync(_updatePlaylistRequestFixture.Create(), CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + PlaylistDetailsDto actualDetails = JsonSerializer.Deserialize( + jsonDocument.RootElement.GetProperty("data").GetRawText(), s_jsonOptions)!; + Assert.Equal(expectedDetails, actualDetails); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldPutTheRequestPayloadOnceToTheDocumentedEndpoint() + { + // Arrange + Guid playlistId = Guid.NewGuid(); + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create( + name: "Late night", + description: "Quiet tracks."); + SetRoutePlaylistId(playlistId); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDetailsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{playlistId}"), + Arg.Is(payload => + payload.Name == "Late night" && + payload.Description == "Quiet tracks."), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsAnUppercaseGuid_ShouldForwardItInLowercase() + { + // Arrange + SetRoutePlaylistId(s_playlistId.ToString().ToUpperInvariant()); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDetailsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_updatePlaylistRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{s_playlistId}"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutAsync( + Arg.Is(endpoint => endpoint.Contains(s_playlistId.ToString().ToUpperInvariant(), StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdIsNotAGuid_ShouldForwardTheEmptyGuid() + { + // Arrange + SetRoutePlaylistId("not-a-guid"); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDetailsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_updatePlaylistRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}"), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenPlaylistIdRouteValueIsMissing_ShouldForwardTheEmptyGuid() + { + // Arrange + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDetailsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_updatePlaylistRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}"), + Arg.Any(), + Arg.Any()); + } + + [Theory] + [InlineData("' OR '1'='1")] // basic SQL injection + [InlineData("1;DROP TABLE")] // destructive injection + [InlineData("../../admin")] // path traversal + [InlineData("")] // markup injection + [InlineData("𝕡𝕝𝕒𝕪𝕝𝕚𝕤𝕥")] // unicode payload + public async Task ExecuteAsync_WhenPlaylistIdIsCrafted_ShouldNormalizeItAndNeverForwardTheRawValue(string payload) + { + // Arrange + SetRoutePlaylistId(payload); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(_playlistDetailsDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(_updatePlaylistRequestFixture.Create(), CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + Arg.Is(endpoint => endpoint == $"users/me/playlists/{ZERO_GUID}"), + Arg.Any(), + Arg.Any()); + await _mockApiHttpClient.DidNotReceive().PutAsync( + Arg.Is(endpoint => endpoint.Contains(payload, StringComparison.Ordinal)), + Arg.Any(), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation() + { + // Arrange + UpdatePlaylistRequest request = _updatePlaylistRequestFixture.Create(); + PlaylistDetailsDto expectedDetails = _playlistDetailsDtoFixture.Create(); + CancellationTokenSource cts = new(); + TaskCompletionSource operationStarted = new(); + TaskCompletionSource cancellationRequested = new(); + SetRoutePlaylistId(s_playlistId); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(callInfo => Task.Run(async () => + { + operationStarted.SetResult(true); + await cancellationRequested.Task; + callInfo.ArgAt(2).ThrowIfCancellationRequested(); + return expectedDetails; + }, callInfo.ArgAt(2))); + + // Act + Task operationTask = _sut.ExecuteAsync(request, cts.Token); + await operationStarted.Task; + cts.Cancel(); + cancellationRequested.SetResult(true); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + /// + /// Sets the route value of the playlist identifier route segment. + /// + /// The value of the playlist identifier route segment. + private void SetRoutePlaylistId(object playlistId) + { + _sut.HttpContext.Request.RouteValues["playlistId"] = playlistId; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs new file mode 100644 index 00000000..884443ce --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/GetPlaybackState/GetPlaybackStateEndpointTests.cs @@ -0,0 +1,91 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.GetPlaybackState; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.GetPlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class GetPlaybackStateEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly GetPlaybackStateEndpoint _sut; + private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public GetPlaybackStateEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenApiReturnsState_ShouldReturnSuccessJsonWithState() + { + // Arrange + PlaybackStateDto expectedState = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_PLAYBACK_STATE, Arg.Any()) + .Returns(expectedState); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(0.35, data.GetProperty("volume").GetDouble()); + Assert.True(data.GetProperty("isMuted").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldRequestPlaybackStateFromApi() + { + // Arrange + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_PLAYBACK_STATE, Arg.Any()) + .Returns(_playbackStateDtoFixture.Create()); + + // Act + await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).GetAsync(ApiRoutes.Users.GET_PLAYBACK_STATE, Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenStateHasNullValues_ShouldStillReturnSuccessJson() + { + // Arrange + PlaybackStateDto expectedState = _playbackStateDtoFixture.Create(includeVolume: false, includeIsMuted: false); + _mockApiHttpClient.GetAsync(ApiRoutes.Users.GET_PLAYBACK_STATE, Arg.Any()) + .Returns(expectedState); + + // Act + IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + JsonElement data = jsonDocument.RootElement.GetProperty("data"); + Assert.Equal(JsonValueKind.Null, data.GetProperty("volume").ValueKind); + Assert.Equal(JsonValueKind.Null, data.GetProperty("isMuted").ValueKind); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs new file mode 100644 index 00000000..7b2242ba --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Endpoints/Tools/Settings/UpdatePlaybackState/UpdatePlaybackStateEndpointTests.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Common.Requests.Common; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Tools.Settings.UpdatePlaybackState; +using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using WebEmptyRequest = Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Tools.Settings.UpdatePlaybackState; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class UpdatePlaybackStateEndpointTests +{ + private readonly IApiHttpClient _mockApiHttpClient; + private readonly UpdatePlaybackStateEndpoint _sut; + private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public UpdatePlaybackStateEndpointTests() + { + _mockApiHttpClient = Substitute.For(); + _sut = Factory.Create(_mockApiHttpClient); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldUpdatePlaybackStateViaApiAndReturnSuccess() + { + // Arrange + PlaybackStateDto request = _playbackStateDtoFixture.Create(volume: 0.35, isMuted: true); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new WebEmptyRequest()); + + // Act + IResult result = await _sut.ExecuteAsync(request, CancellationToken.None); + string body = await JsonResultTestHelper.GetResponseBodyAsync(result); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Users.UPDATE_PLAYBACK_STATE, + Arg.Is(state => state.Volume == 0.35 && state.IsMuted == true), + Arg.Any()); + using JsonDocument jsonDocument = JsonDocument.Parse(body); + Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean()); + Assert.True(jsonDocument.RootElement.GetProperty("data").GetProperty("isUpdated").GetBoolean()); + } + + [Fact] + public async Task ExecuteAsync_WhenCalled_ShouldForwardTheVolumeAndMuteStateToApi() + { + // Arrange + PlaybackStateDto request = _playbackStateDtoFixture.Create(volume: 0.0, isMuted: false); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new WebEmptyRequest()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Users.UPDATE_PLAYBACK_STATE, + Arg.Is(state => state.Volume == 0.0 && state.IsMuted == false), + Arg.Any()); + } + + [Fact] + public async Task ExecuteAsync_WhenRequestHasNullValues_ShouldForwardTheNullsToApi() + { + // Arrange + PlaybackStateDto request = _playbackStateDtoFixture.Create(includeVolume: false, includeIsMuted: false); + _mockApiHttpClient.PutAsync(Arg.Any(), Arg.Any(), Arg.Any()) + .Returns(new WebEmptyRequest()); + + // Act + await _sut.ExecuteAsync(request, CancellationToken.None); + + // Assert + await _mockApiHttpClient.Received(1).PutAsync( + ApiRoutes.Users.UPDATE_PLAYBACK_STATE, + Arg.Is(state => state.Volume == null && state.IsMuted == null), + Arg.Any()); + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeAudioPlayerBuilderTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeAudioPlayerBuilderTests.cs new file mode 100644 index 00000000..bdd743da --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeAudioPlayerBuilderTests.cs @@ -0,0 +1,161 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.TestHelpers; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAudioPlayerBuilderTests +{ + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly ThemeAudioPlayerBuilder _sut; + + /// + /// Initializes a new instance of the class. + /// + public ThemeAudioPlayerBuilderTests() + { + _mockStringLocalizer = CreateLocalizer(); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockHttpContextAccessor = Substitute.For(); + _sut = new ThemeAudioPlayerBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor); + } + + [Fact] + public void Constructor_WhenCalled_ShouldRequestTheLayoutResourcesFromTheWebAssembly() + { + // Arrange + _mockStringLocalizerFactory.ClearReceivedCalls(); + + // Act + _ = new ThemeAudioPlayerBuilder(_mockStringLocalizerFactory, _mockHttpContextAccessor); + + // Assert + _mockStringLocalizerFactory.Received(1).Create("Lumina.Presentation.Web.Views.Shared._Layout", "Lumina.Presentation.Web"); + } + + [Theory] + [InlineData("toggleExpanded", "ToggleExpanded")] // the expanded player toggle + [InlineData("previous", "AudioPlayerPrevious")] // the previous track control + [InlineData("next", "AudioPlayerNext")] // the next track control + [InlineData("stop", "AudioPlayerStop")] // the stop control + [InlineData("repeat", "AudioPlayerRepeat")] // the repeat control + [InlineData("repeatOff", "AudioPlayerRepeatOff")] // repeat turned off + [InlineData("repeatAll", "AudioPlayerRepeatAll")] // repeat of the whole queue + [InlineData("repeatOne", "AudioPlayerRepeatOne")] // repeat of a single track + [InlineData("queue", "AudioPlayerQueue")] // the play queue title + [InlineData("albumArtwork", "AudioPlayerAlbumArtwork")] // the album artwork placeholder + [InlineData("addQueueToPlaylist", "AudioPlayerAddQueueToPlaylist")] // adding the queue to a playlist + [InlineData("addToPlaylist", "PlaylistAddToPlaylist")] // adding a single track to a playlist + [InlineData("selectPlaylist", "AudioPlayerSelectPlaylist")] // the playlist selector + [InlineData("noPlaylists", "AudioPlayerNoPlaylists")] // no saved playlist is available + [InlineData("add", "AudioPlayerAdd")] // the add confirmation + [InlineData("playlistQueueAdded", "AudioPlayerPlaylistQueueAdded")] // the queue was added to a playlist + [InlineData("playlistQueueAddFailed", "AudioPlayerPlaylistQueueAddFailed")] // adding the queue to a playlist failed + public void Build_WhenCalled_ShouldLocalizeThePlayerString(string modelKey, string resourceKey) + { + // Act + ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty); + + // Assert + Assert.True(model.Strings.TryGetValue(modelKey, out object? value), $"The '{modelKey}' string is missing."); + Assert.Equal($"Localized-{resourceKey}", Assert.IsType(value)); + _ = _mockStringLocalizer.Received(1)[resourceKey]; + } + + [Fact] + public void Build_WhenCalled_ShouldPassThroughTheAssetBaseAndTheSubTemplates() + { + // Arrange + string queueItemTemplate = "
  • {{title}}
  • "; + string playlistItemTemplate = "
  • {{name}}
  • "; + + // Act + ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", queueItemTemplate, playlistItemTemplate); + + // Assert + Assert.Equal("/theme-assets/editorial/assets", model.AssetBase); + Assert.Equal(queueItemTemplate, model.QueueItemTemplate); + Assert.Equal(playlistItemTemplate, model.PlaylistItemTemplate); + } + + [Fact] + public void Build_WhenSubTemplatesAreEmpty_ShouldPreserveThemUnchanged() + { + // Act + ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty); + + // Assert + Assert.Equal(string.Empty, model.QueueItemTemplate); + Assert.Equal(string.Empty, model.PlaylistItemTemplate); + } + + [Fact] + public void Build_WhenRequestHasAPathBase_ShouldResolveAppBaseWithATrailingSlash() + { + // Arrange + DefaultHttpContext httpContext = TestHttpContextFactory.Create(); + httpContext.Request.Scheme = "https"; + httpContext.Request.Host = new HostString("localhost", 5001); + httpContext.Request.PathBase = new PathString("/lumina"); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty); + + // Assert + Assert.Equal("https://localhost:5001/lumina/", model.AppBase); + } + + [Fact] + public void Build_WhenRequestHasNoPathBase_ShouldResolveAppBaseWithATrailingSlash() + { + // Arrange + DefaultHttpContext httpContext = TestHttpContextFactory.Create(); + httpContext.Request.Scheme = "https"; + httpContext.Request.Host = new HostString("localhost", 5001); + _mockHttpContextAccessor.HttpContext.Returns(httpContext); + + // Act + ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty); + + // Assert + Assert.Equal("https://localhost:5001/", model.AppBase); + } + + [Fact] + public void Build_WhenRequestIsUnavailable_ShouldReturnAnEmptyAppBase() + { + // Arrange + _mockHttpContextAccessor.HttpContext.Returns((HttpContext?)null); + + // Act + ThemeAudioPlayerDto model = _sut.Build("/theme-assets/editorial/assets", string.Empty, string.Empty); + + // Assert + Assert.Equal(string.Empty, model.AppBase); + } + + /// + /// Creates a substitute string localizer that returns a string prefixed with "Localized-". + /// + /// The created substitute string localizer. + private static IStringLocalizer CreateLocalizer() + { + IStringLocalizer localizer = Substitute.For(); + localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + return localizer; + } +} diff --git a/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeAudioPlayerRendererTests.cs b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeAudioPlayerRendererTests.cs new file mode 100644 index 00000000..13b152f1 --- /dev/null +++ b/tests/UnitTests/Lumina.Presentation.Web.UnitTests/Core/Themes/ThemeAudioPlayerRendererTests.cs @@ -0,0 +1,281 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.Themes; +using Lumina.Presentation.Web.Common.Enums.Primitives; +using Lumina.Presentation.Web.Common.Primitives; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Themes; +using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Localization; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.UnitTests.Core.Themes; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class ThemeAudioPlayerRendererTests +{ + private const string THEME_ID = "editorial"; + private const string SHELL_PAGE_KEY = "shared/audio-player"; + private const string QUEUE_ITEM_PAGE_KEY = "shared/audio-player/queue-item"; + private const string PLAYLIST_ITEM_PAGE_KEY = "shared/audio-player/playlist-item"; + + private readonly IApiHttpClient _mockApiHttpClient; + private readonly IHttpContextAccessor _mockHttpContextAccessor; + private readonly IStringLocalizerFactory _mockStringLocalizerFactory; + private readonly IStringLocalizer _mockStringLocalizer; + private readonly ThemeAudioPlayerRenderer _sut; + private readonly ThemeResponseDtoFixture _themeResponseDtoFixture = new(); + private readonly ThemeTemplateResponseDtoFixture _themeTemplateResponseDtoFixture = new(); + + /// + /// Initializes a new instance of the class. + /// + public ThemeAudioPlayerRendererTests() + { + _mockApiHttpClient = Substitute.For(); + _mockStringLocalizer = CreateLocalizer(); + _mockStringLocalizerFactory = Substitute.For(); + _mockStringLocalizerFactory.Create(Arg.Any(), Arg.Any()).Returns(_mockStringLocalizer); + _mockHttpContextAccessor = Substitute.For(); + ThemeService themeService = new(_mockApiHttpClient); + ThemeAudioPlayerBuilder builder = new(_mockStringLocalizerFactory, _mockHttpContextAccessor); + _sut = new ThemeAudioPlayerRenderer(themeService, new ThemeTemplateEngine(), builder); + } + + [Fact] + public async Task RenderAsync_WhenCalled_ShouldRenderTheShellWithTheThemeAssetBaseAndThePlayerModel() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "
    "); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Contains("/theme-assets/editorial/assets", result.Value); + Assert.Contains("data-queue-label=\"Localized-AudioPlayerQueue\"", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenThemeProvidesSubTemplates_ShouldInlineThemInTheShell() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "{{{queueItemTemplate}}}|{{{playlistItemTemplate}}}"); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, "
  • {{title}}
  • "); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, "
  • {{name}}
  • "); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("
  • {{title}}
  • |
  • {{name}}
  • ", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenSubTemplateIsMissing_ShouldInlineAnEmptySubTemplate() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "{{{queueItemTemplate}}}|{{{playlistItemTemplate}}}"); + StubTemplateFailure(THEME_ID, QUEUE_ITEM_PAGE_KEY, new HttpRequestException("The sub template is unavailable.")); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("|", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenSubTemplateResolvesToTheShellTemplate_ShouldInlineAnEmptySubTemplate() + { + // Arrange + string shellTemplate = "
    {{{queueItemTemplate}}}|{{{playlistItemTemplate}}}
    "; + StubTemplate(THEME_ID, SHELL_PAGE_KEY, shellTemplate); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, shellTemplate); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, shellTemplate); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("
    |
    ", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenTemplateDefinesScripts_ShouldConcatenateTheContentAndTheScript() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "
    content
    {{#scripts}}{{/scripts}}"); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsSuccess); + Assert.Equal("
    content
    ", result.Value); + } + + [Fact] + public async Task RenderAsync_WhenTemplateEngineFails_ShouldReturnTheTemplateErrors() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "{{#unclosed}}"); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Invalid", result.FirstError.Code); + } + + [Fact] + public async Task RenderAsync_WhenShellDocumentCannotBeLoaded_ShouldReturnTemplateUnavailableError() + { + // Arrange + StubTemplateFailure(THEME_ID, SHELL_PAGE_KEY, new HttpRequestException("The theme API is unavailable.")); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code); + Assert.Equal(ErrorType.NotFound, result.FirstError.Type); + } + + [Fact] + public async Task RenderAsync_WhenShellTemplateCannotBeRendered_ShouldReturnTemplateUnavailableError() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, string.Empty, includeTemplate: false); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, string.Empty); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty); + + // Act + Result result = await _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal("Theme.Template.Unavailable", result.FirstError.Code); + Assert.Equal(ErrorType.NotFound, result.FirstError.Type); + } + + [Fact] + public async Task RenderAsync_WhenShellLoadIsCancelled_ShouldRethrowTheCancellation() + { + // Arrange + StubTemplateFailure(THEME_ID, SHELL_PAGE_KEY, new OperationCanceledException()); + + // Act + Task> operationTask = _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + [Fact] + public async Task RenderAsync_WhenSubTemplateLoadIsCancelled_ShouldRethrowTheCancellation() + { + // Arrange + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "
    {{{queueItemTemplate}}}
    "); + StubTemplateFailure(THEME_ID, QUEUE_ITEM_PAGE_KEY, new OperationCanceledException()); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, string.Empty); + + // Act + Task> operationTask = _sut.RenderAsync(THEME_ID, CancellationToken.None); + + // Assert + await Assert.ThrowsAnyAsync(() => operationTask); + } + + [Fact] + public async Task RenderAsync_WhenCalled_ShouldPassTheThemeIdAndTheCancellationTokenToTheTemplateLookups() + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(); + StubTemplate(THEME_ID, SHELL_PAGE_KEY, "shell"); + StubTemplate(THEME_ID, QUEUE_ITEM_PAGE_KEY, "queue"); + StubTemplate(THEME_ID, PLAYLIST_ITEM_PAGE_KEY, "playlist"); + + // Act + await _sut.RenderAsync(THEME_ID, cancellationTokenSource.Token); + + // Assert + string[] pageKeys = [SHELL_PAGE_KEY, QUEUE_ITEM_PAGE_KEY, PLAYLIST_ITEM_PAGE_KEY]; + foreach (string pageKey in pageKeys) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", THEME_ID) + .Replace("{*pageKey}", pageKey); + await _mockApiHttpClient.Received(1).GetAsync(endpoint, Arg.Is(cancellationTokenSource.Token)); + } + await _mockApiHttpClient.DidNotReceive().GetAsync(ApiRoutes.Themes.GET_CURRENT_THEME, Arg.Any()); + } + + /// + /// Stubs the API response that returns a single audio player template document. + /// + /// The manifest id of the theme. + /// The page key of the template. + /// The template returned for the document. + /// Whether the returned document has a template, or a one. + private void StubTemplate(string themeId, string pageKey, string template, bool includeTemplate = true) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", themeId) + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(endpoint, Arg.Any()) + .Returns(_themeTemplateResponseDtoFixture.Create( + theme: _themeResponseDtoFixture.Create(themeId: themeId), + template: template, + includeTemplate: includeTemplate)); + } + + /// + /// Stubs the API response of an audio player template document to fail. + /// + /// The manifest id of the theme. + /// The page key of the template. + /// The exception the API call throws. + private void StubTemplateFailure(string themeId, string pageKey, Exception exception) + { + string endpoint = ApiRoutes.Themes.GET_THEME_TEMPLATE + .Replace("{themeId}", themeId) + .Replace("{*pageKey}", pageKey); + _mockApiHttpClient.GetAsync(endpoint, Arg.Any()) + .Returns(Task.FromException(exception)); + } + + /// + /// Creates a substitute string localizer that returns a string prefixed with "Localized-". + /// + /// The created substitute string localizer. + private static IStringLocalizer CreateLocalizer() + { + IStringLocalizer localizer = Substitute.For(); + localizer[Arg.Any()].Returns(callInfo => new LocalizedString(callInfo.Arg(), $"Localized-{callInfo.Arg()}")); + return localizer; + } +}