Adds music stack test coverage and fixes playlist cache and stream error handling

This commit is contained in:
BinaryAlley committed 2026-10-29 15:46:24 +02:00
1 parent 394f6b510c
commit aba803b106
197 files changed
+29081 -34

No files matched your search

@@ -51,6 +51,10 @@ public class AddPlaylistEntriesEndpoint : BaseEndpoint<AddPlaylistEntriesRequest
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PlaylistEntriesAddedResponse> result = await _addPlaylistEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false);
@@ -51,6 +51,10 @@ public class AddPlaylistEntryEndpoint : BaseEndpoint<AddPlaylistEntryRequest, IR
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PlaylistEntryAddedResponse> result = await _addPlaylistEntryCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false);
@@ -51,6 +51,10 @@ public class AddPlaylistScopeEntriesEndpoint : BaseEndpoint<AddPlaylistScopeEntr
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PlaylistEntriesAddedResponse> result = await _addPlaylistScopeEntriesCommandHandler.HandleAsync(request.ToCommand(playlistId), cancellationToken).ConfigureAwait(false);
@@ -51,6 +51,10 @@ public class CreatePlaylistEndpoint : BaseEndpoint<CreatePlaylistRequest, IResul
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PlaylistResponse> result = await _createPlaylistCommandHandler.HandleAsync(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
@@ -48,6 +48,10 @@ public class DeletePlaylistEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, I
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<Deleted> result = await _deletePlaylistCommandHandler.HandleAsync(new DeletePlaylistCommand(playlistId), cancellationToken).ConfigureAwait(false);
@@ -51,6 +51,10 @@ public class MovePlaylistEntryEndpoint : BaseEndpoint<MovePlaylistEntryRequest,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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();
@@ -49,6 +49,10 @@ public class RemovePlaylistEntryEndpoint : BaseEndpoint<FastEndpoints.EmptyReque
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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();
@@ -51,6 +51,10 @@ public class UpdatePlaylistEndpoint : BaseEndpoint<UpdatePlaylistRequest, IResul
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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();
@@ -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<StreamMusicTrackRequest, IR
AddHeader(forwardHeaders, "If-Modified-Since", HttpContext.Request.Headers.IfModifiedSince);
// The API response is disposed once the copy ends, so that the underlying connection is released as soon as the client stops reading.
await using (ApiStreamResult streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, forwardHeaders, cancellationToken).ConfigureAwait(false))
{ // The proxy owns the status, header, caching and body rules shared with the normalized segment proxy.
await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false);
ApiStreamResult streamResult;
try
{
streamResult = await _streamingApiHttpClient.GetStreamAsync(endpoint, forwardHeaders, cancellationToken).ConfigureAwait(false);
}
catch (ApiException apiException) when (apiException.HttpStatusCode is HttpStatusCode.ServiceUnavailable or HttpStatusCode.TooManyRequests)
{
// A busy normalization pipeline or the stream concurrency limit is an expected, transient condition that the player retries. It is
// answered with a bare status instead of being logged as an unexpected API failure with a stack trace.
HttpContext.Response.StatusCode = (int)apiException.HttpStatusCode;
HttpContext.Response.ContentLength = 0;
return Results.Empty;
}
await using (streamResult) // The proxy owns the status, header, caching and body rules shared with the normalized segment proxy.
await ApiStreamProxy.WriteAsync(HttpContext.Response, streamResult, cancellationToken).ConfigureAwait(false);
return Results.Empty;
}
@@ -0,0 +1,41 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Application.Fixtures.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.Tracks;
/// <summary>
/// Fixture class for the <see cref="TrackAccessSummaryDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackAccessSummaryDtoFixture
{
/// <summary>
/// Creates a random valid <see cref="TrackAccessSummaryDto"/>.
/// </summary>
/// <param name="trackCount">Optional. The number of distinct requested tracks that exist.</param>
/// <param name="libraryIds">Optional. The Ids of the media libraries that contain those tracks. Defaults to a single random library.</param>
/// <returns>The created <see cref="TrackAccessSummaryDto"/>.</returns>
public TrackAccessSummaryDto Create(
int? trackCount = null,
IReadOnlyList<Guid>? libraryIds = null)
{
return new TrackAccessSummaryDto(
trackCount ?? 1,
libraryIds ?? [Guid.NewGuid()]);
}
/// <summary>
/// Creates a list of <see cref="TrackAccessSummaryDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TrackAccessSummaryDto"/> instances.</returns>
public List<TrackAccessSummaryDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="TrackStreamDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackStreamDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TrackStreamDto"/>.
/// </summary>
/// <param name="path">Optional. The file system path of the track.</param>
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist that owns the album the track belongs to.</param>
/// <param name="container">Optional. The container of the audio file of the track.</param>
/// <param name="audioCodec">Optional. The audio codec used by the audio file of the track.</param>
/// <param name="durationInSeconds">Optional. The duration of the audio of the track, in seconds.</param>
/// <param name="sampleRate">Optional. The sample rate of the audio of the track, in Hz.</param>
/// <param name="channels">Optional. The number of audio channels of the track.</param>
/// <param name="bitDepth">Optional. The bit depth of the audio of the track.</param>
/// <param name="bitrate">Optional. The bitrate of the audio of the track, in kbps.</param>
/// <param name="includeContainer">Whether the container should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAudioCodec">Whether the audio codec should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitDepth">Whether the bit depth should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeBitrate">Whether the bitrate should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="TrackStreamDto"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="TrackStreamDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TrackStreamDto"/> instances.</returns>
public List<TrackStreamDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistBulkAddResultDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistBulkAddResultDtoFixture
{
private const long MAXIMUM_RANDOM_POSITION = 1_000_000_000L;
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistBulkAddResultDto"/>.
/// </summary>
/// <param name="firstPosition">Optional. The sparse order key of the first appended entry. Defaults to a bounded random key.</param>
/// <param name="addedCount">Optional. The number of entries appended. Defaults to a bounded random count.</param>
/// <returns>The created <see cref="PlaylistBulkAddResultDto"/>.</returns>
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));
}
/// <summary>
/// Creates a list of <see cref="PlaylistBulkAddResultDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistBulkAddResultDto"/> instances.</returns>
public List<PlaylistBulkAddResultDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistSummaryDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistSummaryDtoFixture
{
private const int MAXIMUM_ENTRY_COUNT = 10_000;
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistSummaryDto"/>.
/// </summary>
/// <param name="id">Optional. The Id of the playlist.</param>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="type">Optional. The kind of media the playlist holds. Defaults to the only supported kind.</param>
/// <param name="entryCount">Optional. The number of entries of the playlist. Defaults to a bounded random count.</param>
/// <param name="createdOnUtc">Optional. The date and time when the playlist was created.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the update date and time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistSummaryDto"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistSummaryDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistSummaryDto"/> instances.</returns>
public List<PlaylistSummaryDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -39,6 +39,7 @@ public class TrackEntityFixture
/// <param name="title">Optional. The title of the track.</param>
/// <param name="container">Optional. The container of the audio file of the track.</param>
/// <param name="trackNumber">Optional. The number of the track on its disc.</param>
/// <param name="discNumber">Optional. The number of the disc the track belongs to.</param>
/// <param name="originalReleaseDate">Optional. The original release date of the track.</param>
/// <param name="originalReleaseYear">Optional. The original release year of the track.</param>
/// <param name="reReleaseDate">Optional. The re-release date of the track.</param>
@@ -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<MusicKey>())
.RuleFor(x => x.Bpm, Random.Shared.Next(40, 240))
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetTrackStreamQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetTrackStreamQueryFixture
{
/// <summary>
/// Creates a random valid query to get the audio file of a track, for streaming.
/// </summary>
/// <param name="libraryId">Optional. The Id of the media library the track belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the album of the track belongs to.</param>
/// <param name="albumId">Optional. The Id of the album the track belongs to.</param>
/// <param name="trackId">Optional. The Id of the track whose audio file is streamed.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="GetTrackStreamQuery"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="GetTrackStreamQuery"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetTrackStreamQuery"/> instances.</returns>
public List<GetTrackStreamQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistEntriesCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="AddPlaylistEntriesCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="trackIds">Optional. The Ids of the tracks to add, in order.</param>
/// <param name="trackCount">Optional. The number of random track Ids to generate when <paramref name="trackIds"/> is not supplied.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackIds">Whether the track Ids should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AddPlaylistEntriesCommand"/>.</returns>
public AddPlaylistEntriesCommand Create(
string? playlistId = null,
List<Guid>? 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);
}
/// <summary>
/// Creates a list of <see cref="AddPlaylistEntriesCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistEntriesCommand"/> instances.</returns>
public List<AddPlaylistEntriesCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates the requested number of distinct random track Ids.
/// </summary>
/// <param name="count">The number of track Ids to create.</param>
/// <returns>The created track Ids.</returns>
private static List<Guid> CreateRandomTrackIds(int count)
{
return [.. Enumerable.Range(0, count).Select(_ => Guid.NewGuid())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistEntryCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="AddPlaylistEntryCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="trackId">Optional. The Id of the track to add.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AddPlaylistEntryCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="AddPlaylistEntryCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistEntryCommand"/> instances.</returns>
public List<AddPlaylistEntryCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistScopeEntriesCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="AddPlaylistScopeEntriesCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="libraryId">Optional. The Id of the music library the scope belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the scope is limited to.</param>
/// <param name="albumId">Optional. The Id of the album the scope is limited to.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AddPlaylistScopeEntriesCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="AddPlaylistScopeEntriesCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistScopeEntriesCommand"/> instances.</returns>
public List<AddPlaylistScopeEntriesCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -25,16 +25,18 @@ public class CreatePlaylistCommandFixture
/// <param name="type">Optional. The kind of media the playlist holds. Defaults to the only supported kind.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeType">Whether the media type should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="CreatePlaylistCommand"/>.</returns>
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);
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="DeletePlaylistCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletePlaylistCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="DeletePlaylistCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="DeletePlaylistCommand"/>.</returns>
public DeletePlaylistCommand Create(
string? playlistId = null,
bool includePlaylistId = true)
{
return new DeletePlaylistCommand(
includePlaylistId ? (playlistId ?? Guid.NewGuid().ToString()) : null);
}
/// <summary>
/// Creates a list of <see cref="DeletePlaylistCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="DeletePlaylistCommand"/> instances.</returns>
public List<DeletePlaylistCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MovePlaylistEntryCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryCommandFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MovePlaylistEntryCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="playlistEntryId">Optional. The Id of the entry to move, taken from the route.</param>
/// <param name="targetPosition">Optional. The new zero based position of the entry.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePlaylistEntryId">Whether the entry Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeTargetPosition">Whether the target position should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MovePlaylistEntryCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="MovePlaylistEntryCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MovePlaylistEntryCommand"/> instances.</returns>
public List<MovePlaylistEntryCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="RemovePlaylistEntryCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemovePlaylistEntryCommandFixture
{
/// <summary>
/// Creates a random valid <see cref="RemovePlaylistEntryCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="playlistEntryId">Optional. The Id of the entry to remove, taken from the route.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includePlaylistEntryId">Whether the entry Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="RemovePlaylistEntryCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="RemovePlaylistEntryCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="RemovePlaylistEntryCommand"/> instances.</returns>
public List<RemovePlaylistEntryCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdatePlaylistCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaylistCommandFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UpdatePlaylistCommand"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist, taken from the route.</param>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="includePlaylistId">Whether the playlist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdatePlaylistCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="UpdatePlaylistCommand"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdatePlaylistCommand"/> instances.</returns>
public List<UpdatePlaylistCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetPlaylistsQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaylistsQueryFixture
{
/// <summary>
/// Creates a <see cref="GetPlaylistsQuery"/>.
/// </summary>
/// <returns>The created <see cref="GetPlaylistsQuery"/>.</returns>
/// <remarks>
/// The query carries no members, because the current user is always taken from the authenticated request context.
/// </remarks>
public GetPlaylistsQuery Create()
{
return new GetPlaylistsQuery();
}
/// <summary>
/// Creates a list of <see cref="GetPlaylistsQuery"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetPlaylistsQuery"/> instances.</returns>
public List<GetPlaylistsQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdatePlaybackStateCommand"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateCommandFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid command to update the playback state the player reports for the current user.
/// </summary>
/// <param name="volume">Optional. The last volume the player reported, as a value between 0 and 1.</param>
/// <param name="isMuted">Optional. The last mute state the player reported.</param>
/// <param name="includeVolume">Whether the volume should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeIsMuted">Whether the mute state should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdatePlaybackStateCommand"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="UpdatePlaybackStateCommand"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdatePlaybackStateCommand"/> instances.</returns>
public List<UpdatePlaybackStateCommand> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="GetPlaybackStateQuery"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackStateQueryFixture
{
/// <summary>
/// Creates a new <see cref="GetPlaybackStateQuery"/> instance.
/// </summary>
/// <returns>The created <see cref="GetPlaybackStateQuery"/>.</returns>
public GetPlaybackStateQuery Create()
{
return new GetPlaybackStateQuery();
}
/// <summary>
/// Creates a list of <see cref="GetPlaybackStateQuery"/> instances.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="GetPlaybackStateQuery"/> instances.</returns>
public List<GetPlaybackStateQuery> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="TrackStreamDataDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class TrackStreamDataDtoFixture
{
private static readonly AudioFileFormat[] s_audioFileFormats = [AudioFileFormat.MP3, AudioFileFormat.FLAC, AudioFileFormat.OGG, AudioFileFormat.WAV];
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="TrackStreamDataDto"/>.
/// </summary>
/// <param name="path">Optional. The file system path of the audio file of the track.</param>
/// <param name="format">Optional. The file format of the audio file of the track.</param>
/// <param name="length">Optional. The length of the audio file of the track, in bytes.</param>
/// <param name="lastModified">Optional. The date and time when the audio file of the track was last modified.</param>
/// <returns>The created <see cref="TrackStreamDataDto"/>.</returns>
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());
}
/// <summary>
/// Creates a list of <see cref="TrackStreamDataDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="TrackStreamDataDto"/> instances.</returns>
public List<TrackStreamDataDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistEntriesRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="AddPlaylistEntriesRequest"/>.
/// </summary>
/// <param name="trackIds">Optional. The Ids of the tracks to add, in order.</param>
/// <param name="trackCount">Optional. The number of random track Ids to generate when <paramref name="trackIds"/> is not supplied.</param>
/// <param name="includeTrackIds">Whether the track Ids should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AddPlaylistEntriesRequest"/>.</returns>
public AddPlaylistEntriesRequest Create(
List<Guid>? trackIds = null,
int trackCount = 3,
bool includeTrackIds = true)
{
return new AddPlaylistEntriesRequest(
includeTrackIds ? (trackIds ?? CreateRandomTrackIds(trackCount)) : null);
}
/// <summary>
/// Creates a list of <see cref="AddPlaylistEntriesRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistEntriesRequest"/> instances.</returns>
public List<AddPlaylistEntriesRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates the requested number of distinct random track Ids.
/// </summary>
/// <param name="count">The number of track Ids to create.</param>
/// <returns>The created track Ids.</returns>
private static List<Guid> CreateRandomTrackIds(int count)
{
return [.. Enumerable.Range(0, count).Select(_ => Guid.NewGuid())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistEntryRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="AddPlaylistEntryRequest"/>.
/// </summary>
/// <param name="trackId">Optional. The Id of the track to add.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AddPlaylistEntryRequest"/>.</returns>
public AddPlaylistEntryRequest Create(
Guid? trackId = null,
bool includeTrackId = true)
{
return new AddPlaylistEntryRequest(
includeTrackId ? (trackId ?? Guid.NewGuid()) : null);
}
/// <summary>
/// Creates a list of <see cref="AddPlaylistEntryRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistEntryRequest"/> instances.</returns>
public List<AddPlaylistEntryRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistScopeEntriesRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesRequestFixture
{
/// <summary>
/// Creates a random valid <see cref="AddPlaylistScopeEntriesRequest"/>.
/// </summary>
/// <param name="libraryId">Optional. The Id of the music library the scope belongs to.</param>
/// <param name="artistId">Optional. The Id of the artist the scope is limited to.</param>
/// <param name="albumId">Optional. The Id of the album the scope is limited to.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="AddPlaylistScopeEntriesRequest"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="AddPlaylistScopeEntriesRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistScopeEntriesRequest"/> instances.</returns>
public List<AddPlaylistScopeEntriesRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="CreatePlaylistRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class CreatePlaylistRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="CreatePlaylistRequest"/>.
/// </summary>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="type">Optional. The kind of media the playlist holds. Defaults to the only supported kind.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeType">Whether the media type should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="CreatePlaylistRequest"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="CreatePlaylistRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="CreatePlaylistRequest"/> instances.</returns>
public List<CreatePlaylistRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MovePlaylistEntryRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="MovePlaylistEntryRequest"/>.
/// </summary>
/// <param name="targetPosition">Optional. The new zero based position of the entry. Defaults to a bounded random position.</param>
/// <param name="includeTargetPosition">Whether the target position should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="MovePlaylistEntryRequest"/>.</returns>
public MovePlaylistEntryRequest Create(
int? targetPosition = null,
bool includeTargetPosition = true)
{
return new MovePlaylistEntryRequest(
includeTargetPosition ? (targetPosition ?? _faker.Random.Int(0, 1_000)) : null);
}
/// <summary>
/// Creates a list of <see cref="MovePlaylistEntryRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MovePlaylistEntryRequest"/> instances.</returns>
public List<MovePlaylistEntryRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdatePlaylistRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaylistRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UpdatePlaylistRequest"/>.
/// </summary>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdatePlaylistRequest"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="UpdatePlaylistRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdatePlaylistRequest"/> instances.</returns>
public List<UpdatePlaylistRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdatePlaybackStateRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="UpdatePlaybackStateRequest"/>.
/// </summary>
/// <param name="volume">Optional. The last volume the player reported, as a value between 0 and 1.</param>
/// <param name="isMuted">Optional. The last mute state the player reported.</param>
/// <param name="includeVolume">Whether the volume should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeIsMuted">Whether the mute state should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="UpdatePlaybackStateRequest"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="UpdatePlaybackStateRequest"/> instances.
/// </summary>
/// <param name="count">Number of elements to create.</param>
/// <returns>The created list.</returns>
public List<UpdatePlaybackStateRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistDetailsResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistDetailsResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistDetailsResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the playlist.</param>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="type">Optional. The kind of media the playlist holds.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistDetailsResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistDetailsResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistDetailsResponse"/> instances.</returns>
public List<PlaylistDetailsResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntriesAddedResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntriesAddedResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistEntriesAddedResponse"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist the entries were added to.</param>
/// <param name="addedCount">Optional. The number of entries that were appended.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistEntriesAddedResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistEntriesAddedResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntriesAddedResponse"/> instances.</returns>
public List<PlaylistEntriesAddedResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntryAddedResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryAddedResponseFixture
{
private readonly Faker _faker = new();
private readonly PlaylistEntryResponseFixture _playlistEntryResponseFixture = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistEntryAddedResponse"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist the entry was added to.</param>
/// <param name="entry">Optional. The added entry.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistEntryAddedResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistEntryAddedResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntryAddedResponse"/> instances.</returns>
public List<PlaylistEntryAddedResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntryMovedResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryMovedResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistEntryMovedResponse"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist whose entry was moved.</param>
/// <param name="entryId">Optional. The Id of the moved entry.</param>
/// <param name="position">Optional. The new zero based position of the entry.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistEntryMovedResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistEntryMovedResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntryMovedResponse"/> instances.</returns>
public List<PlaylistEntryMovedResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntryRemovedResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryRemovedResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistEntryRemovedResponse"/>.
/// </summary>
/// <param name="playlistId">Optional. The Id of the playlist the entry was removed from.</param>
/// <param name="removedEntryId">Optional. The Id of the removed entry.</param>
/// <param name="repositionedCount">Optional. The number of entries that were repositioned, which the contract always reports as zero.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistEntryRemovedResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistEntryRemovedResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntryRemovedResponse"/> instances.</returns>
public List<PlaylistEntryRemovedResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistSummaryResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistSummaryResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistSummaryResponse"/>.
/// </summary>
/// <param name="id">Optional. The Id of the playlist.</param>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="type">Optional. The kind of media the playlist holds.</param>
/// <param name="entryCount">Optional. The number of entries of the playlist.</param>
/// <param name="createdOnUtc">Optional. The date and time when the playlist was created.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the update time should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaylistSummaryResponse"/>.</returns>
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);
}
/// <summary>
/// Creates a list of <see cref="PlaylistSummaryResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistSummaryResponse"/> instances.</returns>
public List<PlaylistSummaryResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaybackStateResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackStateResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaybackStateResponse"/>.
/// </summary>
/// <param name="volume">Optional. The last volume the player reported, as a value between 0 and 1.</param>
/// <param name="isMuted">Optional. The last mute state the player reported.</param>
/// <returns>The created <see cref="PlaybackStateResponse"/>.</returns>
public PlaybackStateResponse Create(
double? volume = null,
bool? isMuted = null)
{
return new PlaybackStateResponse(
volume ?? _faker.Random.Double(0, 1),
isMuted ?? _faker.Random.Bool());
}
/// <summary>
/// Creates a list of <see cref="PlaybackStateResponse"/> instances.
/// </summary>
/// <param name="count">Number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PlaybackStateResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MediaItemId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class MediaItemIdFixture
{
/// <summary>
/// Creates a random valid <see cref="MediaItemId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the media item Id.</param>
/// <returns>The created <see cref="MediaItemId"/>.</returns>
public MediaItemId Create(
Guid? value = null)
{
return MediaItemId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="MediaItemId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MediaItemId"/> instances.</returns>
public List<MediaItemId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UserId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class UserIdFixture
{
/// <summary>
/// Creates a random valid <see cref="UserId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the user Id.</param>
/// <returns>The created <see cref="UserId"/>.</returns>
public UserId Create(
Guid? value = null)
{
return UserId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="UserId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UserId"/> instances.</returns>
public List<UserId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntry"/> entity.
/// </summary>
[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();
/// <summary>
/// Creates a random valid <see cref="PlaylistEntry"/>.
/// </summary>
/// <param name="id">Optional. The Id of the entry.</param>
/// <param name="mediaItemId">Optional. The Id of the media item referenced by the entry.</param>
/// <param name="mediaItemType">Optional. The kind of media item referenced by the entry. Defaults to a music track, which is the kind a music playlist accepts.</param>
/// <param name="position">Optional. The sparse order key of the entry. Defaults to a bounded random key.</param>
/// <returns>The created <see cref="PlaylistEntry"/>.</returns>
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;
}
/// <summary>
/// Creates multiple <see cref="PlaylistEntry"/> instances with randomized test data and distinct positions.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntry"/> instances.</returns>
public List<PlaylistEntry> CreateMany(int count = 3)
{
long firstPosition = _faker.Random.Long(0, MAXIMUM_RANDOM_POSITION);
return [.. Enumerable.Range(0, count).Select(index => Create(position: firstPosition + index))];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistCreatedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistCreatedDomainEventFixture
{
private readonly Faker _faker = new();
private readonly PlaylistIdFixture _playlistIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistCreatedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="playlistId">Optional. The unique identifier of the playlist.</param>
/// <param name="userId">Optional. The unique identifier of the user that owns the playlist.</param>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="type">Optional. The kind of media the playlist holds. Defaults to the only supported kind.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="PlaylistCreatedDomainEvent"/>.</returns>
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);
}
/// <summary>
/// Creates multiple <see cref="PlaylistCreatedDomainEvent"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistCreatedDomainEvent"/> instances.</returns>
public List<PlaylistCreatedDomainEvent> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistDeletedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistDeletedDomainEventFixture
{
private readonly PlaylistIdFixture _playlistIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistDeletedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="playlistId">Optional. The unique identifier of the playlist.</param>
/// <param name="userId">Optional. The unique identifier of the user that owned the playlist.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="PlaylistDeletedDomainEvent"/>.</returns>
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);
}
/// <summary>
/// Creates multiple <see cref="PlaylistDeletedDomainEvent"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistDeletedDomainEvent"/> instances.</returns>
public List<PlaylistDeletedDomainEvent> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistDetailsUpdatedDomainEvent"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistDetailsUpdatedDomainEventFixture
{
private readonly Faker _faker = new();
private readonly PlaylistIdFixture _playlistIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="PlaylistDetailsUpdatedDomainEvent"/>.
/// </summary>
/// <param name="id">Optional. The Id of the domain event.</param>
/// <param name="playlistId">Optional. The unique identifier of the playlist.</param>
/// <param name="userId">Optional. The unique identifier of the user that owns the playlist.</param>
/// <param name="name">Optional. The new name of the playlist.</param>
/// <param name="occurredOnUtc">Optional. The date and time when the domain event occurred.</param>
/// <returns>The created <see cref="PlaylistDetailsUpdatedDomainEvent"/>.</returns>
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);
}
/// <summary>
/// Creates multiple <see cref="PlaylistDetailsUpdatedDomainEvent"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistDetailsUpdatedDomainEvent"/> instances.</returns>
public List<PlaylistDetailsUpdatedDomainEvent> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="Playlist"/> domain aggregate.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistFixture
{
private readonly Faker _faker = new();
private readonly PlaylistIdFixture _playlistIdFixture = new();
private readonly UserIdFixture _userIdFixture = new();
/// <summary>
/// Creates a random valid <see cref="Playlist"/> domain aggregate, with pre-existing data.
/// </summary>
/// <param name="id">Optional. The Id of the playlist.</param>
/// <param name="userId">Optional. The Id of the user that owns the playlist.</param>
/// <param name="name">Optional. The name of the playlist.</param>
/// <param name="description">Optional. The description of the playlist.</param>
/// <param name="type">Optional. The kind of media the playlist holds. Defaults to the only supported kind.</param>
/// <param name="entries">Optional. The ordered entries of the playlist. Defaults to no entries.</param>
/// <param name="createdOnUtc">Optional. The date and time when the playlist was created. Defaults to a few days in the past.</param>
/// <param name="updatedOnUtc">Optional. The date and time when the playlist was last updated.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to no value.</param>
/// <param name="includeUpdatedOnUtc">Whether the update date and time should be included, or forced to no value.</param>
/// <returns>The created <see cref="Playlist"/>.</returns>
/// <remarks>
/// The playlist is built through the rehydrating <see cref="Playlist.Create(PlaylistId, UserId, string, Optional{string}, PlaylistType, List{PlaylistEntry}, DateTime, Optional{DateTime})"/>
/// overload, so it carries no domain events and is never marked as deleted.
/// </remarks>
public Playlist Create(
PlaylistId? id = null,
UserId? userId = null,
string? name = null,
string? description = null,
PlaylistType? type = null,
IEnumerable<PlaylistEntry>? 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<string>.FromNullable(description ?? _faker.Lorem.Sentence()) : Optional<string>.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<DateTime>.Some(updatedOnUtc ?? DateTime.UtcNow) : Optional<DateTime>.None()).Value;
}
/// <summary>
/// Creates multiple <see cref="Playlist"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="Playlist"/> instances.</returns>
public List<Playlist> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntryId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryIdFixture
{
/// <summary>
/// Creates a random valid <see cref="PlaylistEntryId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the playlist entry Id.</param>
/// <returns>The created <see cref="PlaylistEntryId"/>.</returns>
public PlaylistEntryId Create(
Guid? value = null)
{
return PlaylistEntryId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="PlaylistEntryId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntryId"/> instances.</returns>
public List<PlaylistEntryId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistId"/> value object.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistIdFixture
{
/// <summary>
/// Creates a random valid <see cref="PlaylistId"/>.
/// </summary>
/// <param name="value">Optional. The raw value of the playlist Id.</param>
/// <returns>The created <see cref="PlaylistId"/>.</returns>
public PlaylistId Create(
Guid? value = null)
{
return PlaylistId.Create(value ?? Guid.NewGuid());
}
/// <summary>
/// Creates a list of <see cref="PlaylistId"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistId"/> instances.</returns>
public List<PlaylistId> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -28,6 +28,7 @@ public class StubApiHttpClient : IApiHttpClient
private readonly Dictionary<string, Func<object, object>> _postResponseFactories = [];
private readonly Dictionary<string, Func<object, object>> _putResponseFactories = [];
private readonly HashSet<string> _deleteSuccessEndpoints = [];
private readonly Dictionary<string, ApiException> _deleteExceptions = [];
private BlobDataDto? _blobResponse;
/// <summary>
@@ -167,6 +168,16 @@ public class StubApiHttpClient : IApiHttpClient
_deleteSuccessEndpoints.Add(endpoint);
}
/// <summary>
/// Registers the exception thrown when the specified DELETE endpoint is called.
/// </summary>
/// <param name="endpoint">The API endpoint for which to register the exception.</param>
/// <param name="exception">The exception to throw.</param>
public void RegisterDeleteException(string endpoint, ApiException exception)
{
_deleteExceptions[endpoint] = exception;
}
/// <summary>
/// Registers the blob response returned when a blob endpoint is called.
/// </summary>
@@ -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);
@@ -15,7 +15,7 @@ namespace Lumina.Presentation.Web.Fixtures.Common.Api;
[ExcludeFromCodeCoverage]
public class TestApiHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, HttpResponseMessage> _responseFactory;
private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _responseFactory;
/// <summary>
/// Gets the list of requests that were sent through this handler.
@@ -27,11 +27,25 @@ public class TestApiHttpMessageHandler : HttpMessageHandler
/// </summary>
public List<string?> RequestBodies { get; } = [];
/// <summary>
/// Gets the cancellation tokens the requests were sent with.
/// </summary>
public List<CancellationToken> CancellationTokens { get; } = [];
/// <summary>
/// Initializes a new instance of the <see cref="TestApiHttpMessageHandler"/> class.
/// </summary>
/// <param name="responseFactory">The factory that produces the response for a given request.</param>
public TestApiHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> responseFactory)
{
_responseFactory = (request, cancellationToken) => Task.FromResult(responseFactory(request));
}
/// <summary>
/// Initializes a new instance of the <see cref="TestApiHttpMessageHandler"/> class.
/// </summary>
/// <param name="responseFactory">The asynchronous factory that produces the response for a given request and cancellation token.</param>
public TestApiHttpMessageHandler(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> responseFactory)
{
_responseFactory = responseFactory;
}
@@ -45,7 +59,8 @@ public class TestApiHttpMessageHandler : HttpMessageHandler
protected override async Task<HttpResponseMessage> 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);
}
}
@@ -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;
/// <summary>
/// <see cref="HttpContent"/> 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.
/// </summary>
[ExcludeFromCodeCoverage]
public sealed class TrackingStreamContent : HttpContent
{
private readonly byte[] _contentBytes;
private readonly MemoryStream _contentStream;
private readonly bool _shouldFailStreamCreation;
/// <summary>
/// Gets a value indicating whether the content was buffered by the client before it was handed to the caller.
/// </summary>
public bool WasBufferedByClient { get; private set; }
/// <summary>
/// Gets a value indicating whether the content was disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Gets the stream the content hands over when it is read without being buffered first.
/// </summary>
public Stream ContentStream => _contentStream;
/// <summary>
/// Initializes a new instance of the <see cref="TrackingStreamContent"/> class.
/// </summary>
/// <param name="contentBytes">The bytes of the content.</param>
/// <param name="mediaType">The media type the content declares.</param>
/// <param name="shouldFailStreamCreation">Whether obtaining the content stream should fail.</param>
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);
}
/// <summary>
/// Writes the content to the provided stream, recording that the client buffered it.
/// </summary>
/// <param name="stream">The stream the content is written to.</param>
/// <param name="context">The transport context of the serialization, if any.</param>
/// <returns>A task that represents the asynchronous serialization.</returns>
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context)
{
WasBufferedByClient = true;
return stream.WriteAsync(_contentBytes, 0, _contentBytes.Length);
}
/// <summary>
/// Hands over the known content stream without buffering the content first.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The content stream.</returns>
/// <exception cref="InvalidOperationException">Thrown when the content is configured to fail obtaining its stream.</exception>
protected override Task<Stream> CreateContentReadStreamAsync(CancellationToken cancellationToken)
{
if (_shouldFailStreamCreation)
throw new InvalidOperationException("The content stream cannot be obtained.");
return Task.FromResult<Stream>(_contentStream);
}
/// <summary>
/// Computes the length of the content.
/// </summary>
/// <param name="length">The length of the content in bytes.</param>
/// <returns>Always <see langword="true"/>.</returns>
protected override bool TryComputeLength(out long length)
{
length = _contentBytes.Length;
return true;
}
/// <summary>
/// Disposes the content, recording that it was disposed.
/// </summary>
/// <param name="disposing">Whether the content is being disposed.</param>
protected override void Dispose(bool disposing)
{
if (disposing)
IsDisposed = true;
base.Dispose(disposing);
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistDetailsDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistDetailsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="PlaylistDetailsDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional Id of the playlist.</param>
/// <param name="name">Optional name of the playlist.</param>
/// <param name="description">Optional description of the playlist.</param>
/// <param name="type">Optional kind of media the playlist holds.</param>
/// <param name="updatedOnUtc">Optional date and time when the playlist was last updated.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="PlaylistDetailsDto"/> instance.</returns>
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
);
}
/// <summary>
/// Creates multiple <see cref="PlaylistDetailsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistDetailsDto"/> instances.</returns>
public List<PlaylistDetailsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntriesAddedDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntriesAddedDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="PlaylistEntriesAddedDto"/> instance with randomized test data.
/// </summary>
/// <param name="playlistId">Optional Id of the playlist the entries were added to.</param>
/// <param name="addedCount">Optional number of entries that were appended.</param>
/// <param name="updatedOnUtc">Optional date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="PlaylistEntriesAddedDto"/> instance.</returns>
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
);
}
/// <summary>
/// Creates multiple <see cref="PlaylistEntriesAddedDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntriesAddedDto"/> instances.</returns>
public List<PlaylistEntriesAddedDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntryAddedDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryAddedDtoFixture
{
private readonly Faker _faker = new();
private readonly PlaylistEntryDtoFixture _playlistEntryDtoFixture = new();
/// <summary>
/// Creates a new <see cref="PlaylistEntryAddedDto"/> instance with randomized test data.
/// </summary>
/// <param name="playlistId">Optional Id of the playlist the entry was added to.</param>
/// <param name="entry">Optional added entry.</param>
/// <param name="updatedOnUtc">Optional date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="PlaylistEntryAddedDto"/> instance.</returns>
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
);
}
/// <summary>
/// Creates multiple <see cref="PlaylistEntryAddedDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntryAddedDto"/> instances.</returns>
public List<PlaylistEntryAddedDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistEntryMovedDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistEntryMovedDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="PlaylistEntryMovedDto"/> instance with randomized test data.
/// </summary>
/// <param name="playlistId">Optional Id of the playlist whose entry was moved.</param>
/// <param name="entryId">Optional Id of the moved entry.</param>
/// <param name="position">Optional new zero based position of the entry.</param>
/// <param name="updatedOnUtc">Optional date and time when the playlist was last updated.</param>
/// <param name="includeUpdatedOnUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="PlaylistEntryMovedDto"/> instance.</returns>
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
);
}
/// <summary>
/// Creates multiple <see cref="PlaylistEntryMovedDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistEntryMovedDto"/> instances.</returns>
public List<PlaylistEntryMovedDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaylistSummaryDto"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistSummaryDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="PlaylistSummaryDto"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional Id of the playlist.</param>
/// <param name="name">Optional name of the playlist.</param>
/// <param name="description">Optional description of the playlist.</param>
/// <param name="type">Optional kind of media the playlist holds.</param>
/// <param name="entryCount">Optional number of entries of the playlist.</param>
/// <param name="createdOnUtc">Optional date and time when the playlist was created.</param>
/// <param name="updatedOnUtc">Optional date and time when the playlist was last updated.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeUpdatedOnUtc">Whether the last update date should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="PlaylistSummaryDto"/> instance.</returns>
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
);
}
/// <summary>
/// Creates multiple <see cref="PlaylistSummaryDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="PlaylistSummaryDto"/> instances.</returns>
public List<PlaylistSummaryDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -22,14 +22,16 @@ public class ThemeTemplateResponseDtoFixture
/// </summary>
/// <param name="theme">Optional theme the template belongs to.</param>
/// <param name="template">Optional sanitized template content.</param>
/// <param name="includeTemplate">Whether the template content should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="ThemeTemplateResponseDto"/> instance.</returns>
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!
);
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="PlaybackStateDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaybackStateDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a random valid <see cref="PlaybackStateDto"/>.
/// </summary>
/// <param name="volume">Optional. The last volume the player reported, as a value between 0 and 1.</param>
/// <param name="isMuted">Optional. The last mute state the player reported.</param>
/// <param name="includeVolume">Whether the volume should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeIsMuted">Whether the mute state should be included, or forced to <see langword="null"/>.</param>
/// <returns>The created <see cref="PlaybackStateDto"/>.</returns>
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
};
}
/// <summary>
/// Creates a list of <see cref="PlaybackStateDto"/> instances.
/// </summary>
/// <param name="count">Number of elements to create.</param>
/// <returns>The created list.</returns>
public List<PlaybackStateDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistEntriesRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesRequestFixture
{
/// <summary>
/// Creates a new <see cref="AddPlaylistEntriesRequest"/> instance with randomized test data.
/// </summary>
/// <param name="trackIds">Optional Ids of the tracks to add, in order.</param>
/// <param name="trackCount">Optional number of random track Ids to generate when <paramref name="trackIds"/> is not supplied.</param>
/// <param name="includeTrackIds">Whether the track Ids should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="AddPlaylistEntriesRequest"/> instance.</returns>
public AddPlaylistEntriesRequest Create(
List<Guid>? trackIds = null,
int trackCount = 3,
bool includeTrackIds = true)
{
return new AddPlaylistEntriesRequest(
TrackIds: includeTrackIds ? (trackIds ?? CreateRandomTrackIds(trackCount)) : null);
}
/// <summary>
/// Creates multiple <see cref="AddPlaylistEntriesRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistEntriesRequest"/> instances.</returns>
public List<AddPlaylistEntriesRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
/// <summary>
/// Creates the requested number of distinct random track Ids.
/// </summary>
/// <param name="count">The number of track Ids to create.</param>
/// <returns>The created track Ids.</returns>
private static List<Guid> CreateRandomTrackIds(int count)
{
return [.. Enumerable.Range(0, count).Select(_ => Guid.NewGuid())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistEntryRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryRequestFixture
{
/// <summary>
/// Creates a new <see cref="AddPlaylistEntryRequest"/> instance with randomized test data.
/// </summary>
/// <param name="trackId">Optional Id of the track to add.</param>
/// <param name="includeTrackId">Whether the track Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="AddPlaylistEntryRequest"/> instance.</returns>
public AddPlaylistEntryRequest Create(
Guid? trackId = null,
bool includeTrackId = true)
{
return new AddPlaylistEntryRequest(
TrackId: includeTrackId ? (trackId ?? Guid.NewGuid()) : null);
}
/// <summary>
/// Creates multiple <see cref="AddPlaylistEntryRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistEntryRequest"/> instances.</returns>
public List<AddPlaylistEntryRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="AddPlaylistScopeEntriesRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesRequestFixture
{
/// <summary>
/// Creates a new <see cref="AddPlaylistScopeEntriesRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional Id of the music library the scope belongs to.</param>
/// <param name="artistId">Optional Id of the artist the scope is limited to.</param>
/// <param name="albumId">Optional Id of the album the scope is limited to.</param>
/// <param name="includeArtistId">Whether the artist Id should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeAlbumId">Whether the album Id should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="AddPlaylistScopeEntriesRequest"/> instance.</returns>
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);
}
/// <summary>
/// Creates multiple <see cref="AddPlaylistScopeEntriesRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="AddPlaylistScopeEntriesRequest"/> instances.</returns>
public List<AddPlaylistScopeEntriesRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="CreatePlaylistRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class CreatePlaylistRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="CreatePlaylistRequest"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional name of the playlist.</param>
/// <param name="description">Optional description of the playlist.</param>
/// <param name="type">Optional kind of media the playlist holds.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeType">Whether the media type should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="CreatePlaylistRequest"/> instance.</returns>
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);
}
/// <summary>
/// Creates multiple <see cref="CreatePlaylistRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="CreatePlaylistRequest"/> instances.</returns>
public List<CreatePlaylistRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MovePlaylistEntryRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MovePlaylistEntryRequest"/> instance with randomized test data.
/// </summary>
/// <param name="targetPosition">Optional new zero based position of the entry.</param>
/// <param name="includeTargetPosition">Whether the target position should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MovePlaylistEntryRequest"/> instance.</returns>
public MovePlaylistEntryRequest Create(
int? targetPosition = null,
bool includeTargetPosition = true)
{
return new MovePlaylistEntryRequest(
TargetPosition: includeTargetPosition ? (targetPosition ?? _faker.Random.Int(0, 1_000)) : null);
}
/// <summary>
/// Creates multiple <see cref="MovePlaylistEntryRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MovePlaylistEntryRequest"/> instances.</returns>
public List<MovePlaylistEntryRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="UpdatePlaylistRequest"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaylistRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="UpdatePlaylistRequest"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional name of the playlist.</param>
/// <param name="description">Optional description of the playlist.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="includeDescription">Whether the description should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="UpdatePlaylistRequest"/> instance.</returns>
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);
}
/// <summary>
/// Creates multiple <see cref="UpdatePlaylistRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="UpdatePlaylistRequest"/> instances.</returns>
public List<UpdatePlaylistRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddPlaylistEntriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistEntriesAddedResponse>(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<LuminaDbContext>();
List<Guid> 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<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(3, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(2, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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");
}
/// <summary>
/// Reads the media item Ids of the entries of <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The media item Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedTrackIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.MediaItemId)
.ToListAsync();
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Id of the seeded media library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid artistId = Guid.NewGuid();
dbContext.Artists.Add(_artistEntityFixture.Create(
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return artistId;
}
/// <summary>
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <returns>The Id of the seeded album.</returns>
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a track of the album identified by <paramref name="albumId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="mediaItemId">The Id of the referenced track.</param>
/// <param name="position">The sparse order key of the entry.</param>
private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
playlistId: playlistId,
mediaItemId: mediaItemId,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: position));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddPlaylistEntryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistEntryAddedResponse>(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<LuminaDbContext>();
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<PlaylistEntryAddedResponse>(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<LuminaDbContext>();
List<Guid> 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<PlaylistEntryAddedResponse>(firstResponse);
PlaylistEntryAddedResponse? secondEntry = await DeserializeAsync<PlaylistEntryAddedResponse>(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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Id of the seeded media library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid artistId = Guid.NewGuid();
dbContext.Artists.Add(_artistEntityFixture.Create(
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return artistId;
}
/// <summary>
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <returns>The Id of the seeded album.</returns>
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a track of the album identified by <paramref name="albumId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="mediaItemId">The Id of the referenced track.</param>
/// <param name="position">The sparse order key of the entry.</param>
private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
playlistId: playlistId,
mediaItemId: mediaItemId,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: position));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistScopeEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public AddPlaylistScopeEntriesEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistEntriesAddedResponse>(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<LuminaDbContext>();
List<Guid> 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<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(2, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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<PlaylistEntriesAddedResponse>(response);
Assert.NotNull(addedEntries);
Assert.Equal(1, addedEntries!.AddedCount);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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<PlaylistEntriesAddedResponse>(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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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");
}
/// <summary>
/// Reads the media item Ids of the entries of <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The media item Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedTrackIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.MediaItemId)
.ToListAsync();
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Id of the seeded media library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an artist of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the artist belongs to.</param>
/// <param name="name">The name of the artist.</param>
/// <returns>The Id of the seeded artist.</returns>
private async Task<Guid> SeedArtistAsync(Guid libraryId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid artistId = Guid.NewGuid();
dbContext.Artists.Add(_artistEntityFixture.Create(
id: artistId, libraryId: libraryId, name: name, includeAlbums: false, includeContributors: false));
await dbContext.SaveChangesAsync();
return artistId;
}
/// <summary>
/// Seeds an album of the artist identified by <paramref name="artistId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the album belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="title">The title of the album.</param>
/// <returns>The Id of the seeded album.</returns>
private async Task<Guid> SeedAlbumAsync(Guid libraryId, Guid artistId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a track of the album identified by <paramref name="albumId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <param name="durationInSeconds">The duration of the track in seconds.</param>
/// <param name="trackNumber">The number of the track on its album.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, Guid albumId, string title, int durationInSeconds, int trackNumber)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="CreatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CreatePlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="CreatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public CreatePlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistResponse>(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<LuminaDbContext>();
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<PlaylistResponse>(response);
Assert.NotNull(playlist);
Assert.Null(playlist!.Description);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<PlaylistResponse>(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<PlaylistResponse>(response);
Assert.NotNull(playlist);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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);
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="DeletePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletePlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeletePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public DeletePlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="mediaItemId">The Id of the referenced track.</param>
/// <param name="position">The sparse order key of the entry.</param>
private async Task SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
dbContext.PlaylistEntries.Add(_playlistEntryEntityFixture.Create(
playlistId: playlistId,
mediaItemId: mediaItemId,
mediaItemType: PlaylistMediaItemType.MusicTrack,
position: position));
await dbContext.SaveChangesAsync();
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaylistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaylistsEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaylistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPlaylistsEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistSummaryResponse[]>(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<PlaylistSummaryResponse[]>(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<PlaylistSummaryResponse[]>(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<PlaylistSummaryResponse[]>(response);
Assert.NotNull(playlists);
PlaylistSummaryResponse playlist = Assert.Single(playlists!);
Assert.Equal(ownPlaylistId, playlist.Id);
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="description">The description of the playlist, or <see langword="null"/>.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <param name="createdOnUtc">The creation time of the playlist.</param>
/// <param name="updatedOnUtc">The activity time of the playlist, or <see langword="null"/> when it was never updated.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> 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<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
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());
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="MovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="MovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public MovePlaylistEntryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistEntryMovedResponse>(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<LuminaDbContext>();
List<Guid> 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<PlaylistEntryMovedResponse>(response);
Assert.NotNull(movedEntry);
Assert.Equal(2, movedEntry!.Position);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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<PlaylistEntryMovedResponse>(response);
Assert.NotNull(movedEntry);
Assert.Equal(1, movedEntry!.Position);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
List<Guid> 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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> with three ordered entries and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <returns>The Id of the playlist and the Ids of its first, second and third entries.</returns>
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);
}
/// <summary>
/// Reads the entry Ids of the playlist identified by <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The entry Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedEntryIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.Id)
.ToListAsync();
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="mediaItemId">The Id of the referenced track.</param>
/// <param name="position">The sparse order key of the entry.</param>
/// <returns>The Id of the seeded entry.</returns>
private async Task<Guid> SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="RemovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemovePlaylistEntryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="RemovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public RemovePlaylistEntryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistEntryRemovedResponse>(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<LuminaDbContext>();
Assert.False(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == secondEntryId));
List<Guid> 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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
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<LuminaDbContext>();
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherPlaylistEntryId));
List<Guid> 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<LuminaDbContext>();
Assert.True(await dbContext.PlaylistEntries.AnyAsync(entry => entry.Id == otherEntryId));
List<Guid> 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");
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> with three ordered entries and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <returns>The Id of the playlist and the Ids of its first, second and third entries.</returns>
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);
}
/// <summary>
/// Reads the entry Ids of the playlist identified by <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="dbContext">The database context to read from.</param>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The entry Ids in stored order.</returns>
private static async Task<List<Guid>> GetOrderedEntryIdsAsync(LuminaDbContext dbContext, Guid playlistId)
{
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(candidate => candidate.PlaylistId == playlistId)
.OrderBy(candidate => candidate.Position)
.Select(candidate => candidate.Id)
.ToListAsync();
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="mediaItemId">The Id of the referenced track.</param>
/// <param name="position">The sparse order key of the entry.</param>
/// <returns>The Id of the seeded entry.</returns>
private async Task<Guid> SeedPlaylistEntryAsync(Guid playlistId, Guid mediaItemId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaylistEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<Guid> _seededUserIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdatePlaylistEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaylistDetailsResponse>(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<LuminaDbContext>();
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<PlaylistDetailsResponse>(response);
Assert.NotNull(playlist);
Assert.Null(playlist!.Description);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<PlaylistDetailsResponse>(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<LuminaDbContext>();
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<LuminaDbContext>();
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");
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="description">The description of the playlist, or <see langword="null"/>.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, string? description)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and tracks it for cleanup.
/// </summary>
/// <returns>The Id of the seeded user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Gets the Id of the currently authenticated test user.
/// </summary>
/// <returns>The Id of the authenticated test user.</returns>
private Guid GetCurrentUserId()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
UserEntity user = dbContext.Users.First(candidate => candidate.Username == _apiFactory.TestUsername);
return user.Id;
}
/// <summary>
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
/// </summary>
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
/// <param name="response">The HTTP response to read.</param>
/// <returns>The deserialized body.</returns>
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
{
string content = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
}
/// <summary>
/// Asserts that the response is a problem details document with the expected status, title and detail.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedStatus">The expected HTTP status.</param>
/// <param name="expectedTitle">The expected problem title.</param>
/// <param name="expectedDetail">The expected problem detail.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is a validation problem details document carrying the expected error code.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
}
/// <summary>
/// Removes the data seeded by the test and the API factory test user.
/// </summary>
public async Task DisposeAsync()
{
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaybackStateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackStateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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) }
};
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public GetPlaybackStateEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaybackStateResponse>(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<PlaybackStateResponse>(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<PlaybackStateResponse>(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);
}
/// <summary>
/// Stores the playback state of the currently authenticated test user.
/// </summary>
/// <param name="volume">The volume to store.</param>
/// <param name="isMuted">The mute state to store.</param>
/// <returns>The stored settings.</returns>
private async Task<UserSettingsEntity> CreateTestUserSettings(double volume, bool isMuted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds another user and stores that user's playback state, keeping it out of the current user's scope.
/// </summary>
/// <param name="volume">The volume to store.</param>
/// <param name="isMuted">The mute state to store.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task CreateSettingsForAnotherUserAsync(double volume, bool isMuted)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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();
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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
};
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
public UpdatePlaybackStateEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
{
_client = apiFactory.CreateClient();
_apiFactory = apiFactory;
}
/// <summary>
/// Initializes the authenticated API client.
/// </summary>
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<PlaybackStateResponse>(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<PlaybackStateResponse>(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);
}
/// <summary>
/// Asserts that <paramref name="response"/> is a validation problem response carrying the specified error.
/// </summary>
/// <param name="response">The response to assert.</param>
/// <param name="expectedError">The exact error description expected in the validation errors.</param>
/// <returns>A task representing the asynchronous operation.</returns>
private async Task AssertValidationErrorAsync(HttpResponseMessage response, string expectedError)
{
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
string content = await response.Content.ReadAsStringAsync();
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
Assert.NotNull(errors);
Assert.Contains("General.Validation", errors.Keys);
Assert.Contains(expectedError, errors["General.Validation"]);
}
/// <summary>
/// Stores a playback state for the currently authenticated test user.
/// </summary>
/// <param name="volume">The volume to store.</param>
/// <param name="isMuted">The mute state to store.</param>
/// <param name="itemsPerPage">The number of items displayed per page to store.</param>
/// <param name="isPaginationEnabled">Whether pagination is enabled.</param>
/// <returns>The stored settings.</returns>
private async Task<UserSettingsEntity> CreateTestUserSettingsAsync(double volume, bool isMuted, int itemsPerPage, bool isPaginationEnabled)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Reads the stored playback state of the currently authenticated test user.
/// </summary>
/// <returns>The stored settings, or <see langword="null"/> when the user has none.</returns>
private async Task<UserSettingsEntity?> GetCurrentUserSettingsAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
Guid userId = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername).Id;
return await dbContext.UserSettings.FirstOrDefaultAsync(settings => settings.UserId == userId);
}
/// <summary>
/// Disposes API factory resources.
/// </summary>
public async Task DisposeAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
await dbContext.Set<UserSettingsEntity>().ExecuteDeleteAsync();
await dbContext.Set<UserEntity>().ExecuteDeleteAsync();
await dbContext.SaveChangesAsync();
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="StreamMusicTrackEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class StreamMusicTrackEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="StreamMusicTrackEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<string, string> 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);
}
/// <summary>
/// Builds the browser facing route of the direct stream of a track.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The browser facing route of the requested stream.</returns>
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}";
}
/// <summary>
/// Builds the upstream endpoint the stream request is expected to be sent to.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The expected upstream endpoint.</returns>
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());
}
/// <summary>
/// Creates a streamed API response with a status code, a body and a media type.
/// </summary>
/// <param name="statusCode">The status code of the response.</param>
/// <param name="contentBytes">The bytes of the content of the response.</param>
/// <param name="contentType">The media type of the content.</param>
/// <returns>The created streamed response.</returns>
private static async Task<ApiStreamResult> 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);
}
/// <summary>
/// Creates a deterministic byte array that stands in for the content of a stream.
/// </summary>
/// <param name="length">The number of bytes to create.</param>
/// <returns>The created bytes.</returns>
private static byte[] CreateBytes(int length)
{
return [.. Enumerable.Range(0, length).Select(index => (byte)(index % 256))];
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesEndpointTests : IClassFixture<LuminaWebFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public AddPlaylistEntriesEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task AddPlaylistEntries_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldForwardTheEntriesAndReturnTheAddedCount()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid playlistId = Guid.NewGuid();
List<Guid> 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<AddPlaylistEntriesRequest>(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("<b>", 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);
}
/// <summary>
/// Gets the add entries requests that were sent upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream add entries requests that were sent.</returns>
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))];
}
/// <summary>
/// Builds the add entries request for the specified playlist route value.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="request">The request payload to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured add entries request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<AddPlaylistEntryRequest>(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("<b>", 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);
}
/// <summary>
/// Gets the add entry requests that were sent upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream add entry requests that were sent.</returns>
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))];
}
/// <summary>
/// Builds the add entry request for the specified playlist route value.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="request">The request payload to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured add entry request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="AddPlaylistScopeEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesEndpointTests : IClassFixture<LuminaWebFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<AddPlaylistScopeEntriesRequest>(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<AddPlaylistScopeEntriesRequest>(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("<b>", 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);
}
/// <summary>
/// Gets the add scope entries requests that were sent upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream add scope entries requests that were sent.</returns>
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))];
}
/// <summary>
/// Builds the add scope entries request for the specified playlist route value.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="request">The request payload to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured add scope entries request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="CreatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CreatePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, 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<PlaylistEntryDto> _paginatedDtoFixture = new();
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="CreatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<CreatePlaylistRequest>(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<CreatePlaylistRequest>(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("<b>", 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());
}
/// <summary>
/// Gets the create playlist requests that were sent upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream create playlist requests that were sent.</returns>
private List<(string Endpoint, object? Data)> GetCreateRequests()
{
return [.. _apiFactory.ApiClientStub.PostRequests
.Where(postRequest => postRequest.Endpoint == UPSTREAM_ENDPOINT)];
}
/// <summary>
/// Builds the create playlist request that sends the given <paramref name="request"/>.
/// </summary>
/// <param name="request">The request payload to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured create playlist request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="DeletePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="DeletePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<string> deleteEndpoints = GetDeleteEndpointCalls();
Assert.Equal([expectedEndpoint], deleteEndpoints);
Assert.DoesNotContain(playlistId.ToString().ToUpperInvariant(), string.Join(",", deleteEndpoints), StringComparison.Ordinal);
}
/// <summary>
/// Gets the delete playlist endpoints that were called upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream delete playlist endpoints that were called.</returns>
private List<string> GetDeleteEndpointCalls()
{
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
}
/// <summary>
/// Builds the delete playlist request for the specified route value.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured delete playlist request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaylistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaylistsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string UPSTREAM_ENDPOINT = "users/me/playlists";
private readonly LuminaWebFactory _apiFactory;
private readonly PlaylistSummaryDtoFixture _playlistSummaryDtoFixture = new();
private readonly ProblemDetailsDtoFixture _problemDetailsDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaylistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<JsonElement> 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<PlaylistSummaryDto>());
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 _));
}
/// <summary>
/// Gets the playlist endpoints that were called upstream, excluding the endpoints called by the authentication helpers.
/// </summary>
/// <returns>The list of upstream playlist endpoints that were called.</returns>
private List<string> GetPlaylistEndpointCalls()
{
return [.. _apiFactory.ApiClientStub.GetEndpointsCalled
.Where(endpoint => endpoint == UPSTREAM_ENDPOINT)];
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="PlaylistsIndexViewEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class PlaylistsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string WEB_ROUTE = "/en-us/playlists";
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="PlaylistsIndexViewEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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);
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="MovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="MovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<MovePlaylistEntryRequest>(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("<b>", 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);
}
/// <summary>
/// Gets the move entry requests that were sent upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream move entry requests that were sent.</returns>
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))];
}
/// <summary>
/// Builds the move entry request for the specified route values.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="playlistEntryId">The value of the playlist entry identifier route segment.</param>
/// <param name="request">The request payload to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured move entry request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="RemovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemovePlaylistEntryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
{
private const string ZERO_GUID = "00000000-0000-0000-0000-000000000000";
private readonly LuminaWebFactory _apiFactory;
/// <summary>
/// Initializes a new instance of the <see cref="RemovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<string> removeEndpoints = GetRemoveEndpointCalls();
Assert.Equal([expectedEndpoint], removeEndpoints);
Assert.DoesNotContain(playlistEntryId.ToString().ToUpperInvariant(), string.Join(",", removeEndpoints), StringComparison.Ordinal);
}
/// <summary>
/// Gets the remove entry endpoints that were called upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream remove entry endpoints that were called.</returns>
private List<string> GetRemoveEndpointCalls()
{
return [.. _apiFactory.ApiClientStub.DeleteEndpointsCalled
.Where(endpoint => endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal)
&& endpoint.Contains("/entries/", StringComparison.Ordinal))];
}
/// <summary>
/// Builds the remove entry request for the specified route values.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="playlistEntryId">The value of the playlist entry identifier route segment.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured remove entry request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaylistEndpointTests : IClassFixture<LuminaWebFactory>, 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();
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<UpdatePlaylistRequest>(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<UpdatePlaylistRequest>(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("<b>", 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);
}
/// <summary>
/// Gets the update playlist requests that were sent upstream, excluding the requests made to authenticate the test client.
/// </summary>
/// <returns>The list of upstream update playlist requests that were sent.</returns>
private List<(string Endpoint, object? Data)> GetUpdateRequests()
{
return [.. _apiFactory.ApiClientStub.PutRequests
.Where(putRequest => putRequest.Endpoint.StartsWith("users/me/playlists/", StringComparison.Ordinal))];
}
/// <summary>
/// Builds the update playlist request for the specified route value.
/// </summary>
/// <param name="playlistId">The value of the playlist identifier route segment.</param>
/// <param name="request">The request payload to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request, or <see langword="null"/> to omit it.</param>
/// <returns>The configured update playlist request.</returns>
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;
}
/// <summary>
/// Releases the resources used by the test class and resets the remote API stub.
/// </summary>
public void Dispose()
{
_apiFactory.ApiClientStub.Reset();
GC.SuppressFinalize(this);
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="GetPlaybackStateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaybackStateEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaybackStateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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());
}
}
@@ -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;
/// <summary>
/// Contains integration tests for the <see cref="UpdatePlaybackStateEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class UpdatePlaybackStateEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly PlaybackStateDtoFixture _playbackStateDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="UpdatePlaybackStateEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
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<PlaybackStateDto>(putRequest.Data);
Assert.Equal(0.0, forwardedState.Volume);
Assert.False(forwardedState.IsMuted);
}
/// <summary>
/// Builds the update request that sends the given <paramref name="state"/> to the update playback state endpoint.
/// </summary>
/// <param name="state">The playback state to send.</param>
/// <param name="antiforgeryToken">The antiforgery token to include in the request.</param>
/// <returns>The configured update request.</returns>
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;
}
}
@@ -220,7 +220,7 @@ public class RemoveFavoriteEndpointTests : IClassFixture<LuminaApiFactory>, IDis
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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);
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetTrackStreamEndpoint"/> class.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
[ExcludeFromCodeCoverage]
public class GetTrackStreamEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
{
private const string ACTIVE_CONTENT_BODY = "<html><body><script>alert('active')</script></body></html>";
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<string> _temporaryFiles = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetTrackStreamEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<Microsoft.AspNetCore.Mvc.ProblemDetails>(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<Microsoft.AspNetCore.Mvc.ProblemDetails>(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<Microsoft.AspNetCore.Mvc.ProblemDetails>(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<Microsoft.AspNetCore.Mvc.ProblemDetails>(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);
}
/// <summary>
/// Seeds a user distinct from the authenticated test user and returns its Id.
/// </summary>
/// <returns>The Id of the seeded other user.</returns>
private async Task<Guid> SeedOtherUserAsync()
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an empty music library owned by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <returns>The Id of the seeded library.</returns>
private async Task<Guid> SeedEmptyLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a library owned by <paramref name="userId"/>, an artist of that library, an album of that artist and a track of that album.
/// </summary>
/// <param name="userId">The Id of the user that owns the library.</param>
/// <param name="trackPath">The file system path of the audio file of the track.</param>
/// <returns>The Ids of the seeded library, artist, album and track.</returns>
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<LuminaDbContext>();
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);
}
/// <summary>
/// Writes a file with the provided <paramref name="contentBytes"/> inside the content root of the test, and returns its full path.
/// </summary>
/// <param name="fileName">The name of the file to write.</param>
/// <param name="contentBytes">The bytes of the file to write.</param>
/// <returns>The full path of the written file.</returns>
private string WriteContentFile(string fileName, byte[] contentBytes)
{
string filePath = Path.Combine(_contentRootPath, fileName);
File.WriteAllBytes(filePath, contentBytes);
return filePath;
}
/// <summary>
/// Builds the route of the direct stream of a track.
/// </summary>
/// <param name="libraryId">The Id of the media library the track belongs to.</param>
/// <param name="artistId">The Id of the artist the album belongs to.</param>
/// <param name="albumId">The Id of the album the track belongs to.</param>
/// <param name="trackId">The Id of the track.</param>
/// <returns>The route of the requested stream.</returns>
private static string BuildStreamPath(Guid libraryId, Guid artistId, Guid albumId, Guid trackId)
{
return $"/api/v1/libraries/{libraryId}/artists/{artistId}/albums/{albumId}/tracks/{trackId}/stream";
}
/// <summary>
/// Builds the route of the direct stream of a track, with a malicious payload in one of its route values.
/// </summary>
/// <param name="routeValue">The name of the route value that carries the payload.</param>
/// <param name="payload">The malicious payload.</param>
/// <returns>The route of the requested stream, with the payload URL-escaped.</returns>
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";
}
/// <summary>
/// Disposes the API factory resources, the seeded users and the temporary files of the test.
/// </summary>
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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="AddPlaylistEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntriesEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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("<script>alert(1)</script>")] // 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));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Id of the seeded media library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an artist, an album and a track of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist still exists.</returns>
private async Task<bool> PlaylistExistsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId);
}
/// <summary>
/// Determines whether the playlist identified by <paramref name="playlistId"/> holds any entry.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist holds at least one entry.</returns>
private async Task<bool> PlaylistHasEntriesAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId);
}
/// <summary>
/// Reads the detail of a problem details body.
/// </summary>
/// <param name="content">The problem details body to read.</param>
/// <returns>The problem detail.</returns>
private static string? GetProblemDetail(string content)
{
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
return problemDetails!["detail"].GetString();
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private static async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Asserts that the response body exposes only the fields of the documented playlist response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the catalogue rows and playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> 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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="AddPlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistEntryEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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("<script>alert(1)</script>")] // 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));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Id of the seeded media library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an artist, an album and a track of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist still exists.</returns>
private async Task<bool> PlaylistExistsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId);
}
/// <summary>
/// Determines whether the playlist identified by <paramref name="playlistId"/> holds any entry.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist holds at least one entry.</returns>
private async Task<bool> PlaylistHasEntriesAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId);
}
/// <summary>
/// Reads the detail of a problem details body.
/// </summary>
/// <param name="content">The problem details body to read.</param>
/// <returns>The problem detail.</returns>
private static string? GetProblemDetail(string content)
{
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
return problemDetails!["detail"].GetString();
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private static async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Asserts that the response body exposes only the fields of the documented playlist entry contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the catalogue rows and playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> 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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="AddPlaylistScopeEntriesEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddPlaylistScopeEntriesEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededLibraryIds = [];
private readonly List<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="AddPlaylistScopeEntriesEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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("<script>alert(1)</script>")] // 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));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a music library owned by <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the media library.</param>
/// <returns>The Id of the seeded media library.</returns>
private async Task<Guid> SeedLibraryAsync(Guid userId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an artist, an album and a track of the library identified by <paramref name="libraryId"/>.
/// </summary>
/// <param name="libraryId">The Id of the library the track belongs to.</param>
/// <param name="title">The title of the track.</param>
/// <returns>The Id of the seeded track.</returns>
private async Task<Guid> SeedTrackAsync(Guid libraryId, string title)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist already holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist still exists.</returns>
private async Task<bool> PlaylistExistsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId);
}
/// <summary>
/// Determines whether the playlist identified by <paramref name="playlistId"/> holds any entry.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist holds at least one entry.</returns>
private async Task<bool> PlaylistHasEntriesAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.PlaylistEntries.AnyAsync(entry => entry.PlaylistId == playlistId);
}
/// <summary>
/// Reads the detail of a problem details body.
/// </summary>
/// <param name="content">The problem details body to read.</param>
/// <returns>The problem detail.</returns>
private static string? GetProblemDetail(string content)
{
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
return problemDetails!["detail"].GetString();
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private static async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Asserts that the response body exposes only the fields of the documented playlist response contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the catalogue rows and playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> libraryIds = [.. _seededLibraryIds];
List<Guid> 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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="CreatePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class CreatePlaylistEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="CreatePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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("<script>alert(1)</script>")] // 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<PlaylistResponse>(content, _jsonOptions);
Assert.NotNull(playlist);
_seededPlaylistIds.Add(playlist!.Id);
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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<PlaylistResponse>(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<PlaylistResponse>(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();
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Reads the detail of a problem details body.
/// </summary>
/// <param name="content">The problem details body to read.</param>
/// <returns>The problem detail.</returns>
private static string? GetProblemDetail(string content)
{
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
return problemDetails!["detail"].GetString();
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Asserts that the response body exposes only the fields of the documented playlist contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="DeletePlaylistEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class DeletePlaylistEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="DeletePlaylistEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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("<script>alert(1)</script>")] // 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));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist still exists.</returns>
private async Task<bool> PlaylistExistsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId);
}
/// <summary>
/// Reads the detail of a problem details body.
/// </summary>
/// <param name="content">The problem details body to read.</param>
/// <returns>The problem detail.</returns>
private static string? GetProblemDetail(string content)
{
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
return problemDetails!["detail"].GetString();
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Removes the playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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);
}
}
@@ -287,7 +287,7 @@ public class GetPlaylistEndpointTests : IClassFixture<LuminaApiFactory>, IDispos
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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);
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="GetPlaylistsEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetPlaylistsEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="GetPlaylistsEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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<PlaylistSummaryResponse[]>(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<PlaylistSummaryResponse[]>(content, _jsonOptions);
Assert.NotNull(playlists);
PlaylistSummaryResponse playlist = Assert.Single(playlists!);
Assert.Equal(ownPlaylistId, playlist.Id);
Assert.True(await PlaylistExistsAsync(ownPlaylistId));
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist still exists.</returns>
private async Task<bool> PlaylistExistsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId);
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
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());
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Asserts that the response body exposes only the fields of the documented playlist summary contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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);
}
}
@@ -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;
/// <summary>
/// Contains security tests for the <see cref="MovePlaylistEntryEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MovePlaylistEntryEndpointTests : IClassFixture<LuminaApiFactory>, 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<Guid> _seededPlaylistIds = [];
private readonly List<string> _seededUsernames = [];
/// <summary>
/// Initializes a new instance of the <see cref="MovePlaylistEntryEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected in-memory API factory.</param>
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("<script>alert(1)</script>")] // 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("<script>alert(1)</script>")] // 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);
}
/// <summary>
/// Creates a test user and authenticates it on <paramref name="client"/>.
/// </summary>
/// <param name="client">The HTTP client to authenticate.</param>
/// <returns>The Id and username of the created user.</returns>
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
{
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
_seededUsernames.Add(username);
return (userId, username);
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> with three ordered entries and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <returns>The Id of the playlist and the Ids of its first, second and third entries.</returns>
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);
}
/// <summary>
/// Seeds a playlist of <paramref name="userId"/> and tracks it for cleanup.
/// </summary>
/// <param name="userId">The Id of the user that owns the playlist.</param>
/// <param name="name">The name of the playlist.</param>
/// <param name="entryCount">The number of entries the playlist holds.</param>
/// <returns>The Id of the seeded playlist.</returns>
private async Task<Guid> SeedPlaylistAsync(Guid userId, string name, int entryCount)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Seeds an entry of the playlist identified by <paramref name="playlistId"/>.
/// </summary>
/// <param name="playlistId">The Id of the playlist the entry belongs to.</param>
/// <param name="position">The sparse order key of the entry.</param>
/// <returns>The Id of the seeded entry.</returns>
private async Task<Guid> SeedPlaylistEntryAsync(Guid playlistId, long position)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
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;
}
/// <summary>
/// Reads the entry Ids of the playlist identified by <paramref name="playlistId"/>, in stored order.
/// </summary>
/// <param name="playlistId">The Id of the playlist whose entries are read.</param>
/// <returns>The entry Ids in stored order.</returns>
private async Task<List<Guid>> GetOrderedEntryIdsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.PlaylistEntries
.AsNoTracking()
.Where(entry => entry.PlaylistId == playlistId)
.OrderBy(entry => entry.Position)
.Select(entry => entry.Id)
.ToListAsync();
}
/// <summary>
/// Asserts that the playlist identified by <paramref name="playlistId"/> still exists.
/// </summary>
/// <param name="playlistId">The Id of the playlist to look up.</param>
/// <returns><see langword="true"/> when the playlist still exists.</returns>
private async Task<bool> PlaylistExistsAsync(Guid playlistId)
{
using IServiceScope scope = _apiFactory.Services.CreateScope();
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
return await dbContext.Playlists.AnyAsync(playlist => playlist.Id == playlistId);
}
/// <summary>
/// Reads the detail of a problem details body.
/// </summary>
/// <param name="content">The problem details body to read.</param>
/// <returns>The problem detail.</returns>
private static string? GetProblemDetail(string content)
{
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content);
Assert.NotNull(problemDetails);
return problemDetails!["detail"].GetString();
}
/// <summary>
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstance">The expected request instance path.</param>
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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);
}
/// <summary>
/// Asserts the shape of a validation problem details response and returns its raw body.
/// </summary>
/// <param name="response">The HTTP response to assert on.</param>
/// <param name="expectedInstancePrefix">The expected prefix of the request instance path.</param>
/// <param name="expectedErrorCode">The expected validation error code.</param>
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
private async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>();
Assert.NotNull(errors);
Assert.Contains(expectedErrorCode, errors!["General.Validation"]);
AssertNoSensitiveData(content);
return content;
}
/// <summary>
/// Asserts that the response body carries no credentials, secrets or stack traces.
/// </summary>
/// <param name="content">The response body to assert on.</param>
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);
}
/// <summary>
/// Asserts that the response body exposes only the fields of the documented playlist entry contract.
/// </summary>
/// <param name="content">The response body to assert on.</param>
private static void AssertNoDatabaseOnlyFields(string content)
{
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Removes the playlists seeded by the test and the test users.
/// </summary>
public void Dispose()
{
_client.Dispose();
using (IServiceScope scope = _apiFactory.Services.CreateScope())
{
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
List<Guid> 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);
}
}
Loaded 100 of 197 files, more files were not shown because too many files have changed in this diff. Show more