mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Implements tests for commit 00d7eff777
Covers genre consumption and delete-item-history across application, contracts, API, and Web. Changes the new string-bound request pipelines to return validation problems instead of 500 for malformed values.
This commit is contained in:
1 parent
968061e89a
commit
1afb078efc
91 files changed
+14499
-50
No files matched your search
+6
-8
@@ -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.
|
||||
/// </summary>
|
||||
/// <param name="TargetUserId">The Id of the user the records must belong to, or <see langword="null"/> for the current user.</param>
|
||||
/// <param name="MediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
|
||||
/// <param name="MediaKind">The name of the kind of the consumed media item, taken from the route.</param>
|
||||
/// <param name="MediaItemId">The Id of the consumed media item, taken from the route.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, taken from the route.</param>
|
||||
[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;
|
||||
+7
-1
@@ -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<Delete
|
||||
if (!canAccessTarget)
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
// The validator guarantees that the route values are well formed before this point.
|
||||
MediaKind mediaKind = Enum.Parse<MediaKind>(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<Deleted> 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;
|
||||
|
||||
|
||||
+20
-4
@@ -24,20 +24,36 @@ public class DeleteConsumptionItemHistoryCommandValidator : AbstractValidator<De
|
||||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
|
||||
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
|
||||
// Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected.
|
||||
RuleFor(command => command.MediaKind)
|
||||
.IsInEnum()
|
||||
.NotEmpty()
|
||||
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => mediaKind != MediaKind.None)
|
||||
.IsInEnum<DeleteConsumptionItemHistoryCommand, MediaKind>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+6
-8
@@ -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;
|
||||
/// </summary>
|
||||
/// <param name="TargetUserId">The Id of the user whose statistics are retrieved, or <see langword="null"/> for the current user.</param>
|
||||
/// <param name="LibraryId">The Id of the media library to restrict the statistics to, or <see langword="null"/> for every library.</param>
|
||||
/// <param name="MediaKind">The kind of media to restrict the statistics to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="FromUtc">The inclusive start of the date range, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, or <see langword="null"/> when the range has no end.</param>
|
||||
/// <param name="MediaKind">The name of the kind of media to restrict the statistics to, or <see langword="null"/> for every kind.</param>
|
||||
/// <param name="FromUtc">The inclusive start of the date range, in UTC, as a text value, or <see langword="null"/> when the range has no start.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, as a text value, or <see langword="null"/> when the range has no end.</param>
|
||||
[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;
|
||||
+5
-1
@@ -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<GetGenreConsumption
|
||||
return ApplicationErrors.Authorization.NotAuthorized;
|
||||
|
||||
Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId);
|
||||
MediaKind? mediaKind = query.MediaKind is null ? null : Enum.Parse<MediaKind>(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<IReadOnlyList<MediaConsumptionRecordEntity>> 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;
|
||||
|
||||
|
||||
+33
-8
@@ -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<GetGenreConsu
|
||||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
|
||||
// Only the member names of the media kind enumeration are accepted, so a numeric value that happens to parse as a kind is rejected.
|
||||
RuleFor(query => 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<GetGenreConsumptionQuery, MediaKind>()
|
||||
.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);
|
||||
}
|
||||
}
|
||||
+6
-8
@@ -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;
|
||||
/// <summary>
|
||||
/// Represents a request to delete every consumption record of a media item.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
|
||||
/// <param name="MediaKind">The name of the kind of the consumed media item, taken from the route.</param>
|
||||
/// <param name="MediaItemId">The Id of the consumed media item, taken from the route.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, taken from the route.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; LibraryId: {LibraryId}")]
|
||||
public sealed record DeleteConsumptionItemHistoryRequest(
|
||||
MediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
Guid LibraryId
|
||||
string? MediaKind,
|
||||
string? MediaItemId,
|
||||
string? LibraryId
|
||||
);
|
||||
@@ -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.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The Id of the media library to restrict the statistics to. Optional.</param>
|
||||
/// <param name="MediaKind">The kind of media to restrict the statistics to. Optional.</param>
|
||||
/// <param name="FromUtc">The inclusive start of the date range. Optional.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range. Optional.</param>
|
||||
/// <param name="MediaKind">The name of the kind of media to restrict the statistics to. Optional.</param>
|
||||
/// <param name="FromUtc">The inclusive start of the date range, in UTC, as a text value. Optional.</param>
|
||||
/// <param name="ToUtc">The inclusive end of the date range, in UTC, as a text value. Optional.</param>
|
||||
[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
|
||||
);
|
||||
+2
-2
@@ -26,8 +26,8 @@ public class GetGenreConsumptionEndpointSummary : Summary<GetGenreConsumptionEnd
|
||||
ExampleRequest = new GetGenreConsumptionRequest(
|
||||
LibraryId: null,
|
||||
MediaKind: null,
|
||||
FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
|
||||
FromUtc: "2026-10-01T00:00:00.0000000Z",
|
||||
ToUtc: "2026-10-31T23:59:59.0000000Z"
|
||||
);
|
||||
|
||||
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
|
||||
|
||||
+2
-2
@@ -26,8 +26,8 @@ public class GetUserGenreConsumptionEndpointSummary : Summary<GetUserGenreConsum
|
||||
ExampleRequest = new GetGenreConsumptionRequest(
|
||||
LibraryId: null,
|
||||
MediaKind: null,
|
||||
FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
|
||||
ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
|
||||
FromUtc: "2026-10-01T00:00:00.0000000Z",
|
||||
ToUtc: "2026-10-31T23:59:59.0000000Z"
|
||||
);
|
||||
|
||||
Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves.";
|
||||
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Bogus;
|
||||
using Lumina.Application.Common.DTO.MediaConsumption;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Fixtures.Common.DTO.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GenreConsumptionDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreConsumptionDtoFixture
|
||||
{
|
||||
private const int MAXIMUM_DURATION_MILLISECONDS = 36_000_000;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GenreConsumptionDto"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The lowercase name of the genre. Defaults to a random lowercase word.</param>
|
||||
/// <param name="consumedItemCount">Optional. The number of distinct consumed media items that carry the genre. Defaults to a bounded random count.</param>
|
||||
/// <param name="consumedDurationMilliseconds">Optional. The consumed duration of the media items that carry the genre, in milliseconds. Defaults to a bounded random duration.</param>
|
||||
/// <param name="includeName">Whether the genre name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeConsumedItemCount">Whether the consumed item count should be included, or forced to zero.</param>
|
||||
/// <param name="includeConsumedDurationMilliseconds">Whether the consumed duration should be included, or forced to zero.</param>
|
||||
/// <returns>The created <see cref="GenreConsumptionDto"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GenreConsumptionDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GenreConsumptionDto"/> instances.</returns>
|
||||
public List<GenreConsumptionDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+69
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeleteConsumptionItemHistoryCommand"/> class.
|
||||
/// </summary>
|
||||
[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
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="DeleteConsumptionItemHistoryCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="targetUserId">Optional. The Id of the user the records must belong to. Defaults to a random user Id.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of the consumed media item. Defaults to the name of a random supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the consumed media item. Defaults to a random Id.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that contains the media item. Defaults to a random Id.</param>
|
||||
/// <param name="includeTargetUserId">Whether the target user Id should be included, or forced to <see langword="null"/> so that the current user is targeted.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemId">Whether the media item Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="DeleteConsumptionItemHistoryCommand"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="DeleteConsumptionItemHistoryCommand"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeleteConsumptionItemHistoryCommand"/> instances.</returns>
|
||||
public List<DeleteConsumptionItemHistoryCommand> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+79
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetGenreConsumptionQuery"/> record.
|
||||
/// </summary>
|
||||
[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
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetGenreConsumptionQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="targetUserId">Optional. The Id of the user whose statistics are retrieved. Defaults to a random Id.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded UTC moment in the future, as a text value.</param>
|
||||
/// <param name="includeTargetUserId">Whether the target user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetGenreConsumptionQuery"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetGenreConsumptionQuery"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetGenreConsumptionQuery"/> instances.</returns>
|
||||
public List<GetGenreConsumptionQuery> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+64
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeleteConsumptionItemHistoryRequest"/> record.
|
||||
/// </summary>
|
||||
[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
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="DeleteConsumptionItemHistoryRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of the consumed media item. Defaults to the name of a random supported kind.</param>
|
||||
/// <param name="mediaItemId">Optional. The Id of the consumed media item. Defaults to a random Id.</param>
|
||||
/// <param name="libraryId">Optional. The Id of the media library that contains the media item. Defaults to a random Id.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaItemId">Whether the media item Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="DeleteConsumptionItemHistoryRequest"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="DeleteConsumptionItemHistoryRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeleteConsumptionItemHistoryRequest"/> instances.</returns>
|
||||
public List<DeleteConsumptionItemHistoryRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+74
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetGenreConsumptionRequest"/> record.
|
||||
/// </summary>
|
||||
[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
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GetGenreConsumptionRequest"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional. The Id of the media library to restrict the statistics to. Defaults to a random Id.</param>
|
||||
/// <param name="mediaKind">Optional. The name of the kind of media to restrict the statistics to. Defaults to the name of a random supported kind.</param>
|
||||
/// <param name="fromUtc">Optional. The inclusive start of the date range. Defaults to a bounded UTC moment in the past, as a text value.</param>
|
||||
/// <param name="toUtc">Optional. The inclusive end of the date range. Defaults to a bounded UTC moment in the future, as a text value.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>The created <see cref="GetGenreConsumptionRequest"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GetGenreConsumptionRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetGenreConsumptionRequest"/> instances.</returns>
|
||||
public List<GetGenreConsumptionRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+54
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GenreConsumptionResponse"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreConsumptionResponseFixture
|
||||
{
|
||||
private const double MAXIMUM_DURATION_SECONDS = 36_000;
|
||||
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a random valid <see cref="GenreConsumptionResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional. The lowercase name of the genre. Defaults to a random lowercase word.</param>
|
||||
/// <param name="consumedItemCount">Optional. The number of distinct consumed media items that carry the genre. Defaults to a bounded random count.</param>
|
||||
/// <param name="consumedDurationInSeconds">Optional. The consumed duration of the media items that carry the genre, in seconds. Defaults to a bounded random duration.</param>
|
||||
/// <param name="includeName">Whether the genre name should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeConsumedItemCount">Whether the consumed item count should be included, or forced to zero.</param>
|
||||
/// <param name="includeConsumedDurationInSeconds">Whether the consumed duration should be included, or forced to zero.</param>
|
||||
/// <returns>The created <see cref="GenreConsumptionResponse"/>.</returns>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a list of <see cref="GenreConsumptionResponse"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GenreConsumptionResponse"/> instances.</returns>
|
||||
public List<GenreConsumptionResponse> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+46
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="AllUsersConsumptionStatisticsDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class AllUsersConsumptionStatisticsDtoFixture
|
||||
{
|
||||
private readonly ConsumptionTotalsDtoFixture _consumptionTotalsDtoFixture = new();
|
||||
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="AllUsersConsumptionStatisticsDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="total">Optional combined consumption statistics of every user.</param>
|
||||
/// <param name="users">Optional consumption statistics of each user.</param>
|
||||
/// <param name="includeUsers">Whether the per user statistics should be included, or forced to an empty collection.</param>
|
||||
/// <returns>A configured <see cref="AllUsersConsumptionStatisticsDto"/> instance.</returns>
|
||||
public AllUsersConsumptionStatisticsDto Create(
|
||||
ConsumptionTotalsDto? total = null,
|
||||
IReadOnlyList<ConsumptionSummaryDto>? users = null,
|
||||
bool includeUsers = true)
|
||||
{
|
||||
return new AllUsersConsumptionStatisticsDto(
|
||||
Total: total ?? _consumptionTotalsDtoFixture.Create(),
|
||||
Users: includeUsers ? (users ?? [.. _consumptionSummaryDtoFixture.CreateMany(2)]) : []
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="AllUsersConsumptionStatisticsDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="AllUsersConsumptionStatisticsDto"/> instances.</returns>
|
||||
public List<AllUsersConsumptionStatisticsDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+78
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ConsumedItemDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ConsumedItemDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ConsumedItemDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">Optional Id of the consumed media item.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library that contains the media item.</param>
|
||||
/// <param name="isAvailable">Optional value indicating whether the media item is still available.</param>
|
||||
/// <param name="title">Optional title of the media item.</param>
|
||||
/// <param name="collectionTitle">Optional title of the collection that contains the media item.</param>
|
||||
/// <param name="creatorName">Optional name of the creator of the media item.</param>
|
||||
/// <param name="coverPath">Optional path of the cover art of the media item.</param>
|
||||
/// <param name="lastConsumedOnUtc">Optional date and time when the media item was last consumed.</param>
|
||||
/// <param name="countedSessionCount">Optional number of counted sessions.</param>
|
||||
/// <param name="completedSessionCount">Optional number of completed sessions.</param>
|
||||
/// <param name="consumedDurationInSeconds">Optional consumed duration, in seconds.</param>
|
||||
/// <param name="includeCoverPath">Whether the cover path should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="ConsumedItemDto"/> instance.</returns>
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ConsumedItemDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ConsumedItemDto"/> instances.</returns>
|
||||
public List<ConsumedItemDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ConsumptionSummaryDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ConsumptionSummaryDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MediaKindConsumptionSummaryDtoFixture _mediaKindConsumptionSummaryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ConsumptionSummaryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user the statistics belong to.</param>
|
||||
/// <param name="totalConsumedDurationInSeconds">Optional total consumed duration, in seconds.</param>
|
||||
/// <param name="countedSessionCount">Optional number of counted sessions.</param>
|
||||
/// <param name="completedSessionCount">Optional number of completed sessions.</param>
|
||||
/// <param name="stoppedSessionCount">Optional number of stopped sessions.</param>
|
||||
/// <param name="completionRate">Optional fraction of the counted sessions that completed.</param>
|
||||
/// <param name="mediaKindSummaries">Optional consumption statistics broken down by media kind.</param>
|
||||
/// <param name="includeMediaKindSummaries">Whether the media kind summaries should be included, or forced to an empty collection.</param>
|
||||
/// <returns>A configured <see cref="ConsumptionSummaryDto"/> instance.</returns>
|
||||
public ConsumptionSummaryDto Create(
|
||||
Guid? userId = null,
|
||||
double? totalConsumedDurationInSeconds = null,
|
||||
int? countedSessionCount = null,
|
||||
int? completedSessionCount = null,
|
||||
int? stoppedSessionCount = null,
|
||||
double? completionRate = null,
|
||||
IReadOnlyList<MediaKindConsumptionSummaryDto>? 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)]) : []
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ConsumptionSummaryDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ConsumptionSummaryDto"/> instances.</returns>
|
||||
public List<ConsumptionSummaryDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+59
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ConsumptionTotalsDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ConsumptionTotalsDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
private readonly MediaKindConsumptionSummaryDtoFixture _mediaKindConsumptionSummaryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ConsumptionTotalsDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="totalConsumedDurationInSeconds">Optional total consumed duration, in seconds.</param>
|
||||
/// <param name="countedSessionCount">Optional number of counted sessions.</param>
|
||||
/// <param name="completedSessionCount">Optional number of completed sessions.</param>
|
||||
/// <param name="stoppedSessionCount">Optional number of stopped sessions.</param>
|
||||
/// <param name="completionRate">Optional fraction of the counted sessions that completed.</param>
|
||||
/// <param name="mediaKindSummaries">Optional consumption statistics broken down by media kind.</param>
|
||||
/// <param name="includeMediaKindSummaries">Whether the media kind summaries should be included, or forced to an empty collection.</param>
|
||||
/// <returns>A configured <see cref="ConsumptionTotalsDto"/> instance.</returns>
|
||||
public ConsumptionTotalsDto Create(
|
||||
double? totalConsumedDurationInSeconds = null,
|
||||
int? countedSessionCount = null,
|
||||
int? completedSessionCount = null,
|
||||
int? stoppedSessionCount = null,
|
||||
double? completionRate = null,
|
||||
IReadOnlyList<MediaKindConsumptionSummaryDto>? 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)]) : []
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ConsumptionTotalsDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ConsumptionTotalsDto"/> instances.</returns>
|
||||
public List<ConsumptionTotalsDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GenreConsumptionDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreConsumptionDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GenreConsumptionDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional lowercase name of the genre.</param>
|
||||
/// <param name="consumedItemCount">Optional number of distinct consumed media items that carry the genre.</param>
|
||||
/// <param name="consumedDurationInSeconds">Optional consumed duration, in seconds.</param>
|
||||
/// <returns>A configured <see cref="GenreConsumptionDto"/> instance.</returns>
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GenreConsumptionDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GenreConsumptionDto"/> instances.</returns>
|
||||
public List<GenreConsumptionDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+57
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="MediaKindConsumptionSummaryDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class MediaKindConsumptionSummaryDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="MediaKindConsumptionSummaryDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="mediaKind">Optional kind of media the statistics belong to.</param>
|
||||
/// <param name="totalConsumedDurationInSeconds">Optional total consumed duration, in seconds.</param>
|
||||
/// <param name="countedSessionCount">Optional number of counted sessions.</param>
|
||||
/// <param name="completedSessionCount">Optional number of completed sessions.</param>
|
||||
/// <param name="stoppedSessionCount">Optional number of stopped sessions.</param>
|
||||
/// <param name="completionRate">Optional fraction of the counted sessions that completed.</param>
|
||||
/// <returns>A configured <see cref="MediaKindConsumptionSummaryDto"/> instance.</returns>
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="MediaKindConsumptionSummaryDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="MediaKindConsumptionSummaryDto"/> instances.</returns>
|
||||
public List<MediaKindConsumptionSummaryDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+86
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="StatisticsPageDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StatisticsPageDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="StatisticsPageDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="title">Optional localized title of the page.</param>
|
||||
/// <param name="isAdmin">Optional value indicating whether the current user is an administrator.</param>
|
||||
/// <param name="currentUserId">Optional Id of the current user.</param>
|
||||
/// <param name="culture">Optional culture of the page.</param>
|
||||
/// <param name="getStatisticsUrl">Optional route that returns the statistics of the selected user.</param>
|
||||
/// <param name="getAllUsersStatisticsUrl">Optional route that returns the statistics of every user.</param>
|
||||
/// <param name="getRecentlyConsumedUrl">Optional route that returns the recently consumed media items.</param>
|
||||
/// <param name="getMostConsumedUrl">Optional route that returns the most consumed media items.</param>
|
||||
/// <param name="getTagConsumptionUrl">Optional route that returns the tag consumption.</param>
|
||||
/// <param name="getGenreConsumptionUrl">Optional route that returns the genre consumption.</param>
|
||||
/// <param name="getLibrariesUrl">Optional route that returns the libraries available for the library filter.</param>
|
||||
/// <param name="getUsersUrl">Optional route that returns the users available for the administrator user selector.</param>
|
||||
/// <param name="deleteConsumptionItemHistoryUrl">Optional route that deletes every consumption record of a media item.</param>
|
||||
/// <param name="clearConsumptionHistoryUrl">Optional route that deletes the consumption history.</param>
|
||||
/// <param name="clearResumePointsUrl">Optional route that deletes the resume points.</param>
|
||||
/// <param name="includeCurrentUserId">Whether the current user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="StatisticsPageDto"/> instance.</returns>
|
||||
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()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="StatisticsPageDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="StatisticsPageDto"/> instances.</returns>
|
||||
public List<StatisticsPageDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+47
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="TagConsumptionDto"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class TagConsumptionDtoFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="TagConsumptionDto"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="name">Optional lowercase name of the tag.</param>
|
||||
/// <param name="consumedItemCount">Optional number of distinct consumed media items that carry the tag.</param>
|
||||
/// <param name="consumedDurationInSeconds">Optional consumed duration, in seconds.</param>
|
||||
/// <returns>A configured <see cref="TagConsumptionDto"/> instance.</returns>
|
||||
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)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="TagConsumptionDto"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="TagConsumptionDto"/> instances.</returns>
|
||||
public List<TagConsumptionDto> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+43
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ClearConsumptionHistoryRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ClearConsumptionHistoryRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose history is deleted.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="ClearConsumptionHistoryRequest"/> instance.</returns>
|
||||
public ClearConsumptionHistoryRequest Create(
|
||||
string? userId = null,
|
||||
bool includeUserId = true)
|
||||
{
|
||||
return new ClearConsumptionHistoryRequest(
|
||||
UserId: includeUserId ? (userId ?? _faker.Random.Guid().ToString()) : null
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ClearConsumptionHistoryRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ClearConsumptionHistoryRequest"/> instances.</returns>
|
||||
public List<ClearConsumptionHistoryRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+48
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="ClearResumePointsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="ClearResumePointsRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose resume points are deleted.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the deletion to.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="ClearResumePointsRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="ClearResumePointsRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="ClearResumePointsRequest"/> instances.</returns>
|
||||
public List<ClearResumePointsRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+54
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="DeleteConsumptionItemHistoryRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="DeleteConsumptionItemHistoryRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose history is deleted.</param>
|
||||
/// <param name="mediaKind">Optional kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">Optional Id of the consumed media item.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library that contains the media item.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="DeleteConsumptionItemHistoryRequest"/> instance.</returns>
|
||||
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()
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="DeleteConsumptionItemHistoryRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="DeleteConsumptionItemHistoryRequest"/> instances.</returns>
|
||||
public List<DeleteConsumptionItemHistoryRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+60
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetAllUsersConsumptionStatisticsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetAllUsersConsumptionStatisticsRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the statistics to.</param>
|
||||
/// <param name="mediaKind">Optional kind of media to restrict the statistics to.</param>
|
||||
/// <param name="fromUtc">Optional inclusive start of the date range.</param>
|
||||
/// <param name="toUtc">Optional inclusive end of the date range.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetAllUsersConsumptionStatisticsRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetAllUsersConsumptionStatisticsRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetAllUsersConsumptionStatisticsRequest"/> instances.</returns>
|
||||
public List<GetAllUsersConsumptionStatisticsRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+65
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetConsumptionStatisticsRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetConsumptionStatisticsRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose statistics are retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the statistics to.</param>
|
||||
/// <param name="mediaKind">Optional kind of media to restrict the statistics to.</param>
|
||||
/// <param name="fromUtc">Optional inclusive start of the date range.</param>
|
||||
/// <param name="toUtc">Optional inclusive end of the date range.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetConsumptionStatisticsRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetConsumptionStatisticsRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetConsumptionStatisticsRequest"/> instances.</returns>
|
||||
public List<GetConsumptionStatisticsRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+65
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetGenreConsumptionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetGenreConsumptionRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose statistics are retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the statistics to.</param>
|
||||
/// <param name="mediaKind">Optional kind of media to restrict the statistics to.</param>
|
||||
/// <param name="fromUtc">Optional inclusive start of the date range.</param>
|
||||
/// <param name="toUtc">Optional inclusive end of the date range.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetGenreConsumptionRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetGenreConsumptionRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetGenreConsumptionRequest"/> instances.</returns>
|
||||
public List<GetGenreConsumptionRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+75
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetMostConsumedRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetMostConsumedRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose history is retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the history to.</param>
|
||||
/// <param name="mediaKind">Optional kind of media to restrict the history to.</param>
|
||||
/// <param name="fromUtc">Optional inclusive start of the date range.</param>
|
||||
/// <param name="toUtc">Optional inclusive end of the date range.</param>
|
||||
/// <param name="currentPage">Optional one based page of media items to return.</param>
|
||||
/// <param name="perPage">Optional number of media items per page.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the page size should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetMostConsumedRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetMostConsumedRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetMostConsumedRequest"/> instances.</returns>
|
||||
public List<GetMostConsumedRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+75
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetRecentlyConsumedRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetRecentlyConsumedRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose history is retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the history to.</param>
|
||||
/// <param name="mediaKind">Optional kind of media to restrict the history to.</param>
|
||||
/// <param name="fromUtc">Optional inclusive start of the date range.</param>
|
||||
/// <param name="toUtc">Optional inclusive end of the date range.</param>
|
||||
/// <param name="currentPage">Optional one based page of media items to return.</param>
|
||||
/// <param name="perPage">Optional number of media items per page.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeCurrentPage">Whether the current page should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includePerPage">Whether the page size should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetRecentlyConsumedRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetRecentlyConsumedRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetRecentlyConsumedRequest"/> instances.</returns>
|
||||
public List<GetRecentlyConsumedRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+65
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Fixture class for the <see cref="GetTagConsumptionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionRequestFixture
|
||||
{
|
||||
private readonly Faker _faker = new();
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new <see cref="GetTagConsumptionRequest"/> instance with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="userId">Optional Id of the user whose statistics are retrieved.</param>
|
||||
/// <param name="libraryId">Optional Id of the media library to restrict the statistics to.</param>
|
||||
/// <param name="mediaKind">Optional kind of media to restrict the statistics to.</param>
|
||||
/// <param name="fromUtc">Optional inclusive start of the date range.</param>
|
||||
/// <param name="toUtc">Optional inclusive end of the date range.</param>
|
||||
/// <param name="includeUserId">Whether the user Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeLibraryId">Whether the library Id should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeMediaKind">Whether the media kind should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeFromUtc">Whether the start of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <param name="includeToUtc">Whether the end of the date range should be included, or forced to <see langword="null"/>.</param>
|
||||
/// <returns>A configured <see cref="GetTagConsumptionRequest"/> instance.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates multiple <see cref="GetTagConsumptionRequest"/> instances with randomized test data.
|
||||
/// </summary>
|
||||
/// <param name="count">Number of instances to create.</param>
|
||||
/// <returns>List of configured <see cref="GetTagConsumptionRequest"/> instances.</returns>
|
||||
public List<GetTagConsumptionRequest> CreateMany(int count = 3)
|
||||
{
|
||||
return [.. Enumerable.Range(0, count).Select(_ => Create())];
|
||||
}
|
||||
}
|
||||
+425
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
+456
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public DeleteUserConsumptionItemHistoryEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedConsumptionRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
+524
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a track and a book in two libraries of <paramref name="userId"/>, with counted and uncounted sessions.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the libraries and the consumption records.</param>
|
||||
/// <returns>
|
||||
/// The Ids of the music library and the ebook library, and the unique rock, favourite, book club, and ignored genre names that were seeded.
|
||||
/// </returns>
|
||||
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<LuminaDbContext>();
|
||||
|
||||
// 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<string, GenreEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="status">The state of the session.</param>
|
||||
/// <param name="startedOnUtc">The date and time when the session started.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> 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<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
+485
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserGenreConsumptionEndpointTests : IClassFixture<AuthenticatedLuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
public GetUserGenreConsumptionEndpointTests(AuthenticatedLuminaApiFactory apiFactory)
|
||||
{
|
||||
_client = apiFactory.CreateClient();
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes authenticated API client.
|
||||
/// </summary>
|
||||
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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = await DeserializeAsync<List<GenreConsumptionResponse>>(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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <param name="libraryType">The type of the library.</param>
|
||||
/// <param name="title">The title of the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId, LibraryType libraryType, string title)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: title, libraryType: libraryType, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a genre-bearing track of <paramref name="libraryId"/>, together with its artist and album.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the track.</param>
|
||||
/// <param name="trackTitle">The title of the track.</param>
|
||||
/// <param name="albumTitle">The title of the album that contains the track.</param>
|
||||
/// <param name="artistName">The name of the artist of the album.</param>
|
||||
/// <param name="genreNames">The genre names carried by the track.</param>
|
||||
/// <returns>The Id of the seeded track.</returns>
|
||||
private async Task<Guid> SeedTrackAsync(Guid libraryId, string trackTitle, string albumTitle, string artistName, IReadOnlyList<string> genreNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a genre-bearing book of <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="libraryId">The Id of the library that owns the book.</param>
|
||||
/// <param name="bookTitle">The title of the book.</param>
|
||||
/// <param name="genreNames">The genre names carried by the book.</param>
|
||||
/// <returns>The Id of the seeded book.</returns>
|
||||
private async Task<Guid> SeedBookAsync(Guid libraryId, string bookTitle, IReadOnlyList<string> genreNames)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a completed consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <param name="consecutivePagesRead">The number of consecutive pages read in the session.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(
|
||||
Guid userId,
|
||||
Guid libraryId,
|
||||
MediaKind mediaKind,
|
||||
Guid mediaItemId,
|
||||
long consumedDurationMilliseconds,
|
||||
int consecutivePagesRead)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the seeded user.</returns>
|
||||
private async Task<Guid> SeedUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid userId = Guid.NewGuid();
|
||||
string username = $"otheruser_{Guid.NewGuid()}";
|
||||
dbContext.Users.Add(_userEntityFixture.Create(id: userId, username: username, password: "TestPass123!"));
|
||||
await dbContext.SaveChangesAsync();
|
||||
_seededUsernames.Add(username);
|
||||
return userId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the currently authenticated test user.
|
||||
/// </summary>
|
||||
/// <returns>The Id of the authenticated test user.</returns>
|
||||
private Guid GetCurrentUserId()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
UserEntity user = dbContext.Users.First(user => user.Username == _apiFactory.TestUsername);
|
||||
return user.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deserializes the body of <paramref name="response"/> to <typeparamref name="TValue"/>.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The type to deserialize the body to.</typeparam>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The deserialized body.</returns>
|
||||
private async Task<TValue?> DeserializeAsync<TValue>(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
return JsonSerializer.Deserialize<TValue>(content, _jsonOptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response carries the cache headers of a private, authorization varying resource.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertCacheHeaders(HttpResponseMessage response)
|
||||
{
|
||||
Assert.True(response.Headers.TryGetValues("Cache-Control", out IEnumerable<string>? cacheControlValues));
|
||||
string cacheControl = string.Join(", ", cacheControlValues!);
|
||||
Assert.Contains("private", cacheControl);
|
||||
Assert.Contains("no-store", cacheControl);
|
||||
Assert.True(response.Headers.TryGetValues("Vary", out IEnumerable<string>? varyValues));
|
||||
Assert.Contains("Authorization", varyValues!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unprocessable entity problem details carrying the expected validation error codes.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCodes">The validation error codes that must all be present.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors.Keys);
|
||||
string[] expectedValidationErrors = [.. expectedErrorCodes.Order()];
|
||||
string[] actualValidationErrors = [.. errors["General.Validation"].Order()];
|
||||
Assert.Equal(expectedValidationErrors, actualValidationErrors);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is a forbidden problem details carrying the exact not authorized shape.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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()!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is an unauthorized problem details carrying the expected request instance path.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes every user created by the test, together with the libraries it owns.
|
||||
/// </summary>
|
||||
public async Task DisposeAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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();
|
||||
}
|
||||
}
|
||||
+154
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = Guid.NewGuid().ToString();
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that clears the consumption history described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the history to clear.</param>
|
||||
/// <returns>The path of the Web route, including the optional query string.</returns>
|
||||
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)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream API path that is expected for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the history to clear.</param>
|
||||
/// <returns>The upstream API path, including the optional escaped user identifier.</returns>
|
||||
private static string BuildExpectedUpstreamPath(ClearConsumptionHistoryRequest request)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(request.UserId)
|
||||
? "users/me/consumption-history"
|
||||
: $"users/{Uri.EscapeDataString(request.UserId)}/consumption-history";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+164
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that clears the resume points described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the resume points to clear.</param>
|
||||
/// <returns>The path of the Web route, including the optional query string.</returns>
|
||||
private static string BuildRequestPath(ClearResumePointsRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the upstream API path that is expected for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the resume points to clear.</param>
|
||||
/// <returns>The upstream API path, including the optional escaped identifiers.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+162
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that deletes the item history described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the item history to delete.</param>
|
||||
/// <returns>The path of the Web route, including the query string.</returns>
|
||||
private static string BuildRequestPath(DeleteConsumptionItemHistoryRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+163
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetAllUsersConsumptionStatisticsRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
}
|
||||
+140
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetConsumptionStatisticsRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
}
|
||||
+140
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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<GenreConsumptionDto>());
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetGenreConsumptionRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
}
|
||||
+99
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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<LibraryDto>());
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+165
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : IClassFixture<LuminaWebFactory>, 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<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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<ConsumedItemDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters and paging are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetMostConsumedRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
}
|
||||
+165
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : IClassFixture<LuminaWebFactory>, 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<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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<ConsumedItemDto> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters and paging are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetRecentlyConsumedRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
}
|
||||
+140
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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<TagConsumptionDto>());
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetTagConsumptionRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
}
|
||||
+122
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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<UserDto>());
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+105
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains integration tests for the <see cref="StatisticsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StatisticsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+465
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
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("<script>alert(1)</script>")] // 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("<script>alert(1)</script>")] // 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("<script>alert(1)</script>")] // 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+540
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionItemHistoryEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
private readonly List<Guid> _adminUserIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
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<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
|
||||
Dictionary<string, JsonElement> 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("<script>alert(1)</script>")] // 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("<script>alert(1)</script>")] // 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("<script>alert(1)</script>")] // 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("<script>alert(1)</script>")] // 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a media library owned by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the library.</param>
|
||||
/// <returns>The Id of the seeded library.</returns>
|
||||
private async Task<Guid> SeedLibraryAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
dbContext.Libraries.Add(_libraryEntityFixture.Create(id: libraryId, userId: userId, title: "Owner Library", libraryType: LibraryType.Music, contentLocations: [], shouldTrackConsumptionProgress: true, completionThresholdPercentage: 100));
|
||||
await dbContext.SaveChangesAsync();
|
||||
return libraryId;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a consumption record of a media item for <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the record.</param>
|
||||
/// <param name="libraryId">The Id of the library that contains the media item.</param>
|
||||
/// <param name="mediaKind">The kind of the consumed media item.</param>
|
||||
/// <param name="mediaItemId">The Id of the consumed media item.</param>
|
||||
/// <param name="consumedDurationMilliseconds">The active duration consumed by the session, in milliseconds.</param>
|
||||
/// <returns>The Id of the seeded record.</returns>
|
||||
private async Task<Guid> SeedRecordAsync(Guid userId, Guid libraryId, MediaKind mediaKind, Guid mediaItemId, long consumedDurationMilliseconds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details document of <paramref name="response"/>.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The parsed problem details fields.</returns>
|
||||
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected with a client error that never discloses internals or deletes rows.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="requestPath">The request path the value was sent in.</param>
|
||||
/// <param name="expectedErrorCode">The validation error code expected when the value reaches the validator.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are no longer stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be deleted.</param>
|
||||
private async Task AssertRecordsAreDeletedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the consumption records identified by <paramref name="recordIds"/> are still stored once the request transaction has completed.
|
||||
/// </summary>
|
||||
/// <param name="recordIds">The Ids of the consumption records that must be preserved.</param>
|
||||
private async Task AssertRecordsArePreservedAsync(params Guid[] recordIds)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
List<MediaConsumptionRecordEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users and admin users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
foreach (Guid userId in _adminUserIds)
|
||||
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
+460
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, IDisposable
|
||||
{
|
||||
private const string JWT_SECRET = "test-key-thats-at-least-32-chars-long-for-jwt";
|
||||
private const string PATH = "/api/v1/users/me/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<string> _seededUsernames = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
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<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a uniquely genred track in a library owned by <paramref name="userId"/> and one completed session of it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the records.</param>
|
||||
/// <returns>The unique name of the seeded genre.</returns>
|
||||
private async Task<string> SeedGenreConsumptionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a validation problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized genres expose only the fields of their documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
}
|
||||
}
|
||||
+617
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserGenreConsumptionEndpointTests : IClassFixture<LuminaApiFactory>, 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<string> _seededUsernames = [];
|
||||
private readonly List<Guid> _adminUserIds = [];
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected in-memory API factory.</param>
|
||||
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<string, JsonElement> foreignProblem = await ReadProblemDetailsAsync(foreignResponse);
|
||||
Dictionary<string, JsonElement> 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<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(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<GenreConsumptionResponse>? genres = JsonSerializer.Deserialize<List<GenreConsumptionResponse>>(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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
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("<script>alert(1)</script>")] // 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<LuminaDbContext>();
|
||||
Assert.Equal(1, await dbContext.MediaConsumptionRecords.CountAsync(record => record.UserId == otherUserId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a test user and authenticates it on <paramref name="client"/>.
|
||||
/// </summary>
|
||||
/// <param name="client">The HTTP client to authenticate.</param>
|
||||
/// <returns>The Id and username of the created user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> CreateAuthenticatedUserAsync(HttpClient client)
|
||||
{
|
||||
(Guid userId, string username) = await _apiFactory.CreateAndAuthenticateUserAsync(client);
|
||||
_seededUsernames.Add(username);
|
||||
return (userId, username);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a user distinct from the authenticated test user and returns its Id and username.
|
||||
/// </summary>
|
||||
/// <returns>The Id and username of the seeded user.</returns>
|
||||
private async Task<(Guid UserId, string Username)> SeedOtherUserAsync()
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Seeds a uniquely genred track in a library owned by <paramref name="userId"/> and one completed session of it.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user that owns the records.</param>
|
||||
/// <returns>The unique name of the seeded genre.</returns>
|
||||
private async Task<string> SeedGenreConsumptionAsync(Guid userId)
|
||||
{
|
||||
using IServiceScope scope = _apiFactory.Services.CreateScope();
|
||||
LuminaDbContext dbContext = scope.ServiceProvider.GetRequiredService<LuminaDbContext>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the unauthenticated problem document produced by the authentication middleware.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
private async Task AssertUnauthorizedAsync(HttpResponseMessage response, string expectedInstance)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is the exact not authorized problem document and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> 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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the problem details document of <paramref name="response"/>.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to read.</param>
|
||||
/// <returns>The parsed problem details fields.</returns>
|
||||
private async Task<Dictionary<string, JsonElement>> ReadProblemDetailsAsync(HttpResponseMessage response)
|
||||
{
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
return problemDetails!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious route value is rejected without disclosing internals.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <param name="pathPrefix">The request path that precedes the malicious value.</param>
|
||||
/// <param name="pathSuffix">The request path that follows the malicious value.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertRejectedRouteValueAsync(HttpResponseMessage response, string payload, string pathPrefix, string pathSuffix, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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 in place, so decoding the middle segment must give the payload back.
|
||||
string? instance = problemDetails["instance"].GetString();
|
||||
Assert.NotNull(instance);
|
||||
Assert.StartsWith(pathPrefix, instance, StringComparison.Ordinal);
|
||||
Assert.EndsWith(pathSuffix, instance, StringComparison.Ordinal);
|
||||
string encodedSegment = instance![pathPrefix.Length..(instance.Length - pathSuffix.Length)];
|
||||
Assert.Equal(payload, Uri.UnescapeDataString(encodedSegment));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts the shape of a validation problem details response and returns its raw body.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
/// <param name="expectedErrorCode">The expected validation error code.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private async Task<string> AssertValidationProblemAsync(HttpResponseMessage response, string expectedInstance, string expectedErrorCode)
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode);
|
||||
Assert.Equal("application/problem+json", response.Content.Headers.ContentType?.MediaType);
|
||||
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Dictionary<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _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<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_jsonOptions);
|
||||
Assert.NotNull(errors);
|
||||
Assert.Contains("General.Validation", errors!.Keys);
|
||||
Assert.Contains(expectedErrorCode, errors["General.Validation"]);
|
||||
AssertNoSensitiveData(content);
|
||||
return content;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that an unparseable media kind is rejected without returning data or disclosing internals.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="expectedInstance">The expected request instance path.</param>
|
||||
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<string, JsonElement>? problemDetails = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(content, _jsonOptions);
|
||||
Assert.NotNull(problemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemDetails!["status"].GetInt32());
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", problemDetails["type"].GetString());
|
||||
Assert.Equal("General.Validation", problemDetails["title"].GetString());
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", problemDetails["detail"].GetString());
|
||||
Assert.Equal(expectedInstance, problemDetails["instance"].GetString());
|
||||
Assert.False(string.IsNullOrEmpty(problemDetails["traceId"].GetString()));
|
||||
|
||||
Dictionary<string, string[]>? errors = problemDetails["errors"].Deserialize<Dictionary<string, string[]>>(_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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that a malicious date bound never causes a server error, never leaks internals, and never returns data of another user.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
/// <param name="payload">The malicious value that was sent.</param>
|
||||
/// <returns>The raw response body, so that leak assertions can be applied to it.</returns>
|
||||
private static async Task<string> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response is not storable by any intermediary and varies by the authorization header.
|
||||
/// </summary>
|
||||
/// <param name="response">The HTTP response to assert on.</param>
|
||||
private static void AssertNonCacheable(HttpResponseMessage response)
|
||||
{
|
||||
Assert.Equal("private, no-store", response.Headers.NonValidated["Cache-Control"].ToString());
|
||||
Assert.Equal("Authorization", response.Headers.NonValidated["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the response body carries no credentials, secrets, persistence details or stack traces.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoSensitiveData(string content)
|
||||
{
|
||||
Assert.DoesNotContain("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("SqliteException", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina.", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("SQL", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(JWT_SECRET, content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Data Source", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asserts that the serialized genres expose only the fields of their documented response contract.
|
||||
/// </summary>
|
||||
/// <param name="content">The response body to assert on.</param>
|
||||
private static void AssertNoDatabaseOnlyFields(string content)
|
||||
{
|
||||
Assert.DoesNotContain("version", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the test users and admin users created by the test.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_client.Dispose();
|
||||
foreach (string username in _seededUsernames)
|
||||
_apiFactory.RemoveTestUser(username);
|
||||
foreach (Guid userId in _adminUserIds)
|
||||
_apiFactory.RemoveAdminUserAsync(userId).GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
#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.SecurityTests.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.SecurityTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = Guid.NewGuid().ToString();
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ClearConsumptionHistoryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: s_userId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearConsumptionHistory_WithCraftedUserId_ShouldEscapeTheValueAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history";
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: CRAFTED_USER_ID);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(EXPECTED_UPSTREAM_PATH);
|
||||
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.Equal([EXPECTED_UPSTREAM_PATH], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that clears the consumption history described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the history to clear.</param>
|
||||
/// <returns>The path of the Web route, including the escaped user identifier.</returns>
|
||||
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)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#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.SecurityTests.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.SecurityTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private static readonly string s_userId = Guid.NewGuid().ToString();
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public ClearResumePointsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: s_userId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ClearResumePoints_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/media-resume-points?libraryId=lib%3Fx%3D1%26y%3D2";
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(userId: CRAFTED_USER_ID, libraryId: CRAFTED_LIBRARY_ID);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(EXPECTED_UPSTREAM_PATH);
|
||||
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.Equal([EXPECTED_UPSTREAM_PATH], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that clears the resume points described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the resume points to clear.</param>
|
||||
/// <returns>The path of the Web route, including the escaped query string.</returns>
|
||||
private static string BuildRequestPath(ClearResumePointsRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
#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.SecurityTests.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.SecurityTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public DeleteConsumptionItemHistoryEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
string antiforgeryToken = await WebTestHelpers.GetAntiforgeryTokenAsync(client);
|
||||
DeleteConsumptionItemHistoryRequest request = CreateRequest(s_userId);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", antiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalledWithoutAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
DeleteConsumptionItemHistoryRequest request = CreateRequest(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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WhenCalledWithInvalidAntiforgeryToken_ShouldRejectRequestAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
DeleteConsumptionItemHistoryRequest request = CreateRequest(s_userId);
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(BuildRequestPath(request));
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", "invalid-token");
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Movie%2F..%2Fadmin%3Fx%3D1")] // path traversal attempt in the media kind
|
||||
[InlineData("NotAMediaKind")] // undefined enum member
|
||||
public async Task DeleteConsumptionItemHistory_WithCraftedMediaKind_ShouldRejectRequestAndNotCallApi(string craftedMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
string path = $"/en-us/library/statistics/api-delete-consumption-item-history?userId={Uri.EscapeDataString(s_userId)}&mediaKind={craftedMediaKind}&mediaItemId={s_mediaItemId}&libraryId={s_libraryId}";
|
||||
HttpRequestMessage deleteRequest = CreateDeleteRequest(path);
|
||||
deleteRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(deleteRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteConsumptionItemHistory_WithCraftedUserId_ShouldEscapeTheValueAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/media-items/Movie/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222";
|
||||
DeleteConsumptionItemHistoryRequest request = CreateRequest(CRAFTED_USER_ID);
|
||||
_apiFactory.ApiClientStub.RegisterDeleteSuccess(EXPECTED_UPSTREAM_PATH);
|
||||
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.Equal([EXPECTED_UPSTREAM_PATH], _apiFactory.ApiClientStub.DeleteEndpointsCalled);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the request used by the tests for the specified user.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose item history is deleted.</param>
|
||||
/// <returns>The configured request.</returns>
|
||||
private DeleteConsumptionItemHistoryRequest CreateRequest(string userId)
|
||||
{
|
||||
return _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: userId,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route that deletes the item history described by <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request describing the item history to delete.</param>
|
||||
/// <returns>The path of the Web route, including the escaped query string.</returns>
|
||||
private static string BuildRequestPath(DeleteConsumptionItemHistoryRequest request)
|
||||
{
|
||||
List<string> 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)}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds a DELETE request for <paramref name="path"/> that carries the JSON content type required by the antiforgery middleware.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the Web route to call.</param>
|
||||
/// <returns>The configured DELETE request.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-all-users-statistics";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new();
|
||||
private readonly AllUsersConsumptionStatisticsDtoFixture _allUsersConsumptionStatisticsDtoFixture = new();
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_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: []);
|
||||
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(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WhenCalledByAdminUser_ShouldReturnStatisticsWithoutLeakingSecrets()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics";
|
||||
AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create();
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, expectedStatistics);
|
||||
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());
|
||||
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);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAllUsersConsumptionStatistics_WithCraftedLibraryId_ShouldEscapeTheValueAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2";
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: CRAFTED_LIBRARY_ID,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_apiFactory.ApiClientStub.RegisterGetResponse(EXPECTED_UPSTREAM_PATH, _allUsersConsumptionStatisticsDtoFixture.Create(includeUsers: false));
|
||||
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);
|
||||
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
|
||||
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request filters.</returns>
|
||||
private static string BuildRequestPath(GetAllUsersConsumptionStatisticsRequest request)
|
||||
{
|
||||
List<string> parameters = [];
|
||||
if (!string.IsNullOrWhiteSpace(request.LibraryId))
|
||||
parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
|
||||
return parameters.Count == 0
|
||||
? WEB_ROUTE
|
||||
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-statistics";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new();
|
||||
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetConsumptionStatisticsEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Movie%2F..%2Fadmin%3Fx%3D1")] // path traversal attempt in the media kind
|
||||
[InlineData("NotAMediaKind")] // undefined enum member
|
||||
public async Task GetConsumptionStatistics_WithCraftedMediaKind_ShouldRejectRequestAndNotCallApi(string craftedMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, $"{WEB_ROUTE}?mediaKind={craftedMediaKind}");
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
|
||||
// Assert
|
||||
using JsonDocument json = JsonDocument.Parse(content);
|
||||
Assert.False(json.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.DoesNotContain(_apiFactory.ApiClientStub.GetEndpointsCalled, endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal));
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetConsumptionStatistics_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2";
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
userId: CRAFTED_USER_ID,
|
||||
libraryId: CRAFTED_LIBRARY_ID,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_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));
|
||||
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());
|
||||
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
|
||||
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
|
||||
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);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetConsumptionStatisticsRequest request)
|
||||
{
|
||||
List<string> 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
|
||||
? WEB_ROUTE
|
||||
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-genre-consumption";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
|
||||
private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetGenreConsumptionEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetGenreConsumption_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/genres?libraryId=lib%3Fx%3D1%26y%3D2";
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
userId: CRAFTED_USER_ID,
|
||||
libraryId: CRAFTED_LIBRARY_ID,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
GenreConsumptionDto[] expectedGenres = [_genreConsumptionDtoFixture.Create()];
|
||||
_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());
|
||||
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
|
||||
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetGenreConsumptionRequest request)
|
||||
{
|
||||
List<string> 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
|
||||
? WEB_ROUTE
|
||||
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetLibrariesEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetLibraries_WhenCalledByAuthenticatedUser_ShouldReturnLibrariesWithoutLeakingSecrets()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
LibraryDto[] expectedLibraries = [_libraryDtoFixture.Create(title: "Books", 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());
|
||||
Assert.Equal(1, json.RootElement.GetProperty("data").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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-most-consumed";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetMostConsumedEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetMostConsumed_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/most-consumed?libraryId=lib%3Fx%3D1%26y%3D2¤tPage=1&perPage=10";
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
userId: CRAFTED_USER_ID,
|
||||
libraryId: CRAFTED_LIBRARY_ID,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(data: [_consumedItemDtoFixture.Create()]);
|
||||
_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());
|
||||
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
|
||||
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetMostConsumedRequest request)
|
||||
{
|
||||
List<string> 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
|
||||
? WEB_ROUTE
|
||||
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.DTO.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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-recently-consumed";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetRecentlyConsumedEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetRecentlyConsumed_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/recently-consumed?libraryId=lib%3Fx%3D1%26y%3D2¤tPage=1&perPage=10";
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
userId: CRAFTED_USER_ID,
|
||||
libraryId: CRAFTED_LIBRARY_ID,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(data: [_consumedItemDtoFixture.Create()]);
|
||||
_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());
|
||||
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
|
||||
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetRecentlyConsumedRequest request)
|
||||
{
|
||||
List<string> 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
|
||||
? WEB_ROUTE
|
||||
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics/api-get-tag-consumption";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new();
|
||||
private readonly TagConsumptionDtoFixture _tagConsumptionDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetTagConsumptionEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetTagConsumption_WithCraftedUserAndLibraryIds_ShouldEscapeTheValuesAndKeepTheDocumentedUpstreamPath()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
const string CRAFTED_USER_ID = "user/../admin?x=1&y=2";
|
||||
const string CRAFTED_LIBRARY_ID = "lib?x=1&y=2";
|
||||
const string EXPECTED_UPSTREAM_PATH = "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/tags?libraryId=lib%3Fx%3D1%26y%3D2";
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
userId: CRAFTED_USER_ID,
|
||||
libraryId: CRAFTED_LIBRARY_ID,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
TagConsumptionDto[] expectedTags = [_tagConsumptionDtoFixture.Create()];
|
||||
_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());
|
||||
string[] dataEndpoints = [.. _apiFactory.ApiClientStub.GetEndpointsCalled.Where(endpoint => endpoint.StartsWith("users/", StringComparison.Ordinal))];
|
||||
Assert.Equal([EXPECTED_UPSTREAM_PATH], dataEndpoints);
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path of the Web route for <paramref name="request"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request whose filters are forwarded.</param>
|
||||
/// <returns>The path of the Web route, including the query string built from the request values.</returns>
|
||||
private static string BuildRequestPath(GetTagConsumptionRequest request)
|
||||
{
|
||||
List<string> 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
|
||||
? WEB_ROUTE
|
||||
: $"{WEB_ROUTE}?{string.Join("&", parameters)}";
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
#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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.GetUsers;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests : IClassFixture<LuminaWebFactory>, 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();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public GetUsersEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
HttpClient client = WebTestHelpers.CreateAnonymousClient(_apiFactory);
|
||||
HttpRequestMessage getRequest = new(HttpMethod.Get, WEB_ROUTE);
|
||||
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||
|
||||
// Act
|
||||
HttpResponseMessage response = await client.SendAsync(getRequest);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
|
||||
Assert.Equal("http://localhost/en-us/auth/login", response.Headers.Location!.ToString());
|
||||
Assert.Empty(_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);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUsers_WhenCalledByAdminUser_ShouldReturnUsersWithoutLeakingCredentials()
|
||||
{
|
||||
// Arrange
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
_apiFactory.ApiClientStub.AuthorizationResponse = _getAuthorizationResponseFixture.Create(userId: Guid.NewGuid(), role: "Admin", permissions: []);
|
||||
UserDto[] expectedUsers = [_userDtoFixture.Create(username: "alice")];
|
||||
_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());
|
||||
Assert.Equal(1, json.RootElement.GetProperty("data").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("password", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("hash", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("salt", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
#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.SecurityTests.Common.Setup;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.SecurityTests.Core.Endpoints.Library.Statistics.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains security tests for the <see cref="StatisticsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StatisticsIndexViewEndpointTests : IClassFixture<LuminaWebFactory>, IDisposable
|
||||
{
|
||||
private const string WEB_ROUTE = "/en-us/library/statistics";
|
||||
|
||||
private readonly LuminaWebFactory _apiFactory;
|
||||
private readonly GetAuthorizationResponseFixture _getAuthorizationResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
/// <param name="apiFactory">Injected Web application factory.</param>
|
||||
public StatisticsIndexViewEndpointTests(LuminaWebFactory apiFactory)
|
||||
{
|
||||
_apiFactory = apiFactory;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StatisticsIndexView_WhenCalledWithoutAuthentication_ShouldRedirectToLoginAndNotCallApi()
|
||||
{
|
||||
// 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_WhenCalledByRegularUser_ShouldHideAdministrativeDataAndNotLeakSecrets()
|
||||
{
|
||||
// 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.DoesNotContain("statistics-user-selector", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("api-get-users", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("auth/users", _apiFactory.ApiClientStub.GetEndpointsCalled);
|
||||
Assert.True(response.Headers.CacheControl?.NoStore);
|
||||
Assert.Contains("Cookie", response.Headers.Vary);
|
||||
Assert.DoesNotContain("test_jwt_token", content, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain("Exception", content, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.DoesNotContain(" at Lumina", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StatisticsIndexView_WhenCalledByAdminUser_ShouldRenderAdministrativeUserSelector()
|
||||
{
|
||||
// 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.Contains("statistics-user-selector", content, StringComparison.Ordinal);
|
||||
Assert.Contains("api-get-users", content, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the resources used by the test class and resets the remote API stub.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
_apiFactory.ApiClientStub.Reset();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaConsumption;
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Fixtures.Common.DTO.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GenreConsumptionDtoMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GenreConsumptionDtoMappingTests
|
||||
{
|
||||
private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenMappingGenreConsumption_ShouldMapAllPropertiesCorrectly()
|
||||
{
|
||||
// Arrange
|
||||
GenreConsumptionDto genreConsumption = _genreConsumptionDtoFixture.Create(
|
||||
name: "science-fiction",
|
||||
consumedItemCount: 17,
|
||||
consumedDurationMilliseconds: 4_500);
|
||||
|
||||
// Act
|
||||
GenreConsumptionResponse result = genreConsumption.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal("science-fiction", result.Name);
|
||||
Assert.Equal(17, result.ConsumedItemCount);
|
||||
Assert.Equal(4.5, result.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponse_WhenDurationExceedsTimeSpanRange_ShouldClampToMaximumRepresentableSeconds()
|
||||
{
|
||||
// Arrange
|
||||
GenreConsumptionDto genreConsumption = _genreConsumptionDtoFixture.Create(consumedDurationMilliseconds: long.MaxValue);
|
||||
double expectedClampedSeconds = TimeSpan.FromMilliseconds(TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond).TotalSeconds;
|
||||
|
||||
// Act
|
||||
GenreConsumptionResponse result = genreConsumption.ToResponse();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(expectedClampedSeconds, result.ConsumedDurationInSeconds);
|
||||
Assert.True(result.ConsumedDurationInSeconds <= TimeSpan.MaxValue.TotalSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenMappingMultipleGenreConsumptions_ShouldMapThemInOrder()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreConsumptionDto> genreConsumptions =
|
||||
[
|
||||
_genreConsumptionDtoFixture.Create(name: "first", consumedItemCount: 1, consumedDurationMilliseconds: 1_000),
|
||||
_genreConsumptionDtoFixture.Create(name: "second", consumedItemCount: 2, consumedDurationMilliseconds: 2_000),
|
||||
_genreConsumptionDtoFixture.Create(name: "third", consumedItemCount: 3, consumedDurationMilliseconds: 3_000)
|
||||
];
|
||||
|
||||
// Act
|
||||
IReadOnlyList<GenreConsumptionResponse> result = genreConsumptions.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.Equal(3, result.Count);
|
||||
Assert.Equal("first", result[0].Name);
|
||||
Assert.Equal(1, result[0].ConsumedItemCount);
|
||||
Assert.Equal(1.0, result[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal("second", result[1].Name);
|
||||
Assert.Equal(2, result[1].ConsumedItemCount);
|
||||
Assert.Equal(2.0, result[1].ConsumedDurationInSeconds);
|
||||
Assert.Equal("third", result[2].Name);
|
||||
Assert.Equal(3, result[2].ConsumedItemCount);
|
||||
Assert.Equal(3.0, result[2].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToResponses_WhenInputIsEmpty_ShouldReturnAnEmptyList()
|
||||
{
|
||||
// Arrange
|
||||
List<GenreConsumptionDto> genreConsumptions = [];
|
||||
|
||||
// Act
|
||||
IReadOnlyList<GenreConsumptionResponse> result = genreConsumptions.ToResponses();
|
||||
|
||||
// Assert
|
||||
Assert.Empty(result);
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Common.Mapping.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionRequestMapping"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionRequestMappingTests
|
||||
{
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionRequestMappingTests"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionRequestMappingTests()
|
||||
{
|
||||
_getGenreConsumptionRequestFixture = new GetGenreConsumptionRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMappingPopulatedRequest_ShouldMapEveryRequestField()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string mediaKind = nameof(MediaKind.Book);
|
||||
string fromUtc = "2025-01-02T03:04:05.0000000Z";
|
||||
string toUtc = "2025-02-03T04:05:06.0000000Z";
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionQuery result = request.ToQuery(targetUserId.ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Equal(targetUserId.ToString(), result.TargetUserId);
|
||||
Assert.Equal(libraryId, result.LibraryId);
|
||||
Assert.Equal(mediaKind, result.MediaKind);
|
||||
Assert.Equal(fromUtc, result.FromUtc);
|
||||
Assert.Equal(toUtc, result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenTargetUserIdIsNull_ShouldMapNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionQuery result = request.ToQuery(null);
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.TargetUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.FromUtc);
|
||||
Assert.NotNull(result.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ToQuery_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionQuery result = request.ToQuery(Guid.NewGuid().ToString());
|
||||
|
||||
// Assert
|
||||
Assert.Null(result.ToUtc);
|
||||
Assert.NotNull(result.FromUtc);
|
||||
}
|
||||
}
|
||||
+286
@@ -0,0 +1,286 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
using Lumina.Application.Fixtures.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteConsumptionItemHistoryCommandHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryCommandHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IMediaConsumptionRecordRepository _mockMediaConsumptionRecordRepository;
|
||||
private readonly IMediaResumePointRepository _mockMediaResumePointRepository;
|
||||
private readonly IValidator<DeleteConsumptionItemHistoryCommand> _mockValidator;
|
||||
private readonly DeleteConsumptionItemHistoryCommandHandler _sut;
|
||||
private readonly DeleteConsumptionItemHistoryCommandFixture _deleteConsumptionItemHistoryCommandFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryCommandHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteConsumptionItemHistoryCommandHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_mockMediaConsumptionRecordRepository = Substitute.For<IMediaConsumptionRecordRepository>();
|
||||
_mockMediaResumePointRepository = Substitute.For<IMediaResumePointRepository>();
|
||||
|
||||
_mockUnitOfWork.MediaConsumptionRecordRepository.Returns(_mockMediaConsumptionRecordRepository);
|
||||
_mockUnitOfWork.MediaResumePointRepository.Returns(_mockMediaResumePointRepository);
|
||||
// Default stubs: saving changes succeeds, the current user is authenticated, the target is accessible and the records are deleted.
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(Result.Success);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockMediaConsumptionRecordRepository.DeleteAllByMediaItemIdForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.Deleted);
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<DeleteConsumptionItemHistoryCommand>>();
|
||||
_mockValidator.Validate(Arg.Any<DeleteConsumptionItemHistoryCommand>()).Returns([]);
|
||||
|
||||
_sut = new DeleteConsumptionItemHistoryCommandHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotDeleteAnything()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<DeleteConsumptionItemHistoryCommand>())
|
||||
.Returns([DomainErrors.MediaConsumption.MediaItemIdCannotBeEmpty]);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.MediaConsumption.MediaItemIdCannotBeEmpty, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.DidNotReceive().DeleteAllByMediaItemIdForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotDeleteAnything()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.DidNotReceive().DeleteAllByMediaItemIdForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesAccessToTheTarget_ShouldReturnNotAuthorizedAndNotDeleteAnything()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create();
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
_userId,
|
||||
Arg.Is<ConsumptionActivityAccessPolicyContext>(context => context.TargetUserId == Guid.Parse(command.TargetUserId!)),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.DidNotReceive().DeleteAllByMediaItemIdForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheRecordsCannotBeDeleted_ShouldReturnThatErrorAndNotSaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The consumption records could not be deleted.");
|
||||
_mockMediaConsumptionRecordRepository.DeleteAllByMediaItemIdForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSaveChangesFails_ShouldReturnThatError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create();
|
||||
Error error = ApplicationErrors.Persistence.ConcurrencyConflict;
|
||||
_mockUnitOfWork.SaveChangesAsync(Arg.Any<CancellationToken>()).Returns(error);
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheTargetUserIsNotSupplied_ShouldDeleteTheHistoryOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(
|
||||
includeTargetUserId: false,
|
||||
mediaKind: nameof(MediaKind.Movie),
|
||||
mediaItemId: mediaItemId.ToString(),
|
||||
libraryId: libraryId.ToString());
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
_userId,
|
||||
Arg.Is<ConsumptionActivityAccessPolicyContext>(context => context.TargetUserId == _userId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.Received(1).DeleteAllByMediaItemIdForUserAsync(
|
||||
_userId,
|
||||
MediaKind.Movie,
|
||||
mediaItemId,
|
||||
libraryId,
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheTargetUserIsSupplied_ShouldDeleteTheHistoryOfTheTargetUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(
|
||||
targetUserId: targetUserId.ToString(),
|
||||
mediaKind: nameof(MediaKind.Book),
|
||||
mediaItemId: mediaItemId.ToString(),
|
||||
libraryId: libraryId.ToString());
|
||||
|
||||
// Act
|
||||
Result<Deleted> result = await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(Result.Deleted, result.Value);
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
_userId,
|
||||
Arg.Is<ConsumptionActivityAccessPolicyContext>(context => context.TargetUserId == targetUserId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.Received(1).DeleteAllByMediaItemIdForUserAsync(
|
||||
targetUserId,
|
||||
MediaKind.Book,
|
||||
mediaItemId,
|
||||
libraryId,
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.DidNotReceive().DeleteAllByMediaItemIdForUserAsync(
|
||||
_userId, Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldNotUseAnyOtherRepository()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(includeTargetUserId: false);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockMediaConsumptionRecordRepository.DidNotReceive().DeleteForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaConsumptionRecordRepository.DidNotReceive().DeleteAllForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteForUserAndMediaItemAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<MediaKind>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteAllForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
await _mockMediaResumePointRepository.DidNotReceive().DeleteAllForUserInLibraryAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCalled_ShouldForwardTheCancellationTokenToEveryDependency()
|
||||
{
|
||||
// Arrange
|
||||
Guid mediaItemId = Guid.NewGuid();
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(
|
||||
includeTargetUserId: false,
|
||||
mediaKind: nameof(MediaKind.TvEpisode),
|
||||
mediaItemId: mediaItemId.ToString(),
|
||||
libraryId: libraryId.ToString());
|
||||
using CancellationTokenSource cancellationTokenSource = new();
|
||||
CancellationToken cancellationToken = cancellationTokenSource.Token;
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(command, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
_userId,
|
||||
Arg.Any<ConsumptionActivityAccessPolicyContext>(),
|
||||
Arg.Is(cancellationToken));
|
||||
await _mockMediaConsumptionRecordRepository.Received(1).DeleteAllByMediaItemIdForUserAsync(
|
||||
_userId,
|
||||
MediaKind.TvEpisode,
|
||||
mediaItemId,
|
||||
libraryId,
|
||||
Arg.Is(cancellationToken));
|
||||
await _mockUnitOfWork.Received(1).SaveChangesAsync(Arg.Is(cancellationToken));
|
||||
}
|
||||
}
|
||||
+214
@@ -0,0 +1,214 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
using Lumina.Application.Fixtures.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteConsumptionItemHistoryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryCommandValidatorTests
|
||||
{
|
||||
private readonly DeleteConsumptionItemHistoryCommandValidator _validator = new();
|
||||
private readonly DeleteConsumptionItemHistoryCommandFixture _deleteConsumptionItemHistoryCommandFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTargetUserIdIsNotSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(includeTargetUserId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the target user Id is empty
|
||||
[InlineData(" ")] // the target user Id is whitespace only
|
||||
[InlineData("not-a-guid")] // the target user Id is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // the target user Id is the empty Guid
|
||||
public void Validate_WhenTargetUserIdIsEmptyOrInvalid_ShouldHaveValidationError(string targetUserId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(targetUserId: targetUserId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTargetUserIdIsAValidGuid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(targetUserId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the media kind is empty
|
||||
[InlineData(" ")] // the media kind is whitespace only
|
||||
[InlineData("not-a-media-kind")] // the media kind is not a member name
|
||||
[InlineData("999")] // the media kind is numeric, which must not be accepted as a member name
|
||||
[InlineData("None")] // None is not a valid media kind for a consumption record
|
||||
public void Validate_WhenMediaKindIsInvalid_ShouldHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(MediaKind.MusicTrack))] // a kind supported by the current catalogues
|
||||
[InlineData(nameof(MediaKind.Book))] // another kind supported by the current catalogues
|
||||
[InlineData(nameof(MediaKind.Movie))] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(nameof(MediaKind.Photo))] // a kind that every session counts for, still a defined kind
|
||||
[InlineData("musicTrack")] // member names are matched case-insensitively
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(includeMediaItemId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the media item Id is empty
|
||||
[InlineData(" ")] // the media item Id is whitespace only
|
||||
[InlineData("not-a-guid")] // the media item Id is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // the media item Id is the empty Guid
|
||||
public void Validate_WhenMediaItemIdIsEmptyOrInvalid_ShouldHaveValidationError(string mediaItemId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(mediaItemId: mediaItemId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaItemIdIsAValidGuid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(mediaItemId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNotSupplied_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the library Id is empty
|
||||
[InlineData(" ")] // the library Id is whitespace only
|
||||
[InlineData("not-a-guid")] // the library Id is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // the library Id is the empty Guid
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string libraryId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsAValidGuid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create(libraryId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenCommandIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryCommand command = _deleteConsumptionItemHistoryCommandFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(command);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+998
@@ -0,0 +1,998 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
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.Repositories.BookLibrary;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
|
||||
using Lumina.Application.Common.DataAccess.UoW;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
|
||||
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
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.WrittenContentLibrary.BookLibrary;
|
||||
using Lumina.Application.Fixtures.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionQueryHandler"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionQueryHandlerTests
|
||||
{
|
||||
private readonly IUnitOfWork _mockUnitOfWork;
|
||||
private readonly IConsumptionStatisticsRepository _mockConsumptionStatisticsRepository;
|
||||
private readonly ITrackRepository _mockTrackRepository;
|
||||
private readonly IBookRepository _mockBookRepository;
|
||||
private readonly ICurrentUserService _mockCurrentUserService;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly IValidator<GetGenreConsumptionQuery> _mockValidator;
|
||||
private readonly GetGenreConsumptionQueryHandler _sut;
|
||||
private readonly GetGenreConsumptionQueryFixture _getGenreConsumptionQueryFixture = new();
|
||||
private readonly MediaConsumptionRecordEntityFixture _mediaConsumptionRecordEntityFixture = new();
|
||||
private readonly TrackEntityFixture _trackEntityFixture = new();
|
||||
private readonly AlbumEntityFixture _albumEntityFixture = new();
|
||||
private readonly ArtistEntityFixture _artistEntityFixture = new();
|
||||
private readonly BookEntityFixture _bookEntityFixture = new();
|
||||
private readonly GenreEntityFixture _genreEntityFixture = new();
|
||||
private readonly Guid _userId = Guid.NewGuid();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionQueryHandlerTests"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionQueryHandlerTests()
|
||||
{
|
||||
_mockUnitOfWork = Substitute.For<IUnitOfWork>();
|
||||
_mockConsumptionStatisticsRepository = Substitute.For<IConsumptionStatisticsRepository>();
|
||||
_mockTrackRepository = Substitute.For<ITrackRepository>();
|
||||
_mockBookRepository = Substitute.For<IBookRepository>();
|
||||
_mockCurrentUserService = Substitute.For<ICurrentUserService>();
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
|
||||
_mockUnitOfWork.ConsumptionStatisticsRepository.Returns(_mockConsumptionStatisticsRepository);
|
||||
_mockUnitOfWork.TrackRepository.Returns(_mockTrackRepository);
|
||||
_mockUnitOfWork.BookRepository.Returns(_mockBookRepository);
|
||||
_mockCurrentUserService.UserId.Returns(_userId);
|
||||
// Default stubs: the current user can read both the consumption activity and every library, and no item exists.
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(true);
|
||||
StubRecords();
|
||||
StubTracks();
|
||||
StubBooks();
|
||||
|
||||
_mockValidator = Substitute.For<IValidator<GetGenreConsumptionQuery>>();
|
||||
_mockValidator.Validate(Arg.Any<GetGenreConsumptionQuery>()).Returns([]);
|
||||
|
||||
_sut = new GetGenreConsumptionQueryHandler(_mockUnitOfWork, _mockCurrentUserService, _mockAuthorizationService, _mockValidator);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenValidatorReturnsError_ShouldReturnValidationErrorAndNotReadRecords()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
_mockValidator.Validate(Arg.Any<GetGenreConsumptionQuery>())
|
||||
.Returns([DomainErrors.MediaConsumption.TargetUserIdIsInvalid]);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(DomainErrors.MediaConsumption.TargetUserIdIsInvalid, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockConsumptionStatisticsRepository.DidNotReceive().GetForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>());
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenCurrentUserIsNull_ShouldReturnNotAuthorizedAndNotReadRecords()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
_mockCurrentUserService.UserId.Returns((Guid?)null);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockAuthorizationService.DidNotReceive().EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
await _mockConsumptionStatisticsRepository.DidNotReceive().GetForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenPolicyDeniesTheTarget_ShouldReturnNotAuthorizedAndNotReadRecords()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
Arg.Any<Guid>(), Arg.Any<ConsumptionActivityAccessPolicyContext>(), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(ApplicationErrors.Authorization.NotAuthorized, result.FirstError);
|
||||
await _mockConsumptionStatisticsRepository.DidNotReceive().GetForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheRecordsCannotBeRead_ShouldReturnTheRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
Error error = Error.Failure("Persistence.Failure", "The consumption records could not be read.");
|
||||
_mockConsumptionStatisticsRepository.GetForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenThereAreNoRecords_ShouldReturnAnEmptyListAndNotReadTheCatalogues()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
await _mockTrackRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheTargetUserIsNotSupplied_ShouldReadTheStatisticsOfTheCurrentUser()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(includeTargetUserId: false);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
_userId,
|
||||
Arg.Is<ConsumptionActivityAccessPolicyContext>(context => context.TargetUserId == _userId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForUserAsync(
|
||||
_userId, Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheTargetUserIsSupplied_ShouldEvaluateThePolicyAndReadTheStatisticsOfTheTargetUser()
|
||||
{
|
||||
// Arrange
|
||||
Guid targetUserId = Guid.NewGuid();
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(targetUserId: targetUserId.ToString());
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
|
||||
_userId,
|
||||
Arg.Is<ConsumptionActivityAccessPolicyContext>(context => context.TargetUserId == targetUserId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForUserAsync(
|
||||
targetUserId, Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheQueryIsFiltered_ShouldForwardTheParsedFiltersToTheRecordsRepository()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
DateTime fromUtc = new(2025, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
DateTime toUtc = new(2025, 2, 3, 4, 5, 6, DateTimeKind.Utc);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(
|
||||
includeTargetUserId: false,
|
||||
libraryId: libraryId.ToString(),
|
||||
mediaKind: nameof(MediaKind.Book),
|
||||
fromUtc: fromUtc.ToString("o", CultureInfo.InvariantCulture),
|
||||
toUtc: toUtc.ToString("o", CultureInfo.InvariantCulture));
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForUserAsync(
|
||||
_userId,
|
||||
Arg.Is<Guid?>(value => value == libraryId),
|
||||
Arg.Is<MediaKind?>(value => value == MediaKind.Book),
|
||||
Arg.Is<DateTime?>(value => value == fromUtc),
|
||||
Arg.Is<DateTime?>(value => value == toUtc),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenRecordsSpanSeveralLibraries_ShouldEvaluateTheLibraryAccessOncePerDistinctLibrary()
|
||||
{
|
||||
// Arrange
|
||||
Guid firstLibraryId = Guid.NewGuid();
|
||||
Guid secondLibraryId = Guid.NewGuid();
|
||||
StubRecords(
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
libraryId: firstLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
libraryId: firstLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
libraryId: secondLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == firstLibraryId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.Received(1).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == secondLibraryId),
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockAuthorizationService.Received(2).EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Any<LibraryOwnershipPolicyContext>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAccessibleItemsExist_ShouldEvaluateTheLibraryAccessBeforeReadingTheCatalogues()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Received.InOrder(() =>
|
||||
{
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId,
|
||||
Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == libraryId),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockTrackRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), true, Arg.Any<CancellationToken>());
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAnItemIsInAnInaccessibleLibrary_ShouldExcludeItsGenresWithoutReadingThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid accessibleLibraryId = Guid.NewGuid();
|
||||
Guid inaccessibleLibraryId = Guid.NewGuid();
|
||||
Guid accessibleTrackId = Guid.NewGuid();
|
||||
Guid inaccessibleTrackId = Guid.NewGuid();
|
||||
TrackEntity accessibleTrack = _trackEntityFixture.Create(id: accessibleTrackId, libraryId: accessibleLibraryId, includeMetadata: false);
|
||||
accessibleTrack.Genres = [_genreEntityFixture.Create(name: "jazz")];
|
||||
TrackEntity inaccessibleTrack = _trackEntityFixture.Create(id: inaccessibleTrackId, libraryId: inaccessibleLibraryId, includeMetadata: false);
|
||||
inaccessibleTrack.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: accessibleTrackId,
|
||||
libraryId: accessibleLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: inaccessibleTrackId,
|
||||
libraryId: inaccessibleLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(accessibleTrack, inaccessibleTrack);
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == inaccessibleLibraryId), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("jazz", genre.Name);
|
||||
await _mockTrackRepository.Received(1).GetByIdsAsync(
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(ids => ids.Count == 1 && ids.Contains(accessibleTrackId)),
|
||||
true,
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenATrackHasGenres_ShouldUseTheTrackGenresInsteadOfTheAlbumAndArtistGenres()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
artist.Genres = [_genreEntityFixture.Create(name: "artistgenre")];
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Artist = artist;
|
||||
album.Genres = [_genreEntityFixture.Create(name: "albumgenre")];
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Album = album;
|
||||
track.Genres = [_genreEntityFixture.Create(name: "trackgenre")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("trackgenre", genre.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenATrackHasNoGenresOfItsOwn_ShouldFallBackToItsAlbumGenres()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
artist.Genres = [_genreEntityFixture.Create(name: "artistgenre")];
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Artist = artist;
|
||||
album.Genres = [_genreEntityFixture.Create(name: "albumgenre")];
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Album = album;
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("albumgenre", genre.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenATrackAndItsAlbumHaveNoGenres_ShouldFallBackToItsArtistGenres()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
ArtistEntity artist = _artistEntityFixture.Create(libraryId: libraryId, includeAlbums: false, includeContributors: false);
|
||||
artist.Genres = [_genreEntityFixture.Create(name: "artistgenre")];
|
||||
AlbumEntity album = _albumEntityFixture.Create(libraryId: libraryId, includeTracks: false, includeMetadata: false);
|
||||
album.Artist = artist;
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Album = album;
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("artistgenre", genre.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenATrackHasNoGenresAtAnyLevel_ShouldExcludeTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenABookHasGenres_ShouldUseTheBookGenres()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
book.Genres = [_genreEntityFixture.Create(name: "fantasy")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: bookId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 2_500,
|
||||
consecutivePagesRead: 0));
|
||||
StubBooks(book);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("fantasy", genre.Name);
|
||||
Assert.Equal(1, genre.ConsumedItemCount);
|
||||
Assert.Equal(2.5, genre.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenABookHasNoGenres_ShouldExcludeTheRecord()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: bookId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000,
|
||||
consecutivePagesRead: 6));
|
||||
StubBooks(book);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGenreNamesDifferInCasingAndWhitespace_ShouldTrimLowercaseAndCountEachNameOncePerItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres =
|
||||
[
|
||||
_genreEntityFixture.Create(name: "rock"),
|
||||
_genreEntityFixture.Create(name: "ROCK"),
|
||||
_genreEntityFixture.Create(name: " Rock "),
|
||||
_genreEntityFixture.Create(name: "jazz")
|
||||
];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(2, result.Value.Count);
|
||||
Assert.Equal("jazz", result.Value[0].Name);
|
||||
Assert.Equal(1, result.Value[0].ConsumedItemCount);
|
||||
Assert.Equal(1.0, result.Value[0].ConsumedDurationInSeconds);
|
||||
Assert.Equal("rock", result.Value[1].Name);
|
||||
Assert.Equal(1, result.Value[1].ConsumedItemCount);
|
||||
Assert.Equal(1.0, result.Value[1].ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenGenreNamesAreMissingOrBlank_ShouldSkipThem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres =
|
||||
[
|
||||
_genreEntityFixture.Create(includeName: false),
|
||||
_genreEntityFixture.Create(name: string.Empty),
|
||||
_genreEntityFixture.Create(name: " "),
|
||||
_genreEntityFixture.Create(name: "rock")
|
||||
];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("rock", genre.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAnItemHasSeveralCountedSessions_ShouldCountItOnceAndSumTheirDurations()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 2_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("rock", genre.Name);
|
||||
Assert.Equal(1, genre.ConsumedItemCount);
|
||||
Assert.Equal(3.0, genre.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenATrackSessionIsStoppedBelowTheMinimumDuration_ShouldExcludeTheItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Stopped,
|
||||
consumedDurationMilliseconds: 29_999));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenABookSessionReadsAtMostTheMinimumConsecutivePages_ShouldExcludeTheItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
BookEntity book = _bookEntityFixture.Create(id: bookId, libraryId: libraryId, includeMetadata: false);
|
||||
book.Genres = [_genreEntityFixture.Create(name: "fantasy")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: bookId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Stopped,
|
||||
consumedDurationMilliseconds: 1_000,
|
||||
consecutivePagesRead: 5));
|
||||
StubBooks(book);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenASessionIsCompleted_ShouldCountTheItemRegardlessOfTheThreshold()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 0));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
GenreConsumptionResponse genre = Assert.Single(result.Value);
|
||||
Assert.Equal("rock", genre.Name);
|
||||
Assert.Equal(1, genre.ConsumedItemCount);
|
||||
Assert.Equal(0.0, genre.ConsumedDurationInSeconds);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAnItemIsResolvedInAnotherLibraryThanTheRecord_ShouldExcludeTheItem()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: Guid.NewGuid(), includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Empty(result.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSeveralGenresExist_ShouldOrderThemByCountThenDurationThenName()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid firstTrackId = Guid.NewGuid();
|
||||
Guid secondTrackId = Guid.NewGuid();
|
||||
Guid thirdTrackId = Guid.NewGuid();
|
||||
TrackEntity firstTrack = _trackEntityFixture.Create(id: firstTrackId, libraryId: libraryId, includeMetadata: false);
|
||||
firstTrack.Genres = [_genreEntityFixture.Create(name: "alpha"), _genreEntityFixture.Create(name: "beta")];
|
||||
TrackEntity secondTrack = _trackEntityFixture.Create(id: secondTrackId, libraryId: libraryId, includeMetadata: false);
|
||||
secondTrack.Genres = [_genreEntityFixture.Create(name: "alpha")];
|
||||
TrackEntity thirdTrack = _trackEntityFixture.Create(id: thirdTrackId, libraryId: libraryId, includeMetadata: false);
|
||||
thirdTrack.Genres = [_genreEntityFixture.Create(name: "gamma"), _genreEntityFixture.Create(name: "delta")];
|
||||
StubRecords(
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: firstTrackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 400),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: secondTrackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 600),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: thirdTrackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 5_000));
|
||||
StubTracks(firstTrack, secondTrack, thirdTrack);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Equal(["alpha", "delta", "gamma", "beta"], result.Value.Select(genre => genre.Name));
|
||||
Assert.Equal([2, 1, 1, 1], result.Value.Select(genre => genre.ConsumedItemCount));
|
||||
Assert.Equal([1.0, 5.0, 5.0, 0.4], result.Value.Select(genre => genre.ConsumedDurationInSeconds));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenItemsExist_ShouldReadTheDistinctIdsOfAccessibleItemsWithNavigationProperties()
|
||||
{
|
||||
// Arrange
|
||||
Guid accessibleLibraryId = Guid.NewGuid();
|
||||
Guid inaccessibleLibraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
StubRecords(
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: accessibleLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: accessibleLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 2_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: Guid.NewGuid(),
|
||||
libraryId: inaccessibleLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000),
|
||||
_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: bookId,
|
||||
libraryId: accessibleLibraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000,
|
||||
consecutivePagesRead: 6));
|
||||
_mockAuthorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
|
||||
_userId, Arg.Is<LibraryOwnershipPolicyContext>(context => context.LibraryId == inaccessibleLibraryId), Arg.Any<CancellationToken>())
|
||||
.Returns(false);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockTrackRepository.Received(1).GetByIdsAsync(
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(ids => ids.Count == 1 && ids.Contains(trackId)),
|
||||
true,
|
||||
Arg.Any<CancellationToken>());
|
||||
await _mockBookRepository.Received(1).GetByIdsAsync(
|
||||
Arg.Is<IReadOnlyCollection<Guid>>(ids => ids.Count == 1 && ids.Contains(bookId)),
|
||||
true,
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheTracksCannotBeRead_ShouldReturnTheRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
Error error = Error.Failure("Persistence.Failure", "The tracks could not be read.");
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
_mockTrackRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
await _mockBookRepository.DidNotReceive().GetByIdsAsync(
|
||||
Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheBooksCannotBeRead_ShouldReturnTheRepositoryError()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid bookId = Guid.NewGuid();
|
||||
Error error = Error.Failure("Persistence.Failure", "The books could not be read.");
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: bookId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000,
|
||||
consecutivePagesRead: 6));
|
||||
_mockBookRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(error);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.True(result.IsFailure);
|
||||
Assert.Equal(error, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenSuccessful_ShouldNotSaveChanges()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
Guid trackId = Guid.NewGuid();
|
||||
TrackEntity track = _trackEntityFixture.Create(id: trackId, libraryId: libraryId, includeMetadata: false);
|
||||
track.Genres = [_genreEntityFixture.Create(name: "rock")];
|
||||
StubRecords(_mediaConsumptionRecordEntityFixture.Create(
|
||||
userId: _userId,
|
||||
mediaKind: MediaKind.MusicTrack,
|
||||
mediaItemId: trackId,
|
||||
libraryId: libraryId,
|
||||
status: ConsumptionStatus.Completed,
|
||||
consumedDurationMilliseconds: 1_000));
|
||||
StubTracks(track);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
Result<IReadOnlyList<GenreConsumptionResponse>> result = await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.False(result.IsFailure);
|
||||
Assert.Single(result.Value);
|
||||
await _mockUnitOfWork.DidNotReceive().SaveChangesAsync(Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the consumption statistics repository so that it returns the provided records.
|
||||
/// </summary>
|
||||
/// <param name="records">The records returned by the repository.</param>
|
||||
private void StubRecords(params MediaConsumptionRecordEntity[] records)
|
||||
{
|
||||
_mockConsumptionStatisticsRepository.GetForUserAsync(
|
||||
Arg.Any<Guid>(), Arg.Any<Guid?>(), Arg.Any<MediaKind?>(), Arg.Any<DateTime?>(), Arg.Any<DateTime?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<MediaConsumptionRecordEntity>>(records));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the track repository so that it returns the provided tracks.
|
||||
/// </summary>
|
||||
/// <param name="tracks">The tracks returned by the repository.</param>
|
||||
private void StubTracks(params TrackEntity[] tracks)
|
||||
{
|
||||
_mockTrackRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<TrackEntity>>(tracks));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stubs the book repository so that it returns the provided books.
|
||||
/// </summary>
|
||||
/// <param name="books">The books returned by the repository.</param>
|
||||
private void StubBooks(params BookEntity[] books)
|
||||
{
|
||||
_mockBookRepository.GetByIdsAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<bool>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<BookEntity>>(books));
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Application.Fixtures.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Application.UnitTests.Common.Setup;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.UnitTests.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionQueryValidator"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionQueryValidatorTests
|
||||
{
|
||||
private readonly GetGenreConsumptionQueryValidator _validator = new();
|
||||
private readonly GetGenreConsumptionQueryFixture _getGenreConsumptionQueryFixture = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTargetUserIdIsNotSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(includeTargetUserId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the target user Id is empty
|
||||
[InlineData(" ")] // the target user Id is whitespace only
|
||||
[InlineData("not-a-guid")] // the target user Id is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // the target user Id is the empty Guid
|
||||
public void Validate_WhenTargetUserIdIsEmptyOrInvalid_ShouldHaveValidationError(string targetUserId)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(targetUserId: targetUserId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTargetUserIdIsAValidGuid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(targetUserId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.TargetUserIdIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsNotSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the library Id is empty
|
||||
[InlineData(" ")] // the library Id is whitespace only
|
||||
[InlineData("not-a-guid")] // the library Id is not a Guid
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")] // the library Id is the empty Guid
|
||||
public void Validate_WhenLibraryIdIsEmptyOrInvalid_ShouldHaveValidationError(string libraryId)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenLibraryIdIsAValidGuid_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(libraryId: Guid.NewGuid().ToString());
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenMediaKindIsNotSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")] // the media kind is empty
|
||||
[InlineData(" ")] // the media kind is whitespace only
|
||||
[InlineData("not-a-media-kind")] // the media kind is not a member name
|
||||
[InlineData("999")] // the media kind is numeric, which must not be accepted as a member name
|
||||
[InlineData("None")] // None is not a valid media kind for a consumption record
|
||||
public void Validate_WhenMediaKindIsInvalid_ShouldHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(nameof(MediaKind.MusicTrack))] // a kind supported by the current catalogues
|
||||
[InlineData(nameof(MediaKind.Book))] // another kind supported by the current catalogues
|
||||
[InlineData(nameof(MediaKind.Movie))] // a kind without a catalogue, still a defined kind
|
||||
[InlineData(nameof(MediaKind.Photo))] // a kind that every session counts for, still a defined kind
|
||||
[InlineData("musicTrack")] // member names are matched case-insensitively
|
||||
public void Validate_WhenMediaKindIsDefined_ShouldNotHaveValidationError(string mediaKind)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-date")] // the start is not a date
|
||||
[InlineData("2026-13-01T00:00:00Z")] // the start is a date with an out of range month
|
||||
public void Validate_WhenFromUtcIsMalformed_ShouldHaveValidationError(string fromUtc)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-date")] // the end is not a date
|
||||
[InlineData("2026-13-01T00:00:00Z")] // the end is a date with an out of range month
|
||||
public void Validate_WhenToUtcIsMalformed_ShouldHaveValidationError(string toUtc)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(
|
||||
toUtc: toUtc,
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOnlyTheStartOfTheDateRangeIsSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(
|
||||
fromUtc: new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc).ToString("o", CultureInfo.InvariantCulture),
|
||||
includeToUtc: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenOnlyTheEndOfTheDateRangeIsSupplied_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(
|
||||
toUtc: new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc).ToString("o", CultureInfo.InvariantCulture),
|
||||
includeFromUtc: false);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenBothDateRangeBoundsAreEqual_ShouldNotHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
string bound = new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc).ToString("o", CultureInfo.InvariantCulture);
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(fromUtc: bound, toUtc: bound);
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenTheDateRangeIsInverted_ShouldHaveValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create(
|
||||
fromUtc: new DateTime(2026, 3, 2, 0, 0, 0, DateTimeKind.Utc).ToString("o", CultureInfo.InvariantCulture),
|
||||
toUtc: new DateTime(2026, 3, 1, 0, 0, 0, DateTimeKind.Utc).ToString("o", CultureInfo.InvariantCulture));
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldHaveValidationError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Validate_WhenQueryIsValid_ShouldNotHaveAnyValidationError()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionQuery query = _getGenreConsumptionQueryFixture.Create();
|
||||
|
||||
// Act
|
||||
List<Error> result = _validator.TestValidate(query);
|
||||
|
||||
// Assert
|
||||
result.ShouldNotHaveAnyValidationErrors();
|
||||
}
|
||||
}
|
||||
+29
@@ -191,6 +191,35 @@ public class GetMostConsumedQueryHandlerTests
|
||||
Assert.Equal(error, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheQueryIsFiltered_ShouldForwardTheParsedFiltersToTheRecordsRepository()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
DateTime expectedFromUtc = new(2025, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
DateTime expectedToUtc = new(2025, 2, 3, 4, 5, 6, DateTimeKind.Utc);
|
||||
GetMostConsumedQuery query = _getMostConsumedQueryFixture.Create(
|
||||
includeTargetUserId: false,
|
||||
libraryId: libraryId.ToString(),
|
||||
mediaKind: nameof(MediaKind.Book),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForUserAsync(
|
||||
_userId,
|
||||
Arg.Is<Guid?>(value => value == libraryId),
|
||||
Arg.Is<MediaKind?>(value => value == MediaKind.Book),
|
||||
Arg.Is<DateTime?>(value => value == expectedFromUtc),
|
||||
Arg.Is<DateTime?>(value => value == expectedToUtc),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAnItemHasSeveralSessions_ShouldAggregateThemIntoOneRow()
|
||||
{
|
||||
|
||||
+29
@@ -191,6 +191,35 @@ public class GetRecentlyConsumedQueryHandlerTests
|
||||
Assert.Equal(error, result.FirstError);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenTheQueryIsFiltered_ShouldForwardTheParsedFiltersToTheRecordsRepository()
|
||||
{
|
||||
// Arrange
|
||||
Guid libraryId = Guid.NewGuid();
|
||||
string fromUtc = "2025-01-02T03:04:05Z";
|
||||
string toUtc = "2025-02-03T04:05:06Z";
|
||||
DateTime expectedFromUtc = new(2025, 1, 2, 3, 4, 5, DateTimeKind.Utc);
|
||||
DateTime expectedToUtc = new(2025, 2, 3, 4, 5, 6, DateTimeKind.Utc);
|
||||
GetRecentlyConsumedQuery query = _getRecentlyConsumedQueryFixture.Create(
|
||||
includeTargetUserId: false,
|
||||
libraryId: libraryId.ToString(),
|
||||
mediaKind: nameof(MediaKind.Book),
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Act
|
||||
await _sut.HandleAsync(query, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockConsumptionStatisticsRepository.Received(1).GetForUserAsync(
|
||||
_userId,
|
||||
Arg.Is<Guid?>(value => value == libraryId),
|
||||
Arg.Is<MediaKind?>(value => value == MediaKind.Book),
|
||||
Arg.Is<DateTime?>(value => value == expectedFromUtc),
|
||||
Arg.Is<DateTime?>(value => value == expectedToUtc),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HandleAsync_WhenAnItemHasSeveralSessions_ShouldAggregateThemIntoOneRow()
|
||||
{
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteConsumptionItemHistoryRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryRequestTests
|
||||
{
|
||||
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryRequestTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteConsumptionItemHistoryRequestTests()
|
||||
{
|
||||
_deleteConsumptionItemHistoryRequestFixture = new DeleteConsumptionItemHistoryRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
DeleteConsumptionItemHistoryRequest sut = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.True(Enum.TryParse(sut.MediaKind, ignoreCase: true, out MediaKind parsedMediaKind));
|
||||
Assert.NotEqual(MediaKind.None, parsedMediaKind);
|
||||
Assert.True(Enum.IsDefined(parsedMediaKind));
|
||||
Assert.NotNull(sut.MediaItemId);
|
||||
Assert.True(Guid.TryParse(sut.MediaItemId, out Guid parsedMediaItemId));
|
||||
Assert.NotEqual(Guid.Empty, parsedMediaItemId);
|
||||
Assert.NotNull(sut.LibraryId);
|
||||
Assert.True(Guid.TryParse(sut.LibraryId, out Guid parsedLibraryId));
|
||||
Assert.NotEqual(Guid.Empty, parsedLibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string mediaKind = nameof(MediaKind.Book);
|
||||
string mediaItemId = Guid.NewGuid().ToString();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
DeleteConsumptionItemHistoryRequest sut = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
libraryId: libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(mediaKind, sut.MediaKind);
|
||||
Assert.Equal(mediaItemId, sut.MediaItemId);
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("None")] // None is not a valid media kind for a consumption record
|
||||
[InlineData("999")] // a numeric value that is not a member name
|
||||
[InlineData("not-a-media-kind")] // a textual value that is not a member name
|
||||
[InlineData("")] // an empty media kind
|
||||
public void Constructor_WhenMediaKindIsInvalid_ShouldPreserveItForTheValidator(string mediaKind)
|
||||
{
|
||||
// Act
|
||||
DeleteConsumptionItemHistoryRequest sut = _deleteConsumptionItemHistoryRequestFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(mediaKind, sut.MediaKind);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("not-a-guid")]
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")]
|
||||
public void Constructor_WhenMediaItemIdIsInvalid_ShouldPreserveItForTheValidator(string mediaItemId)
|
||||
{
|
||||
// Act
|
||||
DeleteConsumptionItemHistoryRequest sut = _deleteConsumptionItemHistoryRequestFixture.Create(mediaItemId: mediaItemId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(mediaItemId, sut.MediaItemId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("not-a-guid")]
|
||||
[InlineData("00000000-0000-0000-0000-000000000000")]
|
||||
public void Constructor_WhenLibraryIdIsInvalid_ShouldPreserveItForTheValidator(string libraryId)
|
||||
{
|
||||
// Act
|
||||
DeleteConsumptionItemHistoryRequest sut = _deleteConsumptionItemHistoryRequestFixture.Create(libraryId: libraryId);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
}
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Globalization;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Contracts.UnitTests.Requests.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionRequest"/> record.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionRequestTests
|
||||
{
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionRequestTests"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionRequestTests()
|
||||
{
|
||||
_getGenreConsumptionRequestFixture = new GetGenreConsumptionRequestFixture();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenCreatedWithFixtureDefaults_ShouldProduceAValidRecord()
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(sut.LibraryId);
|
||||
Assert.True(Guid.TryParse(sut.LibraryId, out Guid parsedLibraryId));
|
||||
Assert.NotEqual(Guid.Empty, parsedLibraryId);
|
||||
Assert.NotNull(sut.MediaKind);
|
||||
Assert.True(Enum.TryParse(sut.MediaKind, ignoreCase: true, out MediaKind parsedMediaKind));
|
||||
Assert.NotEqual(MediaKind.None, parsedMediaKind);
|
||||
Assert.True(Enum.IsDefined(parsedMediaKind));
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
Assert.True(DateTime.TryParse(sut.FromUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedFromUtc));
|
||||
Assert.True(DateTime.TryParse(sut.ToUtc, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out DateTime parsedToUtc));
|
||||
Assert.True(parsedFromUtc <= parsedToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenEveryMemberIsSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string mediaKind = nameof(MediaKind.Book);
|
||||
string fromUtc = "2025-01-02T03:04:05.0000000Z";
|
||||
string toUtc = "2025-02-03T04:05:06.0000000Z";
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(libraryId, sut.LibraryId);
|
||||
Assert.Equal(mediaKind, sut.MediaKind);
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(includeLibraryId: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.LibraryId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenMediaKindIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(includeMediaKind: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenFromUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(includeFromUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.FromUtc);
|
||||
Assert.NotNull(sut.ToUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenToUtcIsNull_ShouldPreserveNull()
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(includeToUtc: false);
|
||||
|
||||
// Assert
|
||||
Assert.Null(sut.ToUtc);
|
||||
Assert.NotNull(sut.FromUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenLibraryIdIsEmpty_ShouldPreserveEmpty()
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(libraryId: string.Empty);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(string.Empty, sut.LibraryId);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("999")] // a numeric value that is not a member name
|
||||
[InlineData("not-a-media-kind")] // a textual value that is not a member name
|
||||
[InlineData("")] // an empty media kind
|
||||
public void Constructor_WhenMediaKindIsInvalid_ShouldPreserveItForTheValidator(string mediaKind)
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(mediaKind: mediaKind);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(mediaKind, sut.MediaKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Constructor_WhenDateBoundaryValuesAreSupplied_ShouldPreserveThem()
|
||||
{
|
||||
// Arrange
|
||||
string fromUtc = DateTime.MinValue.ToString("o", CultureInfo.InvariantCulture);
|
||||
string toUtc = DateTime.MaxValue.ToString("o", CultureInfo.InvariantCulture);
|
||||
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(fromUtc, sut.FromUtc);
|
||||
Assert.Equal(toUtc, sut.ToUtc);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-date")] // a textual value that is not a date
|
||||
[InlineData("2026-13-45T99:99:99")] // a value with out of range components
|
||||
public void Constructor_WhenDateBoundsAreMalformed_ShouldPreserveThemForTheValidator(string malformedBound)
|
||||
{
|
||||
// Act
|
||||
GetGenreConsumptionRequest sut = _getGenreConsumptionRequestFixture.Create(
|
||||
fromUtc: malformedBound,
|
||||
toUtc: malformedBound);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(malformedBound, sut.FromUtc);
|
||||
Assert.Equal(malformedBound, sut.ToUtc);
|
||||
}
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<DeleteConsumptionItemHistoryCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly DeleteConsumptionItemHistoryEndpoint _sut;
|
||||
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteConsumptionItemHistoryEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<DeleteConsumptionItemHistoryCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<DeleteConsumptionItemHistoryEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<Deleted> okResult = Assert.IsType<Ok<Deleted>>(result);
|
||||
Assert.Equal(Result.Deleted, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
includeMediaKind: false,
|
||||
includeMediaItemId: false,
|
||||
includeLibraryId: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors =
|
||||
[
|
||||
DomainErrors.MediaConsumption.UnsupportedMediaKind,
|
||||
DomainErrors.MediaConsumption.MediaItemIdCannotBeEmpty,
|
||||
DomainErrors.Library.LibraryIdCannotBeEmpty
|
||||
];
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "UnsupportedMediaKind", "MediaItemIdCannotBeEmpty", "LibraryIdCannotBeEmpty" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsUnexpectedError_ShouldReturnInternalServerErrorProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Internal("ConsumptionItemHistory.Failed", "An internal error has occurred.");
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
|
||||
Assert.Equal("ConsumptionItemHistory.Failed", problemDetails.Title);
|
||||
Assert.Equal("An internal error has occurred.", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteConsumptionItemHistoryCommandWithMappedRequestAndNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
string mediaKind = nameof(MediaKind.Movie);
|
||||
string mediaItemId = Guid.NewGuid().ToString();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
libraryId: libraryId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteConsumptionItemHistoryCommand>(command =>
|
||||
command.TargetUserId == null &&
|
||||
command.MediaKind == mediaKind &&
|
||||
command.MediaItemId == mediaItemId &&
|
||||
command.LibraryId == libraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(Result.Deleted);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteUserConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteUserConsumptionItemHistoryEndpointTests
|
||||
{
|
||||
private readonly ICommandHandler<DeleteConsumptionItemHistoryCommand, Result<Deleted>> _mockHandler;
|
||||
private readonly DeleteUserConsumptionItemHistoryEndpoint _sut;
|
||||
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteUserConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteUserConsumptionItemHistoryEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<ICommandHandler<DeleteConsumptionItemHistoryCommand, Result<Deleted>>>();
|
||||
_sut = FastEndpoints.Factory.Create<DeleteUserConsumptionItemHistoryEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithDeleted()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<Deleted> okResult = Assert.IsType<Ok<Deleted>>(result);
|
||||
Assert.Equal(Result.Deleted, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.MediaConsumption.MediaItemIdCannotBeEmpty];
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "TargetUserIdIsInvalid", "MediaItemIdCannotBeEmpty" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsUnexpectedError_ShouldReturnInternalServerErrorProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Internal("ConsumptionItemHistory.Failed", "An internal error has occurred.");
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
|
||||
Assert.Equal("ConsumptionItemHistory.Failed", problemDetails.Title);
|
||||
Assert.Equal("An internal error has occurred.", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendDeleteConsumptionItemHistoryCommandWithRouteUserIdAndMappedRequest()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
string mediaKind = nameof(MediaKind.Book);
|
||||
string mediaItemId = Guid.NewGuid().ToString();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: mediaItemId,
|
||||
libraryId: libraryId);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = userId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteConsumptionItemHistoryCommand>(command =>
|
||||
command.TargetUserId == userId.ToString() &&
|
||||
command.MediaKind == mediaKind &&
|
||||
command.MediaItemId == mediaItemId &&
|
||||
command.LibraryId == libraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendCommandWithNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(Result.Deleted));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("userId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<DeleteConsumptionItemHistoryCommand>(command =>
|
||||
command.TargetUserId == null &&
|
||||
command.MediaKind == request.MediaKind &&
|
||||
command.MediaItemId == request.MediaItemId &&
|
||||
command.LibraryId == request.LibraryId),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<DeleteConsumptionItemHistoryCommand>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From(Result.Deleted);
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+285
@@ -0,0 +1,285 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetGenreConsumptionQuery, Result<IReadOnlyList<GenreConsumptionResponse>>> _mockHandler;
|
||||
private readonly GetGenreConsumptionEndpoint _sut;
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
|
||||
private readonly GenreConsumptionResponseFixture _genreConsumptionResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetGenreConsumptionQuery, Result<IReadOnlyList<GenreConsumptionResponse>>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetGenreConsumptionEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithGenreConsumptionResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IReadOnlyList<GenreConsumptionResponse> expectedResponse = _genreConsumptionResponseFixture.CreateMany();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IReadOnlyList<GenreConsumptionResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<GenreConsumptionResponse>>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.ConsumptionDateRangeIsInvalid, DomainErrors.MediaConsumption.UnsupportedMediaKind];
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "ConsumptionDateRangeIsInvalid", "UnsupportedMediaKind" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsUnexpectedError_ShouldReturnInternalServerErrorProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Internal("GenreConsumption.Failed", "An internal error has occurred.");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
|
||||
Assert.Equal("GenreConsumption.Failed", problemDetails.Title);
|
||||
Assert.Equal("An internal error has occurred.", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetGenreConsumptionQueryWithMappedRequestAndNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string mediaKind = nameof(MediaKind.MusicTrack);
|
||||
string fromUtc = "2026-01-01T00:00:00.0000000Z";
|
||||
string toUtc = "2026-02-01T00:00:00.0000000Z";
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetGenreConsumptionQuery>(query =>
|
||||
query.TargetUserId == null &&
|
||||
query.LibraryId == libraryId &&
|
||||
query.MediaKind == mediaKind &&
|
||||
query.FromUtc == fromUtc &&
|
||||
query.ToUtc == toUtc),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOptionalFiltersAreNotProvided_ShouldSendQueryWithNullValues()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetGenreConsumptionQuery>(query =>
|
||||
query.TargetUserId == null &&
|
||||
query.LibraryId == null &&
|
||||
query.MediaKind == null &&
|
||||
query.FromUtc == null &&
|
||||
query.ToUtc == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Fixtures.Core.Responses.MediaConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Http.HttpResults;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
using DomainErrors = Lumina.Domain.Common.Errors.Errors;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Api.UnitTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetUserGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUserGenreConsumptionEndpointTests
|
||||
{
|
||||
private readonly IQueryHandler<GetGenreConsumptionQuery, Result<IReadOnlyList<GenreConsumptionResponse>>> _mockHandler;
|
||||
private readonly GetUserGenreConsumptionEndpoint _sut;
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
|
||||
private readonly GenreConsumptionResponseFixture _genreConsumptionResponseFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUserGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetUserGenreConsumptionEndpointTests()
|
||||
{
|
||||
_mockHandler = Substitute.For<IQueryHandler<GetGenreConsumptionQuery, Result<IReadOnlyList<GenreConsumptionResponse>>>>();
|
||||
_sut = FastEndpoints.Factory.Create<GetUserGenreConsumptionEndpoint>(_mockHandler);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldReturnOkResultWithGenreConsumptionResponses()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
IReadOnlyList<GenreConsumptionResponse> expectedResponse = _genreConsumptionResponseFixture.CreateMany();
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(expectedResponse));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Ok<IReadOnlyList<GenreConsumptionResponse>> okResult = Assert.IsType<Ok<IReadOnlyList<GenreConsumptionResponse>>>(result);
|
||||
Assert.Equal(expectedResponse, okResult.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenSuccessful_ShouldSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany()));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsError_ShouldStillSetPrivateNoStoreCacheHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Contains("Authorization", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsValidationErrors_ShouldReturnValidationProblemResultWithErrorsGroupedByCode()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
List<Error> expectedErrors = [DomainErrors.MediaConsumption.TargetUserIdIsInvalid, DomainErrors.MediaConsumption.UnsupportedMediaKind];
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedErrors);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = "not-a-user-guid";
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
HttpValidationProblemDetails validationProblemDetails = Assert.IsType<HttpValidationProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status422UnprocessableEntity, validationProblemDetails.Status);
|
||||
Assert.Equal("General.Validation", validationProblemDetails.Title);
|
||||
Assert.Equal("OneOrMoreValidationErrorsOccurred", validationProblemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc4918#section-11.2", validationProblemDetails.Type);
|
||||
Assert.NotNull(validationProblemDetails.Extensions["traceId"]);
|
||||
KeyValuePair<string, string[]> singleErrorGroup = Assert.Single(validationProblemDetails.Errors);
|
||||
Assert.Equal("General.Validation", singleErrorGroup.Key);
|
||||
Assert.Equal(new[] { "TargetUserIdIsInvalid", "UnsupportedMediaKind" }, singleErrorGroup.Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotAuthorizedError_ShouldReturnForbiddenProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = ApplicationErrors.Authorization.NotAuthorized;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, problemDetails.Status);
|
||||
Assert.Equal("General.Unauthorized", problemDetails.Title);
|
||||
Assert.Equal("NotAuthorized", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.4", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsNotFoundError_ShouldReturnNotFoundProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status404NotFound, problemDetails.Status);
|
||||
Assert.Equal("General.NotFound", problemDetails.Title);
|
||||
Assert.Equal("ConsumptionRecordNotFound", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenHandlerReturnsUnexpectedError_ShouldReturnInternalServerErrorProblemResult()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
Error expectedError = Error.Internal("GenreConsumption.Failed", "An internal error has occurred.");
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedError);
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
ProblemHttpResult problemResult = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemResult.StatusCode);
|
||||
Assert.Equal("application/problem+json", problemResult.ContentType);
|
||||
Microsoft.AspNetCore.Mvc.ProblemDetails problemDetails = Assert.IsType<Microsoft.AspNetCore.Mvc.ProblemDetails>(problemResult.ProblemDetails);
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, problemDetails.Status);
|
||||
Assert.Equal("GenreConsumption.Failed", problemDetails.Title);
|
||||
Assert.Equal("An internal error has occurred.", problemDetails.Detail);
|
||||
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.6.1", problemDetails.Type);
|
||||
Assert.NotNull(problemDetails.Extensions["traceId"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSendGetGenreConsumptionQueryWithRouteUserIdAndMappedRequest()
|
||||
{
|
||||
// Arrange
|
||||
Guid userId = Guid.NewGuid();
|
||||
string libraryId = Guid.NewGuid().ToString();
|
||||
string mediaKind = nameof(MediaKind.Book);
|
||||
string fromUtc = "2026-01-01T00:00:00.0000000Z";
|
||||
string toUtc = "2026-02-01T00:00:00.0000000Z";
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
libraryId: libraryId,
|
||||
mediaKind: mediaKind,
|
||||
fromUtc: fromUtc,
|
||||
toUtc: toUtc);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany()));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = userId.ToString();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetGenreConsumptionQuery>(query =>
|
||||
query.TargetUserId == userId.ToString() &&
|
||||
query.LibraryId == libraryId &&
|
||||
query.MediaKind == mediaKind &&
|
||||
query.FromUtc == fromUtc &&
|
||||
query.ToUtc == toUtc),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenRouteValueIsMissing_ShouldSendQueryWithNullTargetUserId()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
CancellationToken cancellationToken = CancellationToken.None;
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany()));
|
||||
_sut.HttpContext.Request.RouteValues.Remove("userId");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, cancellationToken);
|
||||
|
||||
// Assert
|
||||
await _mockHandler.Received(1).HandleAsync(
|
||||
Arg.Is<GetGenreConsumptionQuery>(query =>
|
||||
query.TargetUserId == null &&
|
||||
query.LibraryId == null &&
|
||||
query.MediaKind == null &&
|
||||
query.FromUtc == null &&
|
||||
query.ToUtc == null),
|
||||
Arg.Is(cancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCancellationRequested_ShouldCancelOperation()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
CancellationTokenSource cts = new();
|
||||
TaskCompletionSource<bool> operationStarted = new();
|
||||
TaskCompletionSource<bool> cancellationRequested = new();
|
||||
|
||||
_mockHandler.HandleAsync(Arg.Any<GetGenreConsumptionQuery>(), Arg.Any<CancellationToken>())
|
||||
.Returns(callInfo => Task.Run(async () =>
|
||||
{
|
||||
operationStarted.SetResult(true);
|
||||
await cancellationRequested.Task;
|
||||
callInfo.Arg<CancellationToken>().ThrowIfCancellationRequested();
|
||||
return Result.From<IReadOnlyList<GenreConsumptionResponse>>(_genreConsumptionResponseFixture.CreateMany());
|
||||
}, callInfo.Arg<CancellationToken>()));
|
||||
_sut.HttpContext.Request.RouteValues["userId"] = Guid.NewGuid().ToString();
|
||||
|
||||
// Act
|
||||
Task<IResult> operationTask = _sut.ExecuteAsync(request, cts.Token);
|
||||
await operationStarted.Task;
|
||||
cts.Cancel();
|
||||
cancellationRequested.SetResult(true);
|
||||
|
||||
// Assert
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => operationTask);
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearConsumptionHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearConsumptionHistoryEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ClearConsumptionHistoryEndpoint _sut;
|
||||
private readonly ClearConsumptionHistoryRequestFixture _clearConsumptionHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearConsumptionHistoryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut = Factory.Create<ClearConsumptionHistoryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldDeleteCurrentUserHistory(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: userId, includeUserId: userId is not null);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdIsSet_ShouldRequestUserHistoryWithEscapedUserId()
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create(userId: "user/../admin?x=1&y=2");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
ClearConsumptionHistoryRequest request = _clearConsumptionHistoryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.ClearResumePoints;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="ClearResumePointsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class ClearResumePointsEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly ClearResumePointsEndpoint _sut;
|
||||
private readonly ClearResumePointsRequestFixture _clearResumePointsRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ClearResumePointsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public ClearResumePointsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut = Factory.Create<ClearResumePointsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespaceAndLibraryIdIsNull_ShouldClearCurrentUserResumePointsWithoutFilter(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.CLEAR_RESUME_POINTS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSet_ShouldAppendEscapedLibraryFilterToCurrentUserRoute()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(
|
||||
libraryId: "lib?x=1&y=2",
|
||||
includeUserId: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/media-resume-points?libraryId=lib%3Fx%3D1%26y%3D2"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndLibraryIdAreSet_ShouldRequestUserRouteWithBothValuesEscaped()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2");
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/media-resume-points?libraryId=lib%3Fx%3D1%26y%3D2"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
ClearResumePointsRequest request = _clearResumePointsRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
|
||||
using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="DeleteConsumptionItemHistoryEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DeleteConsumptionItemHistoryEndpointTests
|
||||
{
|
||||
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 IApiHttpClient _mockApiHttpClient;
|
||||
private readonly DeleteConsumptionItemHistoryEndpoint _sut;
|
||||
private readonly DeleteConsumptionItemHistoryRequestFixture _deleteConsumptionItemHistoryRequestFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public DeleteConsumptionItemHistoryEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockApiHttpClient.DeleteAsync(Arg.Any<string>(), Arg.Any<CancellationToken>()).Returns(Task.CompletedTask);
|
||||
_sut = Factory.Create<DeleteConsumptionItemHistoryEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiSucceeds_ShouldReturnSuccessJsonWithoutData()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
Assert.False(jsonDocument.RootElement.TryGetProperty("data", out _));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldDeleteCurrentUserItemHistory(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
mediaKind: MediaKind.Movie,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/media-items/Movie/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(MediaKind.MusicTrack, "MusicTrack")] // a music track
|
||||
[InlineData(MediaKind.PodcastEpisode, "PodcastEpisode")] // a podcast episode
|
||||
[InlineData(MediaKind.Book, "Book")] // a book
|
||||
public async Task ExecuteAsync_WhenMediaKindIsSet_ShouldUseTheMediaKindNameInTheUpstreamRoute(MediaKind mediaKind, string expectedMediaKind)
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
mediaKind: mediaKind,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId,
|
||||
includeUserId: false);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == $"users/me/consumption-history/media-items/{expectedMediaKind}/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdIsSet_ShouldRequestUserRouteWithEscapedUserId()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
mediaKind: MediaKind.Book,
|
||||
mediaItemId: s_mediaItemId,
|
||||
libraryId: s_libraryId);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).DeleteAsync(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/media-items/Book/11111111-1111-1111-1111-111111111111/22222222-2222-2222-2222-222222222222"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
DeleteConsumptionItemHistoryRequest request = _deleteConsumptionItemHistoryRequestFixture.Create();
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+249
@@ -0,0 +1,249 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
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.Common.Routes;
|
||||
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.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetAllUsersConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetAllUsersConsumptionStatisticsEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetAllUsersConsumptionStatisticsEndpoint _sut;
|
||||
private readonly GetAllUsersConsumptionStatisticsRequestFixture _getAllUsersConsumptionStatisticsRequestFixture = new();
|
||||
private readonly AllUsersConsumptionStatisticsDtoFixture _allUsersConsumptionStatisticsDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetAllUsersConsumptionStatisticsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetAllUsersConsumptionStatisticsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsStatistics_ShouldReturnSuccessJsonWithStatistics()
|
||||
{
|
||||
// Arrange
|
||||
AllUsersConsumptionStatisticsDto expectedStatistics = _allUsersConsumptionStatisticsDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedStatistics);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getAllUsersConsumptionStatisticsRequestFixture.Create(includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
AllUsersConsumptionStatisticsDto? returnedStatistics = jsonDocument.RootElement.GetProperty("data").Deserialize<AllUsersConsumptionStatisticsDto>(_jsonOptions);
|
||||
Assert.NotNull(returnedStatistics);
|
||||
Assert.Equal(expectedStatistics.Total.CountedSessionCount, returnedStatistics.Total.CountedSessionCount);
|
||||
Assert.Equal(
|
||||
expectedStatistics.Users.Select(userStatistics => userStatistics.UserId),
|
||||
returnedStatistics.Users.Select(userStatistics => userStatistics.UserId));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenNoFilterIsSupplied_ShouldRequestAllUsersStatisticsWithoutQueryString()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_ALL_USERS_CONSUMPTION_STATISTICS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenAllFiltersAreSupplied_ShouldAppendEveryFilterToTheUpstreamQuery()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?libraryId=lib-1&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenLibraryIdContainsUrlSyntax_ShouldEscapeItInTheUpstreamQuery()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib?x=1&y=2",
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<AllUsersConsumptionStatisticsDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetAllUsersConsumptionStatisticsRequest request = _getAllUsersConsumptionStatisticsRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<AllUsersConsumptionStatisticsDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_allUsersConsumptionStatisticsDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenCalled_ShouldRestrictTheRouteToAdministrators()
|
||||
{
|
||||
// Act
|
||||
_sut.Configure();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(_sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains(AuthorizationPolicies.REQUIRE_ADMIN_ROLE, _sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains("GET", _sut.Definition.Verbs);
|
||||
Assert.Contains(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS, _sut.Definition.Routes);
|
||||
}
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetConsumptionStatisticsEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetConsumptionStatisticsEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetConsumptionStatisticsEndpoint _sut;
|
||||
private readonly GetConsumptionStatisticsRequestFixture _getConsumptionStatisticsRequestFixture = new();
|
||||
private readonly ConsumptionSummaryDtoFixture _consumptionSummaryDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetConsumptionStatisticsEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetConsumptionStatisticsEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsStatistics_ShouldReturnSuccessJsonWithStatistics()
|
||||
{
|
||||
// Arrange
|
||||
ConsumptionSummaryDto expectedStatistics = _consumptionSummaryDtoFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedStatistics);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getConsumptionStatisticsRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
ConsumptionSummaryDto? returnedStatistics = jsonDocument.RootElement.GetProperty("data").Deserialize<ConsumptionSummaryDto>(_jsonOptions);
|
||||
Assert.NotNull(returnedStatistics);
|
||||
Assert.Equal(expectedStatistics.UserId, returnedStatistics.UserId);
|
||||
Assert.Equal(expectedStatistics.CountedSessionCount, returnedStatistics.CountedSessionCount);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldRequestCurrentUserStatisticsWithoutQueryString(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_CONSUMPTION_STATISTICS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserStatisticsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<ConsumptionSummaryDto>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetConsumptionStatisticsRequest request = _getConsumptionStatisticsRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<ConsumptionSummaryDto>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_consumptionSummaryDtoFixture.Create());
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetGenreConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetGenreConsumptionEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetGenreConsumptionEndpoint _sut;
|
||||
private readonly GetGenreConsumptionRequestFixture _getGenreConsumptionRequestFixture = new();
|
||||
private readonly GenreConsumptionDtoFixture _genreConsumptionDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetGenreConsumptionEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsGenres_ShouldReturnSuccessJsonWithGenres()
|
||||
{
|
||||
// Arrange
|
||||
GenreConsumptionDto[] expectedGenres = [.. _genreConsumptionDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedGenres);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getGenreConsumptionRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
GenreConsumptionDto[]? returnedGenres = jsonDocument.RootElement.GetProperty("data").Deserialize<GenreConsumptionDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedGenres);
|
||||
Assert.Equal(expectedGenres.Select(genre => genre.Name), returnedGenres.Select(genre => genre.Name));
|
||||
Assert.Equal(expectedGenres.Select(genre => genre.ConsumedItemCount), returnedGenres.Select(genre => genre.ConsumedItemCount));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldRequestCurrentUserGenresWithoutQueryString(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserGenresWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/genres?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<GenreConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/genres?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetGenreConsumptionRequest request = _getGenreConsumptionRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<GenreConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _genreConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetLibraries;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetLibrariesEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetLibrariesEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetLibrariesEndpoint _sut;
|
||||
private readonly LibraryDtoFixture _libraryDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetLibrariesEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetLibrariesEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetLibrariesEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsLibraries_ShouldReturnSuccessJsonWithLibraries()
|
||||
{
|
||||
// Arrange
|
||||
LibraryDto[] expectedLibraries = [.. _libraryDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedLibraries);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
LibraryDto[]? returnedLibraries = jsonDocument.RootElement.GetProperty("data").Deserialize<LibraryDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedLibraries);
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Id), returnedLibraries.Select(library => library.Id));
|
||||
Assert.Equal(expectedLibraries.Select(library => library.Title), returnedLibraries.Select(library => library.Title));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestEnabledLibrariesFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _libraryDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<LibraryDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Libraries.GET_ENABLED_LIBRARIES),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<LibraryDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _libraryDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetMostConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetMostConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetMostConsumedEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetMostConsumedEndpoint _sut;
|
||||
private readonly GetMostConsumedRequestFixture _getMostConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetMostConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetMostConsumedEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetMostConsumedEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsMostConsumedItems_ShouldReturnSuccessJsonWithPage()
|
||||
{
|
||||
// Arrange
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [.. _consumedItemDtoFixture.CreateMany(2)],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPage);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getMostConsumedRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
PaginatedDto<ConsumedItemDto>? returnedPage = jsonDocument.RootElement.GetProperty("data").Deserialize<PaginatedDto<ConsumedItemDto>>(_jsonOptions);
|
||||
Assert.NotNull(returnedPage);
|
||||
Assert.Equal(expectedPage.Count, returnedPage.Count);
|
||||
Assert.Equal(expectedPage.CurrentPage, returnedPage.CurrentPage);
|
||||
Assert.Equal(expectedPage.PerPage, returnedPage.PerPage);
|
||||
Assert.Equal(expectedPage.NumberOfPages, returnedPage.NumberOfPages);
|
||||
Assert.Equal(expectedPage.Data.Select(item => item.MediaItemId), returnedPage.Data.Select(item => item.MediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespaceAndNoFilterIsSupplied_ShouldRequestCurrentUserItemsWithDefaultPaging(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/most-consumed?currentPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPagingIsSupplied_ShouldOmitEveryOptionalFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
currentPage: 3,
|
||||
perPage: 25,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/most-consumed?currentPage=3&perPage=25"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilterAndUseDefaultPaging()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/most-consumed?libraryId=lib-1¤tPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserItemsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc,
|
||||
currentPage: 4,
|
||||
perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/most-consumed?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z¤tPage=4&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetMostConsumedRequest request = _getMostConsumedRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetRecentlyConsumed;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetRecentlyConsumedEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetRecentlyConsumedEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetRecentlyConsumedEndpoint _sut;
|
||||
private readonly GetRecentlyConsumedRequestFixture _getRecentlyConsumedRequestFixture = new();
|
||||
private readonly ConsumedItemDtoFixture _consumedItemDtoFixture = new();
|
||||
private readonly PaginatedDtoFixture<ConsumedItemDto> _paginatedDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetRecentlyConsumedEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetRecentlyConsumedEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetRecentlyConsumedEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsRecentlyConsumedItems_ShouldReturnSuccessJsonWithPage()
|
||||
{
|
||||
// Arrange
|
||||
PaginatedDto<ConsumedItemDto> expectedPage = _paginatedDtoFixture.Create(
|
||||
data: [.. _consumedItemDtoFixture.CreateMany(2)],
|
||||
currentPage: 2,
|
||||
perPage: 5,
|
||||
count: 12,
|
||||
numberOfPages: 3);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedPage);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getRecentlyConsumedRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
PaginatedDto<ConsumedItemDto>? returnedPage = jsonDocument.RootElement.GetProperty("data").Deserialize<PaginatedDto<ConsumedItemDto>>(_jsonOptions);
|
||||
Assert.NotNull(returnedPage);
|
||||
Assert.Equal(expectedPage.Count, returnedPage.Count);
|
||||
Assert.Equal(expectedPage.CurrentPage, returnedPage.CurrentPage);
|
||||
Assert.Equal(expectedPage.PerPage, returnedPage.PerPage);
|
||||
Assert.Equal(expectedPage.NumberOfPages, returnedPage.NumberOfPages);
|
||||
Assert.Equal(expectedPage.Data.Select(item => item.MediaItemId), returnedPage.Data.Select(item => item.MediaItemId));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespaceAndNoFilterIsSupplied_ShouldRequestCurrentUserItemsWithDefaultPaging(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/recently-consumed?currentPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyPagingIsSupplied_ShouldOmitEveryOptionalFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
currentPage: 3,
|
||||
perPage: 25,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/recently-consumed?currentPage=3&perPage=25"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilterAndUseDefaultPaging()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false,
|
||||
includeCurrentPage: false,
|
||||
includePerPage: false);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-history/recently-consumed?libraryId=lib-1¤tPage=1&perPage=10"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserItemsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc,
|
||||
currentPage: 4,
|
||||
perPage: 20);
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<PaginatedDto<ConsumedItemDto>>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-history/recently-consumed?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z¤tPage=4&perPage=20"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetRecentlyConsumedRequest request = _getRecentlyConsumedRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<PaginatedDto<ConsumedItemDto>>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(_paginatedDtoFixture.Create(data: []));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+222
@@ -0,0 +1,222 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
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.Common.Routes;
|
||||
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 Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetTagConsumptionEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetTagConsumptionEndpointTests
|
||||
{
|
||||
private static readonly DateTime s_fromUtc = new(2024, 3, 4, 5, 6, 7, DateTimeKind.Utc);
|
||||
private static readonly DateTime s_toUtc = new(2025, 6, 7, 8, 9, 10, DateTimeKind.Utc);
|
||||
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetTagConsumptionEndpoint _sut;
|
||||
private readonly GetTagConsumptionRequestFixture _getTagConsumptionRequestFixture = new();
|
||||
private readonly TagConsumptionDtoFixture _tagConsumptionDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetTagConsumptionEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetTagConsumptionEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetTagConsumptionEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsTags_ShouldReturnSuccessJsonWithTags()
|
||||
{
|
||||
// Arrange
|
||||
TagConsumptionDto[] expectedTags = [.. _tagConsumptionDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedTags);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(
|
||||
_getTagConsumptionRequestFixture.Create(includeUserId: false, includeLibraryId: false, includeMediaKind: false, includeFromUtc: false, includeToUtc: false),
|
||||
CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
TagConsumptionDto[]? returnedTags = jsonDocument.RootElement.GetProperty("data").Deserialize<TagConsumptionDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedTags);
|
||||
Assert.Equal(expectedTags.Select(tag => tag.Name), returnedTags.Select(tag => tag.Name));
|
||||
Assert.Equal(expectedTags.Select(tag => tag.ConsumedItemCount), returnedTags.Select(tag => tag.ConsumedItemCount));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no user selected, the current user is implied
|
||||
[InlineData("")] // empty user selected
|
||||
[InlineData(" ")] // whitespace user selected
|
||||
public async Task ExecuteAsync_WhenUserIdIsNullOrWhitespace_ShouldRequestCurrentUserTagsWithoutQueryString(string? userId)
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
userId: userId,
|
||||
includeUserId: userId is not null,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.LibraryStatistics.GET_TAG_CONSUMPTION),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIdAndAllFiltersAreSupplied_ShouldRequestUserTagsWithEscapedValues()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
userId: "user/../admin?x=1&y=2",
|
||||
libraryId: "lib?x=1&y=2",
|
||||
mediaKind: MediaKind.Movie,
|
||||
fromUtc: s_fromUtc,
|
||||
toUtc: s_toUtc);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/user%2F..%2Fadmin%3Fx%3D1%26y%3D2/consumption-statistics/tags?libraryId=lib%3Fx%3D1%26y%3D2&mediaKind=Movie&fromUtc=2024-03-04T05%3A06%3A07.0000000Z&toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyLibraryIdIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
libraryId: "lib-1",
|
||||
includeUserId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?libraryId=lib-1"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyMediaKindIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
mediaKind: MediaKind.Book,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeFromUtc: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?mediaKind=Book"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyFromUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
fromUtc: s_fromUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeToUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?fromUtc=2024-03-04T05%3A06%3A07.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenOnlyToUtcIsSupplied_ShouldOmitEveryOtherFilter()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create(
|
||||
toUtc: s_toUtc,
|
||||
includeUserId: false,
|
||||
includeLibraryId: false,
|
||||
includeMediaKind: false,
|
||||
includeFromUtc: false);
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<TagConsumptionDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == "users/me/consumption-statistics/tags?toUtc=2025-06-07T08%3A09%3A10.0000000Z"),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
GetTagConsumptionRequest request = _getTagConsumptionRequestFixture.Create();
|
||||
_mockApiHttpClient.GetAsync<TagConsumptionDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _tagConsumptionDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(request, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.UsersManagement;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using NSubstitute;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.GetUsers;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="GetUsersEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class GetUsersEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly GetUsersEndpoint _sut;
|
||||
private readonly UserDtoFixture _userDtoFixture = new();
|
||||
private readonly JsonSerializerOptions _jsonOptions = new() { PropertyNameCaseInsensitive = true };
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetUsersEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public GetUsersEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_sut = Factory.Create<GetUsersEndpoint>(_mockApiHttpClient);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenApiReturnsUsers_ShouldReturnSuccessJsonWithUsers()
|
||||
{
|
||||
// Arrange
|
||||
UserDto[] expectedUsers = [.. _userDtoFixture.CreateMany(2)];
|
||||
_mockApiHttpClient.GetAsync<UserDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns(expectedUsers);
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
string body = await JsonResultTestHelper.GetResponseBodyAsync(result);
|
||||
|
||||
// Assert
|
||||
using JsonDocument jsonDocument = JsonDocument.Parse(body);
|
||||
Assert.True(jsonDocument.RootElement.GetProperty("success").GetBoolean());
|
||||
UserDto[]? returnedUsers = jsonDocument.RootElement.GetProperty("data").Deserialize<UserDto[]>(_jsonOptions);
|
||||
Assert.NotNull(returnedUsers);
|
||||
Assert.Equal(expectedUsers.Select(user => user.Id), returnedUsers.Select(user => user.Id));
|
||||
Assert.Equal(expectedUsers.Select(user => user.Username), returnedUsers.Select(user => user.Username));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldRequestUsersFromApi()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<UserDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _userDtoFixture.CreateMany(2)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockApiHttpClient.Received(1).GetAsync<UserDto[]>(
|
||||
Arg.Is<string>(endpoint => endpoint == ApiRoutes.Authentication.USERS),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockApiHttpClient.GetAsync<UserDto[]>(Arg.Any<string>(), Arg.Any<CancellationToken>())
|
||||
.Returns([.. _userDtoFixture.CreateMany(1)]);
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Configure_WhenCalled_ShouldRestrictTheRouteToAdministrators()
|
||||
{
|
||||
// Act
|
||||
_sut.Configure();
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(_sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains(AuthorizationPolicies.REQUIRE_ADMIN_ROLE, _sut.Definition.PreBuiltUserPolicies);
|
||||
Assert.Contains("GET", _sut.Definition.Verbs);
|
||||
Assert.Contains(WebRoutes.LibraryStatistics.GET_USERS, _sut.Definition.Routes);
|
||||
}
|
||||
}
|
||||
+335
@@ -0,0 +1,335 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FastEndpoints;
|
||||
using Lumina.Presentation.Web.Common.Api;
|
||||
using Lumina.Presentation.Web.Common.Authorization;
|
||||
using Lumina.Presentation.Web.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Common.Http;
|
||||
using Lumina.Presentation.Web.Common.Primitives;
|
||||
using Lumina.Presentation.Web.Common.Routes;
|
||||
using Lumina.Presentation.Web.Common.Services;
|
||||
using Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
|
||||
using Lumina.Presentation.Web.Core.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.DTO.Themes;
|
||||
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Localization;
|
||||
using NSubstitute;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Claims;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.UnitTests.Core.Endpoints.Library.Statistics.Index;
|
||||
|
||||
/// <summary>
|
||||
/// Contains unit tests for the <see cref="StatisticsIndexViewEndpoint"/> class.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class StatisticsIndexViewEndpointTests
|
||||
{
|
||||
private readonly IApiHttpClient _mockApiHttpClient;
|
||||
private readonly IUrlService _mockUrlService;
|
||||
private readonly ThemePageRenderer _mockThemePageRenderer;
|
||||
private readonly IStringLocalizerFactory _mockStringLocalizerFactory;
|
||||
private readonly IStringLocalizer _mockStringLocalizer;
|
||||
private readonly IAuthorizationService _mockAuthorizationService;
|
||||
private readonly StatisticsIndexViewEndpoint _sut;
|
||||
private readonly ThemePageRenderResultDtoFixture _themePageRenderResultDtoFixture = new();
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointTests"/> class.
|
||||
/// </summary>
|
||||
public StatisticsIndexViewEndpointTests()
|
||||
{
|
||||
_mockApiHttpClient = Substitute.For<IApiHttpClient>();
|
||||
_mockUrlService = Substitute.For<IUrlService>();
|
||||
_mockThemePageRenderer = Substitute.For<ThemePageRenderer>(new ThemeService(_mockApiHttpClient), new ThemeTemplateEngine());
|
||||
_mockStringLocalizer = Substitute.For<IStringLocalizer>();
|
||||
_mockStringLocalizer[Arg.Any<string>()].Returns(callInfo => new LocalizedString(callInfo.Arg<string>(), $"localized-{callInfo.Arg<string>()}"));
|
||||
_mockStringLocalizer.GetAllStrings(Arg.Any<bool>()).Returns(
|
||||
[
|
||||
new LocalizedString("Title", "localized-Title"),
|
||||
new LocalizedString("Loading", "localized-Loading")
|
||||
]);
|
||||
_mockStringLocalizerFactory = Substitute.For<IStringLocalizerFactory>();
|
||||
_mockStringLocalizerFactory.Create(Arg.Any<string>(), Arg.Any<string>()).Returns(_mockStringLocalizer);
|
||||
_mockAuthorizationService = Substitute.For<IAuthorizationService>();
|
||||
_sut = Factory.Create<StatisticsIndexViewEndpoint>(_mockUrlService, _mockThemePageRenderer, _mockStringLocalizerFactory, _mockAuthorizationService);
|
||||
TestHttpContextFactory.ConfigureSession(_sut.HttpContext, TestHttpContextFactory.CreateSession());
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "en-US");
|
||||
_sut.HttpContext.Request.Path = "/en-us/library/statistics";
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldReturnThemedRazorViewResult()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create(content: "<section>content</section>", script: "<script>script</script>")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Any<ThemePageDto>(),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingSucceeds_ShouldPassLocalizedTitleAndPageDataToTheThemeRenderer()
|
||||
{
|
||||
// Arrange
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS).Returns("http://localhost/en-us/library/statistics/api-get-statistics");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
page.PageKey == "library/statistics/index" &&
|
||||
page.Title == "localized-Title" &&
|
||||
page.PageData.ContainsKey("getStatisticsUrl") &&
|
||||
page.PageData.ContainsKey("getAllUsersStatisticsUrl") &&
|
||||
page.PageData.ContainsKey("getRecentlyConsumedUrl") &&
|
||||
page.PageData.ContainsKey("getMostConsumedUrl") &&
|
||||
page.PageData.ContainsKey("getTagConsumptionUrl") &&
|
||||
page.PageData.ContainsKey("getGenreConsumptionUrl") &&
|
||||
page.PageData.ContainsKey("getLibrariesUrl") &&
|
||||
page.PageData.ContainsKey("getUsersUrl") &&
|
||||
page.PageData.ContainsKey("deleteConsumptionItemHistoryUrl") &&
|
||||
page.PageData.ContainsKey("clearConsumptionHistoryUrl") &&
|
||||
page.PageData.ContainsKey("clearResumePointsUrl") &&
|
||||
page.PageData.ContainsKey("culture") &&
|
||||
page.PageData.ContainsKey("isAdmin") &&
|
||||
page.PageData.ContainsKey("currentUserId") &&
|
||||
page.PageData.ContainsKey("strings") &&
|
||||
string.Equals(
|
||||
page.PageData["getStatisticsUrl"] as string,
|
||||
"http://localhost/en-us/library/statistics/api-get-statistics",
|
||||
StringComparison.Ordinal)),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenThemeRenderingFails_ShouldReturnRazorViewResult()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result<ThemePageRenderResultDto>.Failure(Error.Failure("Theme.Render", "The page could not be rendered.")));
|
||||
|
||||
// Act
|
||||
IResult result = await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.IsType<RazorViewResult>(result);
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Any<ThemePageDto>(),
|
||||
Arg.Is<string?>(requestedThemeId => requestedThemeId == null),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIsAdmin_ShouldExposeAdminFlagUsersUrlAndCurrentUserId()
|
||||
{
|
||||
// Arrange
|
||||
Guid expectedUserId = Guid.NewGuid();
|
||||
ConfigureCurrentUser(expectedUserId.ToString());
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS).Returns("http://localhost/en-us/library/statistics/api-get-users");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
Equals(page.PageData["isAdmin"], true) &&
|
||||
string.Equals(
|
||||
page.PageData["getUsersUrl"] as string,
|
||||
"http://localhost/en-us/library/statistics/api-get-users",
|
||||
StringComparison.Ordinal) &&
|
||||
page.PageData["currentUserId"] != null &&
|
||||
(Guid)page.PageData["currentUserId"]! == expectedUserId),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUserIsNotAdmin_ShouldHideUsersUrl()
|
||||
{
|
||||
// Arrange
|
||||
ConfigureCurrentUser(Guid.NewGuid().ToString());
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(false);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS).Returns("http://localhost/en-us/library/statistics/api-get-users");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
Equals(page.PageData["isAdmin"], false) &&
|
||||
string.Equals(page.PageData["getUsersUrl"] as string, string.Empty, StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockUrlService.DidNotReceive().GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)] // no identifier claim at all
|
||||
[InlineData("")] // empty identifier claim
|
||||
[InlineData("not-a-guid")] // identifier claim that is not a GUID
|
||||
public async Task ExecuteAsync_WhenNameIdentifierIsMissingOrNotAGuid_ShouldLeaveCurrentUserIdNull(string? nameIdentifier)
|
||||
{
|
||||
// Arrange
|
||||
ConfigureCurrentUser(nameIdentifier);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page => page.PageData["currentUserId"] == null),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUrlServiceReturnsUrls_ShouldExposeEveryUrlFromTheRouteConstants()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS).Returns("https://lumina.test/statistics");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS).Returns("https://lumina.test/all-users-statistics");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED).Returns("https://lumina.test/recently-consumed");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED).Returns("https://lumina.test/most-consumed");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION).Returns("https://lumina.test/tag-consumption");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION).Returns("https://lumina.test/genre-consumption");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_LIBRARIES).Returns("https://lumina.test/libraries");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS).Returns("https://lumina.test/users");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY).Returns("https://lumina.test/delete-consumption-item-history");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY).Returns("https://lumina.test/clear-consumption-history");
|
||||
_mockUrlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS).Returns("https://lumina.test/clear-resume-points");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
string.Equals(page.PageData["getStatisticsUrl"] as string, "https://lumina.test/statistics", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getAllUsersStatisticsUrl"] as string, "https://lumina.test/all-users-statistics", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getRecentlyConsumedUrl"] as string, "https://lumina.test/recently-consumed", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getMostConsumedUrl"] as string, "https://lumina.test/most-consumed", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getTagConsumptionUrl"] as string, "https://lumina.test/tag-consumption", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getGenreConsumptionUrl"] as string, "https://lumina.test/genre-consumption", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getLibrariesUrl"] as string, "https://lumina.test/libraries", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getUsersUrl"] as string, "https://lumina.test/users", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["deleteConsumptionItemHistoryUrl"] as string, "https://lumina.test/delete-consumption-item-history", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearConsumptionHistoryUrl"] as string, "https://lumina.test/clear-consumption-history", StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearResumePointsUrl"] as string, "https://lumina.test/clear-resume-points", StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_LIBRARIES);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY);
|
||||
_mockUrlService.Received(1).GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenUrlServiceReturnsNull_ShouldExposeEmptyStrings()
|
||||
{
|
||||
// Arrange
|
||||
_mockAuthorizationService.IsInRoleAsync("Admin", Arg.Any<CancellationToken>()).Returns(true);
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page =>
|
||||
string.Equals(page.PageData["getStatisticsUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getAllUsersStatisticsUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getRecentlyConsumedUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getMostConsumedUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getTagConsumptionUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getGenreConsumptionUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getLibrariesUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["getUsersUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["deleteConsumptionItemHistoryUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearConsumptionHistoryUrl"] as string, string.Empty, StringComparison.Ordinal) &&
|
||||
string.Equals(page.PageData["clearResumePointsUrl"] as string, string.Empty, StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCultureRouteValueIsSet_ShouldExposeThatCulture()
|
||||
{
|
||||
// Arrange
|
||||
TestHttpContextFactory.ConfigureCulture(_sut.HttpContext, "fr-FR");
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
await _mockThemePageRenderer.Received(1).RenderAsync(
|
||||
Arg.Is<ThemePageDto>(page => string.Equals(page.PageData["culture"] as string, "fr-FR", StringComparison.Ordinal)),
|
||||
Arg.Any<string?>(),
|
||||
Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_WhenCalled_ShouldSetPrivateNoStoreAndCookieVaryHeaders()
|
||||
{
|
||||
// Arrange
|
||||
_mockThemePageRenderer.RenderAsync(Arg.Any<ThemePageDto>(), Arg.Any<string?>(), Arg.Any<CancellationToken>())
|
||||
.Returns(Result.From(_themePageRenderResultDtoFixture.Create()));
|
||||
|
||||
// Act
|
||||
await _sut.ExecuteAsync(EmptyRequest.Instance, CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
Assert.Equal("private, no-store", _sut.HttpContext.Response.Headers["Cache-Control"].ToString());
|
||||
Assert.Equal("Cookie", _sut.HttpContext.Response.Headers["Vary"].ToString());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Assigns a claims principal to the HTTP context of the endpoint under test.
|
||||
/// </summary>
|
||||
/// <param name="nameIdentifier">The value of the name identifier claim, or <see langword="null"/> to omit the claim.</param>
|
||||
private void ConfigureCurrentUser(string? nameIdentifier)
|
||||
{
|
||||
List<Claim> claims = nameIdentifier is null ? [] : [new Claim(ClaimTypes.NameIdentifier, nameIdentifier)];
|
||||
_sut.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuthentication"));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user