diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs
index 28ebb3c1..2a18174b 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using System;
using System.Diagnostics;
#endregion
@@ -11,13 +9,13 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionIte
/// Command for deleting every consumption record of a media item of a user.
///
/// The Id of the user the records must belong to, or for the current user.
-/// The kind of the consumed media item.
-/// The Id of the consumed media item.
-/// The Id of the media library that contains the media item.
+/// The name of the kind of the consumed media item, taken from the route.
+/// The Id of the consumed media item, taken from the route.
+/// The Id of the media library that contains the media item, taken from the route.
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public record DeleteConsumptionItemHistoryCommand(
string? TargetUserId,
- MediaKind MediaKind,
- Guid MediaItemId,
- Guid LibraryId
+ string? MediaKind,
+ string? MediaItemId,
+ string? LibraryId
) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs
index 4d431e3b..08cdc001 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs
@@ -6,6 +6,7 @@ using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Threading;
@@ -69,10 +70,15 @@ public class DeleteConsumptionItemHistoryCommandHandler : ICommandHandler(command.MediaKind!, ignoreCase: true);
+ Guid mediaItemId = Guid.Parse(command.MediaItemId!);
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+
// The deletion covers every recorded session of the item in its library, not only the sessions of a date range, so the row
// disappears from the history consistently with clearing the whole history.
Result deleteResult = await _unitOfWork.MediaConsumptionRecordRepository
- .DeleteAllByMediaItemIdForUserAsync(targetUserId, command.MediaKind, command.MediaItemId, command.LibraryId, cancellationToken).ConfigureAwait(false);
+ .DeleteAllByMediaItemIdForUserAsync(targetUserId, mediaKind, mediaItemId, libraryId, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs
index 9f930037..31d9651d 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs
@@ -24,20 +24,36 @@ public class DeleteConsumptionItemHistoryCommandValidator : AbstractValidator command.MediaKind)
- .IsInEnum()
+ .NotEmpty()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
RuleFor(command => command.MediaKind)
- .Must(mediaKind => mediaKind != MediaKind.None)
+ .IsInEnum()
+ .WithError(Errors.MediaConsumption.UnsupportedMediaKind);
+
+ RuleFor(command => command.MediaKind)
+ .Must(mediaKind => mediaKind is null ||
+ !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase))
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
RuleFor(command => command.MediaItemId)
- .Must(mediaItemId => mediaItemId != Guid.Empty)
+ .NotEmpty()
+ .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
+
+ RuleFor(command => command.MediaItemId)
+ .Must(mediaItemId => Guid.TryParse(mediaItemId, out Guid parsedMediaItemId) && parsedMediaItemId != Guid.Empty)
+ .When(command => command.MediaItemId is not null && command.MediaItemId.Length > 0)
.WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
RuleFor(command => command.LibraryId)
- .Must(libraryId => libraryId != Guid.Empty)
+ .NotEmpty()
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.LibraryId)
+ .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
+ .When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs
index 7ca593a6..1b11ae3c 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs
@@ -1,7 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using System;
using System.Diagnostics;
#endregion
@@ -12,14 +10,14 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
///
/// The Id of the user whose statistics are retrieved, or for the current user.
/// The Id of the media library to restrict the statistics to, or for every library.
-/// The kind of media to restrict the statistics to, or for every kind.
-/// The inclusive start of the date range, or when the range has no start.
-/// The inclusive end of the date range, or when the range has no end.
+/// The name of the kind of media to restrict the statistics to, or for every kind.
+/// The inclusive start of the date range, in UTC, as a text value, or when the range has no start.
+/// The inclusive end of the date range, in UTC, as a text value, or when the range has no end.
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
public record GetGenreConsumptionQuery(
string? TargetUserId,
string? LibraryId,
- MediaKind? MediaKind,
- DateTime? FromUtc,
- DateTime? ToUtc
+ string? MediaKind,
+ string? FromUtc,
+ string? ToUtc
) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs
index b4fefa50..1aa45038 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs
@@ -18,6 +18,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.V
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
+using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -83,9 +84,12 @@ public class GetGenreConsumptionQueryHandler : IQueryHandler(query.MediaKind, ignoreCase: true);
+ DateTime? fromUtc = query.FromUtc is null ? null : DateTime.Parse(query.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
+ DateTime? toUtc = query.ToUtc is null ? null : DateTime.Parse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
Result> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
- .GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
+ .GetForUserAsync(targetUserId, libraryId, mediaKind, fromUtc, toUtc, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs
index 58ab2f25..af8d4f0c 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
+using System.Globalization;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
@@ -29,18 +30,42 @@ public class GetGenreConsumptionQueryValidator : AbstractValidator query.MediaKind)
- .IsInEnum()
- .WithError(Errors.MediaConsumption.UnsupportedMediaKind)
- .When(query => query.MediaKind is not null);
-
- RuleFor(query => query.MediaKind)
- .Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None)
+ .IsInEnum()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
- // An inverted range would silently return no records, so it is rejected as an invalid request instead.
+ RuleFor(query => query.MediaKind)
+ .Must(mediaKind => mediaKind is null ||
+ !string.Equals(mediaKind, nameof(MediaKind.None), StringComparison.OrdinalIgnoreCase))
+ .WithError(Errors.MediaConsumption.UnsupportedMediaKind);
+
+ // A malformed bound, or an inverted range, would silently return no records, so both are rejected as an invalid request instead.
RuleFor(query => query.FromUtc)
- .Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value)
+ .Must(fromUtc => fromUtc is null || DateTime.TryParse(
+ fromUtc,
+ CultureInfo.InvariantCulture,
+ DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
+ out _))
+ .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
+
+ RuleFor(query => query.ToUtc)
+ .Must(toUtc => toUtc is null || DateTime.TryParse(
+ toUtc,
+ CultureInfo.InvariantCulture,
+ DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal,
+ out _))
+ .WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
+
+ RuleFor(query => query.FromUtc)
+ .Must((query, fromUtc) =>
+ {
+ if (fromUtc is null || query.ToUtc is null ||
+ !DateTime.TryParse(fromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc) ||
+ !DateTime.TryParse(query.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc))
+ return true;
+ return parsedFromUtc <= parsedToUtc;
+ })
.WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
}
}
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs
index 7014c957..7a2847bb 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs
@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using System;
using System.Diagnostics;
#endregion
@@ -9,12 +7,12 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
///
/// Represents a request to delete every consumption record of a media item.
///
-/// The kind of the consumed media item.
-/// The Id of the consumed media item.
-/// The Id of the media library that contains the media item.
+/// The name of the kind of the consumed media item, taken from the route.
+/// The Id of the consumed media item, taken from the route.
+/// The Id of the media library that contains the media item, taken from the route.
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; LibraryId: {LibraryId}")]
public sealed record DeleteConsumptionItemHistoryRequest(
- MediaKind MediaKind,
- Guid MediaItemId,
- Guid LibraryId
+ string? MediaKind,
+ string? MediaItemId,
+ string? LibraryId
);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs
index f2a76b8c..85eb76d9 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs
@@ -1,6 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
-using System;
using System.Diagnostics;
#endregion
@@ -10,13 +8,13 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
/// Represents a request for getting the consumption statistics of the genres of a user.
///
/// The Id of the media library to restrict the statistics to. Optional.
-/// The kind of media to restrict the statistics to. Optional.
-/// The inclusive start of the date range. Optional.
-/// The inclusive end of the date range. Optional.
+/// The name of the kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range, in UTC, as a text value. Optional.
+/// The inclusive end of the date range, in UTC, as a text value. Optional.
[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
public sealed record GetGenreConsumptionRequest(
string? LibraryId,
- MediaKind? MediaKind,
- DateTime? FromUtc,
- DateTime? ToUtc
+ string? MediaKind,
+ string? FromUtc,
+ string? ToUtc
);
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
index 7b738174..47153c04 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
@@ -26,8 +26,8 @@ public class GetGenreConsumptionEndpointSummary : Summary request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs
index ed53aae1..818707d3 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs
@@ -26,8 +26,8 @@ public class GetUserGenreConsumptionEndpointSummary : Summary
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GenreConsumptionDtoFixture
+{
+ private const int MAXIMUM_DURATION_MILLISECONDS = 36_000_000;
+
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The lowercase name of the genre. Defaults to a random lowercase word.
+ /// Optional. The number of distinct consumed media items that carry the genre. Defaults to a bounded random count.
+ /// Optional. The consumed duration of the media items that carry the genre, in milliseconds. Defaults to a bounded random duration.
+ /// Whether the genre name should be included, or forced to .
+ /// Whether the consumed item count should be included, or forced to zero.
+ /// Whether the consumed duration should be included, or forced to zero.
+ /// The created .
+ public GenreConsumptionDto Create(
+ string? name = null,
+ int? consumedItemCount = null,
+ long? consumedDurationMilliseconds = null,
+ bool includeName = true,
+ bool includeConsumedItemCount = true,
+ bool includeConsumedDurationMilliseconds = true)
+ {
+ return new GenreConsumptionDto(
+ includeName ? name ?? _faker.Lorem.Word().ToLowerInvariant() : null!,
+ includeConsumedItemCount ? consumedItemCount ?? _faker.Random.Int(0, 1000) : 0,
+ includeConsumedDurationMilliseconds ? consumedDurationMilliseconds ?? _faker.Random.Long(0, MAXIMUM_DURATION_MILLISECONDS) : 0);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandFixture.cs
new file mode 100644
index 00000000..6e47dc79
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandFixture.cs
@@ -0,0 +1,69 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryCommandFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaKind[] _supportedMediaKinds =
+ [
+ MediaKind.MusicTrack,
+ MediaKind.PodcastEpisode,
+ MediaKind.Audiobook,
+ MediaKind.Movie,
+ MediaKind.TvEpisode,
+ MediaKind.Book,
+ MediaKind.Photo,
+ MediaKind.Video
+ ];
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the user the records must belong to. Defaults to a random user Id.
+ /// Optional. The name of the kind of the consumed media item. Defaults to the name of a random supported kind.
+ /// Optional. The Id of the consumed media item. Defaults to a random Id.
+ /// Optional. The Id of the media library that contains the media item. Defaults to a random Id.
+ /// Whether the target user Id should be included, or forced to so that the current user is targeted.
+ /// Whether the media kind name should be included, or forced to .
+ /// Whether the media item Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// The created .
+ public DeleteConsumptionItemHistoryCommand Create(
+ string? targetUserId = null,
+ string? mediaKind = null,
+ string? mediaItemId = null,
+ string? libraryId = null,
+ bool includeTargetUserId = true,
+ bool includeMediaKind = true,
+ bool includeMediaItemId = true,
+ bool includeLibraryId = true)
+ {
+ return new DeleteConsumptionItemHistoryCommand(
+ includeTargetUserId ? targetUserId ?? _faker.Random.Guid().ToString() : null,
+ includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
+ includeMediaItemId ? mediaItemId ?? _faker.Random.Guid().ToString() : null,
+ includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryFixture.cs b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryFixture.cs
new file mode 100644
index 00000000..f0e4cc22
--- /dev/null
+++ b/tests/Common/Lumina.Application.Fixtures/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryFixture.cs
@@ -0,0 +1,79 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Fixtures.Core.MediaConsumption.Queries.GetGenreConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionQueryFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaKind[] _supportedMediaKinds =
+ [
+ MediaKind.MusicTrack,
+ MediaKind.PodcastEpisode,
+ MediaKind.Audiobook,
+ MediaKind.Movie,
+ MediaKind.TvEpisode,
+ MediaKind.Book,
+ MediaKind.Photo,
+ MediaKind.Video
+ ];
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the user whose statistics are retrieved. Defaults to a random Id.
+ /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id.
+ /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind.
+ /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value.
+ /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment in the future, as a text value.
+ /// Whether the target user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind name should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// The created .
+ public GetGenreConsumptionQuery Create(
+ string? targetUserId = null,
+ string? libraryId = null,
+ string? mediaKind = null,
+ string? fromUtc = null,
+ string? toUtc = null,
+ bool includeTargetUserId = true,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true)
+ {
+ string resolvedFromUtc = fromUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)).ToString("o", CultureInfo.InvariantCulture);
+ string resolvedToUtc = toUtc ?? DateTime.UtcNow.AddDays(_faker.Random.Int(1, 30)).ToString("o", CultureInfo.InvariantCulture);
+
+ return new GetGenreConsumptionQuery(
+ includeTargetUserId ? targetUserId ?? _faker.Random.Guid().ToString() : null,
+ includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
+ includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
+ includeFromUtc ? resolvedFromUtc : null,
+ includeToUtc ? resolvedToUtc : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequestFixture.cs
new file mode 100644
index 00000000..4867ac12
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequestFixture.cs
@@ -0,0 +1,64 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaKind[] _supportedMediaKinds =
+ [
+ MediaKind.MusicTrack,
+ MediaKind.PodcastEpisode,
+ MediaKind.Audiobook,
+ MediaKind.Movie,
+ MediaKind.TvEpisode,
+ MediaKind.Book,
+ MediaKind.Photo,
+ MediaKind.Video
+ ];
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The name of the kind of the consumed media item. Defaults to the name of a random supported kind.
+ /// Optional. The Id of the consumed media item. Defaults to a random Id.
+ /// Optional. The Id of the media library that contains the media item. Defaults to a random Id.
+ /// Whether the media kind name should be included, or forced to .
+ /// Whether the media item Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// The created .
+ public DeleteConsumptionItemHistoryRequest Create(
+ string? mediaKind = null,
+ string? mediaItemId = null,
+ string? libraryId = null,
+ bool includeMediaKind = true,
+ bool includeMediaItemId = true,
+ bool includeLibraryId = true)
+ {
+ return new DeleteConsumptionItemHistoryRequest(
+ includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
+ includeMediaItemId ? mediaItemId ?? _faker.Random.Guid().ToString() : null,
+ includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetGenreConsumptionRequestFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetGenreConsumptionRequestFixture.cs
new file mode 100644
index 00000000..25c13dc8
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Requests/MediaConsumption/GetGenreConsumptionRequestFixture.cs
@@ -0,0 +1,74 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Globalization;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionRequestFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaKind[] _supportedMediaKinds =
+ [
+ MediaKind.MusicTrack,
+ MediaKind.PodcastEpisode,
+ MediaKind.Audiobook,
+ MediaKind.Movie,
+ MediaKind.TvEpisode,
+ MediaKind.Book,
+ MediaKind.Photo,
+ MediaKind.Video
+ ];
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id.
+ /// Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind.
+ /// Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value.
+ /// Optional. The inclusive end of the date range. Defaults to a bounded UTC moment in the future, as a text value.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind name should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// The created .
+ public GetGenreConsumptionRequest Create(
+ string? libraryId = null,
+ string? mediaKind = null,
+ string? fromUtc = null,
+ string? toUtc = null,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true)
+ {
+ string resolvedFromUtc = fromUtc ?? DateTime.UtcNow.AddDays(-_faker.Random.Int(1, 30)).ToString("o", CultureInfo.InvariantCulture);
+ string resolvedToUtc = toUtc ?? DateTime.UtcNow.AddDays(_faker.Random.Int(1, 30)).ToString("o", CultureInfo.InvariantCulture);
+
+ return new GetGenreConsumptionRequest(
+ includeLibraryId ? libraryId ?? _faker.Random.Guid().ToString() : null,
+ includeMediaKind ? mediaKind ?? _faker.Random.ArrayElement(_supportedMediaKinds).ToString() : null,
+ includeFromUtc ? resolvedFromUtc : null,
+ includeToUtc ? resolvedToUtc : null);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaConsumption/GenreConsumptionResponseFixture.cs b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaConsumption/GenreConsumptionResponseFixture.cs
new file mode 100644
index 00000000..97386d45
--- /dev/null
+++ b/tests/Common/Lumina.Contracts.Fixtures/Core/Responses/MediaConsumption/GenreConsumptionResponseFixture.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Contracts.Responses.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GenreConsumptionResponseFixture
+{
+ private const double MAXIMUM_DURATION_SECONDS = 36_000;
+
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a random valid .
+ ///
+ /// Optional. The lowercase name of the genre. Defaults to a random lowercase word.
+ /// Optional. The number of distinct consumed media items that carry the genre. Defaults to a bounded random count.
+ /// Optional. The consumed duration of the media items that carry the genre, in seconds. Defaults to a bounded random duration.
+ /// Whether the genre name should be included, or forced to .
+ /// Whether the consumed item count should be included, or forced to zero.
+ /// Whether the consumed duration should be included, or forced to zero.
+ /// The created .
+ public GenreConsumptionResponse Create(
+ string? name = null,
+ int? consumedItemCount = null,
+ double? consumedDurationInSeconds = null,
+ bool includeName = true,
+ bool includeConsumedItemCount = true,
+ bool includeConsumedDurationInSeconds = true)
+ {
+ return new GenreConsumptionResponse(
+ includeName ? name ?? _faker.Lorem.Word().ToLowerInvariant() : null!,
+ includeConsumedItemCount ? consumedItemCount ?? _faker.Random.Int(0, 1000) : 0,
+ includeConsumedDurationInSeconds ? consumedDurationInSeconds ?? _faker.Random.Double(0, MAXIMUM_DURATION_SECONDS) : 0);
+ }
+
+ ///
+ /// Creates a list of instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDtoFixture.cs
new file mode 100644
index 00000000..9a2e65e8
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDtoFixture.cs
@@ -0,0 +1,46 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class AllUsersConsumptionStatisticsDtoFixture
+{
+ private readonly ConsumptionTotalsDtoFixture _consumptionTotalsDtoFixture = new();
+ private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional combined consumption statistics of every user.
+ /// Optional consumption statistics of each user.
+ /// Whether the per user statistics should be included, or forced to an empty collection.
+ /// A configured instance.
+ public AllUsersConsumptionStatisticsDto Create(
+ ConsumptionTotalsDto? total = null,
+ IReadOnlyList? users = null,
+ bool includeUsers = true)
+ {
+ return new AllUsersConsumptionStatisticsDto(
+ Total: total ?? _consumptionTotalsDtoFixture.Create(),
+ Users: includeUsers ? (users ?? [.. _consumptionSummaryDtoFixture.CreateMany(2)]) : []
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumedItemDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumedItemDtoFixture.cs
new file mode 100644
index 00000000..eff29575
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumedItemDtoFixture.cs
@@ -0,0 +1,78 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ConsumedItemDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional kind of the consumed media item.
+ /// Optional Id of the consumed media item.
+ /// Optional Id of the media library that contains the media item.
+ /// Optional value indicating whether the media item is still available.
+ /// Optional title of the media item.
+ /// Optional title of the collection that contains the media item.
+ /// Optional name of the creator of the media item.
+ /// Optional path of the cover art of the media item.
+ /// Optional date and time when the media item was last consumed.
+ /// Optional number of counted sessions.
+ /// Optional number of completed sessions.
+ /// Optional consumed duration, in seconds.
+ /// Whether the cover path should be included, or forced to .
+ /// A configured instance.
+ public ConsumedItemDto Create(
+ MediaKind? mediaKind = null,
+ Guid? mediaItemId = null,
+ Guid? libraryId = null,
+ bool? isAvailable = null,
+ string? title = null,
+ string? collectionTitle = null,
+ string? creatorName = null,
+ string? coverPath = null,
+ DateTime? lastConsumedOnUtc = null,
+ int? countedSessionCount = null,
+ int? completedSessionCount = null,
+ double? consumedDurationInSeconds = null,
+ bool includeCoverPath = true)
+ {
+ return new ConsumedItemDto(
+ MediaKind: mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video),
+ MediaItemId: mediaItemId ?? _faker.Random.Guid(),
+ LibraryId: libraryId ?? _faker.Random.Guid(),
+ IsAvailable: isAvailable ?? _faker.Random.Bool(),
+ Title: title ?? _faker.Lorem.Sentence(),
+ CollectionTitle: collectionTitle ?? _faker.Lorem.Sentence(),
+ CreatorName: creatorName ?? _faker.Name.FullName(),
+ CoverPath: includeCoverPath ? (coverPath ?? _faker.System.FilePath()) : null,
+ LastConsumedOnUtc: lastConsumedOnUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31)),
+ CountedSessionCount: countedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletedSessionCount: completedSessionCount ?? _faker.Random.Int(0, 1000),
+ ConsumedDurationInSeconds: consumedDurationInSeconds ?? _faker.Random.Double(0, 100000)
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumptionSummaryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumptionSummaryDtoFixture.cs
new file mode 100644
index 00000000..3dba2aa1
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumptionSummaryDtoFixture.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ConsumptionSummaryDtoFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaKindConsumptionSummaryDtoFixture _mediaKindConsumptionSummaryDtoFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user the statistics belong to.
+ /// Optional total consumed duration, in seconds.
+ /// Optional number of counted sessions.
+ /// Optional number of completed sessions.
+ /// Optional number of stopped sessions.
+ /// Optional fraction of the counted sessions that completed.
+ /// Optional consumption statistics broken down by media kind.
+ /// Whether the media kind summaries should be included, or forced to an empty collection.
+ /// A configured instance.
+ public ConsumptionSummaryDto Create(
+ Guid? userId = null,
+ double? totalConsumedDurationInSeconds = null,
+ int? countedSessionCount = null,
+ int? completedSessionCount = null,
+ int? stoppedSessionCount = null,
+ double? completionRate = null,
+ IReadOnlyList? mediaKindSummaries = null,
+ bool includeMediaKindSummaries = true)
+ {
+ return new ConsumptionSummaryDto(
+ UserId: userId ?? _faker.Random.Guid(),
+ TotalConsumedDurationInSeconds: totalConsumedDurationInSeconds ?? _faker.Random.Double(0, 100000),
+ CountedSessionCount: countedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletedSessionCount: completedSessionCount ?? _faker.Random.Int(0, 1000),
+ StoppedSessionCount: stoppedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletionRate: completionRate ?? _faker.Random.Double(0, 1),
+ MediaKindSummaries: includeMediaKindSummaries ? (mediaKindSummaries ?? [.. _mediaKindConsumptionSummaryDtoFixture.CreateMany(2)]) : []
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumptionTotalsDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumptionTotalsDtoFixture.cs
new file mode 100644
index 00000000..1fd48d10
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/ConsumptionTotalsDtoFixture.cs
@@ -0,0 +1,59 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ConsumptionTotalsDtoFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MediaKindConsumptionSummaryDtoFixture _mediaKindConsumptionSummaryDtoFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional total consumed duration, in seconds.
+ /// Optional number of counted sessions.
+ /// Optional number of completed sessions.
+ /// Optional number of stopped sessions.
+ /// Optional fraction of the counted sessions that completed.
+ /// Optional consumption statistics broken down by media kind.
+ /// Whether the media kind summaries should be included, or forced to an empty collection.
+ /// A configured instance.
+ public ConsumptionTotalsDto Create(
+ double? totalConsumedDurationInSeconds = null,
+ int? countedSessionCount = null,
+ int? completedSessionCount = null,
+ int? stoppedSessionCount = null,
+ double? completionRate = null,
+ IReadOnlyList? mediaKindSummaries = null,
+ bool includeMediaKindSummaries = true)
+ {
+ return new ConsumptionTotalsDto(
+ TotalConsumedDurationInSeconds: totalConsumedDurationInSeconds ?? _faker.Random.Double(0, 100000),
+ CountedSessionCount: countedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletedSessionCount: completedSessionCount ?? _faker.Random.Int(0, 1000),
+ StoppedSessionCount: stoppedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletionRate: completionRate ?? _faker.Random.Double(0, 1),
+ MediaKindSummaries: includeMediaKindSummaries ? (mediaKindSummaries ?? [.. _mediaKindConsumptionSummaryDtoFixture.CreateMany(2)]) : []
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/GenreConsumptionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/GenreConsumptionDtoFixture.cs
new file mode 100644
index 00000000..cd4e33e9
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/GenreConsumptionDtoFixture.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GenreConsumptionDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional lowercase name of the genre.
+ /// Optional number of distinct consumed media items that carry the genre.
+ /// Optional consumed duration, in seconds.
+ /// A configured instance.
+ public GenreConsumptionDto Create(
+ string? name = null,
+ int? consumedItemCount = null,
+ double? consumedDurationInSeconds = null)
+ {
+ return new GenreConsumptionDto(
+ Name: name ?? _faker.Lorem.Word().ToLowerInvariant(),
+ ConsumedItemCount: consumedItemCount ?? _faker.Random.Int(0, 1000),
+ ConsumedDurationInSeconds: consumedDurationInSeconds ?? _faker.Random.Double(0, 100000)
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDtoFixture.cs
new file mode 100644
index 00000000..bfccd343
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDtoFixture.cs
@@ -0,0 +1,57 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class MediaKindConsumptionSummaryDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional kind of media the statistics belong to.
+ /// Optional total consumed duration, in seconds.
+ /// Optional number of counted sessions.
+ /// Optional number of completed sessions.
+ /// Optional number of stopped sessions.
+ /// Optional fraction of the counted sessions that completed.
+ /// A configured instance.
+ public MediaKindConsumptionSummaryDto Create(
+ MediaKind? mediaKind = null,
+ double? totalConsumedDurationInSeconds = null,
+ int? countedSessionCount = null,
+ int? completedSessionCount = null,
+ int? stoppedSessionCount = null,
+ double? completionRate = null)
+ {
+ return new MediaKindConsumptionSummaryDto(
+ MediaKind: mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video),
+ TotalConsumedDurationInSeconds: totalConsumedDurationInSeconds ?? _faker.Random.Double(0, 100000),
+ CountedSessionCount: countedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletedSessionCount: completedSessionCount ?? _faker.Random.Int(0, 1000),
+ StoppedSessionCount: stoppedSessionCount ?? _faker.Random.Int(0, 1000),
+ CompletionRate: completionRate ?? _faker.Random.Double(0, 1)
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/StatisticsPageDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/StatisticsPageDtoFixture.cs
new file mode 100644
index 00000000..beb1a99d
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/StatisticsPageDtoFixture.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class StatisticsPageDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional localized title of the page.
+ /// Optional value indicating whether the current user is an administrator.
+ /// Optional Id of the current user.
+ /// Optional culture of the page.
+ /// Optional route that returns the statistics of the selected user.
+ /// Optional route that returns the statistics of every user.
+ /// Optional route that returns the recently consumed media items.
+ /// Optional route that returns the most consumed media items.
+ /// Optional route that returns the tag consumption.
+ /// Optional route that returns the genre consumption.
+ /// Optional route that returns the libraries available for the library filter.
+ /// Optional route that returns the users available for the administrator user selector.
+ /// Optional route that deletes every consumption record of a media item.
+ /// Optional route that deletes the consumption history.
+ /// Optional route that deletes the resume points.
+ /// Whether the current user Id should be included, or forced to .
+ /// A configured instance.
+ public StatisticsPageDto Create(
+ string? title = null,
+ bool? isAdmin = null,
+ Guid? currentUserId = null,
+ string? culture = null,
+ string? getStatisticsUrl = null,
+ string? getAllUsersStatisticsUrl = null,
+ string? getRecentlyConsumedUrl = null,
+ string? getMostConsumedUrl = null,
+ string? getTagConsumptionUrl = null,
+ string? getGenreConsumptionUrl = null,
+ string? getLibrariesUrl = null,
+ string? getUsersUrl = null,
+ string? deleteConsumptionItemHistoryUrl = null,
+ string? clearConsumptionHistoryUrl = null,
+ string? clearResumePointsUrl = null,
+ bool includeCurrentUserId = true)
+ {
+ return new StatisticsPageDto(
+ Title: title ?? _faker.Lorem.Sentence(),
+ IsAdmin: isAdmin ?? _faker.Random.Bool(),
+ CurrentUserId: includeCurrentUserId ? (currentUserId ?? _faker.Random.Guid()) : null,
+ Culture: culture ?? _faker.PickRandom("en-US", "de-DE", "fr-FR"),
+ GetStatisticsUrl: getStatisticsUrl ?? _faker.Internet.Url(),
+ GetAllUsersStatisticsUrl: getAllUsersStatisticsUrl ?? _faker.Internet.Url(),
+ GetRecentlyConsumedUrl: getRecentlyConsumedUrl ?? _faker.Internet.Url(),
+ GetMostConsumedUrl: getMostConsumedUrl ?? _faker.Internet.Url(),
+ GetTagConsumptionUrl: getTagConsumptionUrl ?? _faker.Internet.Url(),
+ GetGenreConsumptionUrl: getGenreConsumptionUrl ?? _faker.Internet.Url(),
+ GetLibrariesUrl: getLibrariesUrl ?? _faker.Internet.Url(),
+ GetUsersUrl: getUsersUrl ?? _faker.Internet.Url(),
+ DeleteConsumptionItemHistoryUrl: deleteConsumptionItemHistoryUrl ?? _faker.Internet.Url(),
+ ClearConsumptionHistoryUrl: clearConsumptionHistoryUrl ?? _faker.Internet.Url(),
+ ClearResumePointsUrl: clearResumePointsUrl ?? _faker.Internet.Url()
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/TagConsumptionDtoFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/TagConsumptionDtoFixture.cs
new file mode 100644
index 00000000..4c2820ca
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/DTO/MediaConsumption/TagConsumptionDtoFixture.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class TagConsumptionDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional lowercase name of the tag.
+ /// Optional number of distinct consumed media items that carry the tag.
+ /// Optional consumed duration, in seconds.
+ /// A configured instance.
+ public TagConsumptionDto Create(
+ string? name = null,
+ int? consumedItemCount = null,
+ double? consumedDurationInSeconds = null)
+ {
+ return new TagConsumptionDto(
+ Name: name ?? _faker.Lorem.Word().ToLowerInvariant(),
+ ConsumedItemCount: consumedItemCount ?? _faker.Random.Int(0, 1000),
+ ConsumedDurationInSeconds: consumedDurationInSeconds ?? _faker.Random.Double(0, 100000)
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequestFixture.cs
new file mode 100644
index 00000000..5790864d
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequestFixture.cs
@@ -0,0 +1,43 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ClearConsumptionHistoryRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose history is deleted.
+ /// Whether the user Id should be included, or forced to .
+ /// A configured instance.
+ public ClearConsumptionHistoryRequest Create(
+ string? userId = null,
+ bool includeUserId = true)
+ {
+ return new ClearConsumptionHistoryRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/ClearResumePointsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/ClearResumePointsRequestFixture.cs
new file mode 100644
index 00000000..449ab109
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/ClearResumePointsRequestFixture.cs
@@ -0,0 +1,48 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class ClearResumePointsRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose resume points are deleted.
+ /// Optional Id of the media library to restrict the deletion to.
+ /// Whether the user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// A configured instance.
+ public ClearResumePointsRequest Create(
+ string? userId = null,
+ string? libraryId = null,
+ bool includeUserId = true,
+ bool includeLibraryId = true)
+ {
+ return new ClearResumePointsRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequestFixture.cs
new file mode 100644
index 00000000..b911d042
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequestFixture.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose history is deleted.
+ /// Optional kind of the consumed media item.
+ /// Optional Id of the consumed media item.
+ /// Optional Id of the media library that contains the media item.
+ /// Whether the user Id should be included, or forced to .
+ /// A configured instance.
+ public DeleteConsumptionItemHistoryRequest Create(
+ string? userId = null,
+ MediaKind? mediaKind = null,
+ Guid? mediaItemId = null,
+ Guid? libraryId = null,
+ bool includeUserId = true)
+ {
+ return new DeleteConsumptionItemHistoryRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video),
+ MediaItemId: mediaItemId ?? _faker.Random.Guid(),
+ LibraryId: libraryId ?? _faker.Random.Guid()
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequestFixture.cs
new file mode 100644
index 00000000..b70132dd
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequestFixture.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetAllUsersConsumptionStatisticsRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the media library to restrict the statistics to.
+ /// Optional kind of media to restrict the statistics to.
+ /// Optional inclusive start of the date range.
+ /// Optional inclusive end of the date range.
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// A configured instance.
+ public GetAllUsersConsumptionStatisticsRequest Create(
+ string? libraryId = null,
+ MediaKind? mediaKind = null,
+ DateTime? fromUtc = null,
+ DateTime? toUtc = null,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true)
+ {
+ return new GetAllUsersConsumptionStatisticsRequest(
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video)) : null,
+ FromUtc: includeFromUtc ? (fromUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ ToUtc: includeToUtc ? (toUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequestFixture.cs
new file mode 100644
index 00000000..1489f98d
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequestFixture.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetConsumptionStatisticsRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose statistics are retrieved.
+ /// Optional Id of the media library to restrict the statistics to.
+ /// Optional kind of media to restrict the statistics to.
+ /// Optional inclusive start of the date range.
+ /// Optional inclusive end of the date range.
+ /// Whether the user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// A configured instance.
+ public GetConsumptionStatisticsRequest Create(
+ string? userId = null,
+ string? libraryId = null,
+ MediaKind? mediaKind = null,
+ DateTime? fromUtc = null,
+ DateTime? toUtc = null,
+ bool includeUserId = true,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true)
+ {
+ return new GetConsumptionStatisticsRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video)) : null,
+ FromUtc: includeFromUtc ? (fromUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ ToUtc: includeToUtc ? (toUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetGenreConsumptionRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetGenreConsumptionRequestFixture.cs
new file mode 100644
index 00000000..3e56ed92
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetGenreConsumptionRequestFixture.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose statistics are retrieved.
+ /// Optional Id of the media library to restrict the statistics to.
+ /// Optional kind of media to restrict the statistics to.
+ /// Optional inclusive start of the date range.
+ /// Optional inclusive end of the date range.
+ /// Whether the user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// A configured instance.
+ public GetGenreConsumptionRequest Create(
+ string? userId = null,
+ string? libraryId = null,
+ MediaKind? mediaKind = null,
+ DateTime? fromUtc = null,
+ DateTime? toUtc = null,
+ bool includeUserId = true,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true)
+ {
+ return new GetGenreConsumptionRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video)) : null,
+ FromUtc: includeFromUtc ? (fromUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ ToUtc: includeToUtc ? (toUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetMostConsumedRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetMostConsumedRequestFixture.cs
new file mode 100644
index 00000000..ba75412e
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetMostConsumedRequestFixture.cs
@@ -0,0 +1,75 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetMostConsumedRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose history is retrieved.
+ /// Optional Id of the media library to restrict the history to.
+ /// Optional kind of media to restrict the history to.
+ /// Optional inclusive start of the date range.
+ /// Optional inclusive end of the date range.
+ /// Optional one based page of media items to return.
+ /// Optional number of media items per page.
+ /// Whether the user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// Whether the current page should be included, or forced to .
+ /// Whether the page size should be included, or forced to .
+ /// A configured instance.
+ public GetMostConsumedRequest Create(
+ string? userId = null,
+ string? libraryId = null,
+ MediaKind? mediaKind = null,
+ DateTime? fromUtc = null,
+ DateTime? toUtc = null,
+ int? currentPage = null,
+ int? perPage = null,
+ bool includeUserId = true,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true,
+ bool includeCurrentPage = true,
+ bool includePerPage = true)
+ {
+ return new GetMostConsumedRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video)) : null,
+ FromUtc: includeFromUtc ? (fromUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ ToUtc: includeToUtc ? (toUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 10)) : null,
+ PerPage: includePerPage ? (perPage ?? _faker.Random.Int(1, 100)) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetRecentlyConsumedRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetRecentlyConsumedRequestFixture.cs
new file mode 100644
index 00000000..bcd6d3df
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetRecentlyConsumedRequestFixture.cs
@@ -0,0 +1,75 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetRecentlyConsumedRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose history is retrieved.
+ /// Optional Id of the media library to restrict the history to.
+ /// Optional kind of media to restrict the history to.
+ /// Optional inclusive start of the date range.
+ /// Optional inclusive end of the date range.
+ /// Optional one based page of media items to return.
+ /// Optional number of media items per page.
+ /// Whether the user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// Whether the current page should be included, or forced to .
+ /// Whether the page size should be included, or forced to .
+ /// A configured instance.
+ public GetRecentlyConsumedRequest Create(
+ string? userId = null,
+ string? libraryId = null,
+ MediaKind? mediaKind = null,
+ DateTime? fromUtc = null,
+ DateTime? toUtc = null,
+ int? currentPage = null,
+ int? perPage = null,
+ bool includeUserId = true,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true,
+ bool includeCurrentPage = true,
+ bool includePerPage = true)
+ {
+ return new GetRecentlyConsumedRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video)) : null,
+ FromUtc: includeFromUtc ? (fromUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ ToUtc: includeToUtc ? (toUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ CurrentPage: includeCurrentPage ? (currentPage ?? _faker.Random.Int(1, 10)) : null,
+ PerPage: includePerPage ? (perPage ?? _faker.Random.Int(1, 100)) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetTagConsumptionRequestFixture.cs b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetTagConsumptionRequestFixture.cs
new file mode 100644
index 00000000..3eb14f63
--- /dev/null
+++ b/tests/Common/Lumina.Presentation.Web.Fixtures/Common/Requests/Library/Statistics/GetTagConsumptionRequestFixture.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+public class GetTagConsumptionRequestFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional Id of the user whose statistics are retrieved.
+ /// Optional Id of the media library to restrict the statistics to.
+ /// Optional kind of media to restrict the statistics to.
+ /// Optional inclusive start of the date range.
+ /// Optional inclusive end of the date range.
+ /// Whether the user Id should be included, or forced to .
+ /// Whether the library Id should be included, or forced to .
+ /// Whether the media kind should be included, or forced to .
+ /// Whether the start of the date range should be included, or forced to .
+ /// Whether the end of the date range should be included, or forced to .
+ /// A configured instance.
+ public GetTagConsumptionRequest Create(
+ string? userId = null,
+ string? libraryId = null,
+ MediaKind? mediaKind = null,
+ DateTime? fromUtc = null,
+ DateTime? toUtc = null,
+ bool includeUserId = true,
+ bool includeLibraryId = true,
+ bool includeMediaKind = true,
+ bool includeFromUtc = true,
+ bool includeToUtc = true)
+ {
+ return new GetTagConsumptionRequest(
+ UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null,
+ LibraryId: includeLibraryId ? (libraryId ?? _faker.Random.Guid().ToString()) : null,
+ MediaKind: includeMediaKind ? (mediaKind ?? _faker.PickRandom(MediaKind.MusicTrack, MediaKind.PodcastEpisode, MediaKind.Audiobook, MediaKind.Movie, MediaKind.TvEpisode, MediaKind.Book, MediaKind.Photo, MediaKind.Video)) : null,
+ FromUtc: includeFromUtc ? (fromUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null,
+ ToUtc: includeToUtc ? (toUtc ?? _faker.Date.Between(new DateTime(2024, 1, 1), new DateTime(2025, 12, 31))) : null
+ );
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs
new file mode 100644
index 00000000..3e92477f
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs
@@ -0,0 +1,425 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+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.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+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.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private static readonly DateTime s_startedOnUtc = new(2026, 4, 2, 20, 15, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 2, 20, 45, 0, DateTimeKind.Utc);
+
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ _seededUsernames.Add(_apiFactory.TestUsername!);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenItemHasRecords_ShouldDeleteOnlyTheMatchingRecords()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid otherLibraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Other User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 90_000);
+ Guid otherItemRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
+ Guid movedLibraryRecordId = await SeedConsumptionRecordAsync(userId, otherLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ Guid otherKindRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.Book, mediaItemId, 60_000);
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Owner Library");
+ Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ await AssertRecordsAreDeletedAsync(firstRecordId, secondRecordId);
+ await AssertRecordsArePreservedAsync(otherItemRecordId, movedLibraryRecordId, otherKindRecordId, otherUserRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenCalled_ShouldReturnEmptyDeletedBody()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ 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());
+ await AssertRecordsAreDeletedAsync(recordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenItemHasNoRecords_ShouldSucceedWithoutSideEffects()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid existingRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ await AssertRecordsArePreservedAsync(existingRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
+ await AssertRecordsAreDeletedAsync(recordId);
+ HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
+ Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
+ AssertCacheHeaders(secondResponse);
+ await AssertRecordsAreDeletedAsync(recordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenMediaKindIsNone_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.None)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(path);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenMediaItemIdIsEmpty_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.Empty}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(path);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "MediaItemIdCannotBeEmpty");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenLibraryIdIsEmpty_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.Empty}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(path);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ ///
+ /// Seeds a media library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The type of the library.
+ /// The title of the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a consumption record of a media item for .
+ ///
+ /// The Id of the user that owns the record.
+ /// The Id of the library that contains the media item.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The active duration consumed by the session, in milliseconds.
+ /// The Id of the seeded record.
+ private async Task SeedConsumptionRecordAsync(
+ Guid userId,
+ Guid libraryId,
+ MediaKind mediaKind,
+ Guid mediaItemId,
+ long consumedDurationMilliseconds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid recordId = Guid.NewGuid();
+ MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
+ id: recordId,
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: mediaKind,
+ mediaItemId: mediaItemId,
+ status: ConsumptionStatus.Completed,
+ startedOnUtc: s_startedOnUtc,
+ lastActivityOnUtc: s_lastActivityOnUtc,
+ endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
+ consumedDurationMilliseconds: consumedDurationMilliseconds,
+ lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 45_000,
+ lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
+ lastProgressFraction: 0.5,
+ consecutivePagesRead: mediaKind == MediaKind.Book ? 10 : 0);
+ dbContext.MediaConsumptionRecords.Add(record);
+ await dbContext.SaveChangesAsync();
+ return recordId;
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be deleted.
+ private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
+ // has run, instead of assuming that it already has.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ if (storedRecords.Count == 0)
+ return;
+ await Task.Delay(100);
+ }
+ Assert.Empty(storedRecords);
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are still stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be preserved.
+ private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
+ // completion has run, instead of trusting the state observed right after the response.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ await Task.Delay(100);
+ }
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ }
+
+ ///
+ /// Asserts that the response carries the cache headers of a private, authorization varying resource.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertCacheHeaders(HttpResponseMessage response)
+ {
+ Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues));
+ string cacheControl = string.Join(", ", cacheControlValues!);
+ Assert.Contains("private", cacheControl);
+ Assert.Contains("no-store", cacheControl);
+ Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues));
+ Assert.Contains("Authorization", varyValues!);
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, 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.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
+ string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
+ Assert.Equal(expectedValidationErrors, actualValidationErrors);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, 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());
+ }
+
+ ///
+ /// Removes every user created by the test, together with the libraries it owns.
+ ///
+ public async Task DisposeAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ foreach (string username in _seededUsernames)
+ {
+ UserEntity? user = dbContext.Users
+ .Include(candidate => candidate.Libraries)
+ .FirstOrDefault(candidate => candidate.Username == username);
+ if (user is null)
+ continue;
+ dbContext.Libraries.RemoveRange(user.Libraries);
+ dbContext.Users.Remove(user);
+ }
+ await dbContext.SaveChangesAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointTests.cs
new file mode 100644
index 00000000..026ae4f0
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointTests.cs
@@ -0,0 +1,456 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+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.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+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.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private static readonly DateTime s_startedOnUtc = new(2026, 4, 3, 18, 5, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_lastActivityOnUtc = new(2026, 4, 3, 18, 40, 0, DateTimeKind.Utc);
+
+ private HttpClient _client;
+ private readonly AuthenticatedLuminaApiFactory _apiFactory;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteUserConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ _seededUsernames.Add(_apiFactory.TestUsername!);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenCurrentUserNamesThemselves_ShouldDeleteTheItemRecords()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid firstRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ Guid secondRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 90_000);
+ string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ await AssertRecordsAreDeletedAsync(firstRecordId, secondRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
+ {
+ // Arrange
+ _ = GetCurrentUserId();
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/{otherUserId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertForbiddenAsync(response, url);
+ AssertCacheHeaders(response);
+ await AssertRecordsArePreservedAsync(otherUserRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersItemRecords()
+ {
+ // Arrange
+ _ = GetCurrentUserId();
+ Guid targetUserId = await SeedOtherUserAsync();
+ Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.Music, "Target User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid targetRecordId = await SeedConsumptionRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/{targetUserId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
+ HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
+ _seededUsernames.Add(_apiFactory.TestUsername!);
+
+ try
+ {
+ // Act
+ HttpResponseMessage response = await adminClient.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ await AssertRecordsAreDeletedAsync(targetRecordId);
+ }
+ finally
+ {
+ adminClient.Dispose();
+ }
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenTargetUserDoesNotOwnTheItem_ShouldSucceedAndPreserveThatUsersRecords()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid ownRecordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
+ Guid otherUserId = await SeedOtherUserAsync();
+ Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid otherUserRecordId = await SeedConsumptionRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ await AssertRecordsArePreservedAsync(ownRecordId, otherUserRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Current User Library");
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedConsumptionRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
+ await AssertRecordsAreDeletedAsync(recordId);
+ HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
+ Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
+ AssertCacheHeaders(secondResponse);
+ await AssertRecordsAreDeletedAsync(recordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = $"/api/v1/users/not-a-guid/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(path);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "TargetUserIdIsInvalid");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenMediaKindIsNone_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string path = $"/api/v1/users/{userId}/consumption-history/media-items/{nameof(MediaKind.None)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(path);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenUnauthenticated_ShouldReturnUnauthorized()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ ///
+ /// Seeds a media library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The type of the library.
+ /// The title of the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a consumption record of a media item for .
+ ///
+ /// The Id of the user that owns the record.
+ /// The Id of the library that contains the media item.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The active duration consumed by the session, in milliseconds.
+ /// The Id of the seeded record.
+ private async Task SeedConsumptionRecordAsync(
+ Guid userId,
+ Guid libraryId,
+ MediaKind mediaKind,
+ Guid mediaItemId,
+ long consumedDurationMilliseconds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid recordId = Guid.NewGuid();
+ MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
+ id: recordId,
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: mediaKind,
+ mediaItemId: mediaItemId,
+ status: ConsumptionStatus.Completed,
+ startedOnUtc: s_startedOnUtc,
+ lastActivityOnUtc: s_lastActivityOnUtc,
+ endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
+ consumedDurationMilliseconds: consumedDurationMilliseconds,
+ lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 45_000,
+ lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
+ lastProgressFraction: 0.5,
+ consecutivePagesRead: mediaKind == MediaKind.Book ? 10 : 0);
+ dbContext.MediaConsumptionRecords.Add(record);
+ await dbContext.SaveChangesAsync();
+ return recordId;
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be deleted.
+ private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
+ // has run, instead of assuming that it already has.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ if (storedRecords.Count == 0)
+ return;
+ await Task.Delay(100);
+ }
+ Assert.Empty(storedRecords);
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are still stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be preserved.
+ private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
+ // completion has run, instead of trusting the state observed right after the response.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ await Task.Delay(100);
+ }
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ }
+
+ ///
+ /// Asserts that the response carries the cache headers of a private, authorization varying resource.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertCacheHeaders(HttpResponseMessage response)
+ {
+ Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues));
+ string cacheControl = string.Join(", ", cacheControlValues!);
+ Assert.Contains("private", cacheControl);
+ Assert.Contains("no-store", cacheControl);
+ Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues));
+ Assert.Contains("Authorization", varyValues!);
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, 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.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
+ string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
+ Assert.Equal(expectedValidationErrors, actualValidationErrors);
+ }
+
+ ///
+ /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, 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());
+ }
+
+ ///
+ /// Removes every user created by the test, together with the libraries it owns.
+ ///
+ public async Task DisposeAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ foreach (string username in _seededUsernames)
+ {
+ UserEntity? user = dbContext.Users
+ .Include(candidate => candidate.Libraries)
+ .FirstOrDefault(candidate => candidate.Username == username);
+ if (user is null)
+ continue;
+ dbContext.Libraries.RemoveRange(user.Libraries);
+ dbContext.Users.Remove(user);
+ }
+ await dbContext.SaveChangesAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs
new file mode 100644
index 00000000..c865af63
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs
@@ -0,0 +1,524 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+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.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+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.Library.Statistics.GetGenreConsumption;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private static readonly DateTime s_trackCompletedStartedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_trackStoppedStartedOnUtc = new(2026, 3, 2, 10, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_bookCompletedStartedOnUtc = new(2026, 2, 1, 10, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_uncountedBookStartedOnUtc = new(2026, 2, 5, 10, 0, 0, DateTimeKind.Utc);
+
+ 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 BookEntityFixture _bookEntityFixture = new();
+ private readonly GenreEntityFixture _genreEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ _seededUsernames.Add(_apiFactory.TestUsername!);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenGenreBearingItemsWereConsumed_ShouldReturnLowercaseGenresOrderedByItemCountThenDurationThenName()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (Guid musicLibraryId, Guid bookLibraryId, string rockGenre, string favouriteGenre, string bookClubGenre, string ignoredGenre) = await SeedGenreConsumptionScenarioAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/genres");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Equal(3, genres!.Count);
+ Assert.All(genres, genre => Assert.Equal(genre.Name.ToLowerInvariant(), genre.Name));
+ Assert.Equal(
+ new[] { favouriteGenre.ToLowerInvariant(), rockGenre.ToLowerInvariant(), bookClubGenre.ToLowerInvariant() },
+ genres.Select(genre => genre.Name).ToArray());
+
+ Assert.Equal(2, genres[0].ConsumedItemCount);
+ Assert.Equal(360d, genres[0].ConsumedDurationInSeconds, 3);
+ Assert.Equal(2, genres[1].ConsumedItemCount);
+ Assert.Equal(90d, genres[1].ConsumedDurationInSeconds, 3);
+ Assert.Equal(1, genres[2].ConsumedItemCount);
+ Assert.Equal(300d, genres[2].ConsumedDurationInSeconds, 3);
+ Assert.DoesNotContain(genres, genre => genre.Name == ignoredGenre.ToLowerInvariant());
+ Assert.NotEqual(musicLibraryId, bookLibraryId);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenRestrictedToOneLibrary_ShouldReturnOnlyThatLibraryGenres()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, Guid bookLibraryId, _, string favouriteGenre, string bookClubGenre, string ignoredGenre) = await SeedGenreConsumptionScenarioAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?libraryId={bookLibraryId}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Equal(
+ new[] { bookClubGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
+ genres!.Select(genre => genre.Name).ToArray());
+ Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
+ Assert.All(genres, genre => Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3));
+ Assert.DoesNotContain(genres, genre => genre.Name == ignoredGenre.ToLowerInvariant());
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenRestrictedToOneMediaKind_ShouldReturnOnlyThatKindGenres()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?mediaKind={nameof(MediaKind.MusicTrack)}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Equal(
+ new[] { rockGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
+ genres!.Select(genre => genre.Name).ToArray());
+ Assert.Equal(2, genres[0].ConsumedItemCount);
+ Assert.Equal(90d, genres[0].ConsumedDurationInSeconds, 3);
+ Assert.Equal(1, genres[1].ConsumedItemCount);
+ Assert.Equal(60d, genres[1].ConsumedDurationInSeconds, 3);
+ Assert.DoesNotContain(genres, genre => genre.Name == bookClubGenre.ToLowerInvariant());
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenRestrictedToStartDate_ShouldReturnOnlySessionsWithinTheRange()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
+ string fromUtc = Uri.EscapeDataString("2026-03-01T00:00:00");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?fromUtc={fromUtc}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Equal(
+ new[] { rockGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
+ genres!.Select(genre => genre.Name).ToArray());
+ Assert.Equal(2, genres[0].ConsumedItemCount);
+ Assert.Equal(90d, genres[0].ConsumedDurationInSeconds, 3);
+ Assert.Equal(1, genres[1].ConsumedItemCount);
+ Assert.Equal(60d, genres[1].ConsumedDurationInSeconds, 3);
+ Assert.DoesNotContain(genres, genre => genre.Name == bookClubGenre.ToLowerInvariant());
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenRestrictedToEndDate_ShouldReturnOnlySessionsWithinTheRange()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ (_, _, string rockGenre, string favouriteGenre, string bookClubGenre, _) = await SeedGenreConsumptionScenarioAsync(userId);
+ string toUtc = Uri.EscapeDataString("2026-02-28T23:59:59");
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/me/consumption-statistics/genres?toUtc={toUtc}");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Equal(
+ new[] { bookClubGenre.ToLowerInvariant(), favouriteGenre.ToLowerInvariant() },
+ genres!.Select(genre => genre.Name).ToArray());
+ Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
+ Assert.All(genres, genre => Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3));
+ Assert.DoesNotContain(genres, genre => genre.Name == rockGenre.ToLowerInvariant());
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenHistoryIsEmpty_ShouldReturnEmptyCollection()
+ {
+ // Arrange
+ _ = GetCurrentUserId();
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync("/api/v1/users/me/consumption-statistics/genres");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Empty(genres!);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = "/api/v1/users/me/consumption-statistics/genres";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = "/api/v1/users/me/consumption-statistics/genres";
+ string url = $"{path}?libraryId=not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = "/api/v1/users/me/consumption-statistics/genres";
+ string url = $"{path}?mediaKind={nameof(MediaKind.None)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
+ AssertCacheHeaders(response);
+ }
+
+ [Theory]
+ [InlineData("999")] // a number that is not a member name
+ [InlineData("not-a-media-kind")] // a name that is not a member of the enumeration
+ public async Task GetGenreConsumption_WhenMediaKindIsNotAMemberName_ShouldReturnValidationProblem(string mediaKind)
+ {
+ // Arrange
+ string path = "/api/v1/users/me/consumption-statistics/genres";
+ string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
+ AssertCacheHeaders(response);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string path = "/api/v1/users/me/consumption-statistics/genres";
+ string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
+ string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
+ string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
+ AssertCacheHeaders(response);
+ }
+
+ ///
+ /// Seeds a track and a book in two libraries of , with counted and uncounted sessions.
+ ///
+ /// The Id of the user that owns the libraries and the consumption records.
+ ///
+ /// The Ids of the music library and the ebook library, and the unique rock, favourite, book club, and ignored genre names that were seeded.
+ ///
+ private async Task<(Guid musicLibraryId, Guid bookLibraryId, string rockGenre, string favouriteGenre, string bookClubGenre, string ignoredGenre)> SeedGenreConsumptionScenarioAsync(Guid userId)
+ {
+ // Each test seeds its own genre rows, so every name carries a unique suffix to keep the shared Genres table collision free.
+ string suffix = Guid.NewGuid().ToString("N")[..8].ToUpperInvariant();
+ string rockGenre = $"Rock-{suffix}";
+ string favouriteGenre = $"Favourite-{suffix}";
+ string bookClubGenre = $"Book-Club-{suffix}";
+ string ignoredGenre = $"Ignored-{suffix}";
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+
+ // The track and the book share a genre, so the genre rows are resolved once per name, and the whole graph is saved through one context.
+ Dictionary genres = [];
+ GenreEntity ResolveGenre(string name)
+ {
+ if (!genres.TryGetValue(name, out GenreEntity? genre))
+ {
+ genre = _genreEntityFixture.Create(name: name);
+ genres[name] = genre;
+ }
+ return genre;
+ }
+
+ Guid musicLibraryId = Guid.NewGuid();
+ Guid bookLibraryId = Guid.NewGuid();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid firstTrackId = Guid.NewGuid();
+ Guid secondTrackId = Guid.NewGuid();
+ Guid bookId = Guid.NewGuid();
+ Guid uncountedBookId = Guid.NewGuid();
+
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: musicLibraryId, userId: userId, title: "Music Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: bookLibraryId, userId: userId, title: "Book Library", libraryType: LibraryType.EBook, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: musicLibraryId, name: "Queen", includeAlbums: false, includeContributors: false, includeMetadata: false));
+ dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: musicLibraryId, title: "A Night at the Opera", includeTracks: false, includeMetadata: false));
+
+ TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{firstTrackId:N}.flac", title: "Bohemian Rhapsody", includeMetadata: false);
+ firstTrack.Genres.Add(ResolveGenre(rockGenre));
+ firstTrack.Genres.Add(ResolveGenre(favouriteGenre));
+ dbContext.Tracks.Add(firstTrack);
+
+ TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, albumId: albumId, libraryId: musicLibraryId, path: $"/music/{secondTrackId:N}.flac", title: "Love of My Life", includeMetadata: false);
+ secondTrack.Genres.Add(ResolveGenre(rockGenre));
+ dbContext.Tracks.Add(secondTrack);
+
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: bookLibraryId, path: $"/books/{bookId:N}.epub", title: "The Fellowship of the Ring", includeMetadata: false);
+ book.Genres.Add(ResolveGenre(favouriteGenre));
+ book.Genres.Add(ResolveGenre(bookClubGenre));
+ dbContext.Books.Add(book);
+
+ BookEntity uncountedBook = _bookEntityFixture.Create(id: uncountedBookId, libraryId: bookLibraryId, path: $"/books/{uncountedBookId:N}.epub", title: "Uncounted Book", includeMetadata: false);
+ uncountedBook.Genres.Add(ResolveGenre(ignoredGenre));
+ dbContext.Books.Add(uncountedBook);
+
+ await dbContext.SaveChangesAsync();
+
+ await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, firstTrackId, ConsumptionStatus.Completed, s_trackCompletedStartedOnUtc, 60_000, 0);
+ await SeedRecordAsync(userId, musicLibraryId, MediaKind.MusicTrack, secondTrackId, ConsumptionStatus.Stopped, s_trackStoppedStartedOnUtc, 30_000, 0);
+ await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, bookId, ConsumptionStatus.Completed, s_bookCompletedStartedOnUtc, 300_000, 10);
+ await SeedRecordAsync(userId, bookLibraryId, MediaKind.Book, uncountedBookId, ConsumptionStatus.Stopped, s_uncountedBookStartedOnUtc, 500_000, 3);
+
+ return (musicLibraryId, bookLibraryId, rockGenre, favouriteGenre, bookClubGenre, ignoredGenre);
+ }
+
+ ///
+ /// Seeds a consumption record of a media item for .
+ ///
+ /// The Id of the user that owns the record.
+ /// The Id of the library that contains the media item.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The state of the session.
+ /// The date and time when the session started.
+ /// The active duration consumed by the session, in milliseconds.
+ /// The number of consecutive pages read in the session.
+ /// The Id of the seeded record.
+ private async Task SeedRecordAsync(
+ Guid userId,
+ Guid libraryId,
+ MediaKind mediaKind,
+ Guid mediaItemId,
+ ConsumptionStatus status,
+ DateTime startedOnUtc,
+ long consumedDurationMilliseconds,
+ int consecutivePagesRead)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid recordId = Guid.NewGuid();
+ MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
+ id: recordId,
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: mediaKind,
+ mediaItemId: mediaItemId,
+ status: status,
+ startedOnUtc: startedOnUtc,
+ lastActivityOnUtc: startedOnUtc.AddMinutes(1),
+ endedOnUtc: status == ConsumptionStatus.InProgress ? null : startedOnUtc.AddMinutes(2),
+ consumedDurationMilliseconds: consumedDurationMilliseconds,
+ lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
+ lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
+ lastProgressFraction: 0,
+ consecutivePagesRead: consecutivePagesRead);
+ dbContext.MediaConsumptionRecords.Add(record);
+ await dbContext.SaveChangesAsync();
+ return recordId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Deserializes the body of to .
+ ///
+ /// The type to deserialize the body to.
+ /// The HTTP response to read.
+ /// The deserialized body.
+ private async Task DeserializeAsync(HttpResponseMessage response)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+ return JsonSerializer.Deserialize(content, _jsonOptions);
+ }
+
+ ///
+ /// Asserts that the response carries the cache headers of a private, authorization varying resource.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertCacheHeaders(HttpResponseMessage response)
+ {
+ Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues));
+ string cacheControl = string.Join(", ", cacheControlValues!);
+ Assert.Contains("private", cacheControl);
+ Assert.Contains("no-store", cacheControl);
+ Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues));
+ Assert.Contains("Authorization", varyValues!);
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, 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.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
+ string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
+ Assert.Equal(expectedValidationErrors, actualValidationErrors);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, 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());
+ }
+
+ ///
+ /// Removes every user created by the test, together with the libraries it owns.
+ ///
+ public async Task DisposeAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ foreach (string username in _seededUsernames)
+ {
+ UserEntity? user = dbContext.Users
+ .Include(candidate => candidate.Libraries)
+ .FirstOrDefault(candidate => candidate.Username == username);
+ if (user is null)
+ continue;
+ dbContext.Libraries.RemoveRange(user.Libraries);
+ dbContext.Users.Remove(user);
+ }
+ await dbContext.SaveChangesAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointTests.cs
new file mode 100644
index 00000000..0dd6ae0a
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Api.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointTests.cs
@@ -0,0 +1,485 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+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.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+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.Library.Statistics.GetGenreConsumption;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserGenreConsumptionEndpointTests : IClassFixture, IAsyncLifetime
+{
+ private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
+
+ 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 BookEntityFixture _bookEntityFixture = new();
+ private readonly GenreEntityFixture _genreEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetUserGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
+ {
+ _client = apiFactory.CreateClient();
+ _apiFactory = apiFactory;
+ }
+
+ ///
+ /// Initializes authenticated API client.
+ ///
+ public async Task InitializeAsync()
+ {
+ _client = await _apiFactory.CreateAuthenticatedClientAsync();
+ _seededUsernames.Add(_apiFactory.TestUsername!);
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenCurrentUserNamesTheirOwnId_ShouldReturnTheirGenreStatistics()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ Guid libraryId = await SeedLibraryAsync(userId, LibraryType.Music, "Music Library");
+ string suffix = Guid.NewGuid().ToString("N")[..8];
+ string firstGenre = $"First-{suffix}";
+ string secondGenre = $"Second-{suffix}";
+ Guid trackId = await SeedTrackAsync(libraryId, "Bohemian Rhapsody", "A Night at the Opera", "Queen", [firstGenre, secondGenre]);
+ await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, trackId, 60_000, 0);
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync($"/api/v1/users/{userId}/consumption-statistics/genres");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertCacheHeaders(response);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ Assert.Equal(2, genres!.Count);
+ Assert.Equal(
+ new[] { firstGenre.ToLowerInvariant(), secondGenre.ToLowerInvariant() },
+ genres.Select(genre => genre.Name).ToArray());
+ Assert.All(genres, genre => Assert.Equal(1, genre.ConsumedItemCount));
+ Assert.All(genres, genre => Assert.Equal(60d, genre.ConsumedDurationInSeconds, 3));
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndLeakNoData()
+ {
+ // Arrange
+ Guid otherUserId = await SeedUserAsync();
+ Guid otherLibraryId = await SeedLibraryAsync(otherUserId, LibraryType.Music, "Other Library");
+ string secretGenre = $"Secret-{Guid.NewGuid().ToString("N")[..8]}";
+ Guid otherTrackId = await SeedTrackAsync(otherLibraryId, "Secret Track", "Secret Album", "Secret Artist", [secretGenre]);
+ await SeedRecordAsync(otherUserId, otherLibraryId, MediaKind.MusicTrack, otherTrackId, 60_000, 0);
+ string url = $"/api/v1/users/{otherUserId}/consumption-statistics/genres";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertForbiddenAsync(response, url);
+ AssertCacheHeaders(response);
+ string content = await response.Content.ReadAsStringAsync();
+ Assert.DoesNotContain(secretGenre, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Secret Track", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenAdminNamesAnotherUser_ShouldReturnThatUsersGenreStatistics()
+ {
+ // Arrange
+ _ = GetCurrentUserId();
+ Guid targetUserId = await SeedUserAsync();
+ Guid targetLibraryId = await SeedLibraryAsync(targetUserId, LibraryType.EBook, "Target Book Library");
+ string targetGenre = $"Target-{Guid.NewGuid().ToString("N")[..8]}";
+ Guid targetBookId = await SeedBookAsync(targetLibraryId, "Target Book", [targetGenre]);
+ await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.Book, targetBookId, 300_000, 10);
+ HttpClient adminClient = await _apiFactory.CreateAuthenticatedAdminClientAsync();
+ _seededUsernames.Add(_apiFactory.TestUsername!);
+
+ try
+ {
+ // Act
+ HttpResponseMessage response = await adminClient.GetAsync($"/api/v1/users/{targetUserId}/consumption-statistics/genres");
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ List? genres = await DeserializeAsync>(response);
+ Assert.NotNull(genres);
+ GenreConsumptionResponse genre = Assert.Single(genres!);
+ Assert.Equal(targetGenre.ToLowerInvariant(), genre.Name);
+ Assert.Equal(1, genre.ConsumedItemCount);
+ Assert.Equal(300d, genre.ConsumedDurationInSeconds, 3);
+ }
+ finally
+ {
+ adminClient.Dispose();
+ }
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenUserIdIsNotAValidGuid_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ string url = "/api/v1/users/not-a-guid/consumption-statistics/genres";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, url, "TargetUserIdIsInvalid");
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenUnauthenticated_ShouldReturnUnauthorized()
+ {
+ // Arrange
+ HttpClient unauthenticatedClient = _apiFactory.CreateClient();
+ string url = $"/api/v1/users/{Guid.NewGuid()}/consumption-statistics/genres";
+
+ // Act
+ HttpResponseMessage response = await unauthenticatedClient.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenLibraryIdIsNotAValidGuid_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
+ string url = $"{path}?libraryId=not-a-guid";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "LibraryIdCannotBeEmpty");
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenMediaKindIsNone_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
+ string url = $"{path}?mediaKind={nameof(MediaKind.None)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "UnsupportedMediaKind");
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenDateRangeIsInverted_ShouldReturnValidationProblem()
+ {
+ // Arrange
+ Guid userId = GetCurrentUserId();
+ string path = $"/api/v1/users/{userId}/consumption-statistics/genres";
+ string fromUtc = Uri.EscapeDataString("2026-10-31T00:00:00");
+ string toUtc = Uri.EscapeDataString("2026-10-01T00:00:00");
+ string url = $"{path}?fromUtc={fromUtc}&toUtc={toUtc}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnprocessableEntityAsync(response, path, "ConsumptionDateRangeIsInvalid");
+ }
+
+ ///
+ /// Seeds a media library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The type of the library.
+ /// The title of the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a genre-bearing track of , together with its artist and album.
+ ///
+ /// The Id of the library that owns the track.
+ /// The title of the track.
+ /// The title of the album that contains the track.
+ /// The name of the artist of the album.
+ /// The genre names carried by the track.
+ /// The Id of the seeded track.
+ private async Task SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList genreNames)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid artistId = Guid.NewGuid();
+ Guid albumId = Guid.NewGuid();
+ Guid trackId = Guid.NewGuid();
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: artistName, includeAlbums: false, includeContributors: false, includeMetadata: false));
+ dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: albumTitle, includeTracks: false, includeMetadata: false));
+ TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: trackTitle, includeMetadata: false);
+ foreach (string genreName in genreNames)
+ track.Genres.Add(_genreEntityFixture.Create(name: genreName));
+ dbContext.Tracks.Add(track);
+ await dbContext.SaveChangesAsync();
+ return trackId;
+ }
+
+ ///
+ /// Seeds a genre-bearing book of .
+ ///
+ /// The Id of the library that owns the book.
+ /// The title of the book.
+ /// The genre names carried by the book.
+ /// The Id of the seeded book.
+ private async Task SeedBookAsync(Guid libraryId, string bookTitle, IReadOnlyList genreNames)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid bookId = Guid.NewGuid();
+ BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, path: $"/books/{bookId:N}.epub", title: bookTitle, includeMetadata: false);
+ foreach (string genreName in genreNames)
+ book.Genres.Add(_genreEntityFixture.Create(name: genreName));
+ dbContext.Books.Add(book);
+ await dbContext.SaveChangesAsync();
+ return bookId;
+ }
+
+ ///
+ /// Seeds a completed consumption record of a media item for .
+ ///
+ /// The Id of the user that owns the record.
+ /// The Id of the library that contains the media item.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The active duration consumed by the session, in milliseconds.
+ /// The number of consecutive pages read in the session.
+ /// The Id of the seeded record.
+ private async Task SeedRecordAsync(
+ Guid userId,
+ Guid libraryId,
+ MediaKind mediaKind,
+ Guid mediaItemId,
+ long consumedDurationMilliseconds,
+ int consecutivePagesRead)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid recordId = Guid.NewGuid();
+ MediaConsumptionRecordEntity record = _mediaConsumptionRecordEntityFixture.Create(
+ id: recordId,
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: mediaKind,
+ mediaItemId: mediaItemId,
+ status: ConsumptionStatus.Completed,
+ startedOnUtc: s_startedOnUtc,
+ lastActivityOnUtc: s_startedOnUtc.AddMinutes(1),
+ endedOnUtc: s_startedOnUtc.AddMinutes(2),
+ consumedDurationMilliseconds: consumedDurationMilliseconds,
+ lastPositionKind: mediaKind == MediaKind.Book ? MediaPositionKind.Location : MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: mediaKind == MediaKind.Book ? null : 0,
+ lastPositionLocation: mediaKind == MediaKind.Book ? "chapter-1" : null,
+ lastProgressFraction: 0,
+ consecutivePagesRead: consecutivePagesRead);
+ dbContext.MediaConsumptionRecords.Add(record);
+ await dbContext.SaveChangesAsync();
+ return recordId;
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id.
+ ///
+ /// The Id of the seeded user.
+ private async Task SeedUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return userId;
+ }
+
+ ///
+ /// Gets the Id of the currently authenticated test user.
+ ///
+ /// The Id of the authenticated test user.
+ private Guid GetCurrentUserId()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
+ return user.Id;
+ }
+
+ ///
+ /// Deserializes the body of to .
+ ///
+ /// The type to deserialize the body to.
+ /// The HTTP response to read.
+ /// The deserialized body.
+ private async Task DeserializeAsync(HttpResponseMessage response)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+ return JsonSerializer.Deserialize(content, _jsonOptions);
+ }
+
+ ///
+ /// Asserts that the response carries the cache headers of a private, authorization varying resource.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertCacheHeaders(HttpResponseMessage response)
+ {
+ Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable? cacheControlValues));
+ string cacheControl = string.Join(", ", cacheControlValues!);
+ Assert.Contains("private", cacheControl);
+ Assert.Contains("no-store", cacheControl);
+ Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable? varyValues));
+ Assert.Contains("Authorization", varyValues!);
+ }
+
+ ///
+ /// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The validation error codes that must all be present.
+ private async Task AssertUnprocessableEntityAsync(HttpResponseMessage response, string expectedInstance, params string[] expectedErrorCodes)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.UnprocessableEntity, 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.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors.Keys);
+ string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
+ string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
+ Assert.Equal(expectedValidationErrors, actualValidationErrors);
+ }
+
+ ///
+ /// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.NotNull(problemDetails["traceId"].GetString());
+ Assert.NotEmpty(problemDetails["traceId"].GetString()!);
+ }
+
+ ///
+ /// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal((int)HttpStatusCode.Unauthorized, 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());
+ }
+
+ ///
+ /// Removes every user created by the test, together with the libraries it owns.
+ ///
+ public async Task DisposeAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ foreach (string username in _seededUsernames)
+ {
+ UserEntity? user = dbContext.Users
+ .Include(candidate => candidate.Libraries)
+ .FirstOrDefault(candidate => candidate.Username == username);
+ if (user is null)
+ continue;
+ dbContext.Libraries.RemoveRange(user.Libraries);
+ dbContext.Users.Remove(user);
+ }
+ await dbContext.SaveChangesAsync();
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs
new file mode 100644
index 00000000..e2feb2b0
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointTests.cs
@@ -0,0 +1,154 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.Net.Http.Headers;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ClearConsumptionHistoryEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = Guid.NewGuid().ToString();
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public ClearConsumptionHistoryEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task ClearConsumptionHistory_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldDeleteCurrentUserHistoryAndReturnSuccess()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(includeUserId: false);
+ string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+ deleteRequest.Headers.Add("RequestVerificationToken", 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([expectedUpstreamPath], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ }
+
+ [Fact]
+ public async Task ClearConsumptionHistory_WhenUserIdIsProvided_ShouldDeleteSelectedUserHistory()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
+ string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+ deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal([$"users/{s_userId}/consumption-history"], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task ClearConsumptionHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route that clears the consumption history described by .
+ ///
+ /// The request describing the history to clear.
+ /// The path of the Web route, including the optional query string.
+ private static string BuildRequestPath(ClearConsumptionHistoryRequest request)
+ {
+ return string.IsNullOrWhiteSpace(request.UserId)
+ ? "/en-us/library/statistics/api-clear-consumption-history"
+ : $"/en-us/library/statistics/api-clear-consumption-history?userId={Uri.EscapeDataString(request.UserId)}";
+ }
+
+ ///
+ /// Builds the upstream API path that is expected for .
+ ///
+ /// The request describing the history to clear.
+ /// The upstream API path, including the optional escaped user identifier.
+ private static string BuildExpectedUpstreamPath(ClearConsumptionHistoryRequest request)
+ {
+ return string.IsNullOrWhiteSpace(request.UserId)
+ ? "users/me/consumption-history"
+ : $"users/{Uri.EscapeDataString(request.UserId)}/consumption-history";
+ }
+
+ ///
+ /// Builds a DELETE request for that carries the JSON content type required by the antiforgery middleware.
+ ///
+ /// The path of the Web route to call.
+ /// The configured DELETE request.
+ private static HttpRequestMessage CreateDeleteRequest(string path)
+ {
+ HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
+ {
+ 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"));
+ return deleteRequest;
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs
new file mode 100644
index 00000000..85667c4c
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointTests.cs
@@ -0,0 +1,164 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.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.Library.Statistics.ClearResumePoints;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class ClearResumePointsEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = Guid.NewGuid().ToString();
+ private static readonly string s_libraryId = Guid.NewGuid().ToString();
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public ClearResumePointsEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task ClearResumePoints_WhenCalledForCurrentUser_ShouldDeleteCurrentUserResumePointsAndReturnSuccess()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(includeUserId: false, includeLibraryId: false);
+ string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+ deleteRequest.Headers.Add("RequestVerificationToken", 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(["users/me/media-resume-points"], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ }
+
+ [Fact]
+ public async Task ClearResumePoints_WhenUserAndLibraryAreProvided_ShouldDeleteSelectedUserResumePointsWithLibraryFilter()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId, libraryId: s_libraryId);
+ string expectedUpstreamPath = BuildExpectedUpstreamPath(request);
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+ deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal([$"users/{s_userId}/media-resume-points?libraryId={s_libraryId}"], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task ClearResumePoints_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId, libraryId: s_libraryId);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route that clears the resume points described by .
+ ///
+ /// The request describing the resume points to clear.
+ /// The path of the Web route, including the optional query string.
+ private static string BuildRequestPath(ClearResumePointsRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-clear-resume-points"
+ : $"/en-us/library/statistics/api-clear-resume-points?{string.Join("&", parameters)}";
+ }
+
+ ///
+ /// Builds the upstream API path that is expected for .
+ ///
+ /// The request describing the resume points to clear.
+ /// The upstream API path, including the optional escaped identifiers.
+ private static string BuildExpectedUpstreamPath(ClearResumePointsRequest request)
+ {
+ string path = string.IsNullOrWhiteSpace(request.UserId)
+ ? "users/me/media-resume-points"
+ : $"users/{Uri.EscapeDataString(request.UserId)}/media-resume-points";
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ path += $"?libraryId={Uri.EscapeDataString(request.LibraryId)}";
+ return path;
+ }
+
+ ///
+ /// Builds a DELETE request for that carries the JSON content type required by the antiforgery middleware.
+ ///
+ /// The path of the Web route to call.
+ /// The configured DELETE request.
+ private static HttpRequestMessage CreateDeleteRequest(string path)
+ {
+ HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
+ {
+ 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"));
+ return deleteRequest;
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs
new file mode 100644
index 00000000..364ffbb2
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs
@@ -0,0 +1,162 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.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.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = Guid.NewGuid().ToString();
+ private static readonly Guid s_mediaItemId = Guid.Parse("11111111-1111-1111-1111-111111111111");
+ private static readonly Guid s_libraryId = Guid.Parse("22222222-2222-2222-2222-222222222222");
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public DeleteConsumptionItemHistoryEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenCalledForCurrentUser_ShouldDeleteCurrentUserItemHistoryAndReturnSuccess()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
+ includeUserId: false,
+ mediaKind: MediaKind.Movie,
+ mediaItemId: s_mediaItemId,
+ libraryId: s_libraryId);
+ string expectedUpstreamPath = $"users/me/consumption-history/media-items/Movie/{s_mediaItemId}/{s_libraryId}";
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+ deleteRequest.Headers.Add("RequestVerificationToken", 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([expectedUpstreamPath], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenUserIsProvided_ShouldDeleteSelectedUserItemHistory()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
+ userId: s_userId,
+ mediaKind: MediaKind.Book,
+ mediaItemId: s_mediaItemId,
+ libraryId: s_libraryId);
+ string expectedUpstreamPath = $"users/{s_userId}/consumption-history/media-items/Book/{s_mediaItemId}/{s_libraryId}";
+ _apiFactory.ApiClientStub.RegisterDeleteSuccess(expectedUpstreamPath);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+ deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ Assert.Equal([expectedUpstreamPath], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequest()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
+ userId: s_userId,
+ mediaKind: MediaKind.Movie,
+ mediaItemId: s_mediaItemId,
+ libraryId: s_libraryId);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+ HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
+ Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route that deletes the item history described by .
+ ///
+ /// The request describing the item history to delete.
+ /// The path of the Web route, including the query string.
+ private static string BuildRequestPath(DeleteConsumptionItemHistoryRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.ToString())}");
+ parameters.Add($"mediaItemId={request.MediaItemId}");
+ parameters.Add($"libraryId={request.LibraryId}");
+ return $"/en-us/library/statistics/api-delete-consumption-item-history?{string.Join("&", parameters)}";
+ }
+
+ ///
+ /// Builds a DELETE request for that carries the JSON content type required by the antiforgery middleware.
+ ///
+ /// The path of the Web route to call.
+ /// The configured DELETE request.
+ private static HttpRequestMessage CreateDeleteRequest(string path)
+ {
+ HttpRequestMessage deleteRequest = new(HttpMethod.Delete, path)
+ {
+ 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"));
+ return deleteRequest;
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs
new file mode 100644
index 00000000..559c8f9f
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointTests.cs
@@ -0,0 +1,163 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
+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.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
+ private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
+ private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new();
+ private readonly AllUsersConsumptionStatisticsDtoFixture _allUsersConsumptionStatisticsDtoFixture = new();
+ private readonly ConsumptionTotalsDtoFixture _consumptionTotalsDtoFixture = new();
+ private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetAllUsersConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdminWithAllFilters_ShouldReturnStatisticsJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
+ libraryId: s_libraryId,
+ mediaKind: MediaKind.Movie,
+ fromUtc: s_fromUtc,
+ toUtc: s_toUtc);
+ const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
+ ConsumptionTotalsDto total = _consumptionTotalsDtoFixture.Create(countedSessionCount: 42, includeMediaKindSummaries: false);
+ ConsumptionSummaryDto userSummary = _consumptionSummaryDtoFixture.Create(countedSessionCount: 7, includeMediaKindSummaries: false);
+ AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create(total: total, users: [userSummary]);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ 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(42, data.GetProperty("total").GetProperty("countedSessionCount").GetInt32());
+ Assert.Equal(1, data.GetProperty("users").GetArrayLength());
+ Assert.Equal(7, data.GetProperty("users")[0].GetProperty("countedSessionCount").GetInt32());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdminWithoutFilters_ShouldRequestEveryUserAndHandleEmptyUsers()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
+ includeLibraryId: false,
+ includeMediaKind: false,
+ includeFromUtc: false,
+ includeToUtc: false);
+ const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics";
+ AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create(includeUsers: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.Equal(0, json.RootElement.GetProperty("data").GetProperty("users").GetArrayLength());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task GetAllUsersConsumptionStatistics_WhenCalledByNonAdminUser_ShouldRedirectToAccessDeniedAndNotCallApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create();
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("access-denied", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route for .
+ ///
+ /// The request whose filters are forwarded.
+ /// The path of the Web route, including the query string built from the request filters.
+ private static string BuildRequestPath(GetAllUsersConsumptionStatisticsRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-get-all-users-statistics"
+ : $"/en-us/library/statistics/api-get-all-users-statistics?{string.Join("&", parameters)}";
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs
new file mode 100644
index 00000000..5c481d37
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointTests.cs
@@ -0,0 +1,140 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetConsumptionStatisticsEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
+ private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
+ private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
+ private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new();
+ private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
+ private readonly MediaKindConsumptionSummaryDtoFixture _mediaKindConsumptionSummaryDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetConsumptionStatistics_WhenCalledWithoutFilters_ShouldRequestCurrentUserStatistics()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-statistics";
+ GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
+ includeUserId: false,
+ includeLibraryId: false,
+ includeMediaKind: false,
+ includeFromUtc: false,
+ includeToUtc: false);
+ ConsumptionSummaryDto expectedStatistics = _consumptionSummaryDtoFixture.Create(
+ countedSessionCount: 12,
+ mediaKindSummaries: [_mediaKindConsumptionSummaryDtoFixture.Create(mediaKind: MediaKind.Movie)]);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ 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(12, data.GetProperty("countedSessionCount").GetInt32());
+ Assert.Equal(1, data.GetProperty("mediaKindSummaries").GetArrayLength());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task GetConsumptionStatistics_WhenUserIdAndAllFiltersAreProvided_ShouldRequestUserStatisticsWithEscapedValues()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-statistics?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
+ GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
+ userId: s_userId,
+ libraryId: s_libraryId,
+ mediaKind: MediaKind.Movie,
+ fromUtc: s_fromUtc,
+ toUtc: s_toUtc);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _consumptionSummaryDtoFixture.Create(includeMediaKindSummaries: false));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route for .
+ ///
+ /// The request whose filters are forwarded.
+ /// The path of the Web route, including the query string built from the request filters.
+ private static string BuildRequestPath(GetConsumptionStatisticsRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-get-statistics"
+ : $"/en-us/library/statistics/api-get-statistics?{string.Join("&", parameters)}";
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs
new file mode 100644
index 00000000..4bd30d8c
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs
@@ -0,0 +1,140 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
+ private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
+ private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
+ private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
+ private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetGenreConsumptionEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenUserIdAndAllFiltersAreProvided_ShouldReturnGenreConsumptionJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-statistics/genres?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
+ GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
+ userId: s_userId,
+ libraryId: s_libraryId,
+ mediaKind: MediaKind.Movie,
+ fromUtc: s_fromUtc,
+ toUtc: s_toUtc);
+ GenreConsumptionDto[] expectedGenres = [_genreConsumptionDtoFixture.Create(name: "drama", consumedItemCount: 3)];
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedGenres);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ 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(1, data.GetArrayLength());
+ Assert.Equal("drama", data[0].GetProperty("name").GetString());
+ Assert.Equal(3, data[0].GetProperty("consumedItemCount").GetInt32());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenCalledWithoutFilters_ShouldRequestCurrentUserGenresAndHandleEmptyResult()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-statistics/genres";
+ GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
+ includeUserId: false,
+ includeLibraryId: false,
+ includeMediaKind: false,
+ includeFromUtc: false,
+ includeToUtc: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route for .
+ ///
+ /// The request whose filters are forwarded.
+ /// The path of the Web route, including the query string built from the request filters.
+ private static string BuildRequestPath(GetGenreConsumptionRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-get-genre-consumption"
+ : $"/en-us/library/statistics/api-get-genre-consumption?{string.Join("&", parameters)}";
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointTests.cs
new file mode 100644
index 00000000..cd03b172
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointTests.cs
@@ -0,0 +1,99 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Libraries;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Libraries;
+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.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetLibraries;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibrariesEndpointTests : IClassFixture, IDisposable
+{
+ private const string WEB_ROUTE = "/en-us/library/statistics/api-get-libraries";
+ private const string EXPECTED_UPSTREAM_PATH = "libraries/enabled";
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly LibraryDtoFixture _libraryDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetLibrariesEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnEnabledLibrariesJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ LibraryDto[] expectedLibraries =
+ [
+ _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Books", libraryType: "Book", isEnabled: true),
+ _libraryDtoFixture.Create(id: Guid.NewGuid(), title: "Movies", libraryType: "Video", isEnabled: true)
+ ];
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedLibraries);
+ 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);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(2, data.GetArrayLength());
+ Assert.Equal("Books", data[0].GetProperty("title").GetString());
+ Assert.Equal("Movies", data[1].GetProperty("title").GetString());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetLibraries_WhenNoLibrariesExist_ShouldHandleEmptyResult()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs
new file mode 100644
index 00000000..47c150b5
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointTests.cs
@@ -0,0 +1,165 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetMostConsumedEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
+ private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
+ private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
+ private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
+ private static readonly Guid s_mediaItemId = Guid.Parse("33333333-3333-3333-3333-333333333333");
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new();
+ private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
+ private readonly PaginatedDtoFixture _paginatedDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetMostConsumedEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetMostConsumed_WhenUserIdFiltersAndPagingAreProvided_ShouldReturnPageJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-history/most-consumed?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000¤tPage=2&perPage=5";
+ GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
+ userId: s_userId,
+ libraryId: s_libraryId,
+ mediaKind: MediaKind.Movie,
+ fromUtc: s_fromUtc,
+ toUtc: s_toUtc,
+ currentPage: 2,
+ perPage: 5);
+ PaginatedDto expectedPage = _paginatedDtoFixture.Create(
+ data:
+ [
+ _consumedItemDtoFixture.Create(mediaItemId: s_mediaItemId, mediaKind: MediaKind.Movie),
+ _consumedItemDtoFixture.Create(mediaKind: MediaKind.Movie)
+ ],
+ currentPage: 2,
+ perPage: 5,
+ count: 12,
+ numberOfPages: 3);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedPage);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ 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(2, data.GetProperty("data").GetArrayLength());
+ Assert.Equal(2, data.GetProperty("currentPage").GetInt32());
+ Assert.Equal(5, data.GetProperty("perPage").GetInt32());
+ Assert.Equal(s_mediaItemId, data.GetProperty("data")[0].GetProperty("mediaItemId").GetGuid());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetMostConsumed_WhenNoFiltersOrPagingAreProvided_ShouldRequestCurrentUserWithDefaultPaging()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-history/most-consumed?currentPage=1&perPage=10";
+ GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
+ includeUserId: false,
+ includeLibraryId: false,
+ includeMediaKind: false,
+ includeFromUtc: false,
+ includeToUtc: false,
+ includeCurrentPage: false,
+ includePerPage: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _paginatedDtoFixture.Create(data: [], currentPage: 1, perPage: 10));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(0, data.GetProperty("data").GetArrayLength());
+ Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
+ Assert.Equal(10, data.GetProperty("perPage").GetInt32());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route for .
+ ///
+ /// The request whose filters and paging are forwarded.
+ /// The path of the Web route, including the query string built from the request values.
+ private static string BuildRequestPath(GetMostConsumedRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.CurrentPage is not null)
+ parameters.Add($"currentPage={request.CurrentPage.Value.ToString(CultureInfo.InvariantCulture)}");
+ if (request.PerPage is not null)
+ parameters.Add($"perPage={request.PerPage.Value.ToString(CultureInfo.InvariantCulture)}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-get-most-consumed"
+ : $"/en-us/library/statistics/api-get-most-consumed?{string.Join("&", parameters)}";
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs
new file mode 100644
index 00000000..8ed98202
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointTests.cs
@@ -0,0 +1,165 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.Common;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetRecentlyConsumedEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
+ private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
+ private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
+ private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
+ private static readonly Guid s_mediaItemId = Guid.Parse("33333333-3333-3333-3333-333333333333");
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new();
+ private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
+ private readonly PaginatedDtoFixture _paginatedDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetRecentlyConsumedEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetRecentlyConsumed_WhenUserIdFiltersAndPagingAreProvided_ShouldReturnPageJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-history/recently-consumed?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000¤tPage=2&perPage=5";
+ GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
+ userId: s_userId,
+ libraryId: s_libraryId,
+ mediaKind: MediaKind.Movie,
+ fromUtc: s_fromUtc,
+ toUtc: s_toUtc,
+ currentPage: 2,
+ perPage: 5);
+ PaginatedDto expectedPage = _paginatedDtoFixture.Create(
+ data:
+ [
+ _consumedItemDtoFixture.Create(mediaItemId: s_mediaItemId, mediaKind: MediaKind.Movie),
+ _consumedItemDtoFixture.Create(mediaKind: MediaKind.Movie)
+ ],
+ currentPage: 2,
+ perPage: 5,
+ count: 12,
+ numberOfPages: 3);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedPage);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ 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(2, data.GetProperty("data").GetArrayLength());
+ Assert.Equal(2, data.GetProperty("currentPage").GetInt32());
+ Assert.Equal(5, data.GetProperty("perPage").GetInt32());
+ Assert.Equal(s_mediaItemId, data.GetProperty("data")[0].GetProperty("mediaItemId").GetGuid());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetRecentlyConsumed_WhenNoFiltersOrPagingAreProvided_ShouldRequestCurrentUserWithDefaultPaging()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-history/recently-consumed?currentPage=1&perPage=10";
+ GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
+ includeUserId: false,
+ includeLibraryId: false,
+ includeMediaKind: false,
+ includeFromUtc: false,
+ includeToUtc: false,
+ includeCurrentPage: false,
+ includePerPage: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _paginatedDtoFixture.Create(data: [], currentPage: 1, perPage: 10));
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(0, data.GetProperty("data").GetArrayLength());
+ Assert.Equal(1, data.GetProperty("currentPage").GetInt32());
+ Assert.Equal(10, data.GetProperty("perPage").GetInt32());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route for .
+ ///
+ /// The request whose filters and paging are forwarded.
+ /// The path of the Web route, including the query string built from the request values.
+ private static string BuildRequestPath(GetRecentlyConsumedRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.CurrentPage is not null)
+ parameters.Add($"currentPage={request.CurrentPage.Value.ToString(CultureInfo.InvariantCulture)}");
+ if (request.PerPage is not null)
+ parameters.Add($"perPage={request.PerPage.Value.ToString(CultureInfo.InvariantCulture)}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-get-recently-consumed"
+ : $"/en-us/library/statistics/api-get-recently-consumed?{string.Join("&", parameters)}";
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs
new file mode 100644
index 00000000..ee394dd0
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointTests.cs
@@ -0,0 +1,140 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetTagConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Fixtures.Common.Requests.Library.Statistics;
+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.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetTagConsumptionEndpointTests : IClassFixture, IDisposable
+{
+ private static readonly string s_userId = "11111111-1111-1111-1111-111111111111";
+ private static readonly string s_libraryId = "22222222-2222-2222-2222-222222222222";
+ private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7);
+ private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10);
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new();
+ private readonly TagConsumptionDtoFixture _tagConsumptionDtoFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetTagConsumptionEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetTagConsumption_WhenUserIdAndAllFiltersAreProvided_ShouldReturnTagConsumptionJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/11111111-1111-1111-1111-111111111111/consumption-statistics/tags?libraryId=22222222-2222-2222-2222-222222222222&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000&toUtc=2025-06-07T08%3A09%3A10.0000000";
+ GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
+ userId: s_userId,
+ libraryId: s_libraryId,
+ mediaKind: MediaKind.Movie,
+ fromUtc: s_fromUtc,
+ toUtc: s_toUtc);
+ TagConsumptionDto[] expectedTags = [_tagConsumptionDtoFixture.Create(name: "favourite", consumedItemCount: 4)];
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedTags);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ 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(1, data.GetArrayLength());
+ Assert.Equal("favourite", data[0].GetProperty("name").GetString());
+ Assert.Equal(4, data[0].GetProperty("consumedItemCount").GetInt32());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetTagConsumption_WhenCalledWithoutFilters_ShouldRequestCurrentUserTagsAndHandleEmptyResult()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ const string EXPECTED_UPSTREAM_PATH = "users/me/consumption-statistics/tags";
+ GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
+ includeUserId: false,
+ includeLibraryId: false,
+ includeMediaKind: false,
+ includeFromUtc: false,
+ includeToUtc: false);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(BuildRequestPath(request));
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+
+ ///
+ /// Builds the path of the Web route for .
+ ///
+ /// The request whose filters are forwarded.
+ /// The path of the Web route, including the query string built from the request filters.
+ private static string BuildRequestPath(GetTagConsumptionRequest request)
+ {
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.UserId))
+ parameters.Add($"userId={Uri.EscapeDataString(request.UserId)}");
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ return parameters.Count == 0
+ ? "/en-us/library/statistics/api-get-tag-consumption"
+ : $"/en-us/library/statistics/api-get-tag-consumption?{string.Join("&", parameters)}";
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointTests.cs
new file mode 100644
index 00000000..423aca66
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointTests.cs
@@ -0,0 +1,122 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.DTO.UsersManagement;
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers;
+using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
+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.Text.Json;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Statistics.GetUsers;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetUsersEndpointTests : IClassFixture, IDisposable
+{
+ private const string WEB_ROUTE = "/en-us/library/statistics/api-get-users";
+ private const string EXPECTED_UPSTREAM_PATH = "auth/users";
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly UserDtoFixture _userDtoFixture = new();
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public GetUsersEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task GetUsers_WhenCalledByAdminUser_ShouldReturnUsersJson()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ UserDto[] expectedUsers =
+ [
+ _userDtoFixture.Create(id: Guid.NewGuid(), username: "alice"),
+ _userDtoFixture.Create(id: Guid.NewGuid(), username: "bob")
+ ];
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedUsers);
+ 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);
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.True(json.RootElement.GetProperty("success").GetBoolean());
+ JsonElement data = json.RootElement.GetProperty("data");
+ Assert.Equal(2, data.GetArrayLength());
+ Assert.Equal("alice", data[0].GetProperty("username").GetString());
+ Assert.Equal("bob", data[1].GetProperty("username").GetString());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.True(response.Headers.CacheControl?.Private);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetUsers_WhenNoUsersExist_ShouldHandleEmptyResult()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ _apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, Array.Empty());
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
+ string content = await response.Content.ReadAsStringAsync();
+
+ // Assert
+ response.EnsureSuccessStatusCode();
+ using JsonDocument json = JsonDocument.Parse(content);
+ Assert.Equal(0, json.RootElement.GetProperty("data").GetArrayLength());
+ Assert.Contains(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task GetUsers_WhenCalledByNonAdminUser_ShouldRedirectToAccessDeniedAndNotCallApi()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await webClient.Client.GetAsync(WEB_ROUTE);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Contains("access-denied", response.Headers.Location!.ToString());
+ Assert.DoesNotContain(EXPECTED_UPSTREAM_PATH, _apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+}
diff --git a/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointTests.cs b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointTests.cs
new file mode 100644
index 00000000..88ed5660
--- /dev/null
+++ b/tests/IntegrationTests/Lumina.Presentation.Web.IntegrationTests/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointTests.cs
@@ -0,0 +1,105 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
+using Lumina.Presentation.Web.Fixtures.Common.Responses.Authorization;
+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.Library.Statistics.Index;
+
+///
+/// Contains integration tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class StatisticsIndexViewEndpointTests : IClassFixture, IDisposable
+{
+ private const string WEB_ROUTE = "/en-us/library/statistics";
+
+ private readonly LuminaWebFactory _apiFactory;
+ private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Web application factory.
+ public StatisticsIndexViewEndpointTests(LuminaWebFactory apiFactory)
+ {
+ _apiFactory = apiFactory;
+ }
+
+ [Fact]
+ public async Task StatisticsIndexView_WhenCalledByRegularUser_ShouldRenderStatisticsPageWithoutUserSelector()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "User", permissions: []);
+ 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("statistics-page", content, StringComparison.Ordinal);
+ Assert.Contains("const isAdmin = false;", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("statistics-user-selector", content, StringComparison.Ordinal);
+ Assert.True(response.Headers.CacheControl?.NoStore);
+ Assert.Contains("Cookie", response.Headers.Vary);
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
+ }
+
+ [Fact]
+ public async Task StatisticsIndexView_WhenCalledByAnonymousUser_ShouldRedirectToLogin()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
+
+ // Act
+ HttpResponseMessage response = await client.GetAsync(WEB_ROUTE);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
+ Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
+ Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
+ }
+
+ [Fact]
+ public async Task StatisticsIndexView_WhenCalledByAdminUser_ShouldRenderStatisticsPageWithUserSelector()
+ {
+ // Arrange
+ _apiFactory.ApiClientStub.Reset();
+ _apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
+ 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("statistics-user-selector", content, StringComparison.Ordinal);
+ Assert.Contains("const isAdmin = true;", content, StringComparison.Ordinal);
+ Assert.Contains("api-get-users", content, StringComparison.Ordinal);
+ Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
+ }
+
+ ///
+ /// Releases the resources used by the test class and resets the remote API stub.
+ ///
+ public void Dispose()
+ {
+ _apiFactory.ApiClientStub.Reset();
+ GC.SuppressFinalize(this);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs
new file mode 100644
index 00000000..f2ba166b
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointTests.cs
@@ -0,0 +1,465 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+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.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+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.Net;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture, IDisposable
+{
+ private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
+
+ private static readonly DateTime s_startedOnUtc = new(2026, 5, 1, 9, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 1, 9, 10, 0, DateTimeKind.Utc);
+
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteConsumptionItemHistoryEndpointTests(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 DeleteConsumptionItemHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenOwnItemIsDeleted_ShouldReturnNonCacheableResponseWithoutSensitiveData()
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+ AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
+
+ await AssertRecordsAreDeletedAsync(recordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenAnotherUsersItemIdIsUsed_ShouldSucceedAndPreserveThatUsersRecords()
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid ownLibraryId = await SeedLibraryAsync(userId);
+ Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId, MediaKind.MusicTrack, Guid.NewGuid(), 60_000);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
+ Guid sharedItemId = Guid.NewGuid();
+ Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, sharedItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{sharedItemId}/{otherUserLibraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+ AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
+
+ // Deleting an item that does not belong to the caller succeeds, but it must never remove the other user's rows.
+ await AssertRecordsArePreservedAsync(otherUserRecordId, ownRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndDeleteOnlyTheMatchingRecords()
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid ownLibraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid ownRecordId = await SeedRecordAsync(userId, ownLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
+ Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{ownLibraryId}?userId={otherUserId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+
+ // The route identifier belongs to the caller, so the spoofed query parameter cannot redirect the deletion.
+ await AssertRecordsAreDeletedAsync(ownRecordId);
+ await AssertRecordsArePreservedAsync(otherUserRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteConsumptionItemHistory_WhenCalledTwice_ShouldSucceedAndStayDeleted()
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage firstResponse = await _client.DeleteAsync(url);
+ await AssertRecordsAreDeletedAsync(recordId);
+ HttpResponseMessage secondResponse = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, firstResponse.StatusCode);
+ Assert.Equal(HttpStatusCode.OK, secondResponse.StatusCode);
+ AssertNonCacheable(secondResponse);
+ await AssertRecordsAreDeletedAsync(recordId);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteConsumptionItemHistory_WithInjectionInMediaKind_ShouldRejectWithoutDeletingRows(string maliciousMediaKind)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteConsumptionItemHistory_WithInjectionInMediaItemId_ShouldRejectWithoutDeletingRows(string maliciousMediaItemId)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{Uri.EscapeDataString(maliciousMediaItemId)}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteConsumptionItemHistory_WithInjectionInLibraryId_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"/api/v1/users/me/consumption-history/media-items/{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{Uri.EscapeDataString(maliciousLibraryId)}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ ///
+ /// Creates a test user and authenticates it on .
+ ///
+ /// The HTTP client to authenticate.
+ /// The Id and username of the created user.
+ private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
+ {
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ return (userId, username);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id and username.
+ ///
+ /// The Id and username of the seeded user.
+ private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
+ dbContext.Users.Add(user);
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return (userId, username);
+ }
+
+ ///
+ /// Seeds a media library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a consumption record of a media item for .
+ ///
+ /// The Id of the user that owns the record.
+ /// The Id of the library that contains the media item.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The active duration consumed by the session, in milliseconds.
+ /// The Id of the seeded record.
+ private async Task SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid recordId = Guid.NewGuid();
+ dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
+ id: recordId,
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: mediaKind,
+ mediaItemId: mediaItemId,
+ status: ConsumptionStatus.Stopped,
+ startedOnUtc: s_startedOnUtc,
+ lastActivityOnUtc: s_lastActivityOnUtc,
+ endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
+ consumedDurationMilliseconds: consumedDurationMilliseconds,
+ lastPositionKind: MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: 45_000,
+ lastPositionLocation: null,
+ lastProgressFraction: 0.5,
+ consecutivePagesRead: 0));
+ await dbContext.SaveChangesAsync();
+ return recordId;
+ }
+
+ ///
+ /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ AssertNoSensitiveData(content);
+ }
+
+ ///
+ /// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
+ ///
+ /// The HTTP response to assert on.
+ /// The malicious value that was sent.
+ /// The request path the value was sent in.
+ /// The validation error code expected when the value reaches the validator.
+ private async Task AssertRejectedInjectionAsync(HttpResponseMessage response, string payload, string requestPath, string expectedErrorCode)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+
+ // An unparseable route value must never become a server error, and it must never be reported as a successful request.
+ Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
+ Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
+
+ if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
+ {
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+
+ // The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
+ string escapedPayload = Uri.EscapeDataString(payload);
+ int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
+ string? instance = problemDetails["instance"].GetString();
+ Assert.NotNull(instance);
+ Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
+ Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
+ Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors!.Keys);
+ Assert.Contains(expectedErrorCode, errors["General.Validation"]);
+ AssertNonCacheable(response);
+ }
+ else
+ {
+ // A payload that carries encoded path separators is rejected by routing before it reaches the endpoint. That is still a safe rejection.
+ Assert.Contains("/", payload, StringComparison.Ordinal);
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+
+ AssertNoSensitiveData(content);
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be deleted.
+ private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
+ // has run, instead of assuming that it already has.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ if (storedRecords.Count == 0)
+ return;
+ await Task.Delay(100);
+ }
+ Assert.Empty(storedRecords);
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are still stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be preserved.
+ private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
+ // completion has run, instead of trusting the state observed right after the response.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ await Task.Delay(100);
+ }
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ }
+
+ ///
+ /// Asserts that the response is not storable by any intermediary and varies by the authorization header.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertNonCacheable(HttpResponseMessage response)
+ {
+ Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
+ Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
+ }
+
+ ///
+ /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
+ ///
+ /// The response body to assert on.
+ private static void AssertNoSensitiveData(string content)
+ {
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Removes the test users created by the test.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointTests.cs
new file mode 100644
index 00000000..d28189ad
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointTests.cs
@@ -0,0 +1,540 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+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.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+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.Net;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture, IDisposable
+{
+ private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
+ private const string PATH_PREFIX = "/api/v1/users/";
+ private const string PATH_SUFFIX = "/consumption-history/media-items/";
+
+ private static readonly DateTime s_startedOnUtc = new(2026, 5, 2, 9, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_lastActivityOnUtc = new(2026, 5, 2, 9, 10, 0, DateTimeKind.Utc);
+
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ private readonly JsonSerializerOptions _jsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+ private readonly LibraryEntityFixture _libraryEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+ private readonly List _adminUserIds = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public DeleteUserConsumptionItemHistoryEndpointTests(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 DeleteUserConsumptionItemHistory_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenCallerNamesThemselves_ShouldDeleteTheOwnRecords()
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+ AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
+ await AssertRecordsAreDeletedAsync(recordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenRegularUserNamesAnotherUser_ShouldReturnForbiddenAndPreserveTheRecords()
+ {
+ // Arrange
+ await CreateAuthenticatedUserAsync(_client);
+ (Guid targetUserId, _) = await SeedOtherUserAsync();
+ Guid targetLibraryId = await SeedLibraryAsync(targetUserId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ string content = await AssertForbiddenAsync(response, url);
+ AssertNonCacheable(response);
+ AssertNoSensitiveData(content);
+ await AssertRecordsArePreservedAsync(targetRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
+ {
+ // Arrange
+ await CreateAuthenticatedUserAsync(_client);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ Guid otherUserLibraryId = await SeedLibraryAsync(otherUserId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid otherUserRecordId = await SeedRecordAsync(otherUserId, otherUserLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{otherUserLibraryId}";
+ string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Guid.NewGuid()}/{Guid.NewGuid()}";
+
+ // Act
+ HttpResponseMessage foreignResponse = await _client.DeleteAsync(foreignUrl);
+ HttpResponseMessage missingResponse = await _client.DeleteAsync(missingUrl);
+
+ // Assert
+ await AssertForbiddenAsync(foreignResponse, foreignUrl);
+ await AssertForbiddenAsync(missingResponse, missingUrl);
+ Dictionary foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
+ Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse);
+ Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
+ Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
+ Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
+ Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
+ await AssertRecordsArePreservedAsync(otherUserRecordId);
+ }
+
+ [Fact]
+ public async Task DeleteUserConsumptionItemHistory_WhenAdminNamesAnotherUser_ShouldDeleteThatUsersRecords()
+ {
+ // Arrange
+ (Guid targetUserId, _) = await SeedOtherUserAsync();
+ Guid targetLibraryId = await SeedLibraryAsync(targetUserId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid targetRecordId = await SeedRecordAsync(targetUserId, targetLibraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{targetUserId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{targetLibraryId}";
+ HttpClient adminClient = _apiFactory.CreateClient();
+ Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
+ _adminUserIds.Add(adminUserId);
+
+ try
+ {
+ // Act
+ HttpResponseMessage response = await adminClient.DeleteAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+ AssertNoSensitiveData(await response.Content.ReadAsStringAsync());
+ await AssertRecordsAreDeletedAsync(targetRecordId);
+ }
+ finally
+ {
+ adminClient.Dispose();
+ }
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteUserConsumptionItemHistory_WithInjectionInUserIdRouteValue_ShouldRejectWithoutDeletingRows(string maliciousUserId)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousUserId, url, "TargetUserIdIsInvalid");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteUserConsumptionItemHistory_WithInjectionInMediaKind_ShouldRejectWithoutDeletingRows(string maliciousMediaKind)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{Uri.EscapeDataString(maliciousMediaKind)}/{mediaItemId}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousMediaKind, url, "UnsupportedMediaKind");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteUserConsumptionItemHistory_WithInjectionInMediaItemId_ShouldRejectWithoutDeletingRows(string maliciousMediaItemId)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{Uri.EscapeDataString(maliciousMediaItemId)}/{libraryId}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousMediaItemId, url, "MediaItemIdCannotBeEmpty");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task DeleteUserConsumptionItemHistory_WithInjectionInLibraryId_ShouldRejectWithoutDeletingRows(string maliciousLibraryId)
+ {
+ // Arrange
+ (Guid userId, _) = await CreateAuthenticatedUserAsync(_client);
+ Guid libraryId = await SeedLibraryAsync(userId);
+ Guid mediaItemId = Guid.NewGuid();
+ Guid recordId = await SeedRecordAsync(userId, libraryId, MediaKind.MusicTrack, mediaItemId, 60_000);
+ string url = $"{PATH_PREFIX}{userId}{PATH_SUFFIX}{nameof(MediaKind.MusicTrack)}/{mediaItemId}/{Uri.EscapeDataString(maliciousLibraryId)}";
+
+ // Act
+ HttpResponseMessage response = await _client.DeleteAsync(url);
+
+ // Assert
+ await AssertRejectedInjectionAsync(response, maliciousLibraryId, url, "LibraryIdCannotBeEmpty");
+ await AssertRecordsArePreservedAsync(recordId);
+ }
+
+ ///
+ /// Creates a test user and authenticates it on .
+ ///
+ /// The HTTP client to authenticate.
+ /// The Id and username of the created user.
+ private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
+ {
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ return (userId, username);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id and username.
+ ///
+ /// The Id and username of the seeded user.
+ private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
+ dbContext.Users.Add(user);
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return (userId, username);
+ }
+
+ ///
+ /// Seeds a media library owned by .
+ ///
+ /// The Id of the user that owns the library.
+ /// The Id of the seeded library.
+ private async Task SeedLibraryAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid libraryId = Guid.NewGuid();
+ dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ await dbContext.SaveChangesAsync();
+ return libraryId;
+ }
+
+ ///
+ /// Seeds a consumption record of a media item for .
+ ///
+ /// The Id of the user that owns the record.
+ /// The Id of the library that contains the media item.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The active duration consumed by the session, in milliseconds.
+ /// The Id of the seeded record.
+ private async Task SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid recordId = Guid.NewGuid();
+ dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
+ id: recordId,
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: mediaKind,
+ mediaItemId: mediaItemId,
+ status: ConsumptionStatus.Stopped,
+ startedOnUtc: s_startedOnUtc,
+ lastActivityOnUtc: s_lastActivityOnUtc,
+ endedOnUtc: s_lastActivityOnUtc.AddMinutes(1),
+ consumedDurationMilliseconds: consumedDurationMilliseconds,
+ lastPositionKind: MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: 45_000,
+ lastPositionLocation: null,
+ lastProgressFraction: 0.5,
+ consecutivePagesRead: 0));
+ await dbContext.SaveChangesAsync();
+ return recordId;
+ }
+
+ ///
+ /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ AssertNoSensitiveData(content);
+ }
+
+ ///
+ /// Asserts that the response is the exact not authorized problem document and returns its raw body.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The raw response body, so that leak assertions can be applied to it.
+ private async Task AssertForbiddenAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status403Forbidden, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails["type"].GetString());
+ Assert.Equal("General.Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("NotAuthorized", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+ AssertNoSensitiveData(content);
+ return content;
+ }
+
+ ///
+ /// Reads the problem details document of .
+ ///
+ /// The HTTP response to read.
+ /// The parsed problem details fields.
+ private async Task> ReadProblemDetailsAsync(HttpResponseMessage response)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ return problemDetails!;
+ }
+
+ ///
+ /// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
+ ///
+ /// The HTTP response to assert on.
+ /// The malicious value that was sent.
+ /// The request path the value was sent in.
+ /// The validation error code expected when the value reaches the validator.
+ private async Task AssertRejectedInjectionAsync(
+ HttpResponseMessage response,
+ string payload,
+ string requestPath,
+ string expectedErrorCode)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+
+ // An unparseable route value must never become a server error, and it must never be reported as a successful request.
+ Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
+ Assert.NotEqual(HttpStatusCode.OK, response.StatusCode);
+
+ if (response.StatusCode == HttpStatusCode.UnprocessableEntity)
+ {
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
+ Assert.Equal("General.Validation", problemDetails["title"].GetString());
+ Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+
+ // The instance is the request path with the rejected payload still in place, independent of how the server escapes it.
+ string escapedPayload = Uri.EscapeDataString(payload);
+ int payloadIndex = requestPath.IndexOf(escapedPayload, StringComparison.Ordinal);
+ string? instance = problemDetails["instance"].GetString();
+ Assert.NotNull(instance);
+ Assert.True(payloadIndex >= 0, "The escaped payload must appear in the request path.");
+ Assert.StartsWith(requestPath[..payloadIndex], instance, StringComparison.Ordinal);
+ Assert.EndsWith(requestPath[(payloadIndex + escapedPayload.Length)..], instance, StringComparison.Ordinal);
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors!.Keys);
+ Assert.Contains(expectedErrorCode, errors["General.Validation"]);
+ AssertNonCacheable(response);
+ }
+ else
+ {
+ // A payload that carries encoded path separators is rejected by routing before it reaches the endpoint. That is still a safe rejection.
+ Assert.Contains("/", payload, StringComparison.Ordinal);
+ Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
+ }
+
+ AssertNoSensitiveData(content);
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are no longer stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be deleted.
+ private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so the stored state is read until that completion
+ // has run, instead of assuming that it already has.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ if (storedRecords.Count == 0)
+ return;
+ await Task.Delay(100);
+ }
+ Assert.Empty(storedRecords);
+ }
+
+ ///
+ /// Asserts that the consumption records identified by are still stored once the request transaction has completed.
+ ///
+ /// The Ids of the consumption records that must be preserved.
+ private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ List storedRecords = [];
+ // The request transaction is committed or rolled back after the response has been sent, so a record that must survive is read until that
+ // completion has run, instead of trusting the state observed right after the response.
+ for (int attempt = 0; attempt < 20; attempt++)
+ {
+ storedRecords = await dbContext.MediaConsumptionRecords.AsNoTracking()
+ .Where(record => recordIds.Contains(record.Id))
+ .ToListAsync();
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ await Task.Delay(100);
+ }
+ Assert.Equal(recordIds.Length, storedRecords.Count);
+ }
+
+ ///
+ /// Asserts that the response is not storable by any intermediary and varies by the authorization header.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertNonCacheable(HttpResponseMessage response)
+ {
+ Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
+ Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
+ }
+
+ ///
+ /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
+ ///
+ /// The response body to assert on.
+ private static void AssertNoSensitiveData(string content)
+ {
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Removes the test users and admin users created by the test.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ foreach (Guid userId in _adminUserIds)
+ _apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs
new file mode 100644
index 00000000..878fc0ee
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointTests.cs
@@ -0,0 +1,460 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+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.Net;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionEndpointTests : IClassFixture, IDisposable
+{
+ private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
+ private const string PATH = "/api/v1/users/me/consumption-statistics/genres";
+
+ private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
+
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ 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 GenreEntityFixture _genreEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetGenreConsumptionEndpointTests(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 GetGenreConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = PATH;
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WhenSuccessful_ShouldReturnOnlyCallersGenresWithoutSensitiveData()
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ string callerGenre = await SeedGenreConsumptionAsync(callerId);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string url = PATH;
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+
+ string content = await response.Content.ReadAsStringAsync();
+ AssertNoSensitiveData(content);
+ AssertNoDatabaseOnlyFields(content);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+
+ List? genres = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(genres);
+ GenreConsumptionResponse genre = Assert.Single(genres!);
+ Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
+ Assert.Equal(1, genre.ConsumedItemCount);
+ Assert.Equal(60d, genre.ConsumedDurationInSeconds, 3);
+ }
+
+ [Fact]
+ public async Task GetGenreConsumption_WithSpoofedUserIdQueryParameter_ShouldIgnoreItAndReturnCallersGenres()
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ string callerGenre = await SeedGenreConsumptionAsync(callerId);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string url = $"{PATH}?userId={otherUserId}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+
+ string content = await response.Content.ReadAsStringAsync();
+ List? genres = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(genres);
+ GenreConsumptionResponse genre = Assert.Single(genres!);
+ Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetGenreConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ string url = $"{PATH}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertValidationProblemAsync(response, PATH, "LibraryIdCannotBeEmpty");
+ AssertNonCacheable(response);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
+ }
+
+ [Theory]
+ [InlineData("999")] // out of range numeric value
+ [InlineData("not-a-media-kind")] // textual value that is not an enum member
+ public async Task GetGenreConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ string url = $"{PATH}?mediaKind={Uri.EscapeDataString(mediaKind)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ // The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
+ // unsupported kind instead of being rejected by request binding.
+ await AssertRejectedMediaKindAsync(response, PATH);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetGenreConsumption_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string url = $"{PATH}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertSafeDatePayloadResponseAsync(response, maliciousFromUtc);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetGenreConsumption_WithInjectionInToUtc_ShouldRejectWithoutLeakingData(string maliciousToUtc)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string url = $"{PATH}?toUtc={Uri.EscapeDataString(maliciousToUtc)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertSafeDatePayloadResponseAsync(response, maliciousToUtc);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
+ }
+
+ ///
+ /// Creates a test user and authenticates it on .
+ ///
+ /// The HTTP client to authenticate.
+ /// The Id and username of the created user.
+ private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
+ {
+ (Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
+ _seededUsernames.Add(username);
+ return (userId, username);
+ }
+
+ ///
+ /// Seeds a user distinct from the authenticated test user and returns its Id and username.
+ ///
+ /// The Id and username of the seeded user.
+ private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Guid userId = Guid.NewGuid();
+ string username = $"otheruser_{Guid.NewGuid()}";
+ UserEntity user = _userEntityFixture.Create(id: userId, username: username, password: "TestPass123!");
+ dbContext.Users.Add(user);
+ await dbContext.SaveChangesAsync();
+ _seededUsernames.Add(username);
+ return (userId, username);
+ }
+
+ ///
+ /// Seeds a uniquely genred track in a library owned by and one completed session of it.
+ ///
+ /// The Id of the user that owns the records.
+ /// The unique name of the seeded genre.
+ private async Task SeedGenreConsumptionAsync(Guid userId)
+ {
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ string suffix = Guid.NewGuid().ToString("N")[..8];
+ // Genre names are the primary key of a shared table, so every seeded name carries a unique suffix.
+ string genreName = $"Genre-{suffix}";
+ 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: $"Library-{suffix}", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
+ dbContext.Artists.Add(_artistEntityFixture.Create(id: artistId, libraryId: libraryId, name: $"Artist-{suffix}", includeAlbums: false, includeContributors: false, includeMetadata: false));
+ dbContext.Albums.Add(_albumEntityFixture.Create(id: albumId, artistId: artistId, libraryId: libraryId, title: $"Album-{suffix}", includeTracks: false, includeMetadata: false));
+ TrackEntity track = _trackEntityFixture.Create(id: trackId, albumId: albumId, libraryId: libraryId, path: $"/music/{trackId:N}.flac", title: $"Track-{suffix}", includeMetadata: false);
+ GenreEntity genre = _genreEntityFixture.Create(name: genreName);
+ track.Genres.Add(genre);
+ dbContext.Tracks.Add(track);
+ dbContext.MediaConsumptionRecords.Add(_mediaConsumptionRecordEntityFixture.Create(
+ id: Guid.NewGuid(),
+ userId: userId,
+ libraryId: libraryId,
+ mediaKind: MediaKind.MusicTrack,
+ mediaItemId: trackId,
+ status: ConsumptionStatus.Completed,
+ startedOnUtc: s_startedOnUtc,
+ lastActivityOnUtc: s_lastActivityOnUtc,
+ consumedDurationMilliseconds: 60_000,
+ lastPositionKind: MediaPositionKind.TimeOffset,
+ lastPositionTimeOffsetMilliseconds: 60_000,
+ lastProgressFraction: 1.0,
+ consecutivePagesRead: 0));
+ await dbContext.SaveChangesAsync();
+ return genreName;
+ }
+
+ ///
+ /// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
+ Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(problemDetails);
+ Assert.Equal(StatusCodes.Status401Unauthorized, problemDetails!["status"].GetInt32());
+ Assert.Equal("https://tools.ietf.org/html/rfc7235#section-3.1", problemDetails["type"].GetString());
+ Assert.Equal("Unauthorized", problemDetails["title"].GetString());
+ Assert.Equal("Authentication failed", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetProperty("value").GetString());
+ AssertNoSensitiveData(content);
+ }
+
+ ///
+ /// Asserts the shape of a validation problem details response and returns its raw body.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ /// The expected validation error code.
+ /// The raw response body, so that leak assertions can be applied to it.
+ private async Task AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _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("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors!.Keys);
+ Assert.Contains(expectedErrorCode, errors["General.Validation"]);
+ AssertNoSensitiveData(content);
+ return content;
+ }
+
+ ///
+ /// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
+ ///
+ /// The HTTP response to assert on.
+ /// The expected request instance path.
+ private async Task AssertRejectedMediaKindAsync(HttpResponseMessage response, string expectedInstance)
+ {
+ Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
+ Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
+
+ string content = await response.Content.ReadAsStringAsync();
+ Dictionary? problemDetails = JsonSerializer.Deserialize>(content, _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("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
+ Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
+ Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
+
+ Dictionary? errors = problemDetails["errors"].Deserialize>(_jsonOptions);
+ Assert.NotNull(errors);
+ Assert.Contains("General.Validation", errors!.Keys);
+ Assert.Contains("UnsupportedMediaKind", errors["General.Validation"]);
+
+ AssertNonCacheable(response);
+ AssertNoSensitiveData(content);
+ Assert.DoesNotContain("\"consumedItemCount\"", content, StringComparison.Ordinal);
+ }
+
+ ///
+ /// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
+ ///
+ /// The HTTP response to assert on.
+ /// The malicious value that was sent.
+ /// The raw response body, so that leak assertions can be applied to it.
+ private async Task AssertSafeDatePayloadResponseAsync(HttpResponseMessage response, string payload)
+ {
+ string content = await response.Content.ReadAsStringAsync();
+
+ // A bound date is parsed before the handler runs, so an unparseable value must either be ignored or rejected, but it must never reach the
+ // storage medium, fail the request, or disclose internals.
+ Assert.NotEqual(HttpStatusCode.InternalServerError, response.StatusCode);
+ Assert.True(
+ response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.BadRequest || response.StatusCode == HttpStatusCode.UnprocessableEntity,
+ $"Unexpected status code {response.StatusCode} for a date bound payload.");
+
+ AssertNoSensitiveData(content);
+ Assert.DoesNotContain(payload, content, StringComparison.Ordinal);
+ return content;
+ }
+
+ ///
+ /// Asserts that the response is not storable by any intermediary and varies by the authorization header.
+ ///
+ /// The HTTP response to assert on.
+ private static void AssertNonCacheable(HttpResponseMessage response)
+ {
+ Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
+ Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
+ }
+
+ ///
+ /// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
+ ///
+ /// The response body to assert on.
+ private static void AssertNoSensitiveData(string content)
+ {
+ Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
+ Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
+ Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Asserts that the serialized genres expose only the fields of their documented response contract.
+ ///
+ /// The response body to assert on.
+ private static void AssertNoDatabaseOnlyFields(string content)
+ {
+ Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("userId", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("createdBy", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("updatedBy", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("createdOnUtc", content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("updatedOnUtc", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Removes the test users created by the test.
+ ///
+ public void Dispose()
+ {
+ _client.Dispose();
+ foreach (string username in _seededUsernames)
+ _apiFactory.RemoveTestUser(username);
+ }
+}
diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointTests.cs
new file mode 100644
index 00000000..24dd7c10
--- /dev/null
+++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointTests.cs
@@ -0,0 +1,617 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.Common;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.Common;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Fixtures.Common.DataAccess.Entities.UsersManagement;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+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.Net;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Presentation.Api.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// Contains security tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserGenreConsumptionEndpointTests : IClassFixture, IDisposable
+{
+ private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
+ private const string PATH_PREFIX = "/api/v1/users/";
+ private const string PATH_SUFFIX = "/consumption-statistics/genres";
+
+ private static readonly DateTime s_startedOnUtc = new(2026, 3, 1, 10, 0, 0, DateTimeKind.Utc);
+ private static readonly DateTime s_lastActivityOnUtc = new(2026, 3, 1, 10, 5, 0, DateTimeKind.Utc);
+
+ private readonly LuminaApiFactory _apiFactory;
+ private readonly HttpClient _client;
+ 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 GenreEntityFixture _genreEntityFixture = new();
+ private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
+ private readonly UserEntityFixture _userEntityFixture = new();
+ private readonly List _seededUsernames = [];
+ private readonly List _adminUserIds = [];
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected in-memory API factory.
+ public GetUserGenreConsumptionEndpointTests(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 GetUserGenreConsumption_WhenUnauthorized_ShouldReturnUnauthorizedResult()
+ {
+ // Arrange
+ string url = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ await AssertUnauthorizedAsync(response, url);
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenAnotherUsersGenresAreRequested_ShouldReturnForbiddenWithoutDisclosingData()
+ {
+ // Arrange
+ await CreateAuthenticatedUserAsync(_client);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertForbiddenAsync(response, url);
+ AssertNonCacheable(response);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+ Assert.DoesNotContain("consumedItemCount", content, StringComparison.OrdinalIgnoreCase);
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenTargetUserDoesNotExist_ShouldReturnSameForbiddenResultAsForeignUser()
+ {
+ // Arrange
+ await CreateAuthenticatedUserAsync(_client);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ await SeedGenreConsumptionAsync(otherUserId);
+ string foreignUrl = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
+ string missingUrl = $"{PATH_PREFIX}{Guid.NewGuid()}{PATH_SUFFIX}";
+
+ // Act
+ HttpResponseMessage foreignResponse = await _client.GetAsync(foreignUrl);
+ HttpResponseMessage missingResponse = await _client.GetAsync(missingUrl);
+
+ // Assert
+ await AssertForbiddenAsync(foreignResponse, foreignUrl);
+ await AssertForbiddenAsync(missingResponse, missingUrl);
+ Dictionary foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
+ Dictionary missingProblem = await ReadProblemDetailsAsync(missingResponse);
+ Assert.Equal(missingProblem["status"].GetInt32(), foreignProblem["status"].GetInt32());
+ Assert.Equal(missingProblem["title"].GetString(), foreignProblem["title"].GetString());
+ Assert.Equal(missingProblem["detail"].GetString(), foreignProblem["detail"].GetString());
+ Assert.Equal(missingProblem["type"].GetString(), foreignProblem["type"].GetString());
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenAdminRequestsAnotherUser_ShouldReturnOnlyThatUsersGenres()
+ {
+ // Arrange
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ HttpClient adminClient = _apiFactory.CreateClient();
+ Guid adminUserId = await _apiFactory.CreateAndAuthenticateAdminUserAsync(adminClient);
+ _adminUserIds.Add(adminUserId);
+ string url = $"{PATH_PREFIX}{otherUserId}{PATH_SUFFIX}";
+
+ try
+ {
+ // Act
+ HttpResponseMessage response = await adminClient.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+
+ string content = await response.Content.ReadAsStringAsync();
+ AssertNoSensitiveData(content);
+ AssertNoDatabaseOnlyFields(content);
+
+ List? genres = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(genres);
+ GenreConsumptionResponse genre = Assert.Single(genres!);
+ Assert.Equal(otherGenre.ToLowerInvariant(), genre.Name);
+ Assert.Equal(1, genre.ConsumedItemCount);
+ }
+ finally
+ {
+ adminClient.Dispose();
+ }
+ }
+
+ [Fact]
+ public async Task GetUserGenreConsumption_WhenCallerNamesThemselves_ShouldReturnOwnGenres()
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ string callerGenre = await SeedGenreConsumptionAsync(callerId);
+ string url = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ Assert.Equal(HttpStatusCode.OK, response.StatusCode);
+ AssertNonCacheable(response);
+
+ string content = await response.Content.ReadAsStringAsync();
+ List? genres = JsonSerializer.Deserialize>(content, _jsonOptions);
+ Assert.NotNull(genres);
+ GenreConsumptionResponse genre = Assert.Single(genres!);
+ Assert.Equal(callerGenre.ToLowerInvariant(), genre.Name);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetUserGenreConsumption_WithInjectionInUserIdRouteValue_ShouldRejectWithoutLeakingData(string maliciousUserId)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ string url = $"{PATH_PREFIX}{Uri.EscapeDataString(maliciousUserId)}{PATH_SUFFIX}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertRejectedRouteValueAsync(response, maliciousUserId, PATH_PREFIX, PATH_SUFFIX, "TargetUserIdIsInvalid");
+ AssertNonCacheable(response);
+ Assert.DoesNotContain(maliciousUserId, content, StringComparison.Ordinal);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetUserGenreConsumption_WithInjectionInLibraryId_ShouldRejectWithoutLeakingData(string maliciousLibraryId)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
+ string url = $"{path}?libraryId={Uri.EscapeDataString(maliciousLibraryId)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertValidationProblemAsync(response, path, "LibraryIdCannotBeEmpty");
+ AssertNonCacheable(response);
+ Assert.DoesNotContain(maliciousLibraryId, content, StringComparison.Ordinal);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == callerId));
+ }
+
+ [Theory]
+ [InlineData("999")] // out of range numeric value
+ [InlineData("not-a-media-kind")] // textual value that is not an enum member
+ public async Task GetUserGenreConsumption_WithUnsupportedMediaKind_ShouldNotReturnDataOrLeakInternals(string mediaKind)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
+ string url = $"{path}?mediaKind={Uri.EscapeDataString(mediaKind)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ // The media kind is carried as text, so an unknown or numeric name reaches the validator and is reported as an
+ // unsupported kind instead of being rejected by request binding.
+ await AssertRejectedMediaKindAsync(response, path);
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetUserGenreConsumption_WithInjectionInFromUtc_ShouldRejectWithoutLeakingData(string maliciousFromUtc)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
+ string url = $"{path}?fromUtc={Uri.EscapeDataString(maliciousFromUtc)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertSafeDatePayloadResponseAsync(response, maliciousFromUtc);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
+ }
+
+ [Theory]
+ [InlineData("' OR '1'='1")] // boolean-based injection
+ [InlineData("'; DROP TABLE MediaConsumptionRecords--")] // destructive injection
+ [InlineData("1; DELETE FROM MediaConsumptionRecords")] // stacked statement injection
+ [InlineData("../../../etc/passwd")] // path traversal
+ [InlineData("")] // markup injection
+ public async Task GetUserGenreConsumption_WithInjectionInToUtc_ShouldRejectWithoutLeakingData(string maliciousToUtc)
+ {
+ // Arrange
+ (Guid callerId, _) = await CreateAuthenticatedUserAsync(_client);
+ await SeedGenreConsumptionAsync(callerId);
+ (Guid otherUserId, _) = await SeedOtherUserAsync();
+ string otherGenre = await SeedGenreConsumptionAsync(otherUserId);
+ string path = $"{PATH_PREFIX}{callerId}{PATH_SUFFIX}";
+ string url = $"{path}?toUtc={Uri.EscapeDataString(maliciousToUtc)}";
+
+ // Act
+ HttpResponseMessage response = await _client.GetAsync(url);
+
+ // Assert
+ string content = await AssertSafeDatePayloadResponseAsync(response, maliciousToUtc);
+ Assert.DoesNotContain(otherGenre, content, StringComparison.OrdinalIgnoreCase);
+
+ using IServiceScope scope = _apiFactory.Services.CreateScope();
+ LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService();
+ Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
+ }
+
+ ///